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
118bool IsSubstring(const parser::OmpObject &object, SemanticsContext *semaCtx);
119bool IsArrayElement(const parser::OmpObject &object, SemanticsContext *semaCtx);
120
121const Symbol *GetHostSymbol(const Symbol &sym);
122
123// Resolve a user-defined reduction visible in scope under the mangled name
124// mangledName (e.g. "op.myop." for operator(.myop.), or a named reduction).
125// Follows USE associations, operator renames, private visibility, and merged
126// generics exactly as the OpenMP semantic checks do, returning the found
127// (non-ultimate) reduction symbol, or null if none is visible. When type is
128// non-null, only a reduction that supports that type is accepted (used to
129// disambiguate an operator that carries reductions for several types). When
130// ambiguous is non-null, it is set true if more than one distinct reduction
131// supports the type (an operator merged from several modules that each declare
132// a reduction for it, or a mangled reduction name that collides across
133// modules).
134const Symbol *FindUserReductionSymbol(const Scope &scope,
135 const parser::CharBlock &mangledName, const DeclTypeSpec *type = nullptr,
136 bool *ambiguous = nullptr);
137
138// Resolve the user-defined reduction associated with the defined-operator
139// symbol operatorSym. Delegates to FindUserReductionSymbol from scope (the
140// scope where the reduction clause appears) with the operator's mangled
141// ("op...") name. Searching from the clause scope, not the operator's owning
142// scope, finds a reduction that is local, host-, or use-associated there (a
143// reduction may be declared in a contained procedure that host-associates the
144// operator from an enclosing module). type filters by supported type as above.
145const Symbol *FindOperatorUserReductionSymbol(const Scope &scope,
146 const Symbol &operatorSym, const DeclTypeSpec *type = nullptr);
147
148// Mangled reduction name ("op.+", "op.*", "op.AND", ...) that semantics stores
149// an intrinsic-operator user reduction under, produced by the same
150// MakeNameFromOperator the reduction-declaration semantics use so a clause-side
151// lookup matches byte-for-byte.
152parser::CharBlock MangledIntrinsicOperatorReductionName(
153 parser::DefinedOperator::IntrinsicOperator op, SemanticsContext &context);
154
155bool IsMapEnteringType(parser::OmpMapType::Value type);
156bool IsMapExitingType(parser::OmpMapType::Value type);
157
158// Returns true if the symbol has a temporary stack-allocated descriptor.
159// This includes assumed-shape and assumed-rank dummy arguments that are
160// not allocatable or pointer. These descriptors are created on the caller's
161// stack and become invalid after the function returns.
162bool HasTemporaryStackDescriptor(const Symbol &symbol);
163
164MaybeExpr GetEvaluateExpr(const parser::Expr &parserExpr);
165template <typename T> MaybeExpr GetEvaluateExpr(const T &inp) {
166 return GetEvaluateExpr(parser::UnwrapRef<parser::Expr>(inp));
167}
168
169std::optional<evaluate::DynamicType> GetDynamicType(
170 const parser::Expr &parserExpr);
171
172std::optional<bool> GetLogicalValue(const SomeExpr &expr);
173std::optional<int64_t> GetIntValueFromExpr(
174 const parser::Expr &parserExpr, SemanticsContext *semaCtx = nullptr);
175
176template <typename T>
177std::optional<int64_t> GetIntValueFromExpr(
178 const T &wrappedExpr, SemanticsContext *semaCtx = nullptr) {
179 if (auto *parserExpr{parser::Unwrap<parser::Expr>(wrappedExpr)}) {
180 return GetIntValueFromExpr(*parserExpr, semaCtx);
181 }
182 return std::nullopt;
183}
184
185// There are several clauses that take an optional, compile-time
186// constant bool argument. Those clauses are stored as std::optional, e.g.
187// OmpClause::ReverseOffload -> std::optional<OmpReverseOffloadClause>.
188// Retrieve the logical value if present.
189template <typename ClauseTy>
190std::optional<bool> GetLogicalArgument(
191 const std::optional<ClauseTy> &maybeClause, SemanticsContext &semaCtx) {
192 if (maybeClause) {
193 // Scalar<Logical<Constant<common::Indirection<Expr>>>>
194 auto &parserExpr{parser::UnwrapRef<parser::Expr>(*maybeClause)};
195 evaluate::ExpressionAnalyzer ea{semaCtx};
196 if (auto &&maybeExpr{ea.Analyze(parserExpr)}) {
197 if (auto v{GetLogicalValue(*maybeExpr)}) {
198 return *v;
199 }
200 }
201 }
202 return std::nullopt;
203}
204
205std::optional<bool> IsContiguous(
206 SemanticsContext &semaCtx, const parser::OmpObject &object);
207
210 const parser::ScalarExpr *expr;
211 parser::CharBlock source;
212};
213
218enum class UnsupportedSelectorFeature {
219 None,
221 TargetDevice,
225 ClauseOrExtensionProperty,
226};
227
231UnsupportedSelectorFeature FindUnsupportedSelectorFeature(
233 SemanticsContext &semaCtx);
234
243std::optional<DynamicUserCondition> MakeVariantMatchInfo(
244 llvm::omp::VariantMatchInfo &vmi,
246 SemanticsContext &semaCtx);
247
251class OmpVariantMatchContext : public llvm::omp::OMPContext {
252public:
253 OmpVariantMatchContext(bool isDeviceCompilation, llvm::Triple targetTriple,
254 llvm::Triple targetOffloadTriple, std::string targetFeatures,
255 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
256 OmpVariantMatchContext(const SemanticsContext &context,
257 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
258 bool matchesISATrait(llvm::StringRef rawString) const override;
259
260private:
261 std::string features_;
262};
263
264struct MetadirectiveCandidate {
265 MetadirectiveCandidate(const parser::OmpDirectiveSpecification *spec,
266 llvm::omp::VariantMatchInfo vmi, bool isExplicit,
267 std::optional<DynamicUserCondition> dynamicCondition = std::nullopt,
268 bool conditionShouldBeTrue = true)
269 : spec{spec}, vmi{std::move(vmi)}, isExplicit{isExplicit},
270 dynamicCondition{dynamicCondition},
271 conditionShouldBeTrue{conditionShouldBeTrue} {}
272
273 const parser::OmpDirectiveSpecification *spec{nullptr};
274 llvm::omp::VariantMatchInfo vmi;
275 bool isExplicit{false};
276 std::optional<DynamicUserCondition> dynamicCondition;
277 bool conditionShouldBeTrue{true};
278};
279
285
290std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet(
291 const parser::OmpClauseList &clauses, SemanticsContext &context,
292 const OmpVariantMatchContext &matchContext);
293
294std::optional<unsigned> SelectBestMetadirectiveCandidate(
295 llvm::ArrayRef<unsigned> candidateIndices,
297 const OmpVariantMatchContext &matchContext);
298
301bool IsRepeatableMetadirectiveCondition(
302 const parser::ScalarExpr &condition, SemanticsContext &context);
303
305bool AreSameRepeatableMetadirectiveCondition(const parser::ScalarExpr &left,
306 const parser::ScalarExpr &right, SemanticsContext &context);
307
310llvm::SmallVector<unsigned, 4> GetMetadirectiveElsePathCandidates(
311 unsigned selectedIndex, llvm::ArrayRef<unsigned> candidateIndices,
313 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
314
318GetReachableMetadirectiveVariants(const MetadirectiveCandidateSet &candidateSet,
319 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
320
327bool MayVariantBeSelected(
329 SemanticsContext &context, OmpVariantMatchContext &matchContext);
330
331std::vector<SomeExpr> GetTopLevelDesignators(const SomeExpr &expr);
332const SomeExpr *HasStorageOverlap(
333 const SomeExpr &base, llvm::ArrayRef<SomeExpr> exprs);
334
335bool IsAssignment(const parser::ActionStmt *x);
336bool IsPointerAssignment(const evaluate::Assignment &x);
337
338MaybeExpr MakeEvaluateExpr(const parser::OmpStylizedInstance &inp);
339
340enum struct ListItemKind : uint32_t {
341 Depend,
342 DirectiveName,
343 DirectiveSpecification,
344 Extended,
345 IntegerExpression,
346 Interop,
347 Locator,
348 Operation,
349 Parameter,
350 ProcedureArgument,
351 Variable,
352};
353
354std::optional<ListItemKind> GetArgumentListItemKind(
355 llvm::omp::Clause clause, llvm::omp::Version version);
356
357bool IsLoopTransforming(llvm::omp::Directive dir);
358bool HasDataEnvironment(llvm::omp::Directive dir);
359
360bool IsFullUnroll(const parser::OmpDirectiveSpecification &spec);
361
366 parser::OmpAtClause::ActionTime at{
367 parser::OmpAtClause::ActionTime::Compilation};
368 parser::OmpSeverityClause::SevLevel severity{
369 parser::OmpSeverityClause::SevLevel::Fatal};
370 const parser::Expr *message{nullptr};
371};
372
375OmpErrorArgs GetErrorDirectiveArgs(
377OmpErrorArgs GetErrorDirectiveArgs(const parser::OmpErrorDirective &errDir);
378
379inline bool IsDoConcurrentLegal(llvm::omp::Version version) {
380 // DO CONCURRENT is allowed (as an alternative to a Canonical Loop Nest)
381 // in OpenMP 6.0+.
382 return version >= 60;
383}
384
385struct LoopControl {
386 LoopControl(LoopControl &&x) = default;
387 LoopControl(const LoopControl &x) = default;
388 LoopControl(const parser::LoopControl::Bounds &x);
389 LoopControl(const parser::ConcurrentControl &x);
390
391 const parser::Name &iv;
392 parser::omp::WithSource<MaybeExpr> lbound, ubound, step;
393
394private:
395 static parser::omp::WithSource<MaybeExpr> fromParserExpr(
396 const parser::Expr &x);
397};
398
399std::vector<LoopControl> GetLoopControls(const parser::DoConstruct &x);
400
402struct Reason {
403 Reason() = default;
404 Reason(Reason &&) = default;
405 Reason(const Reason &);
406 Reason &operator=(Reason &&) = default;
407 Reason &operator=(const Reason &);
408
409 parser::Messages msgs;
410
411 template <typename... Ts> Reason &Say(Ts &&...args) {
412 msgs.Say(std::forward<Ts>(args)...);
413 return *this;
414 }
415 parser::Message &AttachTo(parser::Message &msg);
416 Reason &Append(const Reason &other) {
417 CopyFrom(other);
418 return *this;
419 }
420 operator bool() const { return !msgs.empty(); }
421
422private:
423 void CopyFrom(const Reason &other);
424};
425
426// A property with an explanation of its value. Both, the property and the
427// reason are optional (the reason can have no messages in it).
428template <typename T> struct WithReason {
429 std::optional<T> value;
430 Reason reason;
431
432 WithReason() = default;
433 WithReason(std::optional<T> v, const Reason &r = Reason())
434 : value(v), reason(r) {}
435 operator bool() const { return value.has_value(); }
436};
437
438WithReason<int64_t> GetArgumentValueWithReason(
439 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
440 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
441WithReason<int64_t> GetNumArgumentsWithReason(
442 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
443 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
444WithReason<int64_t> GetHeightWithReason(
445 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
446 SemanticsContext *semaCtx = nullptr);
447
450std::pair<WithReason<int64_t>, bool> GetAffectedNestDepthWithReason(
451 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
452 SemanticsContext *semaCtx = nullptr);
455std::pair<WithReason<int64_t>, bool> GetGeneratedNestDepthWithReason(
456 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
457 SemanticsContext *semaCtx = nullptr);
461WithReason<std::pair<int64_t, int64_t>> GetAffectedLoopRangeWithReason(
462 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
463 SemanticsContext *semaCtx = nullptr);
465WithReason<int64_t> GetRectangularNestDepthWithReason(
466 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
467 SemanticsContext *semaCtx = nullptr);
468
472std::optional<int64_t> GetMinimumSequenceCount(
473 std::optional<int64_t> first, std::optional<int64_t> count);
474std::optional<int64_t> GetMinimumSequenceCount(
475 std::optional<std::pair<int64_t, int64_t>> range);
476
482std::optional<std::vector<const parser::DoConstruct *>> CollectAffectedDoLoops(
483 const parser::OpenMPLoopConstruct &x, llvm::omp::Version version,
484 SemanticsContext *semaCtx = nullptr);
485
490bool IsDoacrossAffected(const parser::OpenMPLoopConstruct &x);
491
492struct LoopSequence {
493 LoopSequence(const parser::ExecutionPartConstruct &root,
494 llvm::omp::Version version, bool allowAllLoops = false,
495 SemanticsContext *semaCtx = nullptr);
496
497 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
498 LoopSequence(const R &range, llvm::omp::Version version,
499 bool allowAllLoops = false, SemanticsContext *semaCtx = nullptr)
500 : version_(version), allowAllLoops_(allowAllLoops), semaCtx_(semaCtx) {
501 entry_ = std::make_unique<Construct>(range, nullptr);
502 createChildrenFromRange(entry_->location);
503 precalculate();
504 }
505
506 struct Depth {
507 // If this sequence is a nest, the depth of the Canonical Loop Nest rooted
508 // at this sequence. Otherwise unspecified.
509 WithReason<int64_t> semantic;
510 // If this sequence is a nest, the depth of the perfect Canonical Loop Nest
511 // rooted at this sequence. Otherwise unspecified.
512 WithReason<int64_t> perfect;
513 };
514
515 bool isNest() const { return length_.value == 1; }
516 const WithReason<int64_t> &length() const { return length_; }
517 const WithReason<int64_t> &height() const { return height_; }
518 const Depth &depth() const { return depth_; }
519 const std::vector<LoopSequence> &children() const { return children_; }
520 const parser::ExecutionPartConstruct *owner() const { return entry_->owner; }
521
522 WithReason<bool> isWellFormedSequence() const;
523 WithReason<bool> isWellFormedNest() const;
524
527 const LoopSequence *getNestedDoConcurrent() const;
528
529 std::vector<LoopControl> getLoopControls() const;
530 // Check if this loop's bounds are invariant in each of the `outer`
531 // constructs.
532 WithReason<bool> isRectangular(
533 const std::vector<const LoopSequence *> &outer) const;
534
535private:
536 using Construct = ExecutionPartIterator::Construct;
537
538 LoopSequence(std::unique_ptr<Construct> entry, llvm::omp::Version version,
539 bool allowAllLoops, SemanticsContext *semaCtx = nullptr);
540
541 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
542 void createChildrenFromRange(const R &range) {
543 createChildrenFromRange(range.begin(), range.end());
544 }
545
546 std::unique_ptr<Construct> createConstructEntry(
547 const parser::ExecutionPartConstruct &code);
548
549 void createChildrenFromRange( //
550 ExecutionPartIterator::IteratorType begin,
551 ExecutionPartIterator::IteratorType end);
552
554 void precalculate();
555
556 WithReason<int64_t> calculateLength() const;
557 WithReason<int64_t> getNestedLength() const;
558 Depth calculateDepths() const;
559 Depth getNestedDepths() const;
560 WithReason<int64_t> calculateHeight() const;
561
565 const parser::ExecutionPartConstruct *invalidIC_{nullptr};
569 const parser::ExecutionPartConstruct *opaqueIC_{nullptr};
570
575 WithReason<int64_t> length_;
577 Depth depth_;
584 WithReason<int64_t> height_;
585
586 // The core structure of the class:
587 llvm::omp::Version version_; // Needed for GetXyzWithReason
588 bool allowAllLoops_;
589 std::unique_ptr<Construct> entry_;
590 std::vector<LoopSequence> children_;
591 SemanticsContext *semaCtx_{nullptr};
592};
593
594// ---------------------------------------------------------------------------
595// Trait-matching helpers shared between metadirective lowering and
596// declare-variant semantic recording.
597// ---------------------------------------------------------------------------
598
600llvm::omp::TraitSet MapTraitSet(parser::OmpTraitSetSelectorName::Value name);
601
604llvm::omp::TraitSelector MapTraitSelector(
605 const parser::OmpTraitSelectorName &name, llvm::omp::TraitSet set);
606
608std::optional<bool> EvaluateUserCondition(
609 SemanticsContext &semaCtx, const parser::ScalarExpr &scalarExpr);
610
612llvm::APInt *GetTraitScore(
613 const std::optional<parser::OmpTraitSelector::Properties> &props,
614 SemanticsContext &semaCtx, std::optional<llvm::APInt> &scoreStorage);
615
619void ProcessTraitProperties(llvm::omp::VariantMatchInfo &vmi,
620 llvm::omp::TraitSet set, llvm::omp::TraitSelector selector,
621 const std::optional<parser::OmpTraitSelector::Properties> &props,
622 llvm::APInt *scorePtr);
623
624} // namespace omp
625} // namespace Fortran::semantics
626
627#endif // FORTRAN_SEMANTICS_OPENMP_UTILS_H
Definition expression.h:923
Definition char-block.h:26
Definition message.h:202
Definition message.h:334
Definition scope.h:68
Definition semantics.h:71
Definition symbol.h:916
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:5287
Definition parse-tree.h:5294
Definition parse-tree.h:5361
Definition parse-tree.h:3634
Definition parse-tree.h:3659
Definition parse-tree.h:5667
Definition parse-tree.h:3757
Definition openmp-utils.h:55
Non-constant user condition expression and source for runtime lowering.
Definition openmp-utils.h:209
const LoopSequence * getNestedDoConcurrent() const
Definition openmp-utils.cpp:1873
const parser::OmpDirectiveSpecification * fallback
Null represents either an explicit NOTHING fallback or no fallback.
Definition openmp-utils.h:283
Definition openmp-utils.h:365
A representation of a "because" message.
Definition openmp-utils.h:402
Definition openmp-utils.h:58
Definition openmp-utils.h:83
Definition openmp-utils.h:428