llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT--> @llvm/pr-subscribers-clang-modules Author: Zahira Ammarguellat (zahiraam) <details> <summary>Changes</summary> With `-fopenmp-metadirective-runtime-selection`, `CodeGen` now emits a runtime selection for metadirectives with non-constant user conditions. Variants are tried from best to worst score. Static selectors are matched at compile time, conditions at runtime, and otherwise runs if nothing applies. Also: - construct selectors are matched against the enclosing constructs. Fixed compile-time selection, where they never matched. - Standalone variants are supported: they run the directive and then the statement. - All variants are emitted in source order, so target regions in variants get the same names on host and device. --- Patch is 38.13 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/239292.diff 16 Files Affected: - (modified) clang/include/clang/AST/StmtOpenMP.h (+17-1) - (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (-3) - (modified) clang/include/clang/Sema/SemaOpenMP.h (+7-1) - (modified) clang/lib/AST/StmtOpenMP.cpp (+17-2) - (modified) clang/lib/AST/StmtPrinter.cpp (+14-6) - (modified) clang/lib/CodeGen/CGStmtOpenMP.cpp (+57-2) - (modified) clang/lib/Parse/ParseOpenMP.cpp (+37-15) - (modified) clang/lib/Sema/SemaOpenMP.cpp (+9-4) - (modified) clang/lib/Sema/TreeTransform.h (+6-4) - (modified) clang/lib/Serialization/ASTReaderStmt.cpp (+8) - (modified) clang/lib/Serialization/ASTWriterStmt.cpp (+5) - (added) clang/test/OpenMP/metadirective_construct_codegen.cpp (+29) - (modified) clang/test/OpenMP/metadirective_runtime_ast_print.cpp (+20) - (added) clang/test/OpenMP/metadirective_runtime_codegen.cpp (+284) - (modified) clang/test/OpenMP/metadirective_runtime_messages.cpp (-10) - (modified) clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp (+35) ``````````diff diff --git a/clang/include/clang/AST/StmtOpenMP.h b/clang/include/clang/AST/StmtOpenMP.h index a990de6d04f74..46e35d4b48470 100644 --- a/clang/include/clang/AST/StmtOpenMP.h +++ b/clang/include/clang/AST/StmtOpenMP.h @@ -6627,6 +6627,13 @@ class OMPMetaDirective final : public OMPExecutableDirective { /// directive has no 'otherwise' clause. bool HasImplicitOtherwise = false; + /// The OpenMP constructs that enclose the directive. + ArrayRef<llvm::omp::TraitProperty> ConstructTraits; + + /// For each variant, true if it is a standalone directive followed by the + /// statement, stored together as a compound statement. + ArrayRef<bool> DirectiveThenStmt; + OMPMetaDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(OMPMetaDirectiveClass, llvm::omp::OMPD_metadirective, StartLoc, @@ -6669,12 +6676,17 @@ class OMPMetaDirective final : public OMPExecutableDirective { } void setHasImplicitOtherwise(bool V) { HasImplicitOtherwise = V; } + void setConstructTraits(const ASTContext &C, + ArrayRef<llvm::omp::TraitProperty> Traits); + void setDirectiveThenStmt(const ASTContext &C, ArrayRef<bool> Flags); public: static OMPMetaDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions, - ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise); + ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise, + ArrayRef<llvm::omp::TraitProperty> ConstructTraits, + ArrayRef<bool> DirectiveThenStmt); static OMPMetaDirective *CreateEmpty(const ASTContext &C, unsigned NumVariants, EmptyShell); @@ -6685,6 +6697,10 @@ class OMPMetaDirective final : public OMPExecutableDirective { ArrayRef<OMPTraitInfo *> traitInfos() const { return getTrailingTraitInfos(); } + ArrayRef<llvm::omp::TraitProperty> constructTraits() const { + return ConstructTraits; + } + ArrayRef<bool> directiveThenStmt() const { return DirectiveThenStmt; } child_range children() { MutableArrayRef<Stmt *> Children = Data->getChildren(); diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index 2be6ff8344cd6..82aec8b4eb714 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -1568,9 +1568,6 @@ def err_omp_expected_context_selector : Error<"expected valid context selector in %0">; def warn_omp_default_deprecated : Warning<"'default' clause for" " 'metadirective' is deprecated; use 'otherwise' instead">, InGroup<Deprecated>; -def err_omp_metadirective_standalone_variant : Error< - "standalone directive variants are not supported in a 'metadirective' " - "with non-constant user conditions">; def err_omp_requires_out_inout_depend_type : Error< "reserved locator 'omp_all_memory' requires 'out' or 'inout' " "dependency types">; diff --git a/clang/include/clang/Sema/SemaOpenMP.h b/clang/include/clang/Sema/SemaOpenMP.h index 6750f6a9ce4c2..174a7caafa6e4 100644 --- a/clang/include/clang/Sema/SemaOpenMP.h +++ b/clang/include/clang/Sema/SemaOpenMP.h @@ -214,10 +214,13 @@ class SemaOpenMP : public SemaBase { /// Called for metadirectives with user conditions that require runtime /// selection. \p Variants holds one complete directive (or the plain /// associated statement) per entry of \p TraitInfos. + /// \p DirectiveThenStmt marks the variants that are a standalone directive + /// followed by the statement. StmtResult ActOnOpenMPMetaDirective(SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPTraitInfo *> TraitInfos, - ArrayRef<Stmt *> Variants); + ArrayRef<Stmt *> Variants, + ArrayRef<bool> DirectiveThenStmt); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp @@ -1525,6 +1528,9 @@ class SemaOpenMP : public SemaBase { int getOpenMPDeviceNum() const; + /// Return the OpenMP constructs enclosing the current location. + ArrayRef<llvm::omp::TraitProperty> getConstructTraits(); + void setOpenMPDeviceNumID(StringRef ID); enum class OpenMPImpexType { diff --git a/clang/lib/AST/StmtOpenMP.cpp b/clang/lib/AST/StmtOpenMP.cpp index 3812b4a060240..71c992b717b25 100644 --- a/clang/lib/AST/StmtOpenMP.cpp +++ b/clang/lib/AST/StmtOpenMP.cpp @@ -350,18 +350,33 @@ OMPMetaDirective *OMPMetaDirective::allocate(const ASTContext &C, OMPMetaDirective *OMPMetaDirective::Create( const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions, - ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise) { + ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise, + ArrayRef<llvm::omp::TraitProperty> ConstructTraits, + ArrayRef<bool> DirectiveThenStmt) { assert(Variants.size() == Conditions.size() && Variants.size() == TraitInfos.size() && - "Expected one condition and one trait info per variant"); + Variants.size() == DirectiveThenStmt.size() && + "Expected one condition, trait info and flag per variant"); OMPMetaDirective *Dir = allocate(C, Variants.size(), StartLoc, EndLoc); llvm::copy(Variants, Dir->getTrailingVariants().begin()); llvm::copy(Conditions, Dir->getTrailingConditions().begin()); llvm::copy(TraitInfos, Dir->getTrailingTraitInfos().begin()); Dir->setHasImplicitOtherwise(HasImplicitOtherwise); + Dir->setConstructTraits(C, ConstructTraits); + Dir->setDirectiveThenStmt(C, DirectiveThenStmt); return Dir; } +void OMPMetaDirective::setDirectiveThenStmt(const ASTContext &C, + ArrayRef<bool> Flags) { + DirectiveThenStmt = Flags.copy(C); +} + +void OMPMetaDirective::setConstructTraits( + const ASTContext &C, ArrayRef<llvm::omp::TraitProperty> Traits) { + ConstructTraits = Traits.copy(C); +} + OMPMetaDirective *OMPMetaDirective::CreateEmpty(const ASTContext &C, unsigned NumVariants, EmptyShell) { diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp index bed934a70ab51..030985f62280f 100644 --- a/clang/lib/AST/StmtPrinter.cpp +++ b/clang/lib/AST/StmtPrinter.cpp @@ -813,7 +813,11 @@ void StmtPrinter::VisitOMPMetaDirective(OMPMetaDirective *Node) { TraitInfos[I]->print(OS, Policy); OS << ": "; } - if (auto *D = dyn_cast<OMPExecutableDirective>(Variants[I])) { + Stmt *V = Variants[I]; + // A standalone directive is stored together with the statement. + if (Node->directiveThenStmt()[I]) + V = cast<CompoundStmt>(V)->body_front(); + if (auto *D = dyn_cast<OMPExecutableDirective>(V)) { OS << getOpenMPDirectiveName(D->getDirectiveKind(), OpenMPVersion); for (OMPClause *C : D->clauses()) { if (C && !C->isImplicit()) { @@ -825,11 +829,15 @@ void StmtPrinter::VisitOMPMetaDirective(OMPMetaDirective *Node) { OS << ')'; } OS << NL; - // Every variant has the same associated statement; print it once. - Stmt *Body = Variants.front(); - if (auto *D = dyn_cast<OMPExecutableDirective>(Body)) - Body = D->getRawStmt(); - PrintStmt(Body); + // Print the statement once, from a variant that has it. If none has it, + // the statement follows the metadirective. + for (Stmt *V : Variants) { + auto *D = dyn_cast<OMPExecutableDirective>(V); + if (D && D->hasAssociatedStmt()) { + PrintStmt(D->getRawStmt()); + break; + } + } } void StmtPrinter::VisitOMPParallelDirective(OMPParallelDirective *Node) { diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp index b00894c85fd67..ac72a1429ffad 100644 --- a/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -2398,8 +2398,63 @@ void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) { } void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) { - // TODO: Select the variant at runtime. - EmitStmt(S.variants().front()); + // Try variants from best to worst match; 'otherwise' runs if none applies. + TargetOMPContext OMPCtx( + getContext(), /*DiagUnknownTrait=*/[](StringRef) {}, + /*CurrentFunctionDecl=*/nullptr, S.constructTraits(), /*DeviceNum=*/-1); + ArrayRef<Stmt *> Variants = S.variants(); + ArrayRef<Expr *> Conditions = S.conditions(); + SmallVector<llvm::omp::VariantMatchInfo, 4> VMIs; + SmallVector<unsigned, 4> VariantIdx; + std::optional<unsigned> Fallback; + for (auto [I, TI] : llvm::enumerate(S.traitInfos())) { + if (TI->Sets.empty()) { + Fallback = I; + continue; + } + llvm::omp::VariantMatchInfo &VMI = VMIs.emplace_back(); + TI->getAsVariantMatchInfo(getContext(), VMI); + // Treat the condition as true here; it is checked at runtime. + if (Conditions[I]) { + VMI.RequiredTraits.reset( + unsigned(llvm::omp::TraitProperty::user_condition_false)); + VMI.RequiredTraits.set( + unsigned(llvm::omp::TraitProperty::user_condition_true)); + } + VariantIdx.push_back(I); + } + + llvm::BasicBlock *EndBB = createBasicBlock("omp.metadirective.end"); + SmallVector<llvm::BasicBlock *, 4> VariantBBs(Variants.size()); + for (llvm::BasicBlock *&BB : VariantBBs) + BB = createBasicBlock("omp.metadirective.variant"); + while (!VMIs.empty()) { + int Best = llvm::omp::getBestVariantMatchForContext(VMIs, OMPCtx); + if (Best < 0) + break; + unsigned I = VariantIdx[Best]; + VMIs.erase(VMIs.begin() + Best); + VariantIdx.erase(VariantIdx.begin() + Best); + // Without a condition the variant always applies; later ones never run. + const Expr *Cond = Conditions[I]; + if (!Cond) { + Fallback = I; + break; + } + llvm::BasicBlock *ElseBB = createBasicBlock("omp.metadirective.else"); + EmitBranchOnBoolExpr(Cond, VariantBBs[I], ElseBB, /*TrueCount=*/0); + EmitBlock(ElseBB); + } + EmitBranch(Fallback ? VariantBBs[*Fallback] : EndBB); + + // Emit every variant in source order, as the device compilation does, so + // their target regions get the same names on both sides. + for (auto [V, BB] : llvm::zip_equal(Variants, VariantBBs)) { + EmitBlock(BB); + EmitStmt(V); + EmitBranch(EndBB); + } + EmitBlock(EndBB, /*IsFinished=*/true); } namespace { diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index f6fab0b00b0b5..3ca165bcd9536 100644 --- a/clang/lib/Parse/ParseOpenMP.cpp +++ b/clang/lib/Parse/ParseOpenMP.cpp @@ -2621,6 +2621,7 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective( ConsumeToken(); SmallVector<VariantMatchInfo, 4> VMIs; SmallVector<OMPTraitInfo *, 4> TraitInfos; + bool AnyVariantTakesStmt = false; // First iteration of parsing all clauses of metadirective. // This iteration only parses and collects all context selectors ignoring @@ -2677,6 +2678,14 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective( } } + // Note if a variant uses the statement after the pragma. + if (Tok.isNot(tok::r_paren)) { + OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this); + if (DKind != OMPD_unknown && + getDirectiveAssociation(DKind) != Association::None) + AnyVariantTakesStmt = true; + } + // Skip Directive for now. We will parse directive in the second iteration int paren = 0; while (Tok.isNot(tok::r_paren) || paren != 0) { @@ -2715,7 +2724,7 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective( }; TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait), /* CurrentFunctionDecl */ nullptr, - ArrayRef<llvm::omp::TraitProperty>(), + Actions.OpenMP().getConstructTraits(), Actions.OpenMP().getOpenMPDeviceNum()); // A single match is returned for OpenMP 5.0 @@ -2745,9 +2754,11 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective( // data-sharing context. Diagnostics in the associated statement are // reported once per variant. SmallVector<Stmt *, 4> Variants; + SmallVector<bool, 4> DirectiveThenStmt; bool HasError = false; for (unsigned I : llvm::seq<unsigned>(NumVariants)) { bool HasDirective = false; + bool IsDirectiveThenStmt = false; if (I < NumClauses) { OpenMPClauseKind CKind = getOpenMPClauseKind(PP.getSpelling(Tok)); ConsumeToken(); @@ -2776,33 +2787,44 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective( ConsumeAnyToken(); ConsumeAnnotationToken(); } - // No directive or 'nothing': the variant is the associated statement. - if (!Variant.isInvalid() && !Variant.isUsable()) { + // If any variant uses the statement, the others run a copy of it. + auto *D = dyn_cast_or_null<OMPExecutableDirective>(Variant.get()); + if (!Variant.isInvalid() && !(D && D->hasAssociatedStmt()) && + AnyVariantTakesStmt) { ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false); - Variant = ParseStatement(); - } - // A standalone variant does not take the associated statement while - // the others do; reject the mix until Sema models it. - if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(Variant.get()); - D && !D->hasAssociatedStmt()) { - Diag(Loc, diag::err_omp_metadirective_standalone_variant); - Variant = StmtError(); + StmtResult Body = ParseStatement(); + if (Body.isInvalid()) { + Variant = StmtError(); + } else if (Variant.isUsable()) { + Variant = CompoundStmt::Create( + Actions.getASTContext(), {Variant.get(), Body.get()}, + FPOptionsOverride(), Variant.get()->getBeginLoc(), + Body.get()->getEndLoc()); + IsDirectiveThenStmt = true; + } else { + Variant = Body; + } } + // Nothing to run for this variant. + if (!Variant.isInvalid() && !Variant.isUsable()) + Variant = Actions.ActOnNullStmt(Loc); if (VariantTPA) { VariantTPA->Revert(); SkipUntil(tok::r_paren, StopBeforeMatch); T.consumeClose(); } - if (Variant.isInvalid()) + if (Variant.isInvalid()) { HasError = true; - else + } else { Variants.push_back(Variant.get()); + DirectiveThenStmt.push_back(IsDirectiveThenStmt); + } } if (HasError) return StmtError(); - return Actions.OpenMP().ActOnOpenMPMetaDirective(Loc, EndLoc, TraitInfos, - Variants); + return Actions.OpenMP().ActOnOpenMPMetaDirective( + Loc, EndLoc, TraitInfos, Variants, DirectiveThenStmt); } int Idx = 0; diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp index 607ca7a554462..d29637de012b8 100644 --- a/clang/lib/Sema/SemaOpenMP.cpp +++ b/clang/lib/Sema/SemaOpenMP.cpp @@ -3854,7 +3854,8 @@ StmtResult SemaOpenMP::ActOnOpenMPAssumeDirective(ArrayRef<OMPClause *> Clauses, StmtResult SemaOpenMP::ActOnOpenMPMetaDirective( SourceLocation StartLoc, SourceLocation EndLoc, - ArrayRef<OMPTraitInfo *> TraitInfos, ArrayRef<Stmt *> Variants) { + ArrayRef<OMPTraitInfo *> TraitInfos, ArrayRef<Stmt *> Variants, + ArrayRef<bool> DirectiveThenStmt) { // Without an 'otherwise' clause, the last variant is the implicit one. bool HasImplicitOtherwise = Variants.size() == TraitInfos.size() + 1; assert((HasImplicitOtherwise || Variants.size() == TraitInfos.size()) && @@ -3879,9 +3880,9 @@ StmtResult SemaOpenMP::ActOnOpenMPMetaDirective( } Conditions.push_back(Cond); } - return OMPMetaDirective::Create(getASTContext(), StartLoc, EndLoc, Variants, - Conditions, AllTraitInfos, - HasImplicitOtherwise); + return OMPMetaDirective::Create( + getASTContext(), StartLoc, EndLoc, Variants, Conditions, AllTraitInfos, + HasImplicitOtherwise, getConstructTraits(), DirectiveThenStmt); } OMPRequiresDecl * @@ -19195,6 +19196,10 @@ void SemaOpenMP::setOpenMPDeviceNumID(StringRef ID) { DeviceNumID = ID; } int SemaOpenMP::getOpenMPDeviceNum() const { return DeviceNum; } +ArrayRef<llvm::omp::TraitProperty> SemaOpenMP::getConstructTraits() { + return DSAStack->getConstructTraits(); +} + void SemaOpenMP::ActOnOpenMPDeviceNum(Expr *DeviceNumExpr) { llvm::APSInt Result; Expr::EvalResult EvalResult; diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 8dc79a88d1988..d82b11bdf43f3 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -1711,9 +1711,10 @@ class TreeTransform { StmtResult RebuildOMPMetaDirective(SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPTraitInfo *> TraitInfos, - ArrayRef<Stmt *> Variants) { - return getSema().OpenMP().ActOnOpenMPMetaDirective(StartLoc, EndLoc, - TraitInfos, Variants); + ArrayRef<Stmt *> Variants, + ArrayRef<bool> DirectiveThenStmt) { + return getSema().OpenMP().ActOnOpenMPMetaDirective( + StartLoc, EndLoc, TraitInfos, Variants, DirectiveThenStmt); } /// Build a new OpenMP informational directive. @@ -10121,7 +10122,8 @@ TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) { } return getDerived().RebuildOMPMetaDirective(D->getBeginLoc(), D->getEndLoc(), - TraitInfos, Variants); + TraitInfos, Variants, + D->directiveThenStmt()); } template <typename Derived> diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp index b09471c13a48e..12752c988f837 100644 --- a/clang/lib/Serialization/ASTReaderStmt.cpp +++ b/clang/lib/Serialization/ASTReaderStmt.cpp @@ -2547,6 +2547,14 @@ void ASTStmtReader::VisitOMPMetaDirective(OMPMetaDirective *D) { D->setHasImplicitOtherwise(Record.readBool()); for (OMPTraitInfo *&TI : D->getTrailingTraitInfos()) TI = Record.readOMPTraitInfo(); + SmallVector<llvm::omp::TraitProperty, 4> ConstructTraits(Record.readInt()); + for (llvm::omp::TraitProperty &Trait : ConstructTraits) + Trait = llvm::omp::TraitProperty(Record.readInt()); + D->setConstructTraits(Record.getContext(), ConstructTraits); + SmallVector<bool, 4> DirectiveThenStmt(D->getNumVariants()); + for (bool &Flag : DirectiveThenStmt) + Flag = Record.readBool(); + D->setDirectiveThenStmt(Record.getContext(), DirectiveThenStmt); } void ASTStmtReader::VisitOMPParallelDirective(OMPParallelDirective *D) { diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp index f91f318426290..c417d855d00e1 100644 --- a/clang/lib/Serialization/ASTWriterStmt.cpp +++ b/clang/lib/Serialization/ASTWriterStmt.cpp @@ -2618,6 +2618,11 @@ void ASTStmtWriter::VisitOMPMetaDirective(OMPMetaDirective *D) { Record.writeBool(D->hasImplicitOtherwise()); for (const OMPTraitInfo *TI : D->traitInfos()) Record.writeOMPTraitInfo(TI); + Record.push_back(D->constructTraits().size()); + for (llvm::omp::TraitProperty Trait : D->constructTraits()) + Record.push_back(unsigned(Trait)); + for (bool Flag : D->directiveThenStmt()) + Record.writeBool(Flag); Code = serialization::STMT_OMP_META_DIRECTIVE; } diff --git a/clang/test/OpenMP/metadirective_construct_codegen.cpp b/clang/test/OpenMP/m... [truncated] `````````` </details> https://github.com/llvm/llvm-project/pull/239292 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
