llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT--> @llvm/pr-subscribers-clang-codegen @llvm/pr-subscribers-clang Author: Akash Manna (akash-manna-sky) <details> <summary>Changes</summary> Fixes #<!-- -->87466 For a `for` with `reduction(inscan)` that is not combined with `parallel`, the scan buffer was emitted inside the outlined function, so every thread filled a private copy and ran the prefix pass on it, reading slots it never wrote. A non-constant trip count also re-emitted the loop pre-inits into `LocalDeclMap` and tripped an assertion. The buffer is now allocated once per team: a `single` region allocates it, `__kmpc_copyprivate` hands the pointer to the other threads, the master thread does the prefix pass and the final copy, and the allocating thread frees it after the end barrier. Assisted-by: LLMs. --- Patch is 54.77 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/242653.diff 7 Files Affected: - (modified) clang/docs/ReleaseNotes.md (+2) - (modified) clang/lib/CodeGen/CGOpenMPRuntime.cpp (+126-38) - (modified) clang/lib/CodeGen/CGOpenMPRuntime.h (+20) - (modified) clang/lib/CodeGen/CGStmtOpenMP.cpp (+202-42) - (added) clang/test/OpenMP/GH87466.cpp (+168) - (modified) clang/test/OpenMP/for_scan_codegen.cpp (+96-10) - (modified) clang/test/OpenMP/for_simd_scan_codegen.cpp (+96-10) ``````````diff diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md index 6d1dbbbb6eb77b..f17e444b7c697d 100644 --- a/clang/docs/ReleaseNotes.md +++ b/clang/docs/ReleaseNotes.md @@ -1513,6 +1513,8 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use - The `loop` construct without a `bind` clause or with `bind(thread)` is now allowed inside a `simd` region for OpenMP 5.0 or later, as the OpenMP specification permits. +- Fixed wrong results and an assertion failure for `reduction(inscan, ...)` on a + worksharing loop that is not combined with `parallel`. (#GH87466) - Constructs nested inside a loop-transforming construct are now checked against the restrictions of an enclosing `simd` region or of a loop with an `order(concurrent)` clause. Previously, such constructs (e.g. `parallel` diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp index d3a6ffee3ea748..a7a2c7294eb407 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp +++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp @@ -2288,20 +2288,32 @@ void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF, /// Given an array of pointers to variables, project the address of a /// given variable. static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array, - unsigned Index, const VarDecl *Var) { + unsigned Index, llvm::Type *ElemTy, + CharUnits Align) { // Pull out the pointer to the variable. Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index); llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr); + return Address(Ptr, ElemTy, Align); +} - llvm::Type *ElemTy = CGF.ConvertTypeForMem(Var->getType()); - return Address(Ptr, ElemTy, CGF.getContext().getDeclAlign(Var)); +static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array, + unsigned Index, const VarDecl *Var) { + return emitAddrOfVarFromArray(CGF, Array, Index, + CGF.ConvertTypeForMem(Var->getType()), + CGF.getContext().getDeclAlign(Var)); } +/// Callback that emits the copy of the \p Idx-th copyprivate variable from +/// \p SrcAddr to \p DestAddr in the copyprivate copy function. +using CopyprivateCopyGenTy = llvm::function_ref<void( + CodeGenFunction &CGF, unsigned Idx, Address DestAddr, Address SrcAddr)>; + +/// Emits the copy function for __kmpc_copyprivate. \p VarTypes are the LLVM +/// types and the alignments of the copyprivate variables. static llvm::Value *emitCopyprivateCopyFunction( CodeGenModule &CGM, llvm::Type *ArgsElemType, - ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, - ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps, - SourceLocation Loc) { + ArrayRef<std::pair<llvm::Type *, CharUnits>> VarTypes, + CopyprivateCopyGenTy CopyGen, SourceLocation Loc) { ASTContext &C = CGM.getContext(); // void copy_func(void *LHSArg, void *RHSArg); @@ -2339,34 +2351,105 @@ static llvm::Value *emitCopyprivateCopyFunction( // *(Type1*)Dst[1] = *(Type1*)Src[1]; // ... // *(Typen*)Dst[n] = *(Typen*)Src[n]; - for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) { - const auto *DestVar = - cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()); - Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar); - - const auto *SrcVar = - cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()); - Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar); - - const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl(); - QualType Type = VD->getType(); - CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]); + for (unsigned I = 0, E = VarTypes.size(); I < E; ++I) { + Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, VarTypes[I].first, + VarTypes[I].second); + Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, VarTypes[I].first, + VarTypes[I].second); + CopyGen(CGF, I, DestAddr, SrcAddr); } CGF.FinishFunction(); return Fn; } +void CGOpenMPRuntime::emitCopyprivateCall( + CodeGenFunction &CGF, SourceLocation Loc, Address CopyprivateList, + QualType CopyprivateArrayTy, llvm::Value *CpyFn, llvm::Value *DidIt) { + // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, + // <copy_func>, did_it); + llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy); + Address CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( + CopyprivateList, CGF.VoidPtrTy, CGF.Int8Ty); + llvm::Value *Args[] = { + emitUpdateLocation(CGF, Loc), // ident_t *<loc> + getThreadID(CGF, Loc), // i32 <gtid> + BufSize, // size_t <buf_size> + CL.emitRawPointer(CGF), // void *<copyprivate list> + CpyFn, // void (*) (void *, void *) <copy_func> + DidIt // i32 did_it + }; + CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( + CGM.getModule(), OMPRTL___kmpc_copyprivate), + Args); +} + +void CGOpenMPRuntime::emitCopyprivateBroadcast(CodeGenFunction &CGF, + SourceLocation Loc, + ArrayRef<Address> Addrs, + Address DidIt) { + if (!CGF.HaveInsertPoint()) + return; + ASTContext &C = CGM.getContext(); + llvm::APInt ArraySize(/*unsigned int numBits=*/32, Addrs.size()); + QualType CopyprivateArrayTy = C.getConstantArrayType( + C.VoidPtrTy, ArraySize, nullptr, ArraySizeModifier::Normal, + /*IndexTypeQuals=*/0); + Address CopyprivateList = CGF.CreateMemTempWithoutCast( + CopyprivateArrayTy, ".omp.copyprivate.cpr_list"); + SmallVector<std::pair<llvm::Type *, CharUnits>, 4> VarTypes; + for (unsigned I = 0, E = Addrs.size(); I < E; ++I) { + assert(Addrs[I].getElementType()->isSingleValueType() && + "Expected a scalar copyprivate variable."); + Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I); + CGF.Builder.CreateStore(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( + Addrs[I].emitRawPointer(CGF), CGF.VoidPtrTy), + Elem); + VarTypes.emplace_back(Addrs[I].getElementType(), Addrs[I].getAlignment()); + } + llvm::Value *CpyFn = emitCopyprivateCopyFunction( + CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy), VarTypes, + [](CodeGenFunction &CGF, unsigned, Address DestAddr, Address SrcAddr) { + CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcAddr), DestAddr); + }, + Loc); + emitCopyprivateCall(CGF, Loc, CopyprivateList, CopyprivateArrayTy, CpyFn, + CGF.Builder.CreateLoad(DidIt)); +} + +llvm::Value *CGOpenMPRuntime::emitAllocCall(CodeGenFunction &CGF, + SourceLocation Loc, + llvm::Value *Size, + CharUnits Alignment) { + // Use the default allocator. + llvm::Value *Args[] = {getThreadID(CGF, Loc), CGM.getSize(Alignment), Size, + llvm::ConstantPointerNull::get(CGF.VoidPtrTy)}; + return CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( + CGM.getModule(), OMPRTL___kmpc_aligned_alloc), + Args); +} + +void CGOpenMPRuntime::emitFreeCall(CodeGenFunction &CGF, SourceLocation Loc, + llvm::Value *Ptr) { + llvm::Value *Args[] = { + getThreadID(CGF, Loc), + CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Ptr, CGF.VoidPtrTy), + llvm::ConstantPointerNull::get(CGF.VoidPtrTy)}; + CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), + OMPRTL___kmpc_free), + Args); +} + void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, + ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, - ArrayRef<const Expr *> DstExprs, ArrayRef<const Expr *> AssignmentOps) { if (!CGF.HaveInsertPoint()) return; - assert(CopyprivateVars.size() == SrcExprs.size() && - CopyprivateVars.size() == DstExprs.size() && + assert(CopyprivateVars.size() == DestExprs.size() && + CopyprivateVars.size() == SrcExprs.size() && CopyprivateVars.size() == AssignmentOps.size()); ASTContext &C = CGM.getContext(); // int32 did_it = 0; @@ -2412,6 +2495,7 @@ void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF, // Create a list of all private variables for copyprivate. Address CopyprivateList = CGF.CreateMemTempWithoutCast( CopyprivateArrayTy, ".omp.copyprivate.cpr_list"); + SmallVector<std::pair<llvm::Type *, CharUnits>, 4> VarTypes; for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) { Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I); CGF.Builder.CreateStore( @@ -2419,27 +2503,31 @@ void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF, CGF.EmitLValue(CopyprivateVars[I]).getPointer(CGF), CGF.VoidPtrTy), Elem); + // The pseudo destination and source variables have the same type. + const auto *DestVar = + cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()); + VarTypes.emplace_back( + CGM.getTypes().ConvertTypeForMem(DestVar->getType()), + C.getDeclAlign(DestVar)); } // Build function that copies private values from single region to all other // threads in the corresponding parallel region. llvm::Value *CpyFn = emitCopyprivateCopyFunction( - CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy), CopyprivateVars, - SrcExprs, DstExprs, AssignmentOps, Loc); - llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy); - Address CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( - CopyprivateList, CGF.VoidPtrTy, CGF.Int8Ty); - llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt); - llvm::Value *Args[] = { - emitUpdateLocation(CGF, Loc), // ident_t *<loc> - getThreadID(CGF, Loc), // i32 <gtid> - BufSize, // size_t <buf_size> - CL.emitRawPointer(CGF), // void *<copyprivate list> - CpyFn, // void (*) (void *, void *) <copy_func> - DidItVal // i32 did_it - }; - CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction( - CGM.getModule(), OMPRTL___kmpc_copyprivate), - Args); + CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy), VarTypes, + [&](CodeGenFunction &CGF, unsigned I, Address DestAddr, + Address SrcAddr) { + const auto *DestVar = + cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()); + const auto *SrcVar = + cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()); + QualType Type = + cast<DeclRefExpr>(CopyprivateVars[I])->getDecl()->getType(); + CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, + AssignmentOps[I]); + }, + Loc); + emitCopyprivateCall(CGF, Loc, CopyprivateList, CopyprivateArrayTy, CpyFn, + CGF.Builder.CreateLoad(DidIt)); } } diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.h b/clang/lib/CodeGen/CGOpenMPRuntime.h index ae55295cadc14f..cf26875166aa4b 100644 --- a/clang/lib/CodeGen/CGOpenMPRuntime.h +++ b/clang/lib/CodeGen/CGOpenMPRuntime.h @@ -340,6 +340,12 @@ class CGOpenMPRuntime { /// llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc); + /// Emits the call to __kmpc_copyprivate for the variables whose addresses are + /// stored in \p CopyprivateList (of type \p CopyprivateArrayTy). + void emitCopyprivateCall(CodeGenFunction &CGF, SourceLocation Loc, + Address CopyprivateList, QualType CopyprivateArrayTy, + llvm::Value *CpyFn, llvm::Value *DidIt); + /// Get the function name of an outlined region. std::string getOutlinedHelperName(StringRef Name) const; std::string getOutlinedHelperName(CodeGenFunction &CGF) const; @@ -848,6 +854,20 @@ class CGOpenMPRuntime { ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps); + /// Emits the copyprivate broadcast (with its barrier) of the scalar private + /// variables at \p Addrs from the thread for which the flag at \p DidIt is + /// non-zero to all other threads of the team. + void emitCopyprivateBroadcast(CodeGenFunction &CGF, SourceLocation Loc, + ArrayRef<Address> Addrs, Address DidIt); + + /// Emits __kmpc_aligned_alloc of \p Size bytes aligned to \p Alignment in + /// the default allocator and returns the pointer. + llvm::Value *emitAllocCall(CodeGenFunction &CGF, SourceLocation Loc, + llvm::Value *Size, CharUnits Alignment); + + /// Emits __kmpc_free of the memory \p Ptr allocated with emitAllocCall. + void emitFreeCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *Ptr); + /// Emit an ordered region. /// \param OrderedOpGen Generator for the statement associated with the given /// ordered region. diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp index e63957df3e4069..b2b79dc5cf7cf7 100644 --- a/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp @@ -4294,6 +4294,15 @@ emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, return {LBVal, UBVal}; } +/// Returns true if the directive has a 'reduction' clause with the 'inscan' +/// modifier. +static bool hasInscanReduction(const OMPExecutableDirective &S) { + return llvm::any_of(S.getClausesOfKind<OMPReductionClause>(), + [](const OMPReductionClause *C) { + return C->getModifier() == OMPC_REDUCTION_inscan; + }); +} + /// Emits internal temp array declarations for the directive with inscan /// reductions. /// The code is the following: @@ -4348,6 +4357,140 @@ static void emitScanBasedDirectiveDecls( } } +/// Emits internal temp array declarations for the directive with inscan +/// reductions that is not combined with 'parallel'. All threads of the team +/// execute the directive, so the arrays are allocated by one thread and shared +/// with the others via copyprivate; they are mapped in \p TempsScope. +/// The code is the following: +/// \code +/// size num_iters = <num_iters>; +/// <type> *buffer; +/// int did_it = 0; +/// if (__kmpc_single()) { +/// buffer = __kmpc_aligned_alloc(num_iters * sizeof(<type>)); +/// did_it = 1; +/// } +/// __kmpc_copyprivate(&buffer, did_it); +/// \endcode +/// \returns the address of the did_it flag, non-zero in the allocating thread. +static Address emitScanBasedDirectiveSharedDecls( + CodeGenFunction &CGF, const OMPLoopDirective &S, + llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen, + CodeGenFunction::OMPPrivateScope &TempsScope) { + CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); + llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast( + NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false); + SmallVector<const Expr *, 4> Shareds; + SmallVector<const Expr *, 4> Privates; + SmallVector<const Expr *, 4> ReductionOps; + SmallVector<const Expr *, 4> CopyArrayTemps; + for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { + assert(C->getModifier() == OMPC_REDUCTION_inscan && + "Only inscan reductions are expected."); + Shareds.append(C->varlist_begin(), C->varlist_end()); + Privates.append(C->privates().begin(), C->privates().end()); + ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); + CopyArrayTemps.append(C->copy_array_temps().begin(), + C->copy_array_temps().end()); + } + SmallVector<const VarDecl *, 4> TempVDs; + SmallVector<Address, 4> TempPtrAddrs; + { + ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps); + unsigned Count = 0; + auto *ITA = CopyArrayTemps.begin(); + for (const Expr *IRef : Privates) { + const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); + if (PrivateVD->getType()->isVariablyModifiedType()) { + RedCG.emitSharedOrigLValue(CGF, Count); + RedCG.emitAggregateType(CGF, Count); + } + const auto *TempVD = cast<VarDecl>(cast<DeclRefExpr>(*ITA)->getDecl()); + CodeGenFunction::OpaqueValueMapping DimMapping( + CGF, + cast<OpaqueValueExpr>( + cast<VariableArrayType>(TempVD->getType()->getAsArrayTypeUnsafe()) + ->getSizeExpr()), + RValue::get(OMPScanNumIterations)); + CGF.EmitVariablyModifiedType(TempVD->getType()); + TempVDs.push_back(TempVD); + TempPtrAddrs.push_back( + CGF.CreateMemTemp(CGF.getContext().getPointerType(TempVD->getType()), + TempVD->getName() + ".buf.addr")); + ++ITA; + ++Count; + } + } + Address DidIt = CGF.CreateMemTempWithoutCast( + CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), + ".omp.scan.did_it"); + CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt); + auto &&AllocGen = [&S, &TempVDs, &TempPtrAddrs, + DidIt](CodeGenFunction &CGF, PrePostActionTy &Action) { + Action.Enter(CGF); + for (unsigned I = 0, E = TempVDs.size(); I < E; ++I) { + const VarDecl *TempVD = TempVDs[I]; + QualType Ty = TempVD->getType(); + CharUnits Align = CGF.getContext().getDeclAlign(TempVD); + llvm::Value *Ptr = CGF.CGM.getOpenMPRuntime().emitAllocCall( + CGF, S.getBeginLoc(), CGF.getTypeSize(Ty), Align); + CGF.Builder.CreateStore(Ptr, TempPtrAddrs[I]); + const Expr *Init = TempVD->getInit(); + if (Init && !CGF.isTrivialInitializer(Init)) + CGF.EmitExprAsInit( + Init, TempVD, + CGF.MakeAddrLValue(Address(Ptr, CGF.ConvertTypeForMem(Ty), Align), + Ty, AlignmentSource::Decl), + /*capturedByInit=*/false); + } + CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt); + }; + RT.emitSingleRegion(CGF, AllocGen, S.getBeginLoc(), + /*CopyprivateVars=*/{}, /*DestExprs=*/{}, + /*SrcExprs=*/{}, /*AssignmentOps=*/{}); + RT.emitCopyprivateBroadcast(CGF, S.getBeginLoc(), TempPtrAddrs, DidIt); + for (unsigned I = 0, E = TempVDs.size(); I < E; ++I) { + const VarDecl *TempVD = TempVDs[I]; + llvm::Value *Ptr = CGF.Builder.CreateLoad(TempPtrAddrs[I]); + TempsScope.addPrivate(TempVD, + Address(Ptr, CGF.ConvertTypeForMem(TempVD->getType()), + CGF.getContext().getDeclAlign(TempVD))); + } + (void)TempsScope.Privatize(); + return DidIt; +} + +/// Releases the temp arrays allocated by emitScanBasedDirectiveSharedDecls; +/// must follow the barrier at the end of the directive. +/// The code is the following: +/// \code +/// if (did_it) +/// __kmpc_free(buffer); +/// \endcode +static void emitScanBasedDirectiveSharedDeclsFree(CodeGenFunction &CGF, + const OMPLoopDirective &S, + Address DidIt) { + llvm::BasicBlock *ThenBB = CGF.createBasicBlock("omp.scan.free"); + llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.scan.free.exit"); + llvm::Value *DidItVa... [truncated] `````````` </details> https://github.com/llvm/llvm-project/pull/242653 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
