FLANG
openmp-utils.h
1//===-- lib/Semantics/openmp-utils.h --------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Common utilities used in OpenMP semantic checks.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef FORTRAN_SEMANTICS_OPENMP_UTILS_H
14#define FORTRAN_SEMANTICS_OPENMP_UTILS_H
15
16#include "flang/Evaluate/type.h"
17#include "flang/Parser/char-block.h"
18#include "flang/Parser/message.h"
19#include "flang/Parser/openmp-utils.h"
20#include "flang/Parser/parse-tree.h"
21#include "flang/Parser/tools.h"
22#include "flang/Semantics/tools.h"
23
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Frontend/OpenMP/OMPContext.h"
29#include "llvm/Frontend/OpenMP/OMPVersion.h"
30
31#include <memory>
32#include <optional>
33#include <string>
34#include <type_traits>
35#include <utility>
36#include <vector>
37
38namespace Fortran::semantics {
39class DeclTypeSpec;
40class Scope;
42class Symbol;
43
44// Add this namespace to avoid potential conflicts
45namespace omp {
46using Fortran::parser::omp::BlockRange;
47using Fortran::parser::omp::ExecutionPartIterator;
48using Fortran::parser::omp::is_range_v;
49using Fortran::parser::omp::LoopNestIterator;
50using Fortran::parser::omp::LoopRange;
51
52template <typename T, typename U = std::remove_const_t<T>> U AsRvalue(T &t) {
53 return U(t);
54}
55
56template <typename T> T &&AsRvalue(T &&t) { return std::move(t); }
57
59 // Map of clauses and which directives they are considered to be allowed on
60 // for the purpose of this compilation despite not being allowed by strict
61 // interpretation of the selected spec version.
62 // This is to record cases where we allow a clause because a past/future
63 // spec allows it. This is needed for consistent treatment of clauses as
64 // allowed/disallowed.
65 llvm::DenseMap<llvm::omp::Clause, llvm::omp::Directives> allowedClauses;
66};
67
68bool IsClauseAllowedOnDirective(llvm::omp::Clause clauseId,
69 llvm::omp::Directive dirId, llvm::omp::Version ver,
70 SemanticOverrides *overrides);
71
72bool IsClauseAllowedOnDirective(llvm::omp::Clause clauseId,
73 llvm::omp::Directive dirId, llvm::omp::Version version,
74 SemanticsContext *semaCtx);
75
76const Scope &GetScopingUnit(const Scope &scope);
77const Scope &GetProgramUnit(const Scope &scope);
78
79// There is no consistent way to get the source of an ActionStmt, but there
80// is "source" in Statement<T>. This structure keeps the ActionStmt with the
81// extracted source for further use.
83 : public parser::omp::WithSource<const parser::ActionStmt *> {
84 using parser::omp::WithSource<value_type>::WithSource;
85 value_type stmt() const { return value; }
86 operator bool() const { return stmt() != nullptr; }
87};
88
90SourcedActionStmt GetActionStmt(const parser::Block &block);
91
92std::string ThisVersion(llvm::omp::Version version);
93std::string TryVersion(llvm::omp::Version version);
94
95const Symbol *GetObjectSymbol(
96 const parser::OmpObject &object, bool ultimate = false);
97const Symbol *GetArgumentSymbol(
98 const parser::OmpArgument &argument, bool ultimate = false);
99
100bool IsCommonBlock(const Symbol &sym);
101bool IsExtendedListItem(const Symbol &sym);
102bool IsVariableListItem(const Symbol &sym);
103bool IsTypeParamInquiry(const Symbol &sym);
104bool IsComplexPart(const Symbol &sym);
105bool IsStructureComponent(const Symbol &sym);
106bool IsPrivatizable(const Symbol &sym);
107bool IsVarOrFunctionRef(const MaybeExpr &expr);
108
109bool IsWholeAssumedSizeArray(const parser::OmpObject &object);
110
111bool IsExtendedListItem(
112 const parser::OmpObject &object, SemanticsContext *semaCtx);
113bool IsLocatorListItem(
114 const parser::OmpObject &object, SemanticsContext *semaCtx);
115bool IsVariableListItem(
116 const parser::OmpObject &object, SemanticsContext *semaCtx);
117
118// Analyzes potential substrings and retains diagnostics; may modify semantic
119// state and the parse tree. A missing result indicates an invalid designator,
120// already diagnosed.
121std::optional<bool> IsSubstringAndValidate(
122 const parser::OmpObject &object, SemanticsContext *semaCtx);
123bool IsArrayElement(const parser::OmpObject &object, SemanticsContext *semaCtx);
124
125const Symbol *GetHostSymbol(const Symbol &sym);
126
127// Resolve a user-defined reduction visible in scope under the mangled name
128// mangledName (e.g. "op.myop." for operator(.myop.), or a named reduction).
129// Follows USE associations, operator renames, private visibility, and merged
130// generics exactly as the OpenMP semantic checks do, returning the found
131// (non-ultimate) reduction symbol, or null if none is visible. When type is
132// non-null, only a reduction that supports that type is accepted (used to
133// disambiguate an operator that carries reductions for several types). When
134// ambiguous is non-null, it is set true if more than one distinct reduction
135// supports the type (an operator merged from several modules that each declare
136// a reduction for it, or a mangled reduction name that collides across
137// modules).
138const Symbol *FindUserReductionSymbol(const Scope &scope,
139 const parser::CharBlock &mangledName, const DeclTypeSpec *type = nullptr,
140 bool *ambiguous = nullptr);
141
142// Resolve the user-defined reduction associated with the defined-operator
143// symbol operatorSym. Delegates to FindUserReductionSymbol from scope (the
144// scope where the reduction clause appears) with the operator's mangled
145// ("op...") name. Searching from the clause scope, not the operator's owning
146// scope, finds a reduction that is local, host-, or use-associated there (a
147// reduction may be declared in a contained procedure that host-associates the
148// operator from an enclosing module). type filters by supported type as above.
149const Symbol *FindOperatorUserReductionSymbol(const Scope &scope,
150 const Symbol &operatorSym, const DeclTypeSpec *type = nullptr);
151
152bool IsMapEnteringType(parser::OmpMapType::Value type);
153bool IsMapExitingType(parser::OmpMapType::Value type);
154
155// Returns true if the symbol has a temporary stack-allocated descriptor.
156// This includes assumed-shape and assumed-rank dummy arguments that are
157// not allocatable or pointer. These descriptors are created on the caller's
158// stack and become invalid after the function returns.
159bool HasTemporaryStackDescriptor(const Symbol &symbol);
160
161MaybeExpr GetEvaluateExpr(const parser::Expr &parserExpr);
162template <typename T> MaybeExpr GetEvaluateExpr(const T &inp) {
163 return GetEvaluateExpr(parser::UnwrapRef<parser::Expr>(inp));
164}
165
166std::optional<evaluate::DynamicType> GetDynamicType(
167 const parser::Expr &parserExpr);
168
169std::optional<bool> GetLogicalValue(const SomeExpr &expr);
170std::optional<int64_t> GetIntValueFromExpr(
171 const parser::Expr &parserExpr, SemanticsContext *semaCtx = nullptr);
172
173template <typename T>
174std::optional<int64_t> GetIntValueFromExpr(
175 const T &wrappedExpr, SemanticsContext *semaCtx = nullptr) {
176 if (auto *parserExpr{parser::Unwrap<parser::Expr>(wrappedExpr)}) {
177 return GetIntValueFromExpr(*parserExpr, semaCtx);
178 }
179 return std::nullopt;
180}
181
182// There are several clauses that take an optional, compile-time
183// constant bool argument. Those clauses are stored as std::optional, e.g.
184// OmpClause::ReverseOffload -> std::optional<OmpReverseOffloadClause>.
185// Retrieve the logical value if present.
186template <typename ClauseTy>
187std::optional<bool> GetLogicalArgument(
188 const std::optional<ClauseTy> &maybeClause, SemanticsContext &semaCtx) {
189 if (maybeClause) {
190 // Scalar<Logical<Constant<common::Indirection<Expr>>>>
191 auto &parserExpr{parser::UnwrapRef<parser::Expr>(*maybeClause)};
192 evaluate::ExpressionAnalyzer ea{semaCtx};
193 if (auto &&maybeExpr{ea.Analyze(parserExpr)}) {
194 if (auto v{GetLogicalValue(*maybeExpr)}) {
195 return *v;
196 }
197 }
198 }
199 return std::nullopt;
200}
201
202std::optional<bool> IsContiguous(
203 SemanticsContext &semaCtx, const parser::OmpObject &object);
204
207 const parser::ScalarExpr *expr;
208 parser::CharBlock source;
209};
210
215enum class UnsupportedSelectorFeature {
216 None,
218 TargetDevice,
222 ClauseOrExtensionProperty,
223};
224
228UnsupportedSelectorFeature FindUnsupportedSelectorFeature(
230 SemanticsContext &semaCtx);
231
240std::optional<DynamicUserCondition> MakeVariantMatchInfo(
241 llvm::omp::VariantMatchInfo &vmi,
243 SemanticsContext &semaCtx);
244
248class OmpVariantMatchContext : public llvm::omp::OMPContext {
249public:
250 OmpVariantMatchContext(bool isDeviceCompilation, llvm::Triple targetTriple,
251 llvm::Triple targetOffloadTriple, std::string targetFeatures,
252 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
253 OmpVariantMatchContext(const SemanticsContext &context,
254 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
255 bool matchesISATrait(llvm::StringRef rawString) const override;
256
257private:
258 std::string features_;
259};
260
261struct MetadirectiveCandidate {
262 MetadirectiveCandidate(const parser::OmpDirectiveSpecification *spec,
263 llvm::omp::VariantMatchInfo vmi, bool isExplicit,
264 std::optional<DynamicUserCondition> dynamicCondition = std::nullopt,
265 bool conditionShouldBeTrue = true)
266 : spec{spec}, vmi{std::move(vmi)}, isExplicit{isExplicit},
267 dynamicCondition{dynamicCondition},
268 conditionShouldBeTrue{conditionShouldBeTrue} {}
269
270 const parser::OmpDirectiveSpecification *spec{nullptr};
271 llvm::omp::VariantMatchInfo vmi;
272 bool isExplicit{false};
273 std::optional<DynamicUserCondition> dynamicCondition;
274 bool conditionShouldBeTrue{true};
275};
276
282
283const parser::OmpContextSelector *GetContextSelector(
284 const parser::OmpClause &clause);
285const parser::OmpDirectiveSpecification *GetDirectiveVariant(
286 const parser::OmpClause &clause);
287
292std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet(
293 const parser::OmpClauseList &clauses, SemanticsContext &context,
294 const OmpVariantMatchContext &matchContext);
295
296std::optional<unsigned> SelectBestMetadirectiveCandidate(
297 llvm::ArrayRef<unsigned> candidateIndices,
299 const OmpVariantMatchContext &matchContext);
300
303bool IsRepeatableMetadirectiveCondition(
304 const parser::ScalarExpr &condition, SemanticsContext &context);
305
307bool AreSameRepeatableMetadirectiveCondition(const parser::ScalarExpr &left,
308 const parser::ScalarExpr &right, SemanticsContext &context);
309
312llvm::SmallVector<unsigned, 4> GetMetadirectiveElsePathCandidates(
313 unsigned selectedIndex, llvm::ArrayRef<unsigned> candidateIndices,
315 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
316
320GetReachableMetadirectiveVariants(const MetadirectiveCandidateSet &candidateSet,
321 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
322
329bool MayVariantBeSelected(
331 SemanticsContext &context, OmpVariantMatchContext &matchContext);
332
333std::vector<SomeExpr> GetTopLevelDesignators(const SomeExpr &expr);
334const SomeExpr *HasStorageOverlap(
335 const SomeExpr &base, llvm::ArrayRef<SomeExpr> exprs);
336
337bool IsAssignment(const parser::ActionStmt *x);
338bool IsPointerAssignment(const evaluate::Assignment &x);
339
340MaybeExpr MakeEvaluateExpr(const parser::OmpStylizedInstance &inp);
341
342enum struct ListItemKind : uint32_t {
343 Depend,
344 DirectiveName,
345 DirectiveSpecification,
346 Extended,
347 IntegerExpression,
348 Interop,
349 Locator,
350 Operation,
351 Parameter,
352 ProcedureArgument,
353 Variable,
354};
355
356std::optional<ListItemKind> GetArgumentListItemKind(
357 llvm::omp::Clause clause, llvm::omp::Version version);
358
359bool IsLoopTransforming(llvm::omp::Directive dir);
360bool HasDataEnvironment(llvm::omp::Directive dir);
361
362bool IsFullUnroll(const parser::OmpDirectiveSpecification &spec);
363
368 parser::OmpAtClause::ActionTime at{
369 parser::OmpAtClause::ActionTime::Compilation};
370 parser::OmpSeverityClause::SevLevel severity{
371 parser::OmpSeverityClause::SevLevel::Fatal};
372 const parser::Expr *message{nullptr};
373};
374
377OmpErrorArgs GetErrorDirectiveArgs(
379OmpErrorArgs GetErrorDirectiveArgs(const parser::OmpErrorDirective &errDir);
380
381inline bool IsDoConcurrentLegal(llvm::omp::Version version) {
382 // DO CONCURRENT is allowed (as an alternative to a Canonical Loop Nest)
383 // in OpenMP 6.0+.
384 return version >= 60;
385}
386
387struct LoopControl {
388 LoopControl(LoopControl &&x) = default;
389 LoopControl(const LoopControl &x) = default;
390 LoopControl(const parser::LoopControl::Bounds &x);
391 LoopControl(const parser::ConcurrentControl &x);
392
393 const parser::Name &iv;
394 parser::omp::WithSource<MaybeExpr> lbound, ubound, step;
395
396private:
397 static parser::omp::WithSource<MaybeExpr> fromParserExpr(
398 const parser::Expr &x);
399};
400
401std::vector<LoopControl> GetLoopControls(const parser::DoConstruct &x);
402
404struct Reason {
405 Reason() = default;
406 Reason(Reason &&) = default;
407 Reason(const Reason &);
408 Reason &operator=(Reason &&) = default;
409 Reason &operator=(const Reason &);
410
411 parser::Messages msgs;
412
413 template <typename... Ts> Reason &Say(Ts &&...args) {
414 msgs.Say(std::forward<Ts>(args)...);
415 return *this;
416 }
417 parser::Message &AttachTo(parser::Message &msg);
418 Reason &Append(const Reason &other) {
419 CopyFrom(other);
420 return *this;
421 }
422 operator bool() const { return !msgs.empty(); }
423
424private:
425 void CopyFrom(const Reason &other);
426};
427
428// A property with an explanation of its value. Both, the property and the
429// reason are optional (the reason can have no messages in it).
430template <typename T> struct WithReason {
431 std::optional<T> value;
432 Reason reason;
433
434 WithReason() = default;
435 WithReason(std::optional<T> v, const Reason &r = Reason())
436 : value(v), reason(r) {}
437 operator bool() const { return value.has_value(); }
438};
439
440WithReason<int64_t> GetArgumentValueWithReason(
441 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
442 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
443WithReason<int64_t> GetNumArgumentsWithReason(
444 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
445 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
446WithReason<int64_t> GetHeightWithReason(
447 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
448 SemanticsContext *semaCtx = nullptr);
449
452std::pair<WithReason<int64_t>, bool> GetAffectedNestDepthWithReason(
453 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
454 SemanticsContext *semaCtx = nullptr);
457std::pair<WithReason<int64_t>, bool> GetGeneratedNestDepthWithReason(
458 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
459 SemanticsContext *semaCtx = nullptr);
463WithReason<std::pair<int64_t, int64_t>> GetAffectedLoopRangeWithReason(
464 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
465 SemanticsContext *semaCtx = nullptr);
467WithReason<int64_t> GetRectangularNestDepthWithReason(
468 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
469 SemanticsContext *semaCtx = nullptr);
470
474std::optional<int64_t> GetMinimumSequenceCount(
475 std::optional<int64_t> first, std::optional<int64_t> count);
476std::optional<int64_t> GetMinimumSequenceCount(
477 std::optional<std::pair<int64_t, int64_t>> range);
478
484std::optional<std::vector<const parser::DoConstruct *>> CollectAffectedDoLoops(
485 const parser::OpenMPLoopConstruct &x, llvm::omp::Version version,
486 SemanticsContext *semaCtx = nullptr);
487
492bool IsDoacrossAffected(const parser::OpenMPLoopConstruct &x);
493
494struct LoopSequence {
495 LoopSequence(const parser::ExecutionPartConstruct &root,
496 llvm::omp::Version version, bool allowAllLoops = false,
497 SemanticsContext *semaCtx = nullptr);
498
499 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
500 LoopSequence(const R &range, llvm::omp::Version version,
501 bool allowAllLoops = false, SemanticsContext *semaCtx = nullptr)
502 : version_(version), allowAllLoops_(allowAllLoops), semaCtx_(semaCtx) {
503 entry_ = std::make_unique<Construct>(range, nullptr);
504 createChildrenFromRange(entry_->location);
505 precalculate();
506 }
507
508 struct Depth {
509 // If this sequence is a nest, the depth of the Canonical Loop Nest rooted
510 // at this sequence. Otherwise unspecified.
511 WithReason<int64_t> semantic;
512 // If this sequence is a nest, the depth of the perfect Canonical Loop Nest
513 // rooted at this sequence. Otherwise unspecified.
514 WithReason<int64_t> perfect;
515 };
516
517 bool isNest() const { return length_.value == 1; }
518 const WithReason<int64_t> &length() const { return length_; }
519 const WithReason<int64_t> &height() const { return height_; }
520 const Depth &depth() const { return depth_; }
521 const std::vector<LoopSequence> &children() const { return children_; }
522 const parser::ExecutionPartConstruct *owner() const { return entry_->owner; }
523
524 WithReason<bool> isWellFormedSequence() const;
525 WithReason<bool> isWellFormedNest() const;
526
529 const LoopSequence *getNestedDoConcurrent() const;
530
531 std::vector<LoopControl> getLoopControls() const;
532 // Check if this loop's bounds are invariant in each of the `outer`
533 // constructs.
534 WithReason<bool> isRectangular(
535 const std::vector<const LoopSequence *> &outer) const;
536
537private:
538 using Construct = ExecutionPartIterator::Construct;
539
540 LoopSequence(std::unique_ptr<Construct> entry, llvm::omp::Version version,
541 bool allowAllLoops, SemanticsContext *semaCtx = nullptr);
542
543 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
544 void createChildrenFromRange(const R &range) {
545 createChildrenFromRange(range.begin(), range.end());
546 }
547
548 std::unique_ptr<Construct> createConstructEntry(
549 const parser::ExecutionPartConstruct &code);
550
551 void createChildrenFromRange( //
552 ExecutionPartIterator::IteratorType begin,
553 ExecutionPartIterator::IteratorType end);
554
556 void precalculate();
557
558 WithReason<int64_t> calculateLength() const;
559 WithReason<int64_t> getNestedLength() const;
560 Depth calculateDepths() const;
561 Depth getNestedDepths() const;
562 WithReason<int64_t> calculateHeight() const;
563
567 const parser::ExecutionPartConstruct *invalidIC_{nullptr};
571 const parser::ExecutionPartConstruct *opaqueIC_{nullptr};
572
577 WithReason<int64_t> length_;
579 Depth depth_;
586 WithReason<int64_t> height_;
587
588 // The core structure of the class:
589 llvm::omp::Version version_; // Needed for GetXyzWithReason
590 bool allowAllLoops_;
591 std::unique_ptr<Construct> entry_;
592 std::vector<LoopSequence> children_;
593 SemanticsContext *semaCtx_{nullptr};
594};
595
596// ---------------------------------------------------------------------------
597// Trait-matching helpers shared between metadirective lowering and
598// declare-variant semantic recording.
599// ---------------------------------------------------------------------------
600
602llvm::omp::TraitSet MapTraitSet(parser::OmpTraitSetSelectorName::Value name);
603
606llvm::omp::TraitSelector MapTraitSelector(
607 const parser::OmpTraitSelectorName &name, llvm::omp::TraitSet set);
608
610std::optional<bool> EvaluateUserCondition(
611 SemanticsContext &semaCtx, const parser::ScalarExpr &scalarExpr);
612
614llvm::APInt *GetTraitScore(
615 const std::optional<parser::OmpTraitSelector::Properties> &props,
616 SemanticsContext &semaCtx, std::optional<llvm::APInt> &scoreStorage);
617
621void ProcessTraitProperties(llvm::omp::VariantMatchInfo &vmi,
622 llvm::omp::TraitSet set, llvm::omp::TraitSelector selector,
623 const std::optional<parser::OmpTraitSelector::Properties> &props,
624 llvm::APInt *scorePtr);
625
626} // namespace omp
627} // namespace Fortran::semantics
628
629#endif // FORTRAN_SEMANTICS_OPENMP_UTILS_H
Definition expression.h:960
Definition char-block.h:27
Definition message.h:202
Definition message.h:334
Definition scope.h:69
Definition semantics.h:71
Definition symbol.h:918
Definition FIRType.h:106
Definition OpenACC.h:20
Definition parse-tree.h:501
Definition parse-tree.h:2292
Definition parse-tree.h:2379
Definition parse-tree.h:559
Definition parse-tree.h:1749
Definition parse-tree.h:592
Definition parse-tree.h:5288
Definition parse-tree.h:5272
Definition parse-tree.h:5295
Definition parse-tree.h:5362
Definition parse-tree.h:3634
Definition parse-tree.h:3659
Definition parse-tree.h:5668
Definition parse-tree.h:3757
Definition openmp-utils.h:114
Non-constant user condition expression and source for runtime lowering.
Definition openmp-utils.h:206
const LoopSequence * getNestedDoConcurrent() const
Definition openmp-utils.cpp:1883
const parser::OmpDirectiveSpecification * fallback
Null represents either a clause-free NOTHING fallback or no fallback.
Definition openmp-utils.h:280
Definition openmp-utils.h:367
A representation of a "because" message.
Definition openmp-utils.h:404
Definition openmp-utils.h:58
Definition openmp-utils.h:83
Definition openmp-utils.h:430