https://github.com/zahiraam updated https://github.com/llvm/llvm-project/pull/239292
>From 20affab97a5f6b7e758675b11ec1f4f045911989 Mon Sep 17 00:00:00 2001 From: Zahira Ammarguellat <[email protected]> Date: Thu, 5 Nov 2026 09:00:04 -0800 Subject: [PATCH 1/7] [OpenMP] Emit the metadirective runtime selection --- clang/lib/CodeGen/CGStmtOpenMP.cpp | 54 ++++++- .../OpenMP/metadirective_runtime_codegen.cpp | 138 ++++++++++++++++++ 2 files changed, 190 insertions(+), 2 deletions(-) create mode 100644 clang/test/OpenMP/metadirective_runtime_codegen.cpp diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp index b00894c85fd676..e2ecdf7d6f45ba 100644 --- a/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -2398,8 +2398,58 @@ 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, + /*ConstructTraits=*/{}, /*DeviceNum=*/-1); + ArrayRef<Stmt *> Variants = S.variants(); + ArrayRef<Expr *> Conditions = S.conditions(); + SmallVector<llvm::omp::VariantMatchInfo, 4> VMIs; + SmallVector<unsigned, 4> VariantIdx; + const Stmt *Fallback = nullptr; + for (auto [I, TI] : llvm::enumerate(S.traitInfos())) { + if (TI->Sets.empty()) { + Fallback = Variants[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"); + 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 are unused. + const Expr *Cond = Conditions[I]; + if (!Cond) { + Fallback = Variants[I]; + break; + } + llvm::BasicBlock *WhenBB = createBasicBlock("omp.metadirective.when"); + llvm::BasicBlock *ElseBB = createBasicBlock("omp.metadirective.else"); + EmitBranchOnBoolExpr(Cond, WhenBB, ElseBB, /*TrueCount=*/0); + EmitBlock(WhenBB); + EmitStmt(Variants[I]); + EmitBranch(EndBB); + EmitBlock(ElseBB); + } + if (Fallback) + EmitStmt(Fallback); + EmitBlock(EndBB, /*IsFinished=*/true); } namespace { diff --git a/clang/test/OpenMP/metadirective_runtime_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_codegen.cpp new file mode 100644 index 00000000000000..26de70ff9cd27d --- /dev/null +++ b/clang/test/OpenMP/metadirective_runtime_codegen.cpp @@ -0,0 +1,138 @@ +// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 \ +// RUN: -fopenmp-metadirective-runtime-selection -x c++ \ +// RUN: -triple x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s +// expected-no-diagnostics + +void bar(); + +// The condition selects the 'when' variant; otherwise the 'otherwise' variant +// runs. +// CHECK-LABEL: define {{.*}}void @_Z14when_otherwisei( +// CHECK: [[FLAG:%.*]] = load i32, ptr %flag.addr +// CHECK-NEXT: [[COND:%.*]] = icmp ne i32 [[FLAG]], 0 +// CHECK-NEXT: br i1 [[COND]], label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK: call {{.*}}@__kmpc_fork_call( +// CHECK: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK: [[ELSE]]: +// CHECK: call i32 @__kmpc_single( +// CHECK: br label %[[END]] +// CHECK: [[END]]: +// CHECK-NEXT: ret void +void when_otherwise(int flag) { +#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single) + bar(); +} + +// 'when' clauses are tried in order; the first true condition wins. +// CHECK-LABEL: define {{.*}}void @_Z9two_whensii( +// CHECK: [[A:%.*]] = load i32, ptr %a.addr +// CHECK-NEXT: [[CONDA:%.*]] = icmp ne i32 [[A]], 0 +// CHECK-NEXT: br i1 [[CONDA]], label %[[WHEN0:omp.metadirective.when[0-9]*]], label %[[ELSE0:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN0]]: +// CHECK: call {{.*}}@__kmpc_fork_call( +// CHECK: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK: [[ELSE0]]: +// CHECK: [[B:%.*]] = load i32, ptr %b.addr +// CHECK-NEXT: [[CONDB:%.*]] = icmp ne i32 [[B]], 0 +// CHECK-NEXT: br i1 [[CONDB]], label %[[WHEN1:omp.metadirective.when[0-9]*]], label %[[ELSE1:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN1]]: +// CHECK: call i32 @__kmpc_single( +// CHECK: br label %[[END]] +// CHECK: [[ELSE1]]: +// CHECK-NEXT: call void @_Z3barv() +// CHECK-NEXT: br label %[[END]] +// CHECK: [[END]]: +// CHECK-NEXT: ret void +void two_whens(int a, int b) { +#pragma omp metadirective when(user={condition(a)}: parallel) \ + when(user={condition(b)}: single) otherwise() + bar(); +} + +// Without 'otherwise', the associated statement runs when no condition holds. +// CHECK-LABEL: define {{.*}}void @_Z12no_otherwisei( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK: call {{.*}}@__kmpc_fork_call( +// CHECK: [[ELSE]]: +// CHECK-NEXT: call void @_Z3barv() +// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK: [[END]]: +// CHECK-NEXT: ret void +void no_otherwise(int flag) { +#pragma omp metadirective when(user={condition(flag)}: parallel) + bar(); +} + +// vendor(llvm) always matches, so 'parallel' is always selected. +// CHECK-LABEL: define {{.*}}void @_Z18static_match_firsti( +// CHECK-NOT: icmp +// CHECK: call {{.*}}@__kmpc_fork_call( +// CHECK-NOT: __kmpc_single +// CHECK: ret void +void static_match_first(int flag) { +#pragma omp metadirective when(implementation={vendor(llvm)}: parallel) \ + when(user={condition(flag)}: single) otherwise() + bar(); +} + +// vendor(amd) never matches, so its variant is not emitted. +// CHECK-LABEL: define {{.*}}void @_Z14static_nomatchi( +// CHECK-NOT: __kmpc_fork_call +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK: call i32 @__kmpc_single( +// CHECK: [[ELSE]]: +// CHECK-NEXT: call void @_Z3barv() +// CHECK-NOT: __kmpc_fork_call +// CHECK: ret void +void static_nomatch(int flag) { +#pragma omp metadirective when(implementation={vendor(amd)}: parallel) \ + when(user={condition(flag)}: single) otherwise() + bar(); +} + +// vendor(llvm) runs when the condition fails; plain bar() is never called. +// CHECK-LABEL: define {{.*}}void @_Z17static_match_lasti( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK: call i32 @__kmpc_single( +// CHECK: [[ELSE]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call( +// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK: [[END]]: +// CHECK-NEXT: ret void +void static_match_last(int flag) { +#pragma omp metadirective when(user={condition(flag)}: single) \ + when(implementation={vendor(llvm)}: parallel) + bar(); +} + +// kind(host) scores higher than the condition, so 'parallel' always wins. +// CHECK-LABEL: define {{.*}}void @_Z18device_kind_secondi( +// CHECK-NOT: icmp +// CHECK: call {{.*}}@__kmpc_fork_call( +// CHECK-NOT: __kmpc_single +// CHECK: ret void +void device_kind_second(int flag) { +#pragma omp metadirective when(user={condition(flag)}: single) \ + when(device={kind(host)}: parallel) + bar(); +} + +// score(5) makes the second variant the first one tried. +// CHECK-LABEL: define {{.*}}void @_Z14score_reordersi( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK: call i32 @__kmpc_single( +// CHECK: [[ELSE]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call( +// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK: [[END]]: +// CHECK-NEXT: ret void +void score_reorders(int flag) { +#pragma omp metadirective when(implementation={vendor(llvm)}: parallel) \ + when(user={condition(flag)}, implementation={vendor(score(5): llvm)}: single) + bar(); +} >From f05ebf1db3a06e2836d3589ce3909f4c192a1b78 Mon Sep 17 00:00:00 2001 From: Zahira Ammarguellat <[email protected]> Date: Thu, 5 Nov 2026 09:54:02 -0800 Subject: [PATCH 2/7] match construct selectors --- clang/include/clang/AST/StmtOpenMP.h | 11 ++- clang/include/clang/Sema/SemaOpenMP.h | 3 + clang/lib/AST/StmtOpenMP.cpp | 11 ++- clang/lib/CodeGen/CGStmtOpenMP.cpp | 3 +- clang/lib/Parse/ParseOpenMP.cpp | 2 +- clang/lib/Sema/SemaOpenMP.cpp | 6 +- clang/lib/Serialization/ASTReaderStmt.cpp | 4 + clang/lib/Serialization/ASTWriterStmt.cpp | 3 + .../metadirective_construct_codegen.cpp | 29 +++++++ .../OpenMP/metadirective_runtime_codegen.cpp | 80 +++++++++++++++++++ 10 files changed, 146 insertions(+), 6 deletions(-) create mode 100644 clang/test/OpenMP/metadirective_construct_codegen.cpp diff --git a/clang/include/clang/AST/StmtOpenMP.h b/clang/include/clang/AST/StmtOpenMP.h index a990de6d04f746..b7b2b2498a0610 100644 --- a/clang/include/clang/AST/StmtOpenMP.h +++ b/clang/include/clang/AST/StmtOpenMP.h @@ -6627,6 +6627,9 @@ 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; + OMPMetaDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(OMPMetaDirectiveClass, llvm::omp::OMPD_metadirective, StartLoc, @@ -6669,12 +6672,15 @@ class OMPMetaDirective final : public OMPExecutableDirective { } void setHasImplicitOtherwise(bool V) { HasImplicitOtherwise = V; } + void setConstructTraits(const ASTContext &C, + ArrayRef<llvm::omp::TraitProperty> Traits); 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); static OMPMetaDirective *CreateEmpty(const ASTContext &C, unsigned NumVariants, EmptyShell); @@ -6685,6 +6691,9 @@ class OMPMetaDirective final : public OMPExecutableDirective { ArrayRef<OMPTraitInfo *> traitInfos() const { return getTrailingTraitInfos(); } + ArrayRef<llvm::omp::TraitProperty> constructTraits() const { + return ConstructTraits; + } child_range children() { MutableArrayRef<Stmt *> Children = Data->getChildren(); diff --git a/clang/include/clang/Sema/SemaOpenMP.h b/clang/include/clang/Sema/SemaOpenMP.h index 6750f6a9ce4c23..b5c5c3f9a4acdc 100644 --- a/clang/include/clang/Sema/SemaOpenMP.h +++ b/clang/include/clang/Sema/SemaOpenMP.h @@ -1525,6 +1525,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 3812b4a060240f..6e7ccf53605187 100644 --- a/clang/lib/AST/StmtOpenMP.cpp +++ b/clang/lib/AST/StmtOpenMP.cpp @@ -350,7 +350,8 @@ 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) { assert(Variants.size() == Conditions.size() && Variants.size() == TraitInfos.size() && "Expected one condition and one trait info per variant"); @@ -359,9 +360,17 @@ OMPMetaDirective *OMPMetaDirective::Create( llvm::copy(Conditions, Dir->getTrailingConditions().begin()); llvm::copy(TraitInfos, Dir->getTrailingTraitInfos().begin()); Dir->setHasImplicitOtherwise(HasImplicitOtherwise); + Dir->setConstructTraits(C, ConstructTraits); return Dir; } +void OMPMetaDirective::setConstructTraits( + const ASTContext &C, ArrayRef<llvm::omp::TraitProperty> Traits) { + auto *Mem = C.Allocate<llvm::omp::TraitProperty>(Traits.size()); + llvm::copy(Traits, Mem); + ConstructTraits = {Mem, Traits.size()}; +} + OMPMetaDirective *OMPMetaDirective::CreateEmpty(const ASTContext &C, unsigned NumVariants, EmptyShell) { diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp index e2ecdf7d6f45ba..bcfddd7fec95eb 100644 --- a/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -2401,8 +2401,7 @@ void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) { // Try variants from best to worst match; 'otherwise' runs if none applies. TargetOMPContext OMPCtx( getContext(), /*DiagUnknownTrait=*/[](StringRef) {}, - /*CurrentFunctionDecl=*/nullptr, - /*ConstructTraits=*/{}, /*DeviceNum=*/-1); + /*CurrentFunctionDecl=*/nullptr, S.constructTraits(), /*DeviceNum=*/-1); ArrayRef<Stmt *> Variants = S.variants(); ArrayRef<Expr *> Conditions = S.conditions(); SmallVector<llvm::omp::VariantMatchInfo, 4> VMIs; diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index f6fab0b00b0b59..00b3b39ff42e65 100644 --- a/clang/lib/Parse/ParseOpenMP.cpp +++ b/clang/lib/Parse/ParseOpenMP.cpp @@ -2715,7 +2715,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 diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp index 607ca7a554462d..c37926f9f59e75 100644 --- a/clang/lib/Sema/SemaOpenMP.cpp +++ b/clang/lib/Sema/SemaOpenMP.cpp @@ -3881,7 +3881,7 @@ StmtResult SemaOpenMP::ActOnOpenMPMetaDirective( } return OMPMetaDirective::Create(getASTContext(), StartLoc, EndLoc, Variants, Conditions, AllTraitInfos, - HasImplicitOtherwise); + HasImplicitOtherwise, getConstructTraits()); } OMPRequiresDecl * @@ -19195,6 +19195,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/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp index b09471c13a48e2..6cd9b5c8f91c03 100644 --- a/clang/lib/Serialization/ASTReaderStmt.cpp +++ b/clang/lib/Serialization/ASTReaderStmt.cpp @@ -2547,6 +2547,10 @@ 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); } void ASTStmtReader::VisitOMPParallelDirective(OMPParallelDirective *D) { diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp index f91f318426290c..1ab9c55d909564 100644 --- a/clang/lib/Serialization/ASTWriterStmt.cpp +++ b/clang/lib/Serialization/ASTWriterStmt.cpp @@ -2618,6 +2618,9 @@ 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)); Code = serialization::STMT_OMP_META_DIRECTIVE; } diff --git a/clang/test/OpenMP/metadirective_construct_codegen.cpp b/clang/test/OpenMP/metadirective_construct_codegen.cpp new file mode 100644 index 00000000000000..7707780b010784 --- /dev/null +++ b/clang/test/OpenMP/metadirective_construct_codegen.cpp @@ -0,0 +1,29 @@ +// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=52 -x c++ \ +// RUN: -triple x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s +// expected-no-diagnostics + +void bar(); + +// construct={parallel} matches inside the parallel region. +// CHECK-LABEL: define internal void @_Z17compile_time_pathv.omp_outlined( +// CHECK-NOT: __kmpc_masked +// CHECK: call i32 @__kmpc_single( +// CHECK-NOT: __kmpc_masked +// CHECK: ret void +void compile_time_path() { +#pragma omp parallel + { +#pragma omp metadirective when(construct={parallel}: single) otherwise(masked) + bar(); + } +} + +// Outside a parallel region, construct={parallel} does not match. +// CHECK-LABEL: define {{.*}}void @_Z9no_regionv( +// CHECK-NOT: __kmpc_single +// CHECK: call i32 @__kmpc_masked( +// CHECK: ret void +void no_region() { +#pragma omp metadirective when(construct={parallel}: single) otherwise(masked) + bar(); +} diff --git a/clang/test/OpenMP/metadirective_runtime_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_codegen.cpp index 26de70ff9cd27d..f7ab66ed8d27ad 100644 --- a/clang/test/OpenMP/metadirective_runtime_codegen.cpp +++ b/clang/test/OpenMP/metadirective_runtime_codegen.cpp @@ -136,3 +136,83 @@ void score_reorders(int flag) { when(user={condition(flag)}, implementation={vendor(score(5): llvm)}: single) bar(); } + +void baz(int); + +// Loop variants: each one runs its own loop. +// CHECK-LABEL: define {{.*}}void @_Z13loop_variantsii( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call({{.*}}@_Z13loop_variantsii.omp_outlined +// CHECK: [[ELSE]]: +// CHECK: call void @__kmpc_for_static_init_4( +// CHECK: call void @_Z3bazi( +// CHECK: call void @__kmpc_for_static_fini( +// CHECK: call void @__kmpc_barrier( +// CHECK: define internal void @_Z13loop_variantsii.omp_outlined( +// CHECK: call void @__kmpc_for_static_init_4( +// CHECK: call void @_Z3bazi( +// CHECK: call void @__kmpc_for_static_fini( +void loop_variants(int flag, int n) { +#pragma omp metadirective when(user={condition(flag)}: parallel for) otherwise(for) + for (int i = 0; i < n; ++i) + baz(i); +} + +// A metadirective inside a variant of another one. The empty 'otherwise()' +// runs the block, so the inner metadirective runs on both paths. +// CHECK-LABEL: define {{.*}}void @_Z6nestedii( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call({{.*}}@_Z6nestedii.omp_outlined, ptr %b.addr) +// CHECK: [[ELSE]]: +// CHECK-NEXT: {{%.*}} = load i32, ptr %b.addr +// CHECK-NEXT: {{%.*}} = icmp ne i32 +// CHECK-NEXT: br i1 {{.*}}, label %[[IWHEN:omp.metadirective.when[0-9]*]], label %[[IELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[IWHEN]]: +// CHECK-NEXT: call i32 @__kmpc_single( +// CHECK: [[IELSE]]: +// CHECK-NEXT: call i32 @__kmpc_masked( +// CHECK: define internal void @_Z6nestedii.omp_outlined( +// CHECK: br i1 {{.*}}, label %[[OWHEN:omp.metadirective.when[0-9]*]], label %[[OELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[OWHEN]]: +// CHECK: call i32 @__kmpc_single( +// CHECK: [[OELSE]]: +// CHECK: call i32 @__kmpc_masked( +void nested(int a, int b) { +#pragma omp metadirective when(user={condition(a)}: parallel) otherwise() + { +#pragma omp metadirective when(user={condition(b)}: single) otherwise(masked) + bar(); + } +} + +// construct={parallel} matches inside the parallel region and scores higher, +// so 'single' is always selected. +// CHECK-LABEL: define internal void @_Z12runtime_pathi.omp_outlined( +// CHECK-NOT: __kmpc_masked +// CHECK: call i32 @__kmpc_single( +// CHECK-NOT: __kmpc_masked +// CHECK: ret void +void runtime_path(int flag) { +#pragma omp parallel + { +#pragma omp metadirective when(construct={parallel}: single) \ + when(user={condition(flag)}: masked) + bar(); + } +} + +// Instantiated template. Kept last: the instantiation may be emitted at the +// end of the file. +// CHECK-LABEL: define {{.*}}void @_Z4tmplIiEvT_( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call({{.*}}@_Z4tmplIiEvT_.omp_outlined +// CHECK: [[ELSE]]: +// CHECK-NEXT: call i32 @__kmpc_single( +template <typename T> void tmpl(T flag) { +#pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single) + bar(); +} +void inst() { tmpl(1); } >From dca28af84b8608685d8783efc26b2822d8019fd6 Mon Sep 17 00:00:00 2001 From: Zahira Ammarguellat <[email protected]> Date: Thu, 5 Nov 2026 12:53:59 -0800 Subject: [PATCH 3/7] Added standalone variant support --- clang/include/clang/AST/StmtOpenMP.h | 9 +++- .../clang/Basic/DiagnosticParseKinds.td | 3 -- clang/include/clang/Sema/SemaOpenMP.h | 5 +- clang/lib/AST/StmtOpenMP.cpp | 16 ++++-- clang/lib/AST/StmtPrinter.cpp | 20 +++++--- clang/lib/Parse/ParseOpenMP.cpp | 50 +++++++++++++------ clang/lib/Sema/SemaOpenMP.cpp | 9 ++-- clang/lib/Sema/TreeTransform.h | 10 ++-- clang/lib/Serialization/ASTReaderStmt.cpp | 4 ++ clang/lib/Serialization/ASTWriterStmt.cpp | 2 + .../metadirective_runtime_ast_print.cpp | 20 ++++++++ .../OpenMP/metadirective_runtime_codegen.cpp | 39 +++++++++++++++ .../OpenMP/metadirective_runtime_messages.cpp | 10 ---- 13 files changed, 149 insertions(+), 48 deletions(-) diff --git a/clang/include/clang/AST/StmtOpenMP.h b/clang/include/clang/AST/StmtOpenMP.h index b7b2b2498a0610..46e35d4b484709 100644 --- a/clang/include/clang/AST/StmtOpenMP.h +++ b/clang/include/clang/AST/StmtOpenMP.h @@ -6630,6 +6630,10 @@ class OMPMetaDirective final : public OMPExecutableDirective { /// 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, @@ -6674,13 +6678,15 @@ 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<llvm::omp::TraitProperty> ConstructTraits); + ArrayRef<llvm::omp::TraitProperty> ConstructTraits, + ArrayRef<bool> DirectiveThenStmt); static OMPMetaDirective *CreateEmpty(const ASTContext &C, unsigned NumVariants, EmptyShell); @@ -6694,6 +6700,7 @@ class OMPMetaDirective final : public OMPExecutableDirective { 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 2be6ff8344cd6d..82aec8b4eb714f 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 b5c5c3f9a4acdc..174a7caafa6e41 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 diff --git a/clang/lib/AST/StmtOpenMP.cpp b/clang/lib/AST/StmtOpenMP.cpp index 6e7ccf53605187..71c992b717b256 100644 --- a/clang/lib/AST/StmtOpenMP.cpp +++ b/clang/lib/AST/StmtOpenMP.cpp @@ -351,24 +351,30 @@ OMPMetaDirective *OMPMetaDirective::Create( const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<Stmt *> Variants, ArrayRef<Expr *> Conditions, ArrayRef<OMPTraitInfo *> TraitInfos, bool HasImplicitOtherwise, - ArrayRef<llvm::omp::TraitProperty> ConstructTraits) { + 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) { - auto *Mem = C.Allocate<llvm::omp::TraitProperty>(Traits.size()); - llvm::copy(Traits, Mem); - ConstructTraits = {Mem, Traits.size()}; + ConstructTraits = Traits.copy(C); } OMPMetaDirective *OMPMetaDirective::CreateEmpty(const ASTContext &C, diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp index bed934a70ab519..030985f62280f5 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/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index 00b3b39ff42e65..3ca165bcd9536b 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) { @@ -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 c37926f9f59e75..d29637de012b8d 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, getConstructTraits()); + return OMPMetaDirective::Create( + getASTContext(), StartLoc, EndLoc, Variants, Conditions, AllTraitInfos, + HasImplicitOtherwise, getConstructTraits(), DirectiveThenStmt); } OMPRequiresDecl * diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 8dc79a88d19889..d82b11bdf43f34 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 6cd9b5c8f91c03..12752c988f8374 100644 --- a/clang/lib/Serialization/ASTReaderStmt.cpp +++ b/clang/lib/Serialization/ASTReaderStmt.cpp @@ -2551,6 +2551,10 @@ void ASTStmtReader::VisitOMPMetaDirective(OMPMetaDirective *D) { 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 1ab9c55d909564..c417d855d00e17 100644 --- a/clang/lib/Serialization/ASTWriterStmt.cpp +++ b/clang/lib/Serialization/ASTWriterStmt.cpp @@ -2621,6 +2621,8 @@ void ASTStmtWriter::VisitOMPMetaDirective(OMPMetaDirective *D) { 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_runtime_ast_print.cpp b/clang/test/OpenMP/metadirective_runtime_ast_print.cpp index 9980b2df9defd4..013add05fa52a5 100644 --- a/clang/test/OpenMP/metadirective_runtime_ast_print.cpp +++ b/clang/test/OpenMP/metadirective_runtime_ast_print.cpp @@ -49,4 +49,24 @@ void loop(int flag, int n) { ; } +// A standalone variant is printed in its clause; the statement once. +// CHECK-LABEL: void standalone(int flag, int n) { +// CHECK-NEXT: #pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(single) +// CHECK-NEXT: n = 1; +// CHECK-NEXT: } +void standalone(int flag, int n) { +#pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(single) + n = 1; +} + +// All variants are standalone: the statement follows the metadirective. +// CHECK-LABEL: void all_standalone(int flag, int n) { +// CHECK-NEXT: #pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(taskyield) +// CHECK-NEXT: n = 1; +// CHECK-NEXT: } +void all_standalone(int flag, int n) { +#pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(taskyield) + n = 1; +} + #endif diff --git a/clang/test/OpenMP/metadirective_runtime_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_codegen.cpp index f7ab66ed8d27ad..6e1ccfc7dd7cd4 100644 --- a/clang/test/OpenMP/metadirective_runtime_codegen.cpp +++ b/clang/test/OpenMP/metadirective_runtime_codegen.cpp @@ -203,6 +203,45 @@ void runtime_path(int flag) { } } +// A standalone variant runs its directive and then the statement. +// CHECK-LABEL: define internal void @_Z5mixedi.omp_outlined( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK: call void @__kmpc_barrier( +// CHECK-NEXT: call void @_Z3barv() +// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK: [[ELSE]]: +// CHECK: call i32 @__kmpc_single( +// CHECK: [[END]]: +// CHECK-NEXT: ret void +void mixed(int flag) { +#pragma omp parallel + { +#pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(single) + bar(); + } +} + +// All variants are standalone: the statement runs once, after the selection. +// CHECK-LABEL: define internal void @_Z14all_standalonei.omp_outlined( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK: call void @__kmpc_barrier( +// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK: [[ELSE]]: +// CHECK: call i32 @__kmpc_omp_taskyield( +// CHECK-NEXT: br label %[[END]] +// CHECK: [[END]]: +// CHECK-NEXT: call void @_Z3barv() +// CHECK-NEXT: ret void +void all_standalone(int flag) { +#pragma omp parallel + { +#pragma omp metadirective when(user={condition(flag)}: barrier) otherwise(taskyield) + bar(); + } +} + // Instantiated template. Kept last: the instantiation may be emitted at the // end of the file. // CHECK-LABEL: define {{.*}}void @_Z4tmplIiEvT_( diff --git a/clang/test/OpenMP/metadirective_runtime_messages.cpp b/clang/test/OpenMP/metadirective_runtime_messages.cpp index 7419fbe010e19a..f394d46eeddf68 100644 --- a/clang/test/OpenMP/metadirective_runtime_messages.cpp +++ b/clang/test/OpenMP/metadirective_runtime_messages.cpp @@ -60,13 +60,3 @@ void local_decl(int flag) { l.v = 1; } } - -// Standalone directive variants are rejected for now. -void standalone_variant(int flag) { - // expected-error@+1 {{standalone directive variants are not supported in a 'metadirective' with non-constant user conditions}} -#pragma omp metadirective \ - when(user={condition(flag)}: barrier) \ - otherwise(single) - { - } -} >From 82ec53329c72c314a8ed9da1d3c01a966a94142e Mon Sep 17 00:00:00 2001 From: Zahira Ammarguellat <[email protected]> Date: Thu, 5 Nov 2026 13:49:17 -0800 Subject: [PATCH 4/7] Emit variant for target --- clang/lib/CodeGen/CGStmtOpenMP.cpp | 28 ++-- .../OpenMP/metadirective_runtime_codegen.cpp | 147 +++++++++++------- ...irective_runtime_target_device_codegen.cpp | 35 +++++ 3 files changed, 139 insertions(+), 71 deletions(-) diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp index bcfddd7fec95eb..ac72a1429ffad1 100644 --- a/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -2406,10 +2406,10 @@ void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) { ArrayRef<Expr *> Conditions = S.conditions(); SmallVector<llvm::omp::VariantMatchInfo, 4> VMIs; SmallVector<unsigned, 4> VariantIdx; - const Stmt *Fallback = nullptr; + std::optional<unsigned> Fallback; for (auto [I, TI] : llvm::enumerate(S.traitInfos())) { if (TI->Sets.empty()) { - Fallback = Variants[I]; + Fallback = I; continue; } llvm::omp::VariantMatchInfo &VMI = VMIs.emplace_back(); @@ -2425,6 +2425,9 @@ void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) { } 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) @@ -2432,22 +2435,25 @@ void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) { unsigned I = VariantIdx[Best]; VMIs.erase(VMIs.begin() + Best); VariantIdx.erase(VariantIdx.begin() + Best); - // Without a condition the variant always applies; later ones are unused. + // Without a condition the variant always applies; later ones never run. const Expr *Cond = Conditions[I]; if (!Cond) { - Fallback = Variants[I]; + Fallback = I; break; } - llvm::BasicBlock *WhenBB = createBasicBlock("omp.metadirective.when"); llvm::BasicBlock *ElseBB = createBasicBlock("omp.metadirective.else"); - EmitBranchOnBoolExpr(Cond, WhenBB, ElseBB, /*TrueCount=*/0); - EmitBlock(WhenBB); - EmitStmt(Variants[I]); - EmitBranch(EndBB); + EmitBranchOnBoolExpr(Cond, VariantBBs[I], ElseBB, /*TrueCount=*/0); EmitBlock(ElseBB); } - if (Fallback) - EmitStmt(Fallback); + 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); } diff --git a/clang/test/OpenMP/metadirective_runtime_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_codegen.cpp index 6e1ccfc7dd7cd4..f26de940beac6a 100644 --- a/clang/test/OpenMP/metadirective_runtime_codegen.cpp +++ b/clang/test/OpenMP/metadirective_runtime_codegen.cpp @@ -10,12 +10,14 @@ void bar(); // CHECK-LABEL: define {{.*}}void @_Z14when_otherwisei( // CHECK: [[FLAG:%.*]] = load i32, ptr %flag.addr // CHECK-NEXT: [[COND:%.*]] = icmp ne i32 [[FLAG]], 0 -// CHECK-NEXT: br i1 [[COND]], label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] -// CHECK: [[WHEN]]: -// CHECK: call {{.*}}@__kmpc_fork_call( -// CHECK: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK-NEXT: br i1 [[COND]], label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] // CHECK: [[ELSE]]: -// CHECK: call i32 @__kmpc_single( +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call( +// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK: [[OTHER]]: +// CHECK-NEXT: call i32 @__kmpc_single( // CHECK: br label %[[END]] // CHECK: [[END]]: // CHECK-NEXT: ret void @@ -28,20 +30,20 @@ void when_otherwise(int flag) { // CHECK-LABEL: define {{.*}}void @_Z9two_whensii( // CHECK: [[A:%.*]] = load i32, ptr %a.addr // CHECK-NEXT: [[CONDA:%.*]] = icmp ne i32 [[A]], 0 -// CHECK-NEXT: br i1 [[CONDA]], label %[[WHEN0:omp.metadirective.when[0-9]*]], label %[[ELSE0:omp.metadirective.else[0-9]*]] -// CHECK: [[WHEN0]]: -// CHECK: call {{.*}}@__kmpc_fork_call( -// CHECK: br label %[[END:omp.metadirective.end[0-9]*]] +// CHECK-NEXT: br i1 [[CONDA]], label %[[V0:omp.metadirective.variant[0-9]*]], label %[[ELSE0:omp.metadirective.else[0-9]*]] // CHECK: [[ELSE0]]: -// CHECK: [[B:%.*]] = load i32, ptr %b.addr +// CHECK-NEXT: [[B:%.*]] = load i32, ptr %b.addr // CHECK-NEXT: [[CONDB:%.*]] = icmp ne i32 [[B]], 0 -// CHECK-NEXT: br i1 [[CONDB]], label %[[WHEN1:omp.metadirective.when[0-9]*]], label %[[ELSE1:omp.metadirective.else[0-9]*]] -// CHECK: [[WHEN1]]: -// CHECK: call i32 @__kmpc_single( -// CHECK: br label %[[END]] +// CHECK-NEXT: br i1 [[CONDB]], label %[[V1:omp.metadirective.variant[0-9]*]], label %[[ELSE1:omp.metadirective.else[0-9]*]] // CHECK: [[ELSE1]]: +// CHECK-NEXT: br label %[[V2:omp.metadirective.variant[0-9]*]] +// CHECK: [[V0]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call( +// CHECK: [[V1]]: +// CHECK-NEXT: call i32 @__kmpc_single( +// CHECK: [[V2]]: // CHECK-NEXT: call void @_Z3barv() -// CHECK-NEXT: br label %[[END]] +// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] // CHECK: [[END]]: // CHECK-NEXT: ret void void two_whens(int a, int b) { @@ -52,10 +54,12 @@ void two_whens(int a, int b) { // Without 'otherwise', the associated statement runs when no condition holds. // CHECK-LABEL: define {{.*}}void @_Z12no_otherwisei( -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] -// CHECK: [[WHEN]]: -// CHECK: call {{.*}}@__kmpc_fork_call( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] // CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call( +// CHECK: [[OTHER]]: // CHECK-NEXT: call void @_Z3barv() // CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] // CHECK: [[END]]: @@ -68,25 +72,30 @@ void no_otherwise(int flag) { // vendor(llvm) always matches, so 'parallel' is always selected. // CHECK-LABEL: define {{.*}}void @_Z18static_match_firsti( // CHECK-NOT: icmp -// CHECK: call {{.*}}@__kmpc_fork_call( -// CHECK-NOT: __kmpc_single -// CHECK: ret void +// CHECK: br label %[[SEL:omp.metadirective.variant[0-9]*]] +// CHECK: [[SEL]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call( +// CHECK: omp.metadirective.variant{{[0-9]+}}:{{.*}}No predecessors! +// CHECK-NEXT: call i32 @__kmpc_single( +// CHECK: omp.metadirective.variant{{[0-9]+}}:{{.*}}No predecessors! +// CHECK-NEXT: call void @_Z3barv() void static_match_first(int flag) { #pragma omp metadirective when(implementation={vendor(llvm)}: parallel) \ when(user={condition(flag)}: single) otherwise() bar(); } -// vendor(amd) never matches, so its variant is not emitted. +// vendor(amd) never matches, so its variant is never selected. // CHECK-LABEL: define {{.*}}void @_Z14static_nomatchi( -// CHECK-NOT: __kmpc_fork_call -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] -// CHECK: [[WHEN]]: -// CHECK: call i32 @__kmpc_single( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] // CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] +// CHECK: omp.metadirective.variant{{[0-9]*}}:{{.*}}No predecessors! +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call( +// CHECK: [[WHEN]]: +// CHECK-NEXT: call i32 @__kmpc_single( +// CHECK: [[OTHER]]: // CHECK-NEXT: call void @_Z3barv() -// CHECK-NOT: __kmpc_fork_call -// CHECK: ret void void static_nomatch(int flag) { #pragma omp metadirective when(implementation={vendor(amd)}: parallel) \ when(user={condition(flag)}: single) otherwise() @@ -95,14 +104,15 @@ void static_nomatch(int flag) { // vendor(llvm) runs when the condition fails; plain bar() is never called. // CHECK-LABEL: define {{.*}}void @_Z17static_match_lasti( -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] -// CHECK: [[WHEN]]: -// CHECK: call i32 @__kmpc_single( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] // CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] +// CHECK: [[WHEN]]: +// CHECK-NEXT: call i32 @__kmpc_single( +// CHECK: [[OTHER]]: // CHECK-NEXT: call {{.*}}@__kmpc_fork_call( -// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] -// CHECK: [[END]]: -// CHECK-NEXT: ret void +// CHECK: omp.metadirective.variant{{[0-9]+}}:{{.*}}No predecessors! +// CHECK-NEXT: call void @_Z3barv() void static_match_last(int flag) { #pragma omp metadirective when(user={condition(flag)}: single) \ when(implementation={vendor(llvm)}: parallel) @@ -112,9 +122,11 @@ void static_match_last(int flag) { // kind(host) scores higher than the condition, so 'parallel' always wins. // CHECK-LABEL: define {{.*}}void @_Z18device_kind_secondi( // CHECK-NOT: icmp -// CHECK: call {{.*}}@__kmpc_fork_call( -// CHECK-NOT: __kmpc_single -// CHECK: ret void +// CHECK: br label %[[SEL:omp.metadirective.variant[0-9]*]] +// CHECK: omp.metadirective.variant{{[0-9]*}}:{{.*}}No predecessors! +// CHECK-NEXT: call i32 @__kmpc_single( +// CHECK: [[SEL]]: +// CHECK-NEXT: call {{.*}}@__kmpc_fork_call( void device_kind_second(int flag) { #pragma omp metadirective when(user={condition(flag)}: single) \ when(device={kind(host)}: parallel) @@ -123,14 +135,13 @@ void device_kind_second(int flag) { // score(5) makes the second variant the first one tried. // CHECK-LABEL: define {{.*}}void @_Z14score_reordersi( -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] -// CHECK: [[WHEN]]: -// CHECK: call i32 @__kmpc_single( +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] // CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] +// CHECK: [[OTHER]]: // CHECK-NEXT: call {{.*}}@__kmpc_fork_call( -// CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] -// CHECK: [[END]]: -// CHECK-NEXT: ret void +// CHECK: [[WHEN]]: +// CHECK-NEXT: call i32 @__kmpc_single( void score_reorders(int flag) { #pragma omp metadirective when(implementation={vendor(llvm)}: parallel) \ when(user={condition(flag)}, implementation={vendor(score(5): llvm)}: single) @@ -141,10 +152,12 @@ void baz(int); // Loop variants: each one runs its own loop. // CHECK-LABEL: define {{.*}}void @_Z13loop_variantsii( -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] // CHECK: [[WHEN]]: // CHECK-NEXT: call {{.*}}@__kmpc_fork_call({{.*}}@_Z13loop_variantsii.omp_outlined -// CHECK: [[ELSE]]: +// CHECK: [[OTHER]]: // CHECK: call void @__kmpc_for_static_init_4( // CHECK: call void @_Z3bazi( // CHECK: call void @__kmpc_for_static_fini( @@ -162,22 +175,28 @@ void loop_variants(int flag, int n) { // A metadirective inside a variant of another one. The empty 'otherwise()' // runs the block, so the inner metadirective runs on both paths. // CHECK-LABEL: define {{.*}}void @_Z6nestedii( -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] // CHECK: [[WHEN]]: // CHECK-NEXT: call {{.*}}@__kmpc_fork_call({{.*}}@_Z6nestedii.omp_outlined, ptr %b.addr) -// CHECK: [[ELSE]]: +// CHECK: [[OTHER]]: // CHECK-NEXT: {{%.*}} = load i32, ptr %b.addr // CHECK-NEXT: {{%.*}} = icmp ne i32 -// CHECK-NEXT: br i1 {{.*}}, label %[[IWHEN:omp.metadirective.when[0-9]*]], label %[[IELSE:omp.metadirective.else[0-9]*]] +// CHECK-NEXT: br i1 {{.*}}, label %[[IWHEN:omp.metadirective.variant[0-9]*]], label %[[IELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[IELSE]]: +// CHECK-NEXT: br label %[[IOTHER:omp.metadirective.variant[0-9]*]] // CHECK: [[IWHEN]]: // CHECK-NEXT: call i32 @__kmpc_single( -// CHECK: [[IELSE]]: +// CHECK: [[IOTHER]]: // CHECK-NEXT: call i32 @__kmpc_masked( // CHECK: define internal void @_Z6nestedii.omp_outlined( -// CHECK: br i1 {{.*}}, label %[[OWHEN:omp.metadirective.when[0-9]*]], label %[[OELSE:omp.metadirective.else[0-9]*]] +// CHECK: br i1 {{.*}}, label %[[OWHEN:omp.metadirective.variant[0-9]*]], label %[[OELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[OELSE]]: +// CHECK-NEXT: br label %[[OOTHER:omp.metadirective.variant[0-9]*]] // CHECK: [[OWHEN]]: // CHECK: call i32 @__kmpc_single( -// CHECK: [[OELSE]]: +// CHECK: [[OOTHER]]: // CHECK: call i32 @__kmpc_masked( void nested(int a, int b) { #pragma omp metadirective when(user={condition(a)}: parallel) otherwise() @@ -190,10 +209,12 @@ void nested(int a, int b) { // construct={parallel} matches inside the parallel region and scores higher, // so 'single' is always selected. // CHECK-LABEL: define internal void @_Z12runtime_pathi.omp_outlined( -// CHECK-NOT: __kmpc_masked +// CHECK-NOT: icmp +// CHECK: br label %[[SEL:omp.metadirective.variant[0-9]*]] +// CHECK: [[SEL]]: // CHECK: call i32 @__kmpc_single( -// CHECK-NOT: __kmpc_masked -// CHECK: ret void +// CHECK: omp.metadirective.variant{{[0-9]+}}:{{.*}}No predecessors! +// CHECK: call i32 @__kmpc_masked( void runtime_path(int flag) { #pragma omp parallel { @@ -205,12 +226,14 @@ void runtime_path(int flag) { // A standalone variant runs its directive and then the statement. // CHECK-LABEL: define internal void @_Z5mixedi.omp_outlined( -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] // CHECK: [[WHEN]]: // CHECK: call void @__kmpc_barrier( // CHECK-NEXT: call void @_Z3barv() // CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] -// CHECK: [[ELSE]]: +// CHECK: [[OTHER]]: // CHECK: call i32 @__kmpc_single( // CHECK: [[END]]: // CHECK-NEXT: ret void @@ -224,11 +247,13 @@ void mixed(int flag) { // All variants are standalone: the statement runs once, after the selection. // CHECK-LABEL: define internal void @_Z14all_standalonei.omp_outlined( -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] // CHECK: [[WHEN]]: // CHECK: call void @__kmpc_barrier( // CHECK-NEXT: br label %[[END:omp.metadirective.end[0-9]*]] -// CHECK: [[ELSE]]: +// CHECK: [[OTHER]]: // CHECK: call i32 @__kmpc_omp_taskyield( // CHECK-NEXT: br label %[[END]] // CHECK: [[END]]: @@ -245,10 +270,12 @@ void all_standalone(int flag) { // Instantiated template. Kept last: the instantiation may be emitted at the // end of the file. // CHECK-LABEL: define {{.*}}void @_Z4tmplIiEvT_( -// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.when[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: br i1 {{.*}}, label %[[WHEN:omp.metadirective.variant[0-9]*]], label %[[ELSE:omp.metadirective.else[0-9]*]] +// CHECK: [[ELSE]]: +// CHECK-NEXT: br label %[[OTHER:omp.metadirective.variant[0-9]*]] // CHECK: [[WHEN]]: // CHECK-NEXT: call {{.*}}@__kmpc_fork_call({{.*}}@_Z4tmplIiEvT_.omp_outlined -// CHECK: [[ELSE]]: +// CHECK: [[OTHER]]: // CHECK-NEXT: call i32 @__kmpc_single( template <typename T> void tmpl(T flag) { #pragma omp metadirective when(user={condition(flag)}: parallel) otherwise(single) diff --git a/clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp index d58940f4e0d591..82fe52c6e11bd9 100644 --- a/clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp +++ b/clang/test/OpenMP/metadirective_runtime_target_device_codegen.cpp @@ -8,6 +8,16 @@ // RUN: -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s \ // RUN: -fopenmp-is-target-device -fopenmp-host-ir-file-path %t-host.bc \ // RUN: -o - | FileCheck %s +// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -x c++ \ +// RUN: -fopenmp-metadirective-runtime-selection \ +// RUN: -triple x86_64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda \ +// RUN: -emit-llvm %s -o - | FileCheck %s --check-prefix=HOST +// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -x c++ \ +// RUN: -fopenmp-metadirective-runtime-selection \ +// RUN: -triple nvptx64-nvidia-cuda -aux-triple x86_64-unknown-unknown \ +// RUN: -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s \ +// RUN: -fopenmp-is-target-device -fopenmp-host-ir-file-path %t-host.bc \ +// RUN: -o - | FileCheck %s --check-prefix=DEV // expected-no-diagnostics // A target region in a variant of a runtime metadirective gets a device @@ -20,3 +30,28 @@ void target_variant(int flag) { x = 1; } } + +// Two target variants on one line: their kernels differ only by a counter, so +// host and device must number them the same way. The host launches the +// condition(flag) variant (thread_limit 9) as _1, and the device kernel _1 is +// that variant (9 plus the 64 threads added for generic mode). +// HOST: call i32 @__tgt_target_kernel({{.*}}, i32 9, ptr @.__omp_offloading_{{.*}}_Z9same_linei_l{{[0-9]+}}_1.region_id +// DEV-DAG: @__omp_offloading_{{.*}}_Z9same_linei_l{{[0-9]+}}_kernel_environment = {{.*}}, i32 69, i32 -1 +// DEV-DAG: @__omp_offloading_{{.*}}_Z9same_linei_l{{[0-9]+}}_1_kernel_environment = {{.*}}, i32 73, i32 -1 +void same_line(int flag) { + int x = 0; +#pragma omp metadirective when(implementation={vendor(amd)}: target thread_limit(5) map(tofrom: x)) when(user={condition(flag)}: target thread_limit(9) map(tofrom: x)) + x = 1; +} + +// On separate lines, each variant's kernel has its own line number. +// HOST: call i32 @__tgt_target_kernel({{.*}}, i32 9, ptr @.__omp_offloading_{{.*}}_Z14separate_linesi_l{{[0-9]+}}.region_id +// DEV-DAG: @__omp_offloading_{{.*}}_Z14separate_linesi_l{{[0-9]+}}_kernel_environment = {{.*}}, i32 69, i32 -1 +// DEV-DAG: @__omp_offloading_{{.*}}_Z14separate_linesi_l{{[0-9]+}}_kernel_environment = {{.*}}, i32 73, i32 -1 +void separate_lines(int flag) { + int x = 0; +#pragma omp metadirective \ + when(implementation={vendor(amd)}: target thread_limit(5) map(tofrom: x)) \ + when(user={condition(flag)}: target thread_limit(9) map(tofrom: x)) + x = 1; +} >From 90c4c96f4ad4d7d46ef0b952ed0cf2ad95792270 Mon Sep 17 00:00:00 2001 From: Zahira Ammarguellat <[email protected]> Date: Thu, 12 Nov 2026 08:10:34 -0800 Subject: [PATCH 5/7] Addressed review comments --- clang/include/clang/AST/StmtOpenMP.h | 53 ++++++++++++++----- clang/lib/AST/StmtOpenMP.cpp | 31 +++++------ clang/lib/Parse/ParseOpenMP.cpp | 23 +++++--- clang/lib/Serialization/ASTReaderStmt.cpp | 15 +++--- clang/lib/Serialization/ASTWriterStmt.cpp | 2 +- .../OpenMP/metadirective_runtime_ast_dump.cpp | 34 ++++++++++++ 6 files changed, 109 insertions(+), 49 deletions(-) diff --git a/clang/include/clang/AST/StmtOpenMP.h b/clang/include/clang/AST/StmtOpenMP.h index 46e35d4b484709..b3896796841a7e 100644 --- a/clang/include/clang/AST/StmtOpenMP.h +++ b/clang/include/clang/AST/StmtOpenMP.h @@ -6627,27 +6627,33 @@ 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; + /// Number of OpenMP constructs that enclose the directive. + unsigned NumConstructTraits = 0; OMPMetaDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(OMPMetaDirectiveClass, llvm::omp::OMPD_metadirective, StartLoc, EndLoc) {} - /// Layout: the children hold the variants, then their conditions; the - /// trait infos follow the children. + /// Layout: the children (variants, then conditions), the trait infos, one + /// flag per variant, then the OpenMP constructs that enclose the directive. static size_t getTraitInfosOffset(unsigned NumVariants) { return llvm::alignTo(OMPChildren::size(/*NumClauses=*/0, /*HasAssociatedStmt=*/false, 2 * NumVariants), alignof(OMPTraitInfo *)); } + static size_t getFlagsOffset(unsigned NumVariants) { + return getTraitInfosOffset(NumVariants) + + NumVariants * sizeof(OMPTraitInfo *); + } + static size_t getConstructTraitsOffset(unsigned NumVariants) { + return llvm::alignTo(getFlagsOffset(NumVariants) + + NumVariants * sizeof(bool), + alignof(llvm::omp::TraitProperty)); + } static OMPMetaDirective *allocate(const ASTContext &C, unsigned NumVariants, + unsigned NumConstructTraits, SourceLocation StartLoc, SourceLocation EndLoc); @@ -6671,14 +6677,28 @@ class OMPMetaDirective final : public OMPExecutableDirective { ArrayRef<Expr *> getTrailingConditions() const { return const_cast<OMPMetaDirective *>(this)->getTrailingConditions(); } + MutableArrayRef<bool> getTrailingDirectiveThenStmt() { + return {reinterpret_cast<bool *>(reinterpret_cast<char *>(Data) + + getFlagsOffset(getNumVariants())), + getNumVariants()}; + } + MutableArrayRef<llvm::omp::TraitProperty> getTrailingConstructTraits() { + return {reinterpret_cast<llvm::omp::TraitProperty *>( + reinterpret_cast<char *>(Data) + + getConstructTraitsOffset(getNumVariants())), + NumConstructTraits}; + } ArrayRef<OMPTraitInfo *> getTrailingTraitInfos() const { return const_cast<OMPMetaDirective *>(this)->getTrailingTraitInfos(); } + ArrayRef<bool> getTrailingDirectiveThenStmt() const { + return const_cast<OMPMetaDirective *>(this)->getTrailingDirectiveThenStmt(); + } + ArrayRef<llvm::omp::TraitProperty> getTrailingConstructTraits() const { + return const_cast<OMPMetaDirective *>(this)->getTrailingConstructTraits(); + } 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 * @@ -6688,7 +6708,8 @@ class OMPMetaDirective final : public OMPExecutableDirective { ArrayRef<llvm::omp::TraitProperty> ConstructTraits, ArrayRef<bool> DirectiveThenStmt); static OMPMetaDirective *CreateEmpty(const ASTContext &C, - unsigned NumVariants, EmptyShell); + unsigned NumVariants, + unsigned NumConstructTraits, EmptyShell); unsigned getNumVariants() const { return Data->getChildren().size() / 2; } bool hasImplicitOtherwise() const { return HasImplicitOtherwise; } @@ -6698,9 +6719,13 @@ class OMPMetaDirective final : public OMPExecutableDirective { return getTrailingTraitInfos(); } ArrayRef<llvm::omp::TraitProperty> constructTraits() const { - return ConstructTraits; + return getTrailingConstructTraits(); + } + /// For each variant, true if it is a standalone directive followed by the + /// statement, stored together as a compound statement. + ArrayRef<bool> directiveThenStmt() const { + return getTrailingDirectiveThenStmt(); } - ArrayRef<bool> directiveThenStmt() const { return DirectiveThenStmt; } child_range children() { MutableArrayRef<Stmt *> Children = Data->getChildren(); diff --git a/clang/lib/AST/StmtOpenMP.cpp b/clang/lib/AST/StmtOpenMP.cpp index 71c992b717b256..ac2b5045a5a7e5 100644 --- a/clang/lib/AST/StmtOpenMP.cpp +++ b/clang/lib/AST/StmtOpenMP.cpp @@ -333,17 +333,19 @@ void OMPLoopDirective::setFinalsConditions(ArrayRef<Expr *> A) { OMPMetaDirective *OMPMetaDirective::allocate(const ASTContext &C, unsigned NumVariants, + unsigned NumConstructTraits, SourceLocation StartLoc, SourceLocation EndLoc) { - void *Mem = - C.Allocate(sizeof(OMPMetaDirective) + getTraitInfosOffset(NumVariants) + - NumVariants * sizeof(OMPTraitInfo *), - alignof(OMPMetaDirective)); + void *Mem = C.Allocate( + sizeof(OMPMetaDirective) + getConstructTraitsOffset(NumVariants) + + NumConstructTraits * sizeof(llvm::omp::TraitProperty), + alignof(OMPMetaDirective)); auto *Data = OMPChildren::CreateEmpty( reinterpret_cast<OMPMetaDirective *>(Mem) + 1, /*NumClauses=*/0, /*HasAssociatedStmt=*/false, 2 * NumVariants); auto *Dir = new (Mem) OMPMetaDirective(StartLoc, EndLoc); Dir->Data = Data; + Dir->NumConstructTraits = NumConstructTraits; return Dir; } @@ -357,30 +359,23 @@ OMPMetaDirective *OMPMetaDirective::Create( Variants.size() == TraitInfos.size() && Variants.size() == DirectiveThenStmt.size() && "Expected one condition, trait info and flag per variant"); - OMPMetaDirective *Dir = allocate(C, Variants.size(), StartLoc, EndLoc); + OMPMetaDirective *Dir = + allocate(C, Variants.size(), ConstructTraits.size(), StartLoc, EndLoc); llvm::copy(Variants, Dir->getTrailingVariants().begin()); llvm::copy(Conditions, Dir->getTrailingConditions().begin()); llvm::copy(TraitInfos, Dir->getTrailingTraitInfos().begin()); + llvm::copy(DirectiveThenStmt, Dir->getTrailingDirectiveThenStmt().begin()); + llvm::copy(ConstructTraits, Dir->getTrailingConstructTraits().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, + unsigned NumConstructTraits, EmptyShell) { - return allocate(C, NumVariants, SourceLocation(), SourceLocation()); + return allocate(C, NumVariants, NumConstructTraits, SourceLocation(), + SourceLocation()); } OMPParallelDirective *OMPParallelDirective::Create( diff --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp index 3ca165bcd9536b..55dc6ce1a5b57a 100644 --- a/clang/lib/Parse/ParseOpenMP.cpp +++ b/clang/lib/Parse/ParseOpenMP.cpp @@ -2678,17 +2678,25 @@ 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; - } + // Note if a variant uses the statement after the pragma. 'ordered' uses + // it unless it has a 'depend' or 'doacross' clause. + OpenMPDirectiveKind VariantKind = + Tok.is(tok::r_paren) ? OMPD_unknown : parseOpenMPDirectiveKind(*this); + bool TakesStmt = + VariantKind == OMPD_ordered_standalone || + (VariantKind != OMPD_unknown && + getDirectiveAssociation(VariantKind) != Association::None); // Skip Directive for now. We will parse directive in the second iteration int paren = 0; while (Tok.isNot(tok::r_paren) || paren != 0) { + if (VariantKind == OMPD_ordered_standalone && paren == 0 && + Tok.is(tok::identifier)) { + OpenMPClauseKind OrderedCKind = + getOpenMPClauseKind(PP.getSpelling(Tok)); + if (OrderedCKind == OMPC_depend || OrderedCKind == OMPC_doacross) + TakesStmt = false; + } if (Tok.is(tok::l_paren)) paren++; if (Tok.is(tok::r_paren)) @@ -2701,6 +2709,7 @@ StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective( } ConsumeAnyToken(); } + AnyVariantTakesStmt |= TakesStmt; // Parse ')' if (Tok.is(tok::r_paren)) T.consumeClose(); diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp index 12752c988f8374..48a1af12d60a4f 100644 --- a/clang/lib/Serialization/ASTReaderStmt.cpp +++ b/clang/lib/Serialization/ASTReaderStmt.cpp @@ -2541,20 +2541,16 @@ void ASTStmtReader::VisitOMPLoopDirective(OMPLoopDirective *D) { void ASTStmtReader::VisitOMPMetaDirective(OMPMetaDirective *D) { VisitStmt(D); - // The NumVariants field was read in ReadStmtFromStream. - Record.skipInts(1); + // NumVariants and NumConstructTraits were read in ReadStmtFromStream. + Record.skipInts(2); VisitOMPExecutableDirective(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) + for (llvm::omp::TraitProperty &Trait : D->getTrailingConstructTraits()) Trait = llvm::omp::TraitProperty(Record.readInt()); - D->setConstructTraits(Record.getContext(), ConstructTraits); - SmallVector<bool, 4> DirectiveThenStmt(D->getNumVariants()); - for (bool &Flag : DirectiveThenStmt) + for (bool &Flag : D->getTrailingDirectiveThenStmt()) Flag = Record.readBool(); - D->setDirectiveThenStmt(Record.getContext(), DirectiveThenStmt); } void ASTStmtReader::VisitOMPParallelDirective(OMPParallelDirective *D) { @@ -3739,7 +3735,8 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) { case STMT_OMP_META_DIRECTIVE: S = OMPMetaDirective::CreateEmpty( - Context, Record[ASTStmtReader::NumStmtFields], Empty); + Context, Record[ASTStmtReader::NumStmtFields], + Record[ASTStmtReader::NumStmtFields + 1], Empty); break; case STMT_OMP_PARALLEL_DIRECTIVE: diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp index c417d855d00e17..5be7e555262bf6 100644 --- a/clang/lib/Serialization/ASTWriterStmt.cpp +++ b/clang/lib/Serialization/ASTWriterStmt.cpp @@ -2614,11 +2614,11 @@ void ASTStmtWriter::VisitOMPLoopDirective(OMPLoopDirective *D) { void ASTStmtWriter::VisitOMPMetaDirective(OMPMetaDirective *D) { VisitStmt(D); Record.push_back(D->getNumVariants()); + Record.push_back(D->constructTraits().size()); VisitOMPExecutableDirective(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()) diff --git a/clang/test/OpenMP/metadirective_runtime_ast_dump.cpp b/clang/test/OpenMP/metadirective_runtime_ast_dump.cpp index 8de671834e1413..d440b9b8179846 100644 --- a/clang/test/OpenMP/metadirective_runtime_ast_dump.cpp +++ b/clang/test/OpenMP/metadirective_runtime_ast_dump.cpp @@ -31,6 +31,40 @@ template <typename T> void tmpl(T flag) { } void inst() { tmpl(1); } +// A block 'ordered' variant uses the statement, so 'otherwise' gets a copy. +// CHECK-LABEL: FunctionDecl {{.*}} ordered_block +// CHECK: OMPMetaDirective +// CHECK-NEXT: OMPOrderedBlockAssocDirective +// CHECK-NOT: NullStmt +// CHECK-COUNT-2: BinaryOperator {{.*}} 'int' lvalue '=' +// CHECK-NOT: NullStmt +// CHECK: ImplicitCastExpr {{.*}} 'bool' <IntegralToBoolean> +void ordered_block(int flag, int n) { +#pragma omp for ordered + for (int i = 0; i < n; ++i) { +#pragma omp metadirective when(user={condition(flag)}: ordered) otherwise(nothing) + n = i; + } +} + +// An 'ordered' variant with 'doacross' is standalone, so the statement stays +// outside the variants. +// CHECK-LABEL: FunctionDecl {{.*}} ordered_doacross +// CHECK: OMPMetaDirective +// CHECK-NEXT: OMPOrderedStandaloneDirective +// CHECK-NEXT: OMPDoacrossClause +// CHECK-NEXT: NullStmt +// CHECK-NEXT: ImplicitCastExpr {{.*}} 'bool' <IntegralToBoolean> +// CHECK: <<<NULL>>> +// CHECK-NEXT: BinaryOperator {{.*}} 'int' lvalue '=' +void ordered_doacross(int flag, int n) { +#pragma omp for ordered(1) + for (int i = 0; i < n; ++i) { +#pragma omp metadirective when(user={condition(flag)}: ordered doacross(source:)) otherwise(nothing) + n = i; + } +} + // Without 'otherwise', the last variant is the plain associated statement. // CHECK-LABEL: FunctionDecl {{.*}} no_otherwise // CHECK: OMPMetaDirective >From 65d23df12018683c8487a63dc363fddb440aabf4 Mon Sep 17 00:00:00 2001 From: Zahira Ammarguellat <[email protected]> Date: Thu, 19 Nov 2026 09:48:34 -0800 Subject: [PATCH 6/7] Fixed the variants order issue --- clang/lib/CodeGen/CGStmtOpenMP.cpp | 23 +++++++++----- .../OpenMP/metadirective_runtime_codegen.cpp | 24 +++++++++++++++ .../include/llvm/Frontend/OpenMP/OMPContext.h | 8 +++++ llvm/lib/Frontend/OpenMP/OMPContext.cpp | 30 +++++++++++++++++++ llvm/unittests/Frontend/OpenMPContextTest.cpp | 25 ++++++++++++++++ 5 files changed, 103 insertions(+), 7 deletions(-) diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp index ac72a1429ffad1..5795f4f2a88398 100644 --- a/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -2406,6 +2406,8 @@ void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) { ArrayRef<Expr *> Conditions = S.conditions(); SmallVector<llvm::omp::VariantMatchInfo, 4> VMIs; SmallVector<unsigned, 4> VariantIdx; + SmallVector<unsigned, 4> ConditionIds; + SmallVector<llvm::FoldingSetNodeID, 4> CondProfiles; std::optional<unsigned> Fallback; for (auto [I, TI] : llvm::enumerate(S.traitInfos())) { if (TI->Sets.empty()) { @@ -2422,19 +2424,26 @@ void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) { unsigned(llvm::omp::TraitProperty::user_condition_true)); } VariantIdx.push_back(I); + // Identical conditions share an id; 0 means no condition. + unsigned Id = 0; + if (const Expr *Cond = Conditions[I]) { + llvm::FoldingSetNodeID Profile; + Cond->Profile(Profile, getContext(), /*Canonical=*/true); + auto *It = llvm::find(CondProfiles, Profile); + Id = std::distance(CondProfiles.begin(), It) + 1; + if (It == CondProfiles.end()) + CondProfiles.push_back(Profile); + } + ConditionIds.push_back(Id); } 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); + for (unsigned Idx : llvm::omp::getOrderedVariantMatchesForContext( + VMIs, OMPCtx, ConditionIds)) { + unsigned I = VariantIdx[Idx]; // Without a condition the variant always applies; later ones never run. const Expr *Cond = Conditions[I]; if (!Cond) { diff --git a/clang/test/OpenMP/metadirective_runtime_codegen.cpp b/clang/test/OpenMP/metadirective_runtime_codegen.cpp index f26de940beac6a..f50c43487ca4a4 100644 --- a/clang/test/OpenMP/metadirective_runtime_codegen.cpp +++ b/clang/test/OpenMP/metadirective_runtime_codegen.cpp @@ -267,6 +267,30 @@ void all_standalone(int flag) { } } +// Equal scores keep the clause order, even if one selector is a superset +// (OpenMP 6.0 [9.4]). +// CHECK-LABEL: define {{.*}}void @_Z9tie_orderii( +// CHECK-NOT: load i32, ptr %b.addr +// CHECK: [[A:%.*]] = load i32, ptr %a.addr +// CHECK-NEXT: icmp ne i32 [[A]], 0 +// CHECK: load i32, ptr %b.addr +void tie_order(int a, int b) { +#pragma omp metadirective when(user={condition(a)}: parallel) \ + when(user={condition(b)}, implementation={vendor(llvm)}: single) + bar(); +} + +// OpenMP 6.0 [9.3]: a strict subset of another selector scores zero. +// CHECK-LABEL: define {{.*}}void @_Z9same_condi( +// CHECK: br i1 %{{.*}}, label %[[FIRST:[a-z0-9.]+]], label % +// CHECK: [[FIRST]]: +// CHECK-NEXT: call {{.*}} @__kmpc_single( +void same_cond(int x) { +#pragma omp metadirective when(user={condition(x)}: parallel) \ + when(user={condition(x)}, implementation={vendor(llvm)}: single) + bar(); +} + // Instantiated template. Kept last: the instantiation may be emitted at the // end of the file. // CHECK-LABEL: define {{.*}}void @_Z4tmplIiEvT_( diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPContext.h b/llvm/include/llvm/Frontend/OpenMP/OMPContext.h index 1231fa1b9c1ca8..8e3d120486a6c5 100644 --- a/llvm/include/llvm/Frontend/OpenMP/OMPContext.h +++ b/llvm/include/llvm/Frontend/OpenMP/OMPContext.h @@ -213,6 +213,14 @@ LLVM_ABI int getBestVariantMatchForContext(const SmallVectorImpl<VariantMatchInfo> &VMIs, const OMPContext &Ctx); +/// Return the indices (into \p VMIs) of the variants applicable in \p Ctx, +/// by decreasing score and, for equal scores, by position in \p VMIs. +/// \p ConditionIds gives each variant's user condition an id (0 for none); +/// a selector is only a subset of another if their conditions match. +LLVM_ABI SmallVector<unsigned> getOrderedVariantMatchesForContext( + const SmallVectorImpl<VariantMatchInfo> &VMIs, const OMPContext &Ctx, + ArrayRef<unsigned> ConditionIds = {}); + } // namespace omp template <> struct DenseMapInfo<omp::TraitProperty> { diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index c7b689aee50ef8..9d43a2e5f8a843 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -441,6 +441,36 @@ int llvm::omp::getBestVariantMatchForContext( return BestVMIIdx; } +SmallVector<unsigned> llvm::omp::getOrderedVariantMatchesForContext( + const SmallVectorImpl<VariantMatchInfo> &VMIs, const OMPContext &Ctx, + ArrayRef<unsigned> ConditionIds) { + SmallVector<std::pair<APInt, unsigned>> Scores; + for (auto [Idx, VMI] : enumerate(VMIs)) { + SmallVector<unsigned, 8> ConstructMatches; + if (isVariantApplicableInContextHelper( + VMI, Ctx, &ConstructMatches, + /*DeviceOrImplementationSetOnly=*/false)) + Scores.emplace_back(getVariantMatchScore(VMI, Ctx, ConstructMatches), + Idx); + } + // OpenMP 6.0 [9.3]: a strict subset of another selector scores zero. + for (auto &Entry : Scores) { + unsigned Idx = Entry.second; + unsigned Cond = ConditionIds.empty() ? 0 : ConditionIds[Idx]; + if (any_of(Scores, [&](const auto &Other) { + unsigned J = Other.second; + return J != Idx && (Cond == 0 || Cond == ConditionIds[J]) && + isStrictSubset(VMIs[Idx], VMIs[J]); + })) + Entry.first = APInt(64, 0); + } + // OpenMP 6.0 [9.4]: higher scores first; ties keep the clause order. + stable_sort(Scores, [](const auto &LHS, const auto &RHS) { + return LHS.first.ugt(RHS.first); + }); + return to_vector(make_second_range(Scores)); +} + TraitSet llvm::omp::getOpenMPContextTraitSetKind(StringRef S) { return StringSwitch<TraitSet>(S) #define OMP_TRAIT_SET(Enum, Str) .Case(Str, TraitSet::Enum) diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index 5227229a56173d..6daf42b8d0a888 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -523,4 +523,29 @@ TEST_F(OpenMPContextTest, ConstructOrderInStrictSubset) { } } +TEST_F(OpenMPContextTest, OrderedVariantMatches) { + OMPContext Context(false, Triple("x86_64-unknown-linux"), Triple(), -1); + APInt Three(64, 3); + VariantMatchInfo Plain, Vendor, NoMatch, Scored; + Plain.addTrait(TraitProperty::user_condition_true, ""); + Vendor.addTrait(TraitProperty::user_condition_true, ""); + Vendor.addTrait(TraitProperty::implementation_vendor_llvm, ""); + NoMatch.addTrait(TraitProperty::user_condition_false, ""); + Scored.addTrait(TraitProperty::implementation_vendor_llvm, "", &Three); + + // Plain and Scored are strict subsets of Vendor, so they score zero and + // keep their order. NoMatch is dropped. + SmallVector<VariantMatchInfo, 4> Candidates{Plain, Vendor, NoMatch, Scored}; + EXPECT_EQ(getOrderedVariantMatchesForContext(Candidates, Context), + (SmallVector<unsigned>{1, 0, 3})); + + // Same condition: Plain is a strict subset of Vendor and goes last. + SmallVector<VariantMatchInfo, 2> Pair{Plain, Vendor}; + EXPECT_EQ(getOrderedVariantMatchesForContext(Pair, Context, {1, 1}), + (SmallVector<unsigned>{1, 0})); + // Different conditions: no subset, so ties keep their order. + EXPECT_EQ(getOrderedVariantMatchesForContext(Pair, Context, {1, 2}), + (SmallVector<unsigned>{0, 1})); +} + } // namespace >From 93686fb7bf503611c9c4dd2c4acb9317d03875f4 Mon Sep 17 00:00:00 2001 From: Zahira Ammarguellat <[email protected]> Date: Fri, 20 Nov 2026 05:16:55 -0800 Subject: [PATCH 7/7] Match the tie rule of etBestVariantMatchForContext --- .../include/llvm/Frontend/OpenMP/OMPContext.h | 1 + llvm/lib/Frontend/OpenMP/OMPContext.cpp | 45 +++++++++++++------ llvm/unittests/Frontend/OpenMPContextTest.cpp | 7 +-- 3 files changed, 37 insertions(+), 16 deletions(-) diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPContext.h b/llvm/include/llvm/Frontend/OpenMP/OMPContext.h index 3d302d1eb33d20..b623dba2ab7d9d 100644 --- a/llvm/include/llvm/Frontend/OpenMP/OMPContext.h +++ b/llvm/include/llvm/Frontend/OpenMP/OMPContext.h @@ -218,6 +218,7 @@ getBestVariantMatchForContext(const SmallVectorImpl<VariantMatchInfo> &VMIs, /// Return the indices (into \p VMIs) of the variants applicable in \p Ctx, /// by decreasing score and, for equal scores, by position in \p VMIs. +/// Among equal scores, a strict subset of another variant goes after it. /// \p ConditionIds gives each variant's user condition an id (0 for none); /// a selector is only a subset of another if their conditions match. LLVM_ABI SmallVector<unsigned> getOrderedVariantMatchesForContext( diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index 02d13aa45a999a..1e73620a72fd96 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -476,22 +476,41 @@ SmallVector<unsigned> llvm::omp::getOrderedVariantMatchesForContext( Scores.emplace_back(getVariantMatchScore(VMI, Ctx, ConstructMatches), Idx); } - // OpenMP 6.0 [9.3]: a strict subset of another selector scores zero. - for (auto &Entry : Scores) { - unsigned Idx = Entry.second; - unsigned Cond = ConditionIds.empty() ? 0 : ConditionIds[Idx]; - if (any_of(Scores, [&](const auto &Other) { - unsigned J = Other.second; - return J != Idx && (Cond == 0 || Cond == ConditionIds[J]) && - isStrictSubset(VMIs[Idx], VMIs[J]); - })) - Entry.first = APInt(64, 0); - } // OpenMP 6.0 [9.4]: higher scores first; ties keep the clause order. stable_sort(Scores, [](const auto &LHS, const auto &RHS) { - return LHS.first.ugt(RHS.first); + unsigned Width = std::max(LHS.first.getBitWidth(), RHS.first.getBitWidth()); + return LHS.first.zext(Width).ugt(RHS.first.zext(Width)); }); - return to_vector(make_second_range(Scores)); + // As in getBestVariantMatchForContext, a strict subset only loses to a + // variant with the same score. OpenMP 6.0 [9.3] would give it a score of + // zero instead. + auto IsSubset = [&](unsigned I, unsigned J) { + unsigned Cond = ConditionIds.empty() ? 0 : ConditionIds[I]; + return I != J && (Cond == 0 || Cond == ConditionIds[J]) && + isStrictSubset(VMIs[I], VMIs[J]); + }; + auto SameScore = [](const APInt &A, const APInt &B) { + unsigned Width = std::max(A.getBitWidth(), B.getBitWidth()); + return A.zext(Width) == B.zext(Width); + }; + SmallVector<unsigned> Order; + for (auto *Begin = Scores.begin(); Begin != Scores.end();) { + auto *End = std::find_if(Begin, Scores.end(), [&](const auto &Entry) { + return !SameScore(Entry.first, Begin->first); + }); + // Take the first variant that isn't a strict subset of another one left. + SmallVector<unsigned> Tied = + to_vector(make_second_range(make_range(Begin, End))); + while (!Tied.empty()) { + auto *It = find_if(Tied, [&](unsigned I) { + return none_of(Tied, [&](unsigned J) { return IsSubset(I, J); }); + }); + Order.push_back(*It); + Tied.erase(It); + } + Begin = End; + } + return Order; } TraitSet llvm::omp::getOpenMPContextTraitSetKind(StringRef S) { diff --git a/llvm/unittests/Frontend/OpenMPContextTest.cpp b/llvm/unittests/Frontend/OpenMPContextTest.cpp index 82d3a675d2a117..ee4f5ce3b3ebd2 100644 --- a/llvm/unittests/Frontend/OpenMPContextTest.cpp +++ b/llvm/unittests/Frontend/OpenMPContextTest.cpp @@ -841,11 +841,12 @@ TEST_F(OpenMPContextTest, OrderedVariantMatches) { NoMatch.addTrait(TraitProperty::user_condition_false, ""); Scored.addTrait(TraitProperty::implementation_vendor_llvm, "", &Three); - // Plain and Scored are strict subsets of Vendor, so they score zero and - // keep their order. NoMatch is dropped. + // Scored has the highest score, even though it is a strict subset of Vendor. + // Plain is a strict subset of Vendor with the same score, so it goes after + // it. NoMatch is dropped. SmallVector<VariantMatchInfo, 4> Candidates{Plain, Vendor, NoMatch, Scored}; EXPECT_EQ(getOrderedVariantMatchesForContext(Candidates, Context), - (SmallVector<unsigned>{1, 0, 3})); + (SmallVector<unsigned>{3, 1, 0})); // Same condition: Plain is a strict subset of Vendor and goes last. SmallVector<VariantMatchInfo, 2> Pair{Plain, Vendor}; _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
