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/SmallVector.h"
27#include "llvm/Frontend/OpenMP/OMPContext.h"
28#include "llvm/Frontend/OpenMP/OMPVersion.h"
29
30#include <memory>
31#include <optional>
32#include <string>
33#include <type_traits>
34#include <utility>
35#include <vector>
36
37namespace Fortran::semantics {
38class DeclTypeSpec;
39class Scope;
41class Symbol;
42
43// Add this namespace to avoid potential conflicts
44namespace omp {
45using Fortran::parser::omp::BlockRange;
46using Fortran::parser::omp::ExecutionPartIterator;
47using Fortran::parser::omp::is_range_v;
48using Fortran::parser::omp::LoopNestIterator;
49using Fortran::parser::omp::LoopRange;
50
51template <typename T, typename U = std::remove_const_t<T>> U AsRvalue(T &t) {
52 return U(t);
53}
54
55template <typename T> T &&AsRvalue(T &&t) { return std::move(t); }
56
57const Scope &GetScopingUnit(const Scope &scope);
58const Scope &GetProgramUnit(const Scope &scope);
59
60// There is no consistent way to get the source of an ActionStmt, but there
61// is "source" in Statement<T>. This structure keeps the ActionStmt with the
62// extracted source for further use.
64 : public parser::omp::WithSource<const parser::ActionStmt *> {
65 using parser::omp::WithSource<value_type>::WithSource;
66 value_type stmt() const { return value; }
67 operator bool() const { return stmt() != nullptr; }
68};
69
71SourcedActionStmt GetActionStmt(const parser::Block &block);
72
73std::string ThisVersion(llvm::omp::Version version);
74std::string TryVersion(llvm::omp::Version version);
75
76const Symbol *GetObjectSymbol(
77 const parser::OmpObject &object, bool ultimate = false);
78const Symbol *GetArgumentSymbol(
79 const parser::OmpArgument &argument, bool ultimate = false);
80
81bool IsCommonBlock(const Symbol &sym);
82bool IsExtendedListItem(const Symbol &sym);
83bool IsVariableListItem(const Symbol &sym);
84bool IsTypeParamInquiry(const Symbol &sym);
85bool IsComplexPart(const Symbol &sym);
86bool IsStructureComponent(const Symbol &sym);
87bool IsPrivatizable(const Symbol &sym);
88bool IsVarOrFunctionRef(const MaybeExpr &expr);
89
90bool IsWholeAssumedSizeArray(const parser::OmpObject &object);
91
92bool IsExtendedListItem(
93 const parser::OmpObject &object, SemanticsContext *semaCtx);
94bool IsLocatorListItem(
95 const parser::OmpObject &object, SemanticsContext *semaCtx);
96bool IsVariableListItem(
97 const parser::OmpObject &object, SemanticsContext *semaCtx);
98
99bool IsSubstring(const parser::OmpObject &object, SemanticsContext *semaCtx);
100bool IsArrayElement(const parser::OmpObject &object, SemanticsContext *semaCtx);
101
102const Symbol *GetHostSymbol(const Symbol &sym);
103
104// Resolve a user-defined reduction visible in scope under the mangled name
105// mangledName (e.g. "op.myop." for operator(.myop.), or a named reduction).
106// Follows USE associations, operator renames, private visibility, and merged
107// generics exactly as the OpenMP semantic checks do, returning the found
108// (non-ultimate) reduction symbol, or null if none is visible. When type is
109// non-null, only a reduction that supports that type is accepted (used to
110// disambiguate an operator that carries reductions for several types). When
111// ambiguous is non-null, it is set true if more than one distinct reduction
112// supports the type (an operator merged from several modules that each declare
113// a reduction for it, or a mangled reduction name that collides across
114// modules).
115const Symbol *FindUserReductionSymbol(const Scope &scope,
116 const parser::CharBlock &mangledName, const DeclTypeSpec *type = nullptr,
117 bool *ambiguous = nullptr);
118
119// Resolve the user-defined reduction associated with the defined-operator
120// symbol operatorSym. Delegates to FindUserReductionSymbol from scope (the
121// scope where the reduction clause appears) with the operator's mangled
122// ("op...") name. Searching from the clause scope, not the operator's owning
123// scope, finds a reduction that is local, host-, or use-associated there (a
124// reduction may be declared in a contained procedure that host-associates the
125// operator from an enclosing module). type filters by supported type as above.
126const Symbol *FindOperatorUserReductionSymbol(const Scope &scope,
127 const Symbol &operatorSym, const DeclTypeSpec *type = nullptr);
128
129// Mangled reduction name ("op.+", "op.*", "op.AND", ...) that semantics stores
130// an intrinsic-operator user reduction under, produced by the same
131// MakeNameFromOperator the reduction-declaration semantics use so a clause-side
132// lookup matches byte-for-byte.
133parser::CharBlock MangledIntrinsicOperatorReductionName(
134 parser::DefinedOperator::IntrinsicOperator op, SemanticsContext &context);
135
136bool IsMapEnteringType(parser::OmpMapType::Value type);
137bool IsMapExitingType(parser::OmpMapType::Value type);
138
139// Returns true if the symbol has a temporary stack-allocated descriptor.
140// This includes assumed-shape and assumed-rank dummy arguments that are
141// not allocatable or pointer. These descriptors are created on the caller's
142// stack and become invalid after the function returns.
143bool HasTemporaryStackDescriptor(const Symbol &symbol);
144
145MaybeExpr GetEvaluateExpr(const parser::Expr &parserExpr);
146template <typename T> MaybeExpr GetEvaluateExpr(const T &inp) {
147 return GetEvaluateExpr(parser::UnwrapRef<parser::Expr>(inp));
148}
149
150std::optional<evaluate::DynamicType> GetDynamicType(
151 const parser::Expr &parserExpr);
152
153std::optional<bool> GetLogicalValue(const SomeExpr &expr);
154std::optional<int64_t> GetIntValueFromExpr(
155 const parser::Expr &parserExpr, SemanticsContext *semaCtx = nullptr);
156
157template <typename T>
158std::optional<int64_t> GetIntValueFromExpr(
159 const T &wrappedExpr, SemanticsContext *semaCtx = nullptr) {
160 if (auto *parserExpr{parser::Unwrap<parser::Expr>(wrappedExpr)}) {
161 return GetIntValueFromExpr(*parserExpr, semaCtx);
162 }
163 return std::nullopt;
164}
165
166// There are several clauses that take an optional, compile-time
167// constant bool argument. Those clauses are stored as std::optional, e.g.
168// OmpClause::ReverseOffload -> std::optional<OmpReverseOffloadClause>.
169// Retrieve the logical value if present.
170template <typename ClauseTy>
171std::optional<bool> GetLogicalArgument(
172 const std::optional<ClauseTy> &maybeClause, SemanticsContext &semaCtx) {
173 if (maybeClause) {
174 // Scalar<Logical<Constant<common::Indirection<Expr>>>>
175 auto &parserExpr{parser::UnwrapRef<parser::Expr>(*maybeClause)};
176 evaluate::ExpressionAnalyzer ea{semaCtx};
177 if (auto &&maybeExpr{ea.Analyze(parserExpr)}) {
178 if (auto v{GetLogicalValue(*maybeExpr)}) {
179 return *v;
180 }
181 }
182 }
183 return std::nullopt;
184}
185
186std::optional<bool> IsContiguous(
187 SemanticsContext &semaCtx, const parser::OmpObject &object);
188
191 const parser::ScalarExpr *expr;
192 parser::CharBlock source;
193};
194
199enum class UnsupportedSelectorFeature {
200 None,
202 TargetDevice,
206 ClauseOrExtensionProperty,
207};
208
212UnsupportedSelectorFeature FindUnsupportedSelectorFeature(
214 SemanticsContext &semaCtx);
215
224std::optional<DynamicUserCondition> MakeVariantMatchInfo(
225 llvm::omp::VariantMatchInfo &vmi,
227 SemanticsContext &semaCtx);
228
232class OmpVariantMatchContext : public llvm::omp::OMPContext {
233public:
234 OmpVariantMatchContext(bool isDeviceCompilation, llvm::Triple targetTriple,
235 llvm::Triple targetOffloadTriple, std::string targetFeatures,
236 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
237 OmpVariantMatchContext(const SemanticsContext &context,
238 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
239 bool matchesISATrait(llvm::StringRef rawString) const override;
240
241private:
242 std::string features_;
243};
244
245struct MetadirectiveCandidate {
246 MetadirectiveCandidate(const parser::OmpDirectiveSpecification *spec,
247 llvm::omp::VariantMatchInfo vmi, bool isExplicit,
248 std::optional<DynamicUserCondition> dynamicCondition = std::nullopt,
249 bool conditionShouldBeTrue = true)
250 : spec{spec}, vmi{std::move(vmi)}, isExplicit{isExplicit},
251 dynamicCondition{dynamicCondition},
252 conditionShouldBeTrue{conditionShouldBeTrue} {}
253
254 const parser::OmpDirectiveSpecification *spec{nullptr};
255 llvm::omp::VariantMatchInfo vmi;
256 bool isExplicit{false};
257 std::optional<DynamicUserCondition> dynamicCondition;
258 bool conditionShouldBeTrue{true};
259};
260
266
271std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet(
272 const parser::OmpClauseList &clauses, SemanticsContext &context,
273 const OmpVariantMatchContext &matchContext);
274
275std::optional<unsigned> SelectBestMetadirectiveCandidate(
276 llvm::ArrayRef<unsigned> candidateIndices,
278 const OmpVariantMatchContext &matchContext);
279
282bool IsRepeatableMetadirectiveCondition(
283 const parser::ScalarExpr &condition, SemanticsContext &context);
284
286bool AreSameRepeatableMetadirectiveCondition(const parser::ScalarExpr &left,
287 const parser::ScalarExpr &right, SemanticsContext &context);
288
291llvm::SmallVector<unsigned, 4> GetMetadirectiveElsePathCandidates(
292 unsigned selectedIndex, llvm::ArrayRef<unsigned> candidateIndices,
294 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
295
299GetReachableMetadirectiveVariants(const MetadirectiveCandidateSet &candidateSet,
300 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
301
308bool MayVariantBeSelected(
310 SemanticsContext &context, OmpVariantMatchContext &matchContext);
311
312std::vector<SomeExpr> GetTopLevelDesignators(const SomeExpr &expr);
313const SomeExpr *HasStorageOverlap(
314 const SomeExpr &base, llvm::ArrayRef<SomeExpr> exprs);
315
316bool IsAssignment(const parser::ActionStmt *x);
317bool IsPointerAssignment(const evaluate::Assignment &x);
318
319MaybeExpr MakeEvaluateExpr(const parser::OmpStylizedInstance &inp);
320
321enum struct ListItemKind : uint32_t {
322 Depend,
323 DirectiveName,
324 DirectiveSpecification,
325 Extended,
326 IntegerExpression,
327 Interop,
328 Locator,
329 Operation,
330 Parameter,
331 ProcedureArgument,
332 Variable,
333};
334
335std::optional<ListItemKind> GetArgumentListItemKind(
336 llvm::omp::Clause clause, llvm::omp::Version version);
337
338bool IsLoopTransforming(llvm::omp::Directive dir);
339bool HasDataEnvironment(llvm::omp::Directive dir);
340
341bool IsFullUnroll(const parser::OmpDirectiveSpecification &spec);
342
347 parser::OmpAtClause::ActionTime at{
348 parser::OmpAtClause::ActionTime::Compilation};
349 parser::OmpSeverityClause::SevLevel severity{
350 parser::OmpSeverityClause::SevLevel::Fatal};
351 const parser::Expr *message{nullptr};
352};
353
356OmpErrorArgs GetErrorDirectiveArgs(
358OmpErrorArgs GetErrorDirectiveArgs(const parser::OmpErrorDirective &errDir);
359
360inline bool IsDoConcurrentLegal(llvm::omp::Version version) {
361 // DO CONCURRENT is allowed (as an alternative to a Canonical Loop Nest)
362 // in OpenMP 6.0+.
363 return version >= 60;
364}
365
366struct LoopControl {
367 LoopControl(LoopControl &&x) = default;
368 LoopControl(const LoopControl &x) = default;
369 LoopControl(const parser::LoopControl::Bounds &x);
370 LoopControl(const parser::ConcurrentControl &x);
371
372 const parser::Name &iv;
373 parser::omp::WithSource<MaybeExpr> lbound, ubound, step;
374
375private:
376 static parser::omp::WithSource<MaybeExpr> fromParserExpr(
377 const parser::Expr &x);
378};
379
380std::vector<LoopControl> GetLoopControls(const parser::DoConstruct &x);
381
383struct Reason {
384 Reason() = default;
385 Reason(Reason &&) = default;
386 Reason(const Reason &);
387 Reason &operator=(Reason &&) = default;
388 Reason &operator=(const Reason &);
389
390 parser::Messages msgs;
391
392 template <typename... Ts> Reason &Say(Ts &&...args) {
393 msgs.Say(std::forward<Ts>(args)...);
394 return *this;
395 }
396 parser::Message &AttachTo(parser::Message &msg);
397 Reason &Append(const Reason &other) {
398 CopyFrom(other);
399 return *this;
400 }
401 operator bool() const { return !msgs.empty(); }
402
403private:
404 void CopyFrom(const Reason &other);
405};
406
407// A property with an explanation of its value. Both, the property and the
408// reason are optional (the reason can have no messages in it).
409template <typename T> struct WithReason {
410 std::optional<T> value;
411 Reason reason;
412
413 WithReason() = default;
414 WithReason(std::optional<T> v, const Reason &r = Reason())
415 : value(v), reason(r) {}
416 operator bool() const { return value.has_value(); }
417};
418
419WithReason<int64_t> GetArgumentValueWithReason(
420 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
421 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
422WithReason<int64_t> GetNumArgumentsWithReason(
423 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
424 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
425WithReason<int64_t> GetHeightWithReason(
426 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
427 SemanticsContext *semaCtx = nullptr);
428
431std::pair<WithReason<int64_t>, bool> GetAffectedNestDepthWithReason(
432 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
433 SemanticsContext *semaCtx = nullptr);
436std::pair<WithReason<int64_t>, bool> GetGeneratedNestDepthWithReason(
437 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
438 SemanticsContext *semaCtx = nullptr);
442WithReason<std::pair<int64_t, int64_t>> GetAffectedLoopRangeWithReason(
443 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
444 SemanticsContext *semaCtx = nullptr);
446WithReason<int64_t> GetRectangularNestDepthWithReason(
447 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
448 SemanticsContext *semaCtx = nullptr);
449
453std::optional<int64_t> GetMinimumSequenceCount(
454 std::optional<int64_t> first, std::optional<int64_t> count);
455std::optional<int64_t> GetMinimumSequenceCount(
456 std::optional<std::pair<int64_t, int64_t>> range);
457
463std::optional<std::vector<const parser::DoConstruct *>> CollectAffectedDoLoops(
464 const parser::OpenMPLoopConstruct &x, llvm::omp::Version version,
465 SemanticsContext *semaCtx = nullptr);
466
471bool IsDoacrossAffected(const parser::OpenMPLoopConstruct &x);
472
473struct LoopSequence {
474 LoopSequence(const parser::ExecutionPartConstruct &root,
475 llvm::omp::Version version, bool allowAllLoops = false,
476 SemanticsContext *semaCtx = nullptr);
477
478 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
479 LoopSequence(const R &range, llvm::omp::Version version,
480 bool allowAllLoops = false, SemanticsContext *semaCtx = nullptr)
481 : version_(version), allowAllLoops_(allowAllLoops), semaCtx_(semaCtx) {
482 entry_ = std::make_unique<Construct>(range, nullptr);
483 createChildrenFromRange(entry_->location);
484 precalculate();
485 }
486
487 struct Depth {
488 // If this sequence is a nest, the depth of the Canonical Loop Nest rooted
489 // at this sequence. Otherwise unspecified.
490 WithReason<int64_t> semantic;
491 // If this sequence is a nest, the depth of the perfect Canonical Loop Nest
492 // rooted at this sequence. Otherwise unspecified.
493 WithReason<int64_t> perfect;
494 };
495
496 bool isNest() const { return length_.value == 1; }
497 const WithReason<int64_t> &length() const { return length_; }
498 const WithReason<int64_t> &height() const { return height_; }
499 const Depth &depth() const { return depth_; }
500 const std::vector<LoopSequence> &children() const { return children_; }
501 const parser::ExecutionPartConstruct *owner() const { return entry_->owner; }
502
503 WithReason<bool> isWellFormedSequence() const;
504 WithReason<bool> isWellFormedNest() const;
505
508 const LoopSequence *getNestedDoConcurrent() const;
509
510 std::vector<LoopControl> getLoopControls() const;
511 // Check if this loop's bounds are invariant in each of the `outer`
512 // constructs.
513 WithReason<bool> isRectangular(
514 const std::vector<const LoopSequence *> &outer) const;
515
516private:
517 using Construct = ExecutionPartIterator::Construct;
518
519 LoopSequence(std::unique_ptr<Construct> entry, llvm::omp::Version version,
520 bool allowAllLoops, SemanticsContext *semaCtx = nullptr);
521
522 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
523 void createChildrenFromRange(const R &range) {
524 createChildrenFromRange(range.begin(), range.end());
525 }
526
527 std::unique_ptr<Construct> createConstructEntry(
528 const parser::ExecutionPartConstruct &code);
529
530 void createChildrenFromRange( //
531 ExecutionPartIterator::IteratorType begin,
532 ExecutionPartIterator::IteratorType end);
533
535 void precalculate();
536
537 WithReason<int64_t> calculateLength() const;
538 WithReason<int64_t> getNestedLength() const;
539 Depth calculateDepths() const;
540 Depth getNestedDepths() const;
541 WithReason<int64_t> calculateHeight() const;
542
546 const parser::ExecutionPartConstruct *invalidIC_{nullptr};
550 const parser::ExecutionPartConstruct *opaqueIC_{nullptr};
551
556 WithReason<int64_t> length_;
558 Depth depth_;
565 WithReason<int64_t> height_;
566
567 // The core structure of the class:
568 llvm::omp::Version version_; // Needed for GetXyzWithReason
569 bool allowAllLoops_;
570 std::unique_ptr<Construct> entry_;
571 std::vector<LoopSequence> children_;
572 SemanticsContext *semaCtx_{nullptr};
573};
574
575// ---------------------------------------------------------------------------
576// Trait-matching helpers shared between metadirective lowering and
577// declare-variant semantic recording.
578// ---------------------------------------------------------------------------
579
581llvm::omp::TraitSet MapTraitSet(parser::OmpTraitSetSelectorName::Value name);
582
585llvm::omp::TraitSelector MapTraitSelector(
586 const parser::OmpTraitSelectorName &name, llvm::omp::TraitSet set);
587
589std::optional<bool> EvaluateUserCondition(
590 SemanticsContext &semaCtx, const parser::ScalarExpr &scalarExpr);
591
593llvm::APInt *GetTraitScore(
594 const std::optional<parser::OmpTraitSelector::Properties> &props,
595 SemanticsContext &semaCtx, std::optional<llvm::APInt> &scoreStorage);
596
600void ProcessTraitProperties(llvm::omp::VariantMatchInfo &vmi,
601 llvm::omp::TraitSet set, llvm::omp::TraitSelector selector,
602 const std::optional<parser::OmpTraitSelector::Properties> &props,
603 llvm::APInt *scorePtr);
604
605} // namespace omp
606} // namespace Fortran::semantics
607
608#endif // FORTRAN_SEMANTICS_OPENMP_UTILS_H
Definition expression.h:923
Definition char-block.h:26
Definition message.h:200
Definition message.h:332
Definition scope.h:68
Definition semantics.h:67
Definition symbol.h:910
Definition FIRType.h:106
Definition OpenACC.h:20
Definition parse-tree.h:501
Definition parse-tree.h:2281
Definition parse-tree.h:2368
Definition parse-tree.h:559
Definition parse-tree.h:1738
Definition parse-tree.h:592
Definition parse-tree.h:5276
Definition parse-tree.h:5283
Definition parse-tree.h:5350
Definition parse-tree.h:3623
Definition parse-tree.h:3648
Definition parse-tree.h:5656
Definition parse-tree.h:3746
Definition openmp-utils.h:55
Non-constant user condition expression and source for runtime lowering.
Definition openmp-utils.h:190
const LoopSequence * getNestedDoConcurrent() const
Definition openmp-utils.cpp:1844
const parser::OmpDirectiveSpecification * fallback
Null represents either an explicit NOTHING fallback or no fallback.
Definition openmp-utils.h:264
Definition openmp-utils.h:346
A representation of a "because" message.
Definition openmp-utils.h:383
Definition openmp-utils.h:64
Definition openmp-utils.h:409