1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit OpenMP nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGCleanup.h" 14 #include "CGOpenMPRuntime.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "TargetInfo.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/OpenMPClause.h" 22 #include "clang/AST/Stmt.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/Basic/OpenMPKinds.h" 26 #include "clang/Basic/PrettyStackTrace.h" 27 #include "llvm/Frontend/OpenMP/OMPConstants.h" 28 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/Support/AtomicOrdering.h" 32 using namespace clang; 33 using namespace CodeGen; 34 using namespace llvm::omp; 35 36 static const VarDecl *getBaseDecl(const Expr *Ref); 37 38 namespace { 39 /// Lexical scope for OpenMP executable constructs, that handles correct codegen 40 /// for captured expressions. 41 class OMPLexicalScope : public CodeGenFunction::LexicalScope { 42 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 43 for (const auto *C : S.clauses()) { 44 if (const auto *CPI = OMPClauseWithPreInit::get(C)) { 45 if (const auto *PreInit = 46 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) { 47 for (const auto *I : PreInit->decls()) { 48 if (!I->hasAttr<OMPCaptureNoInitAttr>()) { 49 CGF.EmitVarDecl(cast<VarDecl>(*I)); 50 } else { 51 CodeGenFunction::AutoVarEmission Emission = 52 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I)); 53 CGF.EmitAutoVarCleanups(Emission); 54 } 55 } 56 } 57 } 58 } 59 } 60 CodeGenFunction::OMPPrivateScope InlinedShareds; 61 62 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) { 63 return CGF.LambdaCaptureFields.lookup(VD) || 64 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) || 65 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) && 66 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD)); 67 } 68 69 public: 70 OMPLexicalScope( 71 CodeGenFunction &CGF, const OMPExecutableDirective &S, 72 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None, 73 const bool EmitPreInitStmt = true) 74 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 75 InlinedShareds(CGF) { 76 if (EmitPreInitStmt) 77 emitPreInitStmt(CGF, S); 78 if (!CapturedRegion.hasValue()) 79 return; 80 assert(S.hasAssociatedStmt() && 81 "Expected associated statement for inlined directive."); 82 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion); 83 for (const auto &C : CS->captures()) { 84 if (C.capturesVariable() || C.capturesVariableByCopy()) { 85 auto *VD = C.getCapturedVar(); 86 assert(VD == VD->getCanonicalDecl() && 87 "Canonical decl must be captured."); 88 DeclRefExpr DRE( 89 CGF.getContext(), const_cast<VarDecl *>(VD), 90 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo && 91 InlinedShareds.isGlobalVarCaptured(VD)), 92 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation()); 93 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address { 94 return CGF.EmitLValue(&DRE).getAddress(CGF); 95 }); 96 } 97 } 98 (void)InlinedShareds.Privatize(); 99 } 100 }; 101 102 /// Lexical scope for OpenMP parallel construct, that handles correct codegen 103 /// for captured expressions. 104 class OMPParallelScope final : public OMPLexicalScope { 105 bool EmitPreInitStmt(const OMPExecutableDirective &S) { 106 OpenMPDirectiveKind Kind = S.getDirectiveKind(); 107 return !(isOpenMPTargetExecutionDirective(Kind) || 108 isOpenMPLoopBoundSharingDirective(Kind)) && 109 isOpenMPParallelDirective(Kind); 110 } 111 112 public: 113 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 114 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None, 115 EmitPreInitStmt(S)) {} 116 }; 117 118 /// Lexical scope for OpenMP teams construct, that handles correct codegen 119 /// for captured expressions. 120 class OMPTeamsScope final : public OMPLexicalScope { 121 bool EmitPreInitStmt(const OMPExecutableDirective &S) { 122 OpenMPDirectiveKind Kind = S.getDirectiveKind(); 123 return !isOpenMPTargetExecutionDirective(Kind) && 124 isOpenMPTeamsDirective(Kind); 125 } 126 127 public: 128 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 129 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None, 130 EmitPreInitStmt(S)) {} 131 }; 132 133 /// Private scope for OpenMP loop-based directives, that supports capturing 134 /// of used expression from loop statement. 135 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope { 136 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) { 137 const DeclStmt *PreInits; 138 CodeGenFunction::OMPMapVars PreCondVars; 139 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) { 140 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 141 for (const auto *E : LD->counters()) { 142 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 143 EmittedAsPrivate.insert(VD->getCanonicalDecl()); 144 (void)PreCondVars.setVarAddr( 145 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType())); 146 } 147 // Mark private vars as undefs. 148 for (const auto *C : LD->getClausesOfKind<OMPPrivateClause>()) { 149 for (const Expr *IRef : C->varlists()) { 150 const auto *OrigVD = 151 cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 152 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 153 (void)PreCondVars.setVarAddr( 154 CGF, OrigVD, 155 Address(llvm::UndefValue::get(CGF.ConvertTypeForMem( 156 CGF.getContext().getPointerType( 157 OrigVD->getType().getNonReferenceType()))), 158 CGF.getContext().getDeclAlign(OrigVD))); 159 } 160 } 161 } 162 (void)PreCondVars.apply(CGF); 163 // Emit init, __range and __end variables for C++ range loops. 164 (void)OMPLoopBasedDirective::doForAllLoops( 165 LD->getInnermostCapturedStmt()->getCapturedStmt(), 166 /*TryImperfectlyNestedLoops=*/true, LD->getLoopsNumber(), 167 [&CGF](unsigned Cnt, const Stmt *CurStmt) { 168 if (const auto *CXXFor = dyn_cast<CXXForRangeStmt>(CurStmt)) { 169 if (const Stmt *Init = CXXFor->getInit()) 170 CGF.EmitStmt(Init); 171 CGF.EmitStmt(CXXFor->getRangeStmt()); 172 CGF.EmitStmt(CXXFor->getEndStmt()); 173 } 174 return false; 175 }); 176 PreInits = cast_or_null<DeclStmt>(LD->getPreInits()); 177 } else if (const auto *Tile = dyn_cast<OMPTileDirective>(&S)) { 178 PreInits = cast_or_null<DeclStmt>(Tile->getPreInits()); 179 } else if (const auto *Unroll = dyn_cast<OMPUnrollDirective>(&S)) { 180 PreInits = cast_or_null<DeclStmt>(Unroll->getPreInits()); 181 } else { 182 llvm_unreachable("Unknown loop-based directive kind."); 183 } 184 if (PreInits) { 185 for (const auto *I : PreInits->decls()) 186 CGF.EmitVarDecl(cast<VarDecl>(*I)); 187 } 188 PreCondVars.restore(CGF); 189 } 190 191 public: 192 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) 193 : CodeGenFunction::RunCleanupsScope(CGF) { 194 emitPreInitStmt(CGF, S); 195 } 196 }; 197 198 class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope { 199 CodeGenFunction::OMPPrivateScope InlinedShareds; 200 201 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) { 202 return CGF.LambdaCaptureFields.lookup(VD) || 203 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) || 204 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) && 205 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD)); 206 } 207 208 public: 209 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 210 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 211 InlinedShareds(CGF) { 212 for (const auto *C : S.clauses()) { 213 if (const auto *CPI = OMPClauseWithPreInit::get(C)) { 214 if (const auto *PreInit = 215 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) { 216 for (const auto *I : PreInit->decls()) { 217 if (!I->hasAttr<OMPCaptureNoInitAttr>()) { 218 CGF.EmitVarDecl(cast<VarDecl>(*I)); 219 } else { 220 CodeGenFunction::AutoVarEmission Emission = 221 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I)); 222 CGF.EmitAutoVarCleanups(Emission); 223 } 224 } 225 } 226 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) { 227 for (const Expr *E : UDP->varlists()) { 228 const Decl *D = cast<DeclRefExpr>(E)->getDecl(); 229 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D)) 230 CGF.EmitVarDecl(*OED); 231 } 232 } else if (const auto *UDP = dyn_cast<OMPUseDeviceAddrClause>(C)) { 233 for (const Expr *E : UDP->varlists()) { 234 const Decl *D = getBaseDecl(E); 235 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D)) 236 CGF.EmitVarDecl(*OED); 237 } 238 } 239 } 240 if (!isOpenMPSimdDirective(S.getDirectiveKind())) 241 CGF.EmitOMPPrivateClause(S, InlinedShareds); 242 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) { 243 if (const Expr *E = TG->getReductionRef()) 244 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())); 245 } 246 // Temp copy arrays for inscan reductions should not be emitted as they are 247 // not used in simd only mode. 248 llvm::DenseSet<CanonicalDeclPtr<const Decl>> CopyArrayTemps; 249 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 250 if (C->getModifier() != OMPC_REDUCTION_inscan) 251 continue; 252 for (const Expr *E : C->copy_array_temps()) 253 CopyArrayTemps.insert(cast<DeclRefExpr>(E)->getDecl()); 254 } 255 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt()); 256 while (CS) { 257 for (auto &C : CS->captures()) { 258 if (C.capturesVariable() || C.capturesVariableByCopy()) { 259 auto *VD = C.getCapturedVar(); 260 if (CopyArrayTemps.contains(VD)) 261 continue; 262 assert(VD == VD->getCanonicalDecl() && 263 "Canonical decl must be captured."); 264 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD), 265 isCapturedVar(CGF, VD) || 266 (CGF.CapturedStmtInfo && 267 InlinedShareds.isGlobalVarCaptured(VD)), 268 VD->getType().getNonReferenceType(), VK_LValue, 269 C.getLocation()); 270 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address { 271 return CGF.EmitLValue(&DRE).getAddress(CGF); 272 }); 273 } 274 } 275 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt()); 276 } 277 (void)InlinedShareds.Privatize(); 278 } 279 }; 280 281 } // namespace 282 283 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 284 const OMPExecutableDirective &S, 285 const RegionCodeGenTy &CodeGen); 286 287 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) { 288 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) { 289 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) { 290 OrigVD = OrigVD->getCanonicalDecl(); 291 bool IsCaptured = 292 LambdaCaptureFields.lookup(OrigVD) || 293 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) || 294 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)); 295 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured, 296 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc()); 297 return EmitLValue(&DRE); 298 } 299 } 300 return EmitLValue(E); 301 } 302 303 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) { 304 ASTContext &C = getContext(); 305 llvm::Value *Size = nullptr; 306 auto SizeInChars = C.getTypeSizeInChars(Ty); 307 if (SizeInChars.isZero()) { 308 // getTypeSizeInChars() returns 0 for a VLA. 309 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) { 310 VlaSizePair VlaSize = getVLASize(VAT); 311 Ty = VlaSize.Type; 312 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts) 313 : VlaSize.NumElts; 314 } 315 SizeInChars = C.getTypeSizeInChars(Ty); 316 if (SizeInChars.isZero()) 317 return llvm::ConstantInt::get(SizeTy, /*V=*/0); 318 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars)); 319 } 320 return CGM.getSize(SizeInChars); 321 } 322 323 void CodeGenFunction::GenerateOpenMPCapturedVars( 324 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) { 325 const RecordDecl *RD = S.getCapturedRecordDecl(); 326 auto CurField = RD->field_begin(); 327 auto CurCap = S.captures().begin(); 328 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), 329 E = S.capture_init_end(); 330 I != E; ++I, ++CurField, ++CurCap) { 331 if (CurField->hasCapturedVLAType()) { 332 const VariableArrayType *VAT = CurField->getCapturedVLAType(); 333 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()]; 334 CapturedVars.push_back(Val); 335 } else if (CurCap->capturesThis()) { 336 CapturedVars.push_back(CXXThisValue); 337 } else if (CurCap->capturesVariableByCopy()) { 338 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation()); 339 340 // If the field is not a pointer, we need to save the actual value 341 // and load it as a void pointer. 342 if (!CurField->getType()->isAnyPointerType()) { 343 ASTContext &Ctx = getContext(); 344 Address DstAddr = CreateMemTemp( 345 Ctx.getUIntPtrType(), 346 Twine(CurCap->getCapturedVar()->getName(), ".casted")); 347 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType()); 348 349 llvm::Value *SrcAddrVal = EmitScalarConversion( 350 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()), 351 Ctx.getPointerType(CurField->getType()), CurCap->getLocation()); 352 LValue SrcLV = 353 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType()); 354 355 // Store the value using the source type pointer. 356 EmitStoreThroughLValue(RValue::get(CV), SrcLV); 357 358 // Load the value using the destination type pointer. 359 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation()); 360 } 361 CapturedVars.push_back(CV); 362 } else { 363 assert(CurCap->capturesVariable() && "Expected capture by reference."); 364 CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer()); 365 } 366 } 367 } 368 369 static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc, 370 QualType DstType, StringRef Name, 371 LValue AddrLV) { 372 ASTContext &Ctx = CGF.getContext(); 373 374 llvm::Value *CastedPtr = CGF.EmitScalarConversion( 375 AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(), 376 Ctx.getPointerType(DstType), Loc); 377 Address TmpAddr = 378 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType)) 379 .getAddress(CGF); 380 return TmpAddr; 381 } 382 383 static QualType getCanonicalParamType(ASTContext &C, QualType T) { 384 if (T->isLValueReferenceType()) 385 return C.getLValueReferenceType( 386 getCanonicalParamType(C, T.getNonReferenceType()), 387 /*SpelledAsLValue=*/false); 388 if (T->isPointerType()) 389 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType())); 390 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) { 391 if (const auto *VLA = dyn_cast<VariableArrayType>(A)) 392 return getCanonicalParamType(C, VLA->getElementType()); 393 if (!A->isVariablyModifiedType()) 394 return C.getCanonicalType(T); 395 } 396 return C.getCanonicalParamType(T); 397 } 398 399 namespace { 400 /// Contains required data for proper outlined function codegen. 401 struct FunctionOptions { 402 /// Captured statement for which the function is generated. 403 const CapturedStmt *S = nullptr; 404 /// true if cast to/from UIntPtr is required for variables captured by 405 /// value. 406 const bool UIntPtrCastRequired = true; 407 /// true if only casted arguments must be registered as local args or VLA 408 /// sizes. 409 const bool RegisterCastedArgsOnly = false; 410 /// Name of the generated function. 411 const StringRef FunctionName; 412 /// Location of the non-debug version of the outlined function. 413 SourceLocation Loc; 414 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired, 415 bool RegisterCastedArgsOnly, StringRef FunctionName, 416 SourceLocation Loc) 417 : S(S), UIntPtrCastRequired(UIntPtrCastRequired), 418 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly), 419 FunctionName(FunctionName), Loc(Loc) {} 420 }; 421 } // namespace 422 423 static llvm::Function *emitOutlinedFunctionPrologue( 424 CodeGenFunction &CGF, FunctionArgList &Args, 425 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> 426 &LocalAddrs, 427 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> 428 &VLASizes, 429 llvm::Value *&CXXThisValue, const FunctionOptions &FO) { 430 const CapturedDecl *CD = FO.S->getCapturedDecl(); 431 const RecordDecl *RD = FO.S->getCapturedRecordDecl(); 432 assert(CD->hasBody() && "missing CapturedDecl body"); 433 434 CXXThisValue = nullptr; 435 // Build the argument list. 436 CodeGenModule &CGM = CGF.CGM; 437 ASTContext &Ctx = CGM.getContext(); 438 FunctionArgList TargetArgs; 439 Args.append(CD->param_begin(), 440 std::next(CD->param_begin(), CD->getContextParamPosition())); 441 TargetArgs.append( 442 CD->param_begin(), 443 std::next(CD->param_begin(), CD->getContextParamPosition())); 444 auto I = FO.S->captures().begin(); 445 FunctionDecl *DebugFunctionDecl = nullptr; 446 if (!FO.UIntPtrCastRequired) { 447 FunctionProtoType::ExtProtoInfo EPI; 448 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI); 449 DebugFunctionDecl = FunctionDecl::Create( 450 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(), 451 SourceLocation(), DeclarationName(), FunctionTy, 452 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static, 453 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false); 454 } 455 for (const FieldDecl *FD : RD->fields()) { 456 QualType ArgType = FD->getType(); 457 IdentifierInfo *II = nullptr; 458 VarDecl *CapVar = nullptr; 459 460 // If this is a capture by copy and the type is not a pointer, the outlined 461 // function argument type should be uintptr and the value properly casted to 462 // uintptr. This is necessary given that the runtime library is only able to 463 // deal with pointers. We can pass in the same way the VLA type sizes to the 464 // outlined function. 465 if (FO.UIntPtrCastRequired && 466 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) || 467 I->capturesVariableArrayType())) 468 ArgType = Ctx.getUIntPtrType(); 469 470 if (I->capturesVariable() || I->capturesVariableByCopy()) { 471 CapVar = I->getCapturedVar(); 472 II = CapVar->getIdentifier(); 473 } else if (I->capturesThis()) { 474 II = &Ctx.Idents.get("this"); 475 } else { 476 assert(I->capturesVariableArrayType()); 477 II = &Ctx.Idents.get("vla"); 478 } 479 if (ArgType->isVariablyModifiedType()) 480 ArgType = getCanonicalParamType(Ctx, ArgType); 481 VarDecl *Arg; 482 if (DebugFunctionDecl && (CapVar || I->capturesThis())) { 483 Arg = ParmVarDecl::Create( 484 Ctx, DebugFunctionDecl, 485 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(), 486 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType, 487 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr); 488 } else { 489 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), 490 II, ArgType, ImplicitParamDecl::Other); 491 } 492 Args.emplace_back(Arg); 493 // Do not cast arguments if we emit function with non-original types. 494 TargetArgs.emplace_back( 495 FO.UIntPtrCastRequired 496 ? Arg 497 : CGM.getOpenMPRuntime().translateParameter(FD, Arg)); 498 ++I; 499 } 500 Args.append( 501 std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 502 CD->param_end()); 503 TargetArgs.append( 504 std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 505 CD->param_end()); 506 507 // Create the function declaration. 508 const CGFunctionInfo &FuncInfo = 509 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs); 510 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 511 512 auto *F = 513 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 514 FO.FunctionName, &CGM.getModule()); 515 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 516 if (CD->isNothrow()) 517 F->setDoesNotThrow(); 518 F->setDoesNotRecurse(); 519 520 // Generate the function. 521 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs, 522 FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(), 523 FO.UIntPtrCastRequired ? FO.Loc 524 : CD->getBody()->getBeginLoc()); 525 unsigned Cnt = CD->getContextParamPosition(); 526 I = FO.S->captures().begin(); 527 for (const FieldDecl *FD : RD->fields()) { 528 // Do not map arguments if we emit function with non-original types. 529 Address LocalAddr(Address::invalid()); 530 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) { 531 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt], 532 TargetArgs[Cnt]); 533 } else { 534 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]); 535 } 536 // If we are capturing a pointer by copy we don't need to do anything, just 537 // use the value that we get from the arguments. 538 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) { 539 const VarDecl *CurVD = I->getCapturedVar(); 540 if (!FO.RegisterCastedArgsOnly) 541 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}}); 542 ++Cnt; 543 ++I; 544 continue; 545 } 546 547 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(), 548 AlignmentSource::Decl); 549 if (FD->hasCapturedVLAType()) { 550 if (FO.UIntPtrCastRequired) { 551 ArgLVal = CGF.MakeAddrLValue( 552 castValueFromUintptr(CGF, I->getLocation(), FD->getType(), 553 Args[Cnt]->getName(), ArgLVal), 554 FD->getType(), AlignmentSource::Decl); 555 } 556 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation()); 557 const VariableArrayType *VAT = FD->getCapturedVLAType(); 558 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg); 559 } else if (I->capturesVariable()) { 560 const VarDecl *Var = I->getCapturedVar(); 561 QualType VarTy = Var->getType(); 562 Address ArgAddr = ArgLVal.getAddress(CGF); 563 if (ArgLVal.getType()->isLValueReferenceType()) { 564 ArgAddr = CGF.EmitLoadOfReference(ArgLVal); 565 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) { 566 assert(ArgLVal.getType()->isPointerType()); 567 ArgAddr = CGF.EmitLoadOfPointer( 568 ArgAddr, ArgLVal.getType()->castAs<PointerType>()); 569 } 570 if (!FO.RegisterCastedArgsOnly) { 571 LocalAddrs.insert( 572 {Args[Cnt], 573 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}}); 574 } 575 } else if (I->capturesVariableByCopy()) { 576 assert(!FD->getType()->isAnyPointerType() && 577 "Not expecting a captured pointer."); 578 const VarDecl *Var = I->getCapturedVar(); 579 LocalAddrs.insert({Args[Cnt], 580 {Var, FO.UIntPtrCastRequired 581 ? castValueFromUintptr( 582 CGF, I->getLocation(), FD->getType(), 583 Args[Cnt]->getName(), ArgLVal) 584 : ArgLVal.getAddress(CGF)}}); 585 } else { 586 // If 'this' is captured, load it into CXXThisValue. 587 assert(I->capturesThis()); 588 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation()); 589 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}}); 590 } 591 ++Cnt; 592 ++I; 593 } 594 595 return F; 596 } 597 598 llvm::Function * 599 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, 600 SourceLocation Loc) { 601 assert( 602 CapturedStmtInfo && 603 "CapturedStmtInfo should be set when generating the captured function"); 604 const CapturedDecl *CD = S.getCapturedDecl(); 605 // Build the argument list. 606 bool NeedWrapperFunction = 607 getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo(); 608 FunctionArgList Args; 609 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs; 610 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes; 611 SmallString<256> Buffer; 612 llvm::raw_svector_ostream Out(Buffer); 613 Out << CapturedStmtInfo->getHelperName(); 614 if (NeedWrapperFunction) 615 Out << "_debug__"; 616 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false, 617 Out.str(), Loc); 618 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs, 619 VLASizes, CXXThisValue, FO); 620 CodeGenFunction::OMPPrivateScope LocalScope(*this); 621 for (const auto &LocalAddrPair : LocalAddrs) { 622 if (LocalAddrPair.second.first) { 623 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() { 624 return LocalAddrPair.second.second; 625 }); 626 } 627 } 628 (void)LocalScope.Privatize(); 629 for (const auto &VLASizePair : VLASizes) 630 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second; 631 PGO.assignRegionCounters(GlobalDecl(CD), F); 632 CapturedStmtInfo->EmitBody(*this, CD->getBody()); 633 (void)LocalScope.ForceCleanup(); 634 FinishFunction(CD->getBodyRBrace()); 635 if (!NeedWrapperFunction) 636 return F; 637 638 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true, 639 /*RegisterCastedArgsOnly=*/true, 640 CapturedStmtInfo->getHelperName(), Loc); 641 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true); 642 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo; 643 Args.clear(); 644 LocalAddrs.clear(); 645 VLASizes.clear(); 646 llvm::Function *WrapperF = 647 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes, 648 WrapperCGF.CXXThisValue, WrapperFO); 649 llvm::SmallVector<llvm::Value *, 4> CallArgs; 650 auto *PI = F->arg_begin(); 651 for (const auto *Arg : Args) { 652 llvm::Value *CallArg; 653 auto I = LocalAddrs.find(Arg); 654 if (I != LocalAddrs.end()) { 655 LValue LV = WrapperCGF.MakeAddrLValue( 656 I->second.second, 657 I->second.first ? I->second.first->getType() : Arg->getType(), 658 AlignmentSource::Decl); 659 if (LV.getType()->isAnyComplexType()) 660 LV.setAddress(WrapperCGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 661 LV.getAddress(WrapperCGF), 662 PI->getType()->getPointerTo( 663 LV.getAddress(WrapperCGF).getAddressSpace()))); 664 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc()); 665 } else { 666 auto EI = VLASizes.find(Arg); 667 if (EI != VLASizes.end()) { 668 CallArg = EI->second.second; 669 } else { 670 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg), 671 Arg->getType(), 672 AlignmentSource::Decl); 673 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc()); 674 } 675 } 676 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType())); 677 ++PI; 678 } 679 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs); 680 WrapperCGF.FinishFunction(); 681 return WrapperF; 682 } 683 684 //===----------------------------------------------------------------------===// 685 // OpenMP Directive Emission 686 //===----------------------------------------------------------------------===// 687 void CodeGenFunction::EmitOMPAggregateAssign( 688 Address DestAddr, Address SrcAddr, QualType OriginalType, 689 const llvm::function_ref<void(Address, Address)> CopyGen) { 690 // Perform element-by-element initialization. 691 QualType ElementTy; 692 693 // Drill down to the base element type on both arrays. 694 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe(); 695 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr); 696 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); 697 698 llvm::Value *SrcBegin = SrcAddr.getPointer(); 699 llvm::Value *DestBegin = DestAddr.getPointer(); 700 // Cast from pointer to array type to pointer to single element. 701 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements); 702 // The basic structure here is a while-do loop. 703 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body"); 704 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done"); 705 llvm::Value *IsEmpty = 706 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty"); 707 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 708 709 // Enter the loop body, making that address the current address. 710 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 711 EmitBlock(BodyBB); 712 713 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy); 714 715 llvm::PHINode *SrcElementPHI = 716 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 717 SrcElementPHI->addIncoming(SrcBegin, EntryBB); 718 Address SrcElementCurrent = 719 Address(SrcElementPHI, 720 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 721 722 llvm::PHINode *DestElementPHI = 723 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); 724 DestElementPHI->addIncoming(DestBegin, EntryBB); 725 Address DestElementCurrent = 726 Address(DestElementPHI, 727 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 728 729 // Emit copy. 730 CopyGen(DestElementCurrent, SrcElementCurrent); 731 732 // Shift the address forward by one element. 733 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32( 734 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 735 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32( 736 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element"); 737 // Check whether we've reached the end. 738 llvm::Value *Done = 739 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 740 Builder.CreateCondBr(Done, DoneBB, BodyBB); 741 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock()); 742 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock()); 743 744 // Done. 745 EmitBlock(DoneBB, /*IsFinished=*/true); 746 } 747 748 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr, 749 Address SrcAddr, const VarDecl *DestVD, 750 const VarDecl *SrcVD, const Expr *Copy) { 751 if (OriginalType->isArrayType()) { 752 const auto *BO = dyn_cast<BinaryOperator>(Copy); 753 if (BO && BO->getOpcode() == BO_Assign) { 754 // Perform simple memcpy for simple copying. 755 LValue Dest = MakeAddrLValue(DestAddr, OriginalType); 756 LValue Src = MakeAddrLValue(SrcAddr, OriginalType); 757 EmitAggregateAssign(Dest, Src, OriginalType); 758 } else { 759 // For arrays with complex element types perform element by element 760 // copying. 761 EmitOMPAggregateAssign( 762 DestAddr, SrcAddr, OriginalType, 763 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) { 764 // Working with the single array element, so have to remap 765 // destination and source variables to corresponding array 766 // elements. 767 CodeGenFunction::OMPPrivateScope Remap(*this); 768 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; }); 769 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; }); 770 (void)Remap.Privatize(); 771 EmitIgnoredExpr(Copy); 772 }); 773 } 774 } else { 775 // Remap pseudo source variable to private copy. 776 CodeGenFunction::OMPPrivateScope Remap(*this); 777 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; }); 778 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; }); 779 (void)Remap.Privatize(); 780 // Emit copying of the whole variable. 781 EmitIgnoredExpr(Copy); 782 } 783 } 784 785 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 786 OMPPrivateScope &PrivateScope) { 787 if (!HaveInsertPoint()) 788 return false; 789 bool DeviceConstTarget = 790 getLangOpts().OpenMPIsDevice && 791 isOpenMPTargetExecutionDirective(D.getDirectiveKind()); 792 bool FirstprivateIsLastprivate = false; 793 llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates; 794 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 795 for (const auto *D : C->varlists()) 796 Lastprivates.try_emplace( 797 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(), 798 C->getKind()); 799 } 800 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate; 801 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 802 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind()); 803 // Force emission of the firstprivate copy if the directive does not emit 804 // outlined function, like omp for, omp simd, omp distribute etc. 805 bool MustEmitFirstprivateCopy = 806 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown; 807 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 808 const auto *IRef = C->varlist_begin(); 809 const auto *InitsRef = C->inits().begin(); 810 for (const Expr *IInit : C->private_copies()) { 811 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 812 bool ThisFirstprivateIsLastprivate = 813 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0; 814 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD); 815 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 816 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD && 817 !FD->getType()->isReferenceType() && 818 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) { 819 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()); 820 ++IRef; 821 ++InitsRef; 822 continue; 823 } 824 // Do not emit copy for firstprivate constant variables in target regions, 825 // captured by reference. 826 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) && 827 FD && FD->getType()->isReferenceType() && 828 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) { 829 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this, 830 OrigVD); 831 ++IRef; 832 ++InitsRef; 833 continue; 834 } 835 FirstprivateIsLastprivate = 836 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate; 837 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) { 838 const auto *VDInit = 839 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl()); 840 bool IsRegistered; 841 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 842 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr, 843 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 844 LValue OriginalLVal; 845 if (!FD) { 846 // Check if the firstprivate variable is just a constant value. 847 ConstantEmission CE = tryEmitAsConstant(&DRE); 848 if (CE && !CE.isReference()) { 849 // Constant value, no need to create a copy. 850 ++IRef; 851 ++InitsRef; 852 continue; 853 } 854 if (CE && CE.isReference()) { 855 OriginalLVal = CE.getReferenceLValue(*this, &DRE); 856 } else { 857 assert(!CE && "Expected non-constant firstprivate."); 858 OriginalLVal = EmitLValue(&DRE); 859 } 860 } else { 861 OriginalLVal = EmitLValue(&DRE); 862 } 863 QualType Type = VD->getType(); 864 if (Type->isArrayType()) { 865 // Emit VarDecl with copy init for arrays. 866 // Get the address of the original variable captured in current 867 // captured region. 868 IsRegistered = PrivateScope.addPrivate( 869 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() { 870 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 871 const Expr *Init = VD->getInit(); 872 if (!isa<CXXConstructExpr>(Init) || 873 isTrivialInitializer(Init)) { 874 // Perform simple memcpy. 875 LValue Dest = 876 MakeAddrLValue(Emission.getAllocatedAddress(), Type); 877 EmitAggregateAssign(Dest, OriginalLVal, Type); 878 } else { 879 EmitOMPAggregateAssign( 880 Emission.getAllocatedAddress(), 881 OriginalLVal.getAddress(*this), Type, 882 [this, VDInit, Init](Address DestElement, 883 Address SrcElement) { 884 // Clean up any temporaries needed by the 885 // initialization. 886 RunCleanupsScope InitScope(*this); 887 // Emit initialization for single element. 888 setAddrOfLocalVar(VDInit, SrcElement); 889 EmitAnyExprToMem(Init, DestElement, 890 Init->getType().getQualifiers(), 891 /*IsInitializer*/ false); 892 LocalDeclMap.erase(VDInit); 893 }); 894 } 895 EmitAutoVarCleanups(Emission); 896 return Emission.getAllocatedAddress(); 897 }); 898 } else { 899 Address OriginalAddr = OriginalLVal.getAddress(*this); 900 IsRegistered = 901 PrivateScope.addPrivate(OrigVD, [this, VDInit, OriginalAddr, VD, 902 ThisFirstprivateIsLastprivate, 903 OrigVD, &Lastprivates, IRef]() { 904 // Emit private VarDecl with copy init. 905 // Remap temp VDInit variable to the address of the original 906 // variable (for proper handling of captured global variables). 907 setAddrOfLocalVar(VDInit, OriginalAddr); 908 EmitDecl(*VD); 909 LocalDeclMap.erase(VDInit); 910 if (ThisFirstprivateIsLastprivate && 911 Lastprivates[OrigVD->getCanonicalDecl()] == 912 OMPC_LASTPRIVATE_conditional) { 913 // Create/init special variable for lastprivate conditionals. 914 Address VDAddr = 915 CGM.getOpenMPRuntime().emitLastprivateConditionalInit( 916 *this, OrigVD); 917 llvm::Value *V = EmitLoadOfScalar( 918 MakeAddrLValue(GetAddrOfLocalVar(VD), (*IRef)->getType(), 919 AlignmentSource::Decl), 920 (*IRef)->getExprLoc()); 921 EmitStoreOfScalar(V, 922 MakeAddrLValue(VDAddr, (*IRef)->getType(), 923 AlignmentSource::Decl)); 924 LocalDeclMap.erase(VD); 925 setAddrOfLocalVar(VD, VDAddr); 926 return VDAddr; 927 } 928 return GetAddrOfLocalVar(VD); 929 }); 930 } 931 assert(IsRegistered && 932 "firstprivate var already registered as private"); 933 // Silence the warning about unused variable. 934 (void)IsRegistered; 935 } 936 ++IRef; 937 ++InitsRef; 938 } 939 } 940 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty(); 941 } 942 943 void CodeGenFunction::EmitOMPPrivateClause( 944 const OMPExecutableDirective &D, 945 CodeGenFunction::OMPPrivateScope &PrivateScope) { 946 if (!HaveInsertPoint()) 947 return; 948 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 949 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) { 950 auto IRef = C->varlist_begin(); 951 for (const Expr *IInit : C->private_copies()) { 952 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 953 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 954 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 955 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() { 956 // Emit private VarDecl with copy init. 957 EmitDecl(*VD); 958 return GetAddrOfLocalVar(VD); 959 }); 960 assert(IsRegistered && "private var already registered as private"); 961 // Silence the warning about unused variable. 962 (void)IsRegistered; 963 } 964 ++IRef; 965 } 966 } 967 } 968 969 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) { 970 if (!HaveInsertPoint()) 971 return false; 972 // threadprivate_var1 = master_threadprivate_var1; 973 // operator=(threadprivate_var2, master_threadprivate_var2); 974 // ... 975 // __kmpc_barrier(&loc, global_tid); 976 llvm::DenseSet<const VarDecl *> CopiedVars; 977 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr; 978 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) { 979 auto IRef = C->varlist_begin(); 980 auto ISrcRef = C->source_exprs().begin(); 981 auto IDestRef = C->destination_exprs().begin(); 982 for (const Expr *AssignOp : C->assignment_ops()) { 983 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 984 QualType Type = VD->getType(); 985 if (CopiedVars.insert(VD->getCanonicalDecl()).second) { 986 // Get the address of the master variable. If we are emitting code with 987 // TLS support, the address is passed from the master as field in the 988 // captured declaration. 989 Address MasterAddr = Address::invalid(); 990 if (getLangOpts().OpenMPUseTLS && 991 getContext().getTargetInfo().isTLSSupported()) { 992 assert(CapturedStmtInfo->lookup(VD) && 993 "Copyin threadprivates should have been captured!"); 994 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true, 995 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 996 MasterAddr = EmitLValue(&DRE).getAddress(*this); 997 LocalDeclMap.erase(VD); 998 } else { 999 MasterAddr = 1000 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD) 1001 : CGM.GetAddrOfGlobal(VD), 1002 getContext().getDeclAlign(VD)); 1003 } 1004 // Get the address of the threadprivate variable. 1005 Address PrivateAddr = EmitLValue(*IRef).getAddress(*this); 1006 if (CopiedVars.size() == 1) { 1007 // At first check if current thread is a master thread. If it is, no 1008 // need to copy data. 1009 CopyBegin = createBasicBlock("copyin.not.master"); 1010 CopyEnd = createBasicBlock("copyin.not.master.end"); 1011 // TODO: Avoid ptrtoint conversion. 1012 auto *MasterAddrInt = 1013 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy); 1014 auto *PrivateAddrInt = 1015 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy); 1016 Builder.CreateCondBr( 1017 Builder.CreateICmpNE(MasterAddrInt, PrivateAddrInt), CopyBegin, 1018 CopyEnd); 1019 EmitBlock(CopyBegin); 1020 } 1021 const auto *SrcVD = 1022 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 1023 const auto *DestVD = 1024 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1025 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp); 1026 } 1027 ++IRef; 1028 ++ISrcRef; 1029 ++IDestRef; 1030 } 1031 } 1032 if (CopyEnd) { 1033 // Exit out of copying procedure for non-master thread. 1034 EmitBlock(CopyEnd, /*IsFinished=*/true); 1035 return true; 1036 } 1037 return false; 1038 } 1039 1040 bool CodeGenFunction::EmitOMPLastprivateClauseInit( 1041 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) { 1042 if (!HaveInsertPoint()) 1043 return false; 1044 bool HasAtLeastOneLastprivate = false; 1045 llvm::DenseSet<const VarDecl *> SIMDLCVs; 1046 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 1047 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 1048 for (const Expr *C : LoopDirective->counters()) { 1049 SIMDLCVs.insert( 1050 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 1051 } 1052 } 1053 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 1054 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 1055 HasAtLeastOneLastprivate = true; 1056 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) && 1057 !getLangOpts().OpenMPSimd) 1058 break; 1059 const auto *IRef = C->varlist_begin(); 1060 const auto *IDestRef = C->destination_exprs().begin(); 1061 for (const Expr *IInit : C->private_copies()) { 1062 // Keep the address of the original variable for future update at the end 1063 // of the loop. 1064 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1065 // Taskloops do not require additional initialization, it is done in 1066 // runtime support library. 1067 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) { 1068 const auto *DestVD = 1069 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1070 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() { 1071 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 1072 /*RefersToEnclosingVariableOrCapture=*/ 1073 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1074 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 1075 return EmitLValue(&DRE).getAddress(*this); 1076 }); 1077 // Check if the variable is also a firstprivate: in this case IInit is 1078 // not generated. Initialization of this variable will happen in codegen 1079 // for 'firstprivate' clause. 1080 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) { 1081 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 1082 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD, C, 1083 OrigVD]() { 1084 if (C->getKind() == OMPC_LASTPRIVATE_conditional) { 1085 Address VDAddr = 1086 CGM.getOpenMPRuntime().emitLastprivateConditionalInit(*this, 1087 OrigVD); 1088 setAddrOfLocalVar(VD, VDAddr); 1089 return VDAddr; 1090 } 1091 // Emit private VarDecl with copy init. 1092 EmitDecl(*VD); 1093 return GetAddrOfLocalVar(VD); 1094 }); 1095 assert(IsRegistered && 1096 "lastprivate var already registered as private"); 1097 (void)IsRegistered; 1098 } 1099 } 1100 ++IRef; 1101 ++IDestRef; 1102 } 1103 } 1104 return HasAtLeastOneLastprivate; 1105 } 1106 1107 void CodeGenFunction::EmitOMPLastprivateClauseFinal( 1108 const OMPExecutableDirective &D, bool NoFinals, 1109 llvm::Value *IsLastIterCond) { 1110 if (!HaveInsertPoint()) 1111 return; 1112 // Emit following code: 1113 // if (<IsLastIterCond>) { 1114 // orig_var1 = private_orig_var1; 1115 // ... 1116 // orig_varn = private_orig_varn; 1117 // } 1118 llvm::BasicBlock *ThenBB = nullptr; 1119 llvm::BasicBlock *DoneBB = nullptr; 1120 if (IsLastIterCond) { 1121 // Emit implicit barrier if at least one lastprivate conditional is found 1122 // and this is not a simd mode. 1123 if (!getLangOpts().OpenMPSimd && 1124 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(), 1125 [](const OMPLastprivateClause *C) { 1126 return C->getKind() == OMPC_LASTPRIVATE_conditional; 1127 })) { 1128 CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(), 1129 OMPD_unknown, 1130 /*EmitChecks=*/false, 1131 /*ForceSimpleCall=*/true); 1132 } 1133 ThenBB = createBasicBlock(".omp.lastprivate.then"); 1134 DoneBB = createBasicBlock(".omp.lastprivate.done"); 1135 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB); 1136 EmitBlock(ThenBB); 1137 } 1138 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 1139 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates; 1140 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) { 1141 auto IC = LoopDirective->counters().begin(); 1142 for (const Expr *F : LoopDirective->finals()) { 1143 const auto *D = 1144 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl(); 1145 if (NoFinals) 1146 AlreadyEmittedVars.insert(D); 1147 else 1148 LoopCountersAndUpdates[D] = F; 1149 ++IC; 1150 } 1151 } 1152 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 1153 auto IRef = C->varlist_begin(); 1154 auto ISrcRef = C->source_exprs().begin(); 1155 auto IDestRef = C->destination_exprs().begin(); 1156 for (const Expr *AssignOp : C->assignment_ops()) { 1157 const auto *PrivateVD = 1158 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1159 QualType Type = PrivateVD->getType(); 1160 const auto *CanonicalVD = PrivateVD->getCanonicalDecl(); 1161 if (AlreadyEmittedVars.insert(CanonicalVD).second) { 1162 // If lastprivate variable is a loop control variable for loop-based 1163 // directive, update its value before copyin back to original 1164 // variable. 1165 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) 1166 EmitIgnoredExpr(FinalExpr); 1167 const auto *SrcVD = 1168 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 1169 const auto *DestVD = 1170 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1171 // Get the address of the private variable. 1172 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD); 1173 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>()) 1174 PrivateAddr = 1175 Address(Builder.CreateLoad(PrivateAddr), 1176 CGM.getNaturalTypeAlignment(RefTy->getPointeeType())); 1177 // Store the last value to the private copy in the last iteration. 1178 if (C->getKind() == OMPC_LASTPRIVATE_conditional) 1179 CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate( 1180 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD, 1181 (*IRef)->getExprLoc()); 1182 // Get the address of the original variable. 1183 Address OriginalAddr = GetAddrOfLocalVar(DestVD); 1184 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp); 1185 } 1186 ++IRef; 1187 ++ISrcRef; 1188 ++IDestRef; 1189 } 1190 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 1191 EmitIgnoredExpr(PostUpdate); 1192 } 1193 if (IsLastIterCond) 1194 EmitBlock(DoneBB, /*IsFinished=*/true); 1195 } 1196 1197 void CodeGenFunction::EmitOMPReductionClauseInit( 1198 const OMPExecutableDirective &D, 1199 CodeGenFunction::OMPPrivateScope &PrivateScope, bool ForInscan) { 1200 if (!HaveInsertPoint()) 1201 return; 1202 SmallVector<const Expr *, 4> Shareds; 1203 SmallVector<const Expr *, 4> Privates; 1204 SmallVector<const Expr *, 4> ReductionOps; 1205 SmallVector<const Expr *, 4> LHSs; 1206 SmallVector<const Expr *, 4> RHSs; 1207 OMPTaskDataTy Data; 1208 SmallVector<const Expr *, 4> TaskLHSs; 1209 SmallVector<const Expr *, 4> TaskRHSs; 1210 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1211 if (ForInscan != (C->getModifier() == OMPC_REDUCTION_inscan)) 1212 continue; 1213 Shareds.append(C->varlist_begin(), C->varlist_end()); 1214 Privates.append(C->privates().begin(), C->privates().end()); 1215 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 1216 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1217 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1218 if (C->getModifier() == OMPC_REDUCTION_task) { 1219 Data.ReductionVars.append(C->privates().begin(), C->privates().end()); 1220 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 1221 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 1222 Data.ReductionOps.append(C->reduction_ops().begin(), 1223 C->reduction_ops().end()); 1224 TaskLHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1225 TaskRHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1226 } 1227 } 1228 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps); 1229 unsigned Count = 0; 1230 auto *ILHS = LHSs.begin(); 1231 auto *IRHS = RHSs.begin(); 1232 auto *IPriv = Privates.begin(); 1233 for (const Expr *IRef : Shareds) { 1234 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl()); 1235 // Emit private VarDecl with reduction init. 1236 RedCG.emitSharedOrigLValue(*this, Count); 1237 RedCG.emitAggregateType(*this, Count); 1238 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD); 1239 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(), 1240 RedCG.getSharedLValue(Count), 1241 [&Emission](CodeGenFunction &CGF) { 1242 CGF.EmitAutoVarInit(Emission); 1243 return true; 1244 }); 1245 EmitAutoVarCleanups(Emission); 1246 Address BaseAddr = RedCG.adjustPrivateAddress( 1247 *this, Count, Emission.getAllocatedAddress()); 1248 bool IsRegistered = PrivateScope.addPrivate( 1249 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; }); 1250 assert(IsRegistered && "private var already registered as private"); 1251 // Silence the warning about unused variable. 1252 (void)IsRegistered; 1253 1254 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 1255 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 1256 QualType Type = PrivateVD->getType(); 1257 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef); 1258 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) { 1259 // Store the address of the original variable associated with the LHS 1260 // implicit variable. 1261 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() { 1262 return RedCG.getSharedLValue(Count).getAddress(*this); 1263 }); 1264 PrivateScope.addPrivate( 1265 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); }); 1266 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) || 1267 isa<ArraySubscriptExpr>(IRef)) { 1268 // Store the address of the original variable associated with the LHS 1269 // implicit variable. 1270 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() { 1271 return RedCG.getSharedLValue(Count).getAddress(*this); 1272 }); 1273 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() { 1274 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD), 1275 ConvertTypeForMem(RHSVD->getType()), 1276 "rhs.begin"); 1277 }); 1278 } else { 1279 QualType Type = PrivateVD->getType(); 1280 bool IsArray = getContext().getAsArrayType(Type) != nullptr; 1281 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this); 1282 // Store the address of the original variable associated with the LHS 1283 // implicit variable. 1284 if (IsArray) { 1285 OriginalAddr = Builder.CreateElementBitCast( 1286 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin"); 1287 } 1288 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; }); 1289 PrivateScope.addPrivate( 1290 RHSVD, [this, PrivateVD, RHSVD, IsArray]() { 1291 return IsArray 1292 ? Builder.CreateElementBitCast( 1293 GetAddrOfLocalVar(PrivateVD), 1294 ConvertTypeForMem(RHSVD->getType()), "rhs.begin") 1295 : GetAddrOfLocalVar(PrivateVD); 1296 }); 1297 } 1298 ++ILHS; 1299 ++IRHS; 1300 ++IPriv; 1301 ++Count; 1302 } 1303 if (!Data.ReductionVars.empty()) { 1304 Data.IsReductionWithTaskMod = true; 1305 Data.IsWorksharingReduction = 1306 isOpenMPWorksharingDirective(D.getDirectiveKind()); 1307 llvm::Value *ReductionDesc = CGM.getOpenMPRuntime().emitTaskReductionInit( 1308 *this, D.getBeginLoc(), TaskLHSs, TaskRHSs, Data); 1309 const Expr *TaskRedRef = nullptr; 1310 switch (D.getDirectiveKind()) { 1311 case OMPD_parallel: 1312 TaskRedRef = cast<OMPParallelDirective>(D).getTaskReductionRefExpr(); 1313 break; 1314 case OMPD_for: 1315 TaskRedRef = cast<OMPForDirective>(D).getTaskReductionRefExpr(); 1316 break; 1317 case OMPD_sections: 1318 TaskRedRef = cast<OMPSectionsDirective>(D).getTaskReductionRefExpr(); 1319 break; 1320 case OMPD_parallel_for: 1321 TaskRedRef = cast<OMPParallelForDirective>(D).getTaskReductionRefExpr(); 1322 break; 1323 case OMPD_parallel_master: 1324 TaskRedRef = 1325 cast<OMPParallelMasterDirective>(D).getTaskReductionRefExpr(); 1326 break; 1327 case OMPD_parallel_sections: 1328 TaskRedRef = 1329 cast<OMPParallelSectionsDirective>(D).getTaskReductionRefExpr(); 1330 break; 1331 case OMPD_target_parallel: 1332 TaskRedRef = 1333 cast<OMPTargetParallelDirective>(D).getTaskReductionRefExpr(); 1334 break; 1335 case OMPD_target_parallel_for: 1336 TaskRedRef = 1337 cast<OMPTargetParallelForDirective>(D).getTaskReductionRefExpr(); 1338 break; 1339 case OMPD_distribute_parallel_for: 1340 TaskRedRef = 1341 cast<OMPDistributeParallelForDirective>(D).getTaskReductionRefExpr(); 1342 break; 1343 case OMPD_teams_distribute_parallel_for: 1344 TaskRedRef = cast<OMPTeamsDistributeParallelForDirective>(D) 1345 .getTaskReductionRefExpr(); 1346 break; 1347 case OMPD_target_teams_distribute_parallel_for: 1348 TaskRedRef = cast<OMPTargetTeamsDistributeParallelForDirective>(D) 1349 .getTaskReductionRefExpr(); 1350 break; 1351 case OMPD_simd: 1352 case OMPD_for_simd: 1353 case OMPD_section: 1354 case OMPD_single: 1355 case OMPD_master: 1356 case OMPD_critical: 1357 case OMPD_parallel_for_simd: 1358 case OMPD_task: 1359 case OMPD_taskyield: 1360 case OMPD_barrier: 1361 case OMPD_taskwait: 1362 case OMPD_taskgroup: 1363 case OMPD_flush: 1364 case OMPD_depobj: 1365 case OMPD_scan: 1366 case OMPD_ordered: 1367 case OMPD_atomic: 1368 case OMPD_teams: 1369 case OMPD_target: 1370 case OMPD_cancellation_point: 1371 case OMPD_cancel: 1372 case OMPD_target_data: 1373 case OMPD_target_enter_data: 1374 case OMPD_target_exit_data: 1375 case OMPD_taskloop: 1376 case OMPD_taskloop_simd: 1377 case OMPD_master_taskloop: 1378 case OMPD_master_taskloop_simd: 1379 case OMPD_parallel_master_taskloop: 1380 case OMPD_parallel_master_taskloop_simd: 1381 case OMPD_distribute: 1382 case OMPD_target_update: 1383 case OMPD_distribute_parallel_for_simd: 1384 case OMPD_distribute_simd: 1385 case OMPD_target_parallel_for_simd: 1386 case OMPD_target_simd: 1387 case OMPD_teams_distribute: 1388 case OMPD_teams_distribute_simd: 1389 case OMPD_teams_distribute_parallel_for_simd: 1390 case OMPD_target_teams: 1391 case OMPD_target_teams_distribute: 1392 case OMPD_target_teams_distribute_parallel_for_simd: 1393 case OMPD_target_teams_distribute_simd: 1394 case OMPD_declare_target: 1395 case OMPD_end_declare_target: 1396 case OMPD_threadprivate: 1397 case OMPD_allocate: 1398 case OMPD_declare_reduction: 1399 case OMPD_declare_mapper: 1400 case OMPD_declare_simd: 1401 case OMPD_requires: 1402 case OMPD_declare_variant: 1403 case OMPD_begin_declare_variant: 1404 case OMPD_end_declare_variant: 1405 case OMPD_unknown: 1406 default: 1407 llvm_unreachable("Enexpected directive with task reductions."); 1408 } 1409 1410 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(TaskRedRef)->getDecl()); 1411 EmitVarDecl(*VD); 1412 EmitStoreOfScalar(ReductionDesc, GetAddrOfLocalVar(VD), 1413 /*Volatile=*/false, TaskRedRef->getType()); 1414 } 1415 } 1416 1417 void CodeGenFunction::EmitOMPReductionClauseFinal( 1418 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) { 1419 if (!HaveInsertPoint()) 1420 return; 1421 llvm::SmallVector<const Expr *, 8> Privates; 1422 llvm::SmallVector<const Expr *, 8> LHSExprs; 1423 llvm::SmallVector<const Expr *, 8> RHSExprs; 1424 llvm::SmallVector<const Expr *, 8> ReductionOps; 1425 bool HasAtLeastOneReduction = false; 1426 bool IsReductionWithTaskMod = false; 1427 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1428 // Do not emit for inscan reductions. 1429 if (C->getModifier() == OMPC_REDUCTION_inscan) 1430 continue; 1431 HasAtLeastOneReduction = true; 1432 Privates.append(C->privates().begin(), C->privates().end()); 1433 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1434 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1435 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 1436 IsReductionWithTaskMod = 1437 IsReductionWithTaskMod || C->getModifier() == OMPC_REDUCTION_task; 1438 } 1439 if (HasAtLeastOneReduction) { 1440 if (IsReductionWithTaskMod) { 1441 CGM.getOpenMPRuntime().emitTaskReductionFini( 1442 *this, D.getBeginLoc(), 1443 isOpenMPWorksharingDirective(D.getDirectiveKind())); 1444 } 1445 bool WithNowait = D.getSingleClause<OMPNowaitClause>() || 1446 isOpenMPParallelDirective(D.getDirectiveKind()) || 1447 ReductionKind == OMPD_simd; 1448 bool SimpleReduction = ReductionKind == OMPD_simd; 1449 // Emit nowait reduction if nowait clause is present or directive is a 1450 // parallel directive (it always has implicit barrier). 1451 CGM.getOpenMPRuntime().emitReduction( 1452 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps, 1453 {WithNowait, SimpleReduction, ReductionKind}); 1454 } 1455 } 1456 1457 static void emitPostUpdateForReductionClause( 1458 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1459 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 1460 if (!CGF.HaveInsertPoint()) 1461 return; 1462 llvm::BasicBlock *DoneBB = nullptr; 1463 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1464 if (const Expr *PostUpdate = C->getPostUpdateExpr()) { 1465 if (!DoneBB) { 1466 if (llvm::Value *Cond = CondGen(CGF)) { 1467 // If the first post-update expression is found, emit conditional 1468 // block if it was requested. 1469 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu"); 1470 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done"); 1471 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1472 CGF.EmitBlock(ThenBB); 1473 } 1474 } 1475 CGF.EmitIgnoredExpr(PostUpdate); 1476 } 1477 } 1478 if (DoneBB) 1479 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 1480 } 1481 1482 namespace { 1483 /// Codegen lambda for appending distribute lower and upper bounds to outlined 1484 /// parallel function. This is necessary for combined constructs such as 1485 /// 'distribute parallel for' 1486 typedef llvm::function_ref<void(CodeGenFunction &, 1487 const OMPExecutableDirective &, 1488 llvm::SmallVectorImpl<llvm::Value *> &)> 1489 CodeGenBoundParametersTy; 1490 } // anonymous namespace 1491 1492 static void 1493 checkForLastprivateConditionalUpdate(CodeGenFunction &CGF, 1494 const OMPExecutableDirective &S) { 1495 if (CGF.getLangOpts().OpenMP < 50) 1496 return; 1497 llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls; 1498 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 1499 for (const Expr *Ref : C->varlists()) { 1500 if (!Ref->getType()->isScalarType()) 1501 continue; 1502 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1503 if (!DRE) 1504 continue; 1505 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1506 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1507 } 1508 } 1509 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 1510 for (const Expr *Ref : C->varlists()) { 1511 if (!Ref->getType()->isScalarType()) 1512 continue; 1513 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1514 if (!DRE) 1515 continue; 1516 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1517 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1518 } 1519 } 1520 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) { 1521 for (const Expr *Ref : C->varlists()) { 1522 if (!Ref->getType()->isScalarType()) 1523 continue; 1524 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1525 if (!DRE) 1526 continue; 1527 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1528 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1529 } 1530 } 1531 // Privates should ne analyzed since they are not captured at all. 1532 // Task reductions may be skipped - tasks are ignored. 1533 // Firstprivates do not return value but may be passed by reference - no need 1534 // to check for updated lastprivate conditional. 1535 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 1536 for (const Expr *Ref : C->varlists()) { 1537 if (!Ref->getType()->isScalarType()) 1538 continue; 1539 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1540 if (!DRE) 1541 continue; 1542 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1543 } 1544 } 1545 CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional( 1546 CGF, S, PrivateDecls); 1547 } 1548 1549 static void emitCommonOMPParallelDirective( 1550 CodeGenFunction &CGF, const OMPExecutableDirective &S, 1551 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1552 const CodeGenBoundParametersTy &CodeGenBoundParameters) { 1553 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1554 llvm::Function *OutlinedFn = 1555 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction( 1556 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 1557 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) { 1558 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 1559 llvm::Value *NumThreads = 1560 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 1561 /*IgnoreResultAssign=*/true); 1562 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause( 1563 CGF, NumThreads, NumThreadsClause->getBeginLoc()); 1564 } 1565 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) { 1566 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF); 1567 CGF.CGM.getOpenMPRuntime().emitProcBindClause( 1568 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc()); 1569 } 1570 const Expr *IfCond = nullptr; 1571 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 1572 if (C->getNameModifier() == OMPD_unknown || 1573 C->getNameModifier() == OMPD_parallel) { 1574 IfCond = C->getCondition(); 1575 break; 1576 } 1577 } 1578 1579 OMPParallelScope Scope(CGF, S); 1580 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 1581 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk 1582 // lower and upper bounds with the pragma 'for' chunking mechanism. 1583 // The following lambda takes care of appending the lower and upper bound 1584 // parameters when necessary 1585 CodeGenBoundParameters(CGF, S, CapturedVars); 1586 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 1587 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn, 1588 CapturedVars, IfCond); 1589 } 1590 1591 static bool isAllocatableDecl(const VarDecl *VD) { 1592 const VarDecl *CVD = VD->getCanonicalDecl(); 1593 if (!CVD->hasAttr<OMPAllocateDeclAttr>()) 1594 return false; 1595 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>(); 1596 // Use the default allocation. 1597 return !((AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc || 1598 AA->getAllocatorType() == OMPAllocateDeclAttr::OMPNullMemAlloc) && 1599 !AA->getAllocator()); 1600 } 1601 1602 static void emitEmptyBoundParameters(CodeGenFunction &, 1603 const OMPExecutableDirective &, 1604 llvm::SmallVectorImpl<llvm::Value *> &) {} 1605 1606 Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable( 1607 CodeGenFunction &CGF, const VarDecl *VD) { 1608 CodeGenModule &CGM = CGF.CGM; 1609 auto &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1610 1611 if (!VD) 1612 return Address::invalid(); 1613 const VarDecl *CVD = VD->getCanonicalDecl(); 1614 if (!isAllocatableDecl(CVD)) 1615 return Address::invalid(); 1616 llvm::Value *Size; 1617 CharUnits Align = CGM.getContext().getDeclAlign(CVD); 1618 if (CVD->getType()->isVariablyModifiedType()) { 1619 Size = CGF.getTypeSize(CVD->getType()); 1620 // Align the size: ((size + align - 1) / align) * align 1621 Size = CGF.Builder.CreateNUWAdd( 1622 Size, CGM.getSize(Align - CharUnits::fromQuantity(1))); 1623 Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align)); 1624 Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align)); 1625 } else { 1626 CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType()); 1627 Size = CGM.getSize(Sz.alignTo(Align)); 1628 } 1629 1630 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>(); 1631 assert(AA->getAllocator() && 1632 "Expected allocator expression for non-default allocator."); 1633 llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator()); 1634 // According to the standard, the original allocator type is a enum (integer). 1635 // Convert to pointer type, if required. 1636 if (Allocator->getType()->isIntegerTy()) 1637 Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy); 1638 else if (Allocator->getType()->isPointerTy()) 1639 Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator, 1640 CGM.VoidPtrTy); 1641 1642 llvm::Value *Addr = OMPBuilder.createOMPAlloc( 1643 CGF.Builder, Size, Allocator, 1644 getNameWithSeparators({CVD->getName(), ".void.addr"}, ".", ".")); 1645 llvm::CallInst *FreeCI = 1646 OMPBuilder.createOMPFree(CGF.Builder, Addr, Allocator); 1647 1648 CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FreeCI); 1649 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 1650 Addr, 1651 CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())), 1652 getNameWithSeparators({CVD->getName(), ".addr"}, ".", ".")); 1653 return Address(Addr, Align); 1654 } 1655 1656 Address CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate( 1657 CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, 1658 SourceLocation Loc) { 1659 CodeGenModule &CGM = CGF.CGM; 1660 if (CGM.getLangOpts().OpenMPUseTLS && 1661 CGM.getContext().getTargetInfo().isTLSSupported()) 1662 return VDAddr; 1663 1664 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1665 1666 llvm::Type *VarTy = VDAddr.getElementType(); 1667 llvm::Value *Data = 1668 CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.Int8PtrTy); 1669 llvm::ConstantInt *Size = CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)); 1670 std::string Suffix = getNameWithSeparators({"cache", ""}); 1671 llvm::Twine CacheName = Twine(CGM.getMangledName(VD)).concat(Suffix); 1672 1673 llvm::CallInst *ThreadPrivateCacheCall = 1674 OMPBuilder.createCachedThreadPrivate(CGF.Builder, Data, Size, CacheName); 1675 1676 return Address(ThreadPrivateCacheCall, VDAddr.getAlignment()); 1677 } 1678 1679 std::string CodeGenFunction::OMPBuilderCBHelpers::getNameWithSeparators( 1680 ArrayRef<StringRef> Parts, StringRef FirstSeparator, StringRef Separator) { 1681 SmallString<128> Buffer; 1682 llvm::raw_svector_ostream OS(Buffer); 1683 StringRef Sep = FirstSeparator; 1684 for (StringRef Part : Parts) { 1685 OS << Sep << Part; 1686 Sep = Separator; 1687 } 1688 return OS.str().str(); 1689 } 1690 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) { 1691 if (CGM.getLangOpts().OpenMPIRBuilder) { 1692 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1693 // Check if we have any if clause associated with the directive. 1694 llvm::Value *IfCond = nullptr; 1695 if (const auto *C = S.getSingleClause<OMPIfClause>()) 1696 IfCond = EmitScalarExpr(C->getCondition(), 1697 /*IgnoreResultAssign=*/true); 1698 1699 llvm::Value *NumThreads = nullptr; 1700 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) 1701 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(), 1702 /*IgnoreResultAssign=*/true); 1703 1704 ProcBindKind ProcBind = OMP_PROC_BIND_default; 1705 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) 1706 ProcBind = ProcBindClause->getProcBindKind(); 1707 1708 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 1709 1710 // The cleanup callback that finalizes all variabels at the given location, 1711 // thus calls destructors etc. 1712 auto FiniCB = [this](InsertPointTy IP) { 1713 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 1714 }; 1715 1716 // Privatization callback that performs appropriate action for 1717 // shared/private/firstprivate/lastprivate/copyin/... variables. 1718 // 1719 // TODO: This defaults to shared right now. 1720 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1721 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) { 1722 // The next line is appropriate only for variables (Val) with the 1723 // data-sharing attribute "shared". 1724 ReplVal = &Val; 1725 1726 return CodeGenIP; 1727 }; 1728 1729 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1730 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt(); 1731 1732 auto BodyGenCB = [ParallelRegionBodyStmt, 1733 this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1734 llvm::BasicBlock &ContinuationBB) { 1735 OMPBuilderCBHelpers::OutlinedRegionBodyRAII ORB(*this, AllocaIP, 1736 ContinuationBB); 1737 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, ParallelRegionBodyStmt, 1738 CodeGenIP, ContinuationBB); 1739 }; 1740 1741 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 1742 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 1743 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP( 1744 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator()); 1745 Builder.restoreIP( 1746 OMPBuilder.createParallel(Builder, AllocaIP, BodyGenCB, PrivCB, FiniCB, 1747 IfCond, NumThreads, ProcBind, S.hasCancel())); 1748 return; 1749 } 1750 1751 // Emit parallel region as a standalone region. 1752 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 1753 Action.Enter(CGF); 1754 OMPPrivateScope PrivateScope(CGF); 1755 bool Copyins = CGF.EmitOMPCopyinClause(S); 1756 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 1757 if (Copyins) { 1758 // Emit implicit barrier to synchronize threads and avoid data races on 1759 // propagation master's thread values of threadprivate variables to local 1760 // instances of that variables of all other implicit threads. 1761 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 1762 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 1763 /*ForceSimpleCall=*/true); 1764 } 1765 CGF.EmitOMPPrivateClause(S, PrivateScope); 1766 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 1767 (void)PrivateScope.Privatize(); 1768 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt()); 1769 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 1770 }; 1771 { 1772 auto LPCRegion = 1773 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 1774 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen, 1775 emitEmptyBoundParameters); 1776 emitPostUpdateForReductionClause(*this, S, 1777 [](CodeGenFunction &) { return nullptr; }); 1778 } 1779 // Check for outer lastprivate conditional update. 1780 checkForLastprivateConditionalUpdate(*this, S); 1781 } 1782 1783 namespace { 1784 /// RAII to handle scopes for loop transformation directives. 1785 class OMPTransformDirectiveScopeRAII { 1786 OMPLoopScope *Scope = nullptr; 1787 CodeGenFunction::CGCapturedStmtInfo *CGSI = nullptr; 1788 CodeGenFunction::CGCapturedStmtRAII *CapInfoRAII = nullptr; 1789 1790 public: 1791 OMPTransformDirectiveScopeRAII(CodeGenFunction &CGF, const Stmt *S) { 1792 if (const auto *Dir = dyn_cast<OMPLoopBasedDirective>(S)) { 1793 Scope = new OMPLoopScope(CGF, *Dir); 1794 CGSI = new CodeGenFunction::CGCapturedStmtInfo(CR_OpenMP); 1795 CapInfoRAII = new CodeGenFunction::CGCapturedStmtRAII(CGF, CGSI); 1796 } 1797 } 1798 ~OMPTransformDirectiveScopeRAII() { 1799 if (!Scope) 1800 return; 1801 delete CapInfoRAII; 1802 delete CGSI; 1803 delete Scope; 1804 } 1805 }; 1806 } // namespace 1807 1808 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop, 1809 int MaxLevel, int Level = 0) { 1810 assert(Level < MaxLevel && "Too deep lookup during loop body codegen."); 1811 const Stmt *SimplifiedS = S->IgnoreContainers(); 1812 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) { 1813 PrettyStackTraceLoc CrashInfo( 1814 CGF.getContext().getSourceManager(), CS->getLBracLoc(), 1815 "LLVM IR generation of compound statement ('{}')"); 1816 1817 // Keep track of the current cleanup stack depth, including debug scopes. 1818 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange()); 1819 for (const Stmt *CurStmt : CS->body()) 1820 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level); 1821 return; 1822 } 1823 if (SimplifiedS == NextLoop) { 1824 if (auto *Dir = dyn_cast<OMPTileDirective>(SimplifiedS)) 1825 SimplifiedS = Dir->getTransformedStmt(); 1826 if (auto *Dir = dyn_cast<OMPUnrollDirective>(SimplifiedS)) 1827 SimplifiedS = Dir->getTransformedStmt(); 1828 if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(SimplifiedS)) 1829 SimplifiedS = CanonLoop->getLoopStmt(); 1830 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) { 1831 S = For->getBody(); 1832 } else { 1833 assert(isa<CXXForRangeStmt>(SimplifiedS) && 1834 "Expected canonical for loop or range-based for loop."); 1835 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS); 1836 CGF.EmitStmt(CXXFor->getLoopVarStmt()); 1837 S = CXXFor->getBody(); 1838 } 1839 if (Level + 1 < MaxLevel) { 1840 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop( 1841 S, /*TryImperfectlyNestedLoops=*/true); 1842 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1); 1843 return; 1844 } 1845 } 1846 CGF.EmitStmt(S); 1847 } 1848 1849 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D, 1850 JumpDest LoopExit) { 1851 RunCleanupsScope BodyScope(*this); 1852 // Update counters values on current iteration. 1853 for (const Expr *UE : D.updates()) 1854 EmitIgnoredExpr(UE); 1855 // Update the linear variables. 1856 // In distribute directives only loop counters may be marked as linear, no 1857 // need to generate the code for them. 1858 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) { 1859 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1860 for (const Expr *UE : C->updates()) 1861 EmitIgnoredExpr(UE); 1862 } 1863 } 1864 1865 // On a continue in the body, jump to the end. 1866 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue"); 1867 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1868 for (const Expr *E : D.finals_conditions()) { 1869 if (!E) 1870 continue; 1871 // Check that loop counter in non-rectangular nest fits into the iteration 1872 // space. 1873 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next"); 1874 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(), 1875 getProfileCount(D.getBody())); 1876 EmitBlock(NextBB); 1877 } 1878 1879 OMPPrivateScope InscanScope(*this); 1880 EmitOMPReductionClauseInit(D, InscanScope, /*ForInscan=*/true); 1881 bool IsInscanRegion = InscanScope.Privatize(); 1882 if (IsInscanRegion) { 1883 // Need to remember the block before and after scan directive 1884 // to dispatch them correctly depending on the clause used in 1885 // this directive, inclusive or exclusive. For inclusive scan the natural 1886 // order of the blocks is used, for exclusive clause the blocks must be 1887 // executed in reverse order. 1888 OMPBeforeScanBlock = createBasicBlock("omp.before.scan.bb"); 1889 OMPAfterScanBlock = createBasicBlock("omp.after.scan.bb"); 1890 // No need to allocate inscan exit block, in simd mode it is selected in the 1891 // codegen for the scan directive. 1892 if (D.getDirectiveKind() != OMPD_simd && !getLangOpts().OpenMPSimd) 1893 OMPScanExitBlock = createBasicBlock("omp.exit.inscan.bb"); 1894 OMPScanDispatch = createBasicBlock("omp.inscan.dispatch"); 1895 EmitBranch(OMPScanDispatch); 1896 EmitBlock(OMPBeforeScanBlock); 1897 } 1898 1899 // Emit loop variables for C++ range loops. 1900 const Stmt *Body = 1901 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(); 1902 // Emit loop body. 1903 emitBody(*this, Body, 1904 OMPLoopBasedDirective::tryToFindNextInnerLoop( 1905 Body, /*TryImperfectlyNestedLoops=*/true), 1906 D.getLoopsNumber()); 1907 1908 // Jump to the dispatcher at the end of the loop body. 1909 if (IsInscanRegion) 1910 EmitBranch(OMPScanExitBlock); 1911 1912 // The end (updates/cleanups). 1913 EmitBlock(Continue.getBlock()); 1914 BreakContinueStack.pop_back(); 1915 } 1916 1917 using EmittedClosureTy = std::pair<llvm::Function *, llvm::Value *>; 1918 1919 /// Emit a captured statement and return the function as well as its captured 1920 /// closure context. 1921 static EmittedClosureTy emitCapturedStmtFunc(CodeGenFunction &ParentCGF, 1922 const CapturedStmt *S) { 1923 LValue CapStruct = ParentCGF.InitCapturedStruct(*S); 1924 CodeGenFunction CGF(ParentCGF.CGM, /*suppressNewContext=*/true); 1925 std::unique_ptr<CodeGenFunction::CGCapturedStmtInfo> CSI = 1926 std::make_unique<CodeGenFunction::CGCapturedStmtInfo>(*S); 1927 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, CSI.get()); 1928 llvm::Function *F = CGF.GenerateCapturedStmtFunction(*S); 1929 1930 return {F, CapStruct.getPointer(ParentCGF)}; 1931 } 1932 1933 /// Emit a call to a previously captured closure. 1934 static llvm::CallInst * 1935 emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap, 1936 llvm::ArrayRef<llvm::Value *> Args) { 1937 // Append the closure context to the argument. 1938 SmallVector<llvm::Value *> EffectiveArgs; 1939 EffectiveArgs.reserve(Args.size() + 1); 1940 llvm::append_range(EffectiveArgs, Args); 1941 EffectiveArgs.push_back(Cap.second); 1942 1943 return ParentCGF.Builder.CreateCall(Cap.first, EffectiveArgs); 1944 } 1945 1946 llvm::CanonicalLoopInfo * 1947 CodeGenFunction::EmitOMPCollapsedCanonicalLoopNest(const Stmt *S, int Depth) { 1948 assert(Depth == 1 && "Nested loops with OpenMPIRBuilder not yet implemented"); 1949 1950 EmitStmt(S); 1951 assert(OMPLoopNestStack.size() >= (size_t)Depth && "Found too few loops"); 1952 1953 // The last added loop is the outermost one. 1954 return OMPLoopNestStack.back(); 1955 } 1956 1957 void CodeGenFunction::EmitOMPCanonicalLoop(const OMPCanonicalLoop *S) { 1958 const Stmt *SyntacticalLoop = S->getLoopStmt(); 1959 if (!getLangOpts().OpenMPIRBuilder) { 1960 // Ignore if OpenMPIRBuilder is not enabled. 1961 EmitStmt(SyntacticalLoop); 1962 return; 1963 } 1964 1965 LexicalScope ForScope(*this, S->getSourceRange()); 1966 1967 // Emit init statements. The Distance/LoopVar funcs may reference variable 1968 // declarations they contain. 1969 const Stmt *BodyStmt; 1970 if (const auto *For = dyn_cast<ForStmt>(SyntacticalLoop)) { 1971 if (const Stmt *InitStmt = For->getInit()) 1972 EmitStmt(InitStmt); 1973 BodyStmt = For->getBody(); 1974 } else if (const auto *RangeFor = 1975 dyn_cast<CXXForRangeStmt>(SyntacticalLoop)) { 1976 if (const DeclStmt *RangeStmt = RangeFor->getRangeStmt()) 1977 EmitStmt(RangeStmt); 1978 if (const DeclStmt *BeginStmt = RangeFor->getBeginStmt()) 1979 EmitStmt(BeginStmt); 1980 if (const DeclStmt *EndStmt = RangeFor->getEndStmt()) 1981 EmitStmt(EndStmt); 1982 if (const DeclStmt *LoopVarStmt = RangeFor->getLoopVarStmt()) 1983 EmitStmt(LoopVarStmt); 1984 BodyStmt = RangeFor->getBody(); 1985 } else 1986 llvm_unreachable("Expected for-stmt or range-based for-stmt"); 1987 1988 // Emit closure for later use. By-value captures will be captured here. 1989 const CapturedStmt *DistanceFunc = S->getDistanceFunc(); 1990 EmittedClosureTy DistanceClosure = emitCapturedStmtFunc(*this, DistanceFunc); 1991 const CapturedStmt *LoopVarFunc = S->getLoopVarFunc(); 1992 EmittedClosureTy LoopVarClosure = emitCapturedStmtFunc(*this, LoopVarFunc); 1993 1994 // Call the distance function to get the number of iterations of the loop to 1995 // come. 1996 QualType LogicalTy = DistanceFunc->getCapturedDecl() 1997 ->getParam(0) 1998 ->getType() 1999 .getNonReferenceType(); 2000 Address CountAddr = CreateMemTemp(LogicalTy, ".count.addr"); 2001 emitCapturedStmtCall(*this, DistanceClosure, {CountAddr.getPointer()}); 2002 llvm::Value *DistVal = Builder.CreateLoad(CountAddr, ".count"); 2003 2004 // Emit the loop structure. 2005 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 2006 auto BodyGen = [&, this](llvm::OpenMPIRBuilder::InsertPointTy CodeGenIP, 2007 llvm::Value *IndVar) { 2008 Builder.restoreIP(CodeGenIP); 2009 2010 // Emit the loop body: Convert the logical iteration number to the loop 2011 // variable and emit the body. 2012 const DeclRefExpr *LoopVarRef = S->getLoopVarRef(); 2013 LValue LCVal = EmitLValue(LoopVarRef); 2014 Address LoopVarAddress = LCVal.getAddress(*this); 2015 emitCapturedStmtCall(*this, LoopVarClosure, 2016 {LoopVarAddress.getPointer(), IndVar}); 2017 2018 RunCleanupsScope BodyScope(*this); 2019 EmitStmt(BodyStmt); 2020 }; 2021 llvm::CanonicalLoopInfo *CL = 2022 OMPBuilder.createCanonicalLoop(Builder, BodyGen, DistVal); 2023 2024 // Finish up the loop. 2025 Builder.restoreIP(CL->getAfterIP()); 2026 ForScope.ForceCleanup(); 2027 2028 // Remember the CanonicalLoopInfo for parent AST nodes consuming it. 2029 OMPLoopNestStack.push_back(CL); 2030 } 2031 2032 void CodeGenFunction::EmitOMPInnerLoop( 2033 const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond, 2034 const Expr *IncExpr, 2035 const llvm::function_ref<void(CodeGenFunction &)> BodyGen, 2036 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) { 2037 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end"); 2038 2039 // Start the loop with a block that tests the condition. 2040 auto CondBlock = createBasicBlock("omp.inner.for.cond"); 2041 EmitBlock(CondBlock); 2042 const SourceRange R = S.getSourceRange(); 2043 2044 // If attributes are attached, push to the basic block with them. 2045 const auto &OMPED = cast<OMPExecutableDirective>(S); 2046 const CapturedStmt *ICS = OMPED.getInnermostCapturedStmt(); 2047 const Stmt *SS = ICS->getCapturedStmt(); 2048 const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(SS); 2049 OMPLoopNestStack.clear(); 2050 if (AS) 2051 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), 2052 AS->getAttrs(), SourceLocToDebugLoc(R.getBegin()), 2053 SourceLocToDebugLoc(R.getEnd())); 2054 else 2055 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 2056 SourceLocToDebugLoc(R.getEnd())); 2057 2058 // If there are any cleanups between here and the loop-exit scope, 2059 // create a block to stage a loop exit along. 2060 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 2061 if (RequiresCleanup) 2062 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup"); 2063 2064 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body"); 2065 2066 // Emit condition. 2067 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S)); 2068 if (ExitBlock != LoopExit.getBlock()) { 2069 EmitBlock(ExitBlock); 2070 EmitBranchThroughCleanup(LoopExit); 2071 } 2072 2073 EmitBlock(LoopBody); 2074 incrementProfileCounter(&S); 2075 2076 // Create a block for the increment. 2077 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc"); 2078 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 2079 2080 BodyGen(*this); 2081 2082 // Emit "IV = IV + 1" and a back-edge to the condition block. 2083 EmitBlock(Continue.getBlock()); 2084 EmitIgnoredExpr(IncExpr); 2085 PostIncGen(*this); 2086 BreakContinueStack.pop_back(); 2087 EmitBranch(CondBlock); 2088 LoopStack.pop(); 2089 // Emit the fall-through block. 2090 EmitBlock(LoopExit.getBlock()); 2091 } 2092 2093 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) { 2094 if (!HaveInsertPoint()) 2095 return false; 2096 // Emit inits for the linear variables. 2097 bool HasLinears = false; 2098 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2099 for (const Expr *Init : C->inits()) { 2100 HasLinears = true; 2101 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl()); 2102 if (const auto *Ref = 2103 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) { 2104 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 2105 const auto *OrigVD = cast<VarDecl>(Ref->getDecl()); 2106 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 2107 CapturedStmtInfo->lookup(OrigVD) != nullptr, 2108 VD->getInit()->getType(), VK_LValue, 2109 VD->getInit()->getExprLoc()); 2110 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(), 2111 VD->getType()), 2112 /*capturedByInit=*/false); 2113 EmitAutoVarCleanups(Emission); 2114 } else { 2115 EmitVarDecl(*VD); 2116 } 2117 } 2118 // Emit the linear steps for the linear clauses. 2119 // If a step is not constant, it is pre-calculated before the loop. 2120 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep())) 2121 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) { 2122 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl())); 2123 // Emit calculation of the linear step. 2124 EmitIgnoredExpr(CS); 2125 } 2126 } 2127 return HasLinears; 2128 } 2129 2130 void CodeGenFunction::EmitOMPLinearClauseFinal( 2131 const OMPLoopDirective &D, 2132 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 2133 if (!HaveInsertPoint()) 2134 return; 2135 llvm::BasicBlock *DoneBB = nullptr; 2136 // Emit the final values of the linear variables. 2137 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2138 auto IC = C->varlist_begin(); 2139 for (const Expr *F : C->finals()) { 2140 if (!DoneBB) { 2141 if (llvm::Value *Cond = CondGen(*this)) { 2142 // If the first post-update expression is found, emit conditional 2143 // block if it was requested. 2144 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu"); 2145 DoneBB = createBasicBlock(".omp.linear.pu.done"); 2146 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 2147 EmitBlock(ThenBB); 2148 } 2149 } 2150 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl()); 2151 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 2152 CapturedStmtInfo->lookup(OrigVD) != nullptr, 2153 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 2154 Address OrigAddr = EmitLValue(&DRE).getAddress(*this); 2155 CodeGenFunction::OMPPrivateScope VarScope(*this); 2156 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; }); 2157 (void)VarScope.Privatize(); 2158 EmitIgnoredExpr(F); 2159 ++IC; 2160 } 2161 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 2162 EmitIgnoredExpr(PostUpdate); 2163 } 2164 if (DoneBB) 2165 EmitBlock(DoneBB, /*IsFinished=*/true); 2166 } 2167 2168 static void emitAlignedClause(CodeGenFunction &CGF, 2169 const OMPExecutableDirective &D) { 2170 if (!CGF.HaveInsertPoint()) 2171 return; 2172 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) { 2173 llvm::APInt ClauseAlignment(64, 0); 2174 if (const Expr *AlignmentExpr = Clause->getAlignment()) { 2175 auto *AlignmentCI = 2176 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr)); 2177 ClauseAlignment = AlignmentCI->getValue(); 2178 } 2179 for (const Expr *E : Clause->varlists()) { 2180 llvm::APInt Alignment(ClauseAlignment); 2181 if (Alignment == 0) { 2182 // OpenMP [2.8.1, Description] 2183 // If no optional parameter is specified, implementation-defined default 2184 // alignments for SIMD instructions on the target platforms are assumed. 2185 Alignment = 2186 CGF.getContext() 2187 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 2188 E->getType()->getPointeeType())) 2189 .getQuantity(); 2190 } 2191 assert((Alignment == 0 || Alignment.isPowerOf2()) && 2192 "alignment is not power of 2"); 2193 if (Alignment != 0) { 2194 llvm::Value *PtrValue = CGF.EmitScalarExpr(E); 2195 CGF.emitAlignmentAssumption( 2196 PtrValue, E, /*No second loc needed*/ SourceLocation(), 2197 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment)); 2198 } 2199 } 2200 } 2201 } 2202 2203 void CodeGenFunction::EmitOMPPrivateLoopCounters( 2204 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) { 2205 if (!HaveInsertPoint()) 2206 return; 2207 auto I = S.private_counters().begin(); 2208 for (const Expr *E : S.counters()) { 2209 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2210 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()); 2211 // Emit var without initialization. 2212 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD); 2213 EmitAutoVarCleanups(VarEmission); 2214 LocalDeclMap.erase(PrivateVD); 2215 (void)LoopScope.addPrivate(VD, [&VarEmission]() { 2216 return VarEmission.getAllocatedAddress(); 2217 }); 2218 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) || 2219 VD->hasGlobalStorage()) { 2220 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() { 2221 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), 2222 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD), 2223 E->getType(), VK_LValue, E->getExprLoc()); 2224 return EmitLValue(&DRE).getAddress(*this); 2225 }); 2226 } else { 2227 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() { 2228 return VarEmission.getAllocatedAddress(); 2229 }); 2230 } 2231 ++I; 2232 } 2233 // Privatize extra loop counters used in loops for ordered(n) clauses. 2234 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) { 2235 if (!C->getNumForLoops()) 2236 continue; 2237 for (unsigned I = S.getLoopsNumber(), E = C->getLoopNumIterations().size(); 2238 I < E; ++I) { 2239 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I)); 2240 const auto *VD = cast<VarDecl>(DRE->getDecl()); 2241 // Override only those variables that can be captured to avoid re-emission 2242 // of the variables declared within the loops. 2243 if (DRE->refersToEnclosingVariableOrCapture()) { 2244 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() { 2245 return CreateMemTemp(DRE->getType(), VD->getName()); 2246 }); 2247 } 2248 } 2249 } 2250 } 2251 2252 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, 2253 const Expr *Cond, llvm::BasicBlock *TrueBlock, 2254 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) { 2255 if (!CGF.HaveInsertPoint()) 2256 return; 2257 { 2258 CodeGenFunction::OMPPrivateScope PreCondScope(CGF); 2259 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope); 2260 (void)PreCondScope.Privatize(); 2261 // Get initial values of real counters. 2262 for (const Expr *I : S.inits()) { 2263 CGF.EmitIgnoredExpr(I); 2264 } 2265 } 2266 // Create temp loop control variables with their init values to support 2267 // non-rectangular loops. 2268 CodeGenFunction::OMPMapVars PreCondVars; 2269 for (const Expr * E: S.dependent_counters()) { 2270 if (!E) 2271 continue; 2272 assert(!E->getType().getNonReferenceType()->isRecordType() && 2273 "dependent counter must not be an iterator."); 2274 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2275 Address CounterAddr = 2276 CGF.CreateMemTemp(VD->getType().getNonReferenceType()); 2277 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr); 2278 } 2279 (void)PreCondVars.apply(CGF); 2280 for (const Expr *E : S.dependent_inits()) { 2281 if (!E) 2282 continue; 2283 CGF.EmitIgnoredExpr(E); 2284 } 2285 // Check that loop is executed at least one time. 2286 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 2287 PreCondVars.restore(CGF); 2288 } 2289 2290 void CodeGenFunction::EmitOMPLinearClause( 2291 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) { 2292 if (!HaveInsertPoint()) 2293 return; 2294 llvm::DenseSet<const VarDecl *> SIMDLCVs; 2295 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 2296 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 2297 for (const Expr *C : LoopDirective->counters()) { 2298 SIMDLCVs.insert( 2299 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 2300 } 2301 } 2302 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2303 auto CurPrivate = C->privates().begin(); 2304 for (const Expr *E : C->varlists()) { 2305 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2306 const auto *PrivateVD = 2307 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl()); 2308 if (!SIMDLCVs.count(VD->getCanonicalDecl())) { 2309 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() { 2310 // Emit private VarDecl with copy init. 2311 EmitVarDecl(*PrivateVD); 2312 return GetAddrOfLocalVar(PrivateVD); 2313 }); 2314 assert(IsRegistered && "linear var already registered as private"); 2315 // Silence the warning about unused variable. 2316 (void)IsRegistered; 2317 } else { 2318 EmitVarDecl(*PrivateVD); 2319 } 2320 ++CurPrivate; 2321 } 2322 } 2323 } 2324 2325 static void emitSimdlenSafelenClause(CodeGenFunction &CGF, 2326 const OMPExecutableDirective &D, 2327 bool IsMonotonic) { 2328 if (!CGF.HaveInsertPoint()) 2329 return; 2330 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) { 2331 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(), 2332 /*ignoreResult=*/true); 2333 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 2334 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 2335 // In presence of finite 'safelen', it may be unsafe to mark all 2336 // the memory instructions parallel, because loop-carried 2337 // dependences of 'safelen' iterations are possible. 2338 if (!IsMonotonic) 2339 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>()); 2340 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) { 2341 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(), 2342 /*ignoreResult=*/true); 2343 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 2344 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 2345 // In presence of finite 'safelen', it may be unsafe to mark all 2346 // the memory instructions parallel, because loop-carried 2347 // dependences of 'safelen' iterations are possible. 2348 CGF.LoopStack.setParallel(/*Enable=*/false); 2349 } 2350 } 2351 2352 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D, 2353 bool IsMonotonic) { 2354 // Walk clauses and process safelen/lastprivate. 2355 LoopStack.setParallel(!IsMonotonic); 2356 LoopStack.setVectorizeEnable(); 2357 emitSimdlenSafelenClause(*this, D, IsMonotonic); 2358 if (const auto *C = D.getSingleClause<OMPOrderClause>()) 2359 if (C->getKind() == OMPC_ORDER_concurrent) 2360 LoopStack.setParallel(/*Enable=*/true); 2361 if ((D.getDirectiveKind() == OMPD_simd || 2362 (getLangOpts().OpenMPSimd && 2363 isOpenMPSimdDirective(D.getDirectiveKind()))) && 2364 llvm::any_of(D.getClausesOfKind<OMPReductionClause>(), 2365 [](const OMPReductionClause *C) { 2366 return C->getModifier() == OMPC_REDUCTION_inscan; 2367 })) 2368 // Disable parallel access in case of prefix sum. 2369 LoopStack.setParallel(/*Enable=*/false); 2370 } 2371 2372 void CodeGenFunction::EmitOMPSimdFinal( 2373 const OMPLoopDirective &D, 2374 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 2375 if (!HaveInsertPoint()) 2376 return; 2377 llvm::BasicBlock *DoneBB = nullptr; 2378 auto IC = D.counters().begin(); 2379 auto IPC = D.private_counters().begin(); 2380 for (const Expr *F : D.finals()) { 2381 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 2382 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl()); 2383 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD); 2384 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) || 2385 OrigVD->hasGlobalStorage() || CED) { 2386 if (!DoneBB) { 2387 if (llvm::Value *Cond = CondGen(*this)) { 2388 // If the first post-update expression is found, emit conditional 2389 // block if it was requested. 2390 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then"); 2391 DoneBB = createBasicBlock(".omp.final.done"); 2392 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 2393 EmitBlock(ThenBB); 2394 } 2395 } 2396 Address OrigAddr = Address::invalid(); 2397 if (CED) { 2398 OrigAddr = 2399 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this); 2400 } else { 2401 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD), 2402 /*RefersToEnclosingVariableOrCapture=*/false, 2403 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc()); 2404 OrigAddr = EmitLValue(&DRE).getAddress(*this); 2405 } 2406 OMPPrivateScope VarScope(*this); 2407 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; }); 2408 (void)VarScope.Privatize(); 2409 EmitIgnoredExpr(F); 2410 } 2411 ++IC; 2412 ++IPC; 2413 } 2414 if (DoneBB) 2415 EmitBlock(DoneBB, /*IsFinished=*/true); 2416 } 2417 2418 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF, 2419 const OMPLoopDirective &S, 2420 CodeGenFunction::JumpDest LoopExit) { 2421 CGF.EmitOMPLoopBody(S, LoopExit); 2422 CGF.EmitStopPoint(&S); 2423 } 2424 2425 /// Emit a helper variable and return corresponding lvalue. 2426 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 2427 const DeclRefExpr *Helper) { 2428 auto VDecl = cast<VarDecl>(Helper->getDecl()); 2429 CGF.EmitVarDecl(*VDecl); 2430 return CGF.EmitLValue(Helper); 2431 } 2432 2433 static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S, 2434 const RegionCodeGenTy &SimdInitGen, 2435 const RegionCodeGenTy &BodyCodeGen) { 2436 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF, 2437 PrePostActionTy &) { 2438 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S); 2439 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 2440 SimdInitGen(CGF); 2441 2442 BodyCodeGen(CGF); 2443 }; 2444 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) { 2445 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 2446 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false); 2447 2448 BodyCodeGen(CGF); 2449 }; 2450 const Expr *IfCond = nullptr; 2451 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2452 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 2453 if (CGF.getLangOpts().OpenMP >= 50 && 2454 (C->getNameModifier() == OMPD_unknown || 2455 C->getNameModifier() == OMPD_simd)) { 2456 IfCond = C->getCondition(); 2457 break; 2458 } 2459 } 2460 } 2461 if (IfCond) { 2462 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen); 2463 } else { 2464 RegionCodeGenTy ThenRCG(ThenGen); 2465 ThenRCG(CGF); 2466 } 2467 } 2468 2469 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S, 2470 PrePostActionTy &Action) { 2471 Action.Enter(CGF); 2472 assert(isOpenMPSimdDirective(S.getDirectiveKind()) && 2473 "Expected simd directive"); 2474 OMPLoopScope PreInitScope(CGF, S); 2475 // if (PreCond) { 2476 // for (IV in 0..LastIteration) BODY; 2477 // <Final counter/linear vars updates>; 2478 // } 2479 // 2480 if (isOpenMPDistributeDirective(S.getDirectiveKind()) || 2481 isOpenMPWorksharingDirective(S.getDirectiveKind()) || 2482 isOpenMPTaskLoopDirective(S.getDirectiveKind())) { 2483 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable())); 2484 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable())); 2485 } 2486 2487 // Emit: if (PreCond) - begin. 2488 // If the condition constant folds and can be elided, avoid emitting the 2489 // whole loop. 2490 bool CondConstant; 2491 llvm::BasicBlock *ContBlock = nullptr; 2492 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2493 if (!CondConstant) 2494 return; 2495 } else { 2496 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then"); 2497 ContBlock = CGF.createBasicBlock("simd.if.end"); 2498 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 2499 CGF.getProfileCount(&S)); 2500 CGF.EmitBlock(ThenBlock); 2501 CGF.incrementProfileCounter(&S); 2502 } 2503 2504 // Emit the loop iteration variable. 2505 const Expr *IVExpr = S.getIterationVariable(); 2506 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 2507 CGF.EmitVarDecl(*IVDecl); 2508 CGF.EmitIgnoredExpr(S.getInit()); 2509 2510 // Emit the iterations count variable. 2511 // If it is not a variable, Sema decided to calculate iterations count on 2512 // each iteration (e.g., it is foldable into a constant). 2513 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2514 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2515 // Emit calculation of the iterations count. 2516 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 2517 } 2518 2519 emitAlignedClause(CGF, S); 2520 (void)CGF.EmitOMPLinearClauseInit(S); 2521 { 2522 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2523 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 2524 CGF.EmitOMPLinearClause(S, LoopScope); 2525 CGF.EmitOMPPrivateClause(S, LoopScope); 2526 CGF.EmitOMPReductionClauseInit(S, LoopScope); 2527 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 2528 CGF, S, CGF.EmitLValue(S.getIterationVariable())); 2529 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 2530 (void)LoopScope.Privatize(); 2531 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2532 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 2533 2534 emitCommonSimdLoop( 2535 CGF, S, 2536 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2537 CGF.EmitOMPSimdInit(S); 2538 }, 2539 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2540 CGF.EmitOMPInnerLoop( 2541 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 2542 [&S](CodeGenFunction &CGF) { 2543 emitOMPLoopBodyWithStopPoint(CGF, S, 2544 CodeGenFunction::JumpDest()); 2545 }, 2546 [](CodeGenFunction &) {}); 2547 }); 2548 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; }); 2549 // Emit final copy of the lastprivate variables at the end of loops. 2550 if (HasLastprivateClause) 2551 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true); 2552 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd); 2553 emitPostUpdateForReductionClause(CGF, S, 2554 [](CodeGenFunction &) { return nullptr; }); 2555 } 2556 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; }); 2557 // Emit: if (PreCond) - end. 2558 if (ContBlock) { 2559 CGF.EmitBranch(ContBlock); 2560 CGF.EmitBlock(ContBlock, true); 2561 } 2562 } 2563 2564 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 2565 ParentLoopDirectiveForScanRegion ScanRegion(*this, S); 2566 OMPFirstScanLoop = true; 2567 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2568 emitOMPSimdRegion(CGF, S, Action); 2569 }; 2570 { 2571 auto LPCRegion = 2572 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2573 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2574 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2575 } 2576 // Check for outer lastprivate conditional update. 2577 checkForLastprivateConditionalUpdate(*this, S); 2578 } 2579 2580 void CodeGenFunction::EmitOMPTileDirective(const OMPTileDirective &S) { 2581 // Emit the de-sugared statement. 2582 OMPTransformDirectiveScopeRAII TileScope(*this, &S); 2583 EmitStmt(S.getTransformedStmt()); 2584 } 2585 2586 void CodeGenFunction::EmitOMPUnrollDirective(const OMPUnrollDirective &S) { 2587 // This function is only called if the unrolled loop is not consumed by any 2588 // other loop-associated construct. Such a loop-associated construct will have 2589 // used the transformed AST. 2590 2591 // Set the unroll metadata for the next emitted loop. 2592 LoopStack.setUnrollState(LoopAttributes::Enable); 2593 2594 if (S.hasClausesOfKind<OMPFullClause>()) { 2595 LoopStack.setUnrollState(LoopAttributes::Full); 2596 } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) { 2597 if (Expr *FactorExpr = PartialClause->getFactor()) { 2598 uint64_t Factor = 2599 FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue(); 2600 assert(Factor >= 1 && "Only positive factors are valid"); 2601 LoopStack.setUnrollCount(Factor); 2602 } 2603 } 2604 2605 EmitStmt(S.getAssociatedStmt()); 2606 } 2607 2608 void CodeGenFunction::EmitOMPOuterLoop( 2609 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S, 2610 CodeGenFunction::OMPPrivateScope &LoopScope, 2611 const CodeGenFunction::OMPLoopArguments &LoopArgs, 2612 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop, 2613 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) { 2614 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2615 2616 const Expr *IVExpr = S.getIterationVariable(); 2617 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2618 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2619 2620 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 2621 2622 // Start the loop with a block that tests the condition. 2623 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond"); 2624 EmitBlock(CondBlock); 2625 const SourceRange R = S.getSourceRange(); 2626 OMPLoopNestStack.clear(); 2627 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 2628 SourceLocToDebugLoc(R.getEnd())); 2629 2630 llvm::Value *BoolCondVal = nullptr; 2631 if (!DynamicOrOrdered) { 2632 // UB = min(UB, GlobalUB) or 2633 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g. 2634 // 'distribute parallel for') 2635 EmitIgnoredExpr(LoopArgs.EUB); 2636 // IV = LB 2637 EmitIgnoredExpr(LoopArgs.Init); 2638 // IV < UB 2639 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond); 2640 } else { 2641 BoolCondVal = 2642 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL, 2643 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST); 2644 } 2645 2646 // If there are any cleanups between here and the loop-exit scope, 2647 // create a block to stage a loop exit along. 2648 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 2649 if (LoopScope.requiresCleanups()) 2650 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 2651 2652 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body"); 2653 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 2654 if (ExitBlock != LoopExit.getBlock()) { 2655 EmitBlock(ExitBlock); 2656 EmitBranchThroughCleanup(LoopExit); 2657 } 2658 EmitBlock(LoopBody); 2659 2660 // Emit "IV = LB" (in case of static schedule, we have already calculated new 2661 // LB for loop condition and emitted it above). 2662 if (DynamicOrOrdered) 2663 EmitIgnoredExpr(LoopArgs.Init); 2664 2665 // Create a block for the increment. 2666 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 2667 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 2668 2669 emitCommonSimdLoop( 2670 *this, S, 2671 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) { 2672 // Generate !llvm.loop.parallel metadata for loads and stores for loops 2673 // with dynamic/guided scheduling and without ordered clause. 2674 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2675 CGF.LoopStack.setParallel(!IsMonotonic); 2676 if (const auto *C = S.getSingleClause<OMPOrderClause>()) 2677 if (C->getKind() == OMPC_ORDER_concurrent) 2678 CGF.LoopStack.setParallel(/*Enable=*/true); 2679 } else { 2680 CGF.EmitOMPSimdInit(S, IsMonotonic); 2681 } 2682 }, 2683 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered, 2684 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2685 SourceLocation Loc = S.getBeginLoc(); 2686 // when 'distribute' is not combined with a 'for': 2687 // while (idx <= UB) { BODY; ++idx; } 2688 // when 'distribute' is combined with a 'for' 2689 // (e.g. 'distribute parallel for') 2690 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; } 2691 CGF.EmitOMPInnerLoop( 2692 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr, 2693 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 2694 CodeGenLoop(CGF, S, LoopExit); 2695 }, 2696 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) { 2697 CodeGenOrdered(CGF, Loc, IVSize, IVSigned); 2698 }); 2699 }); 2700 2701 EmitBlock(Continue.getBlock()); 2702 BreakContinueStack.pop_back(); 2703 if (!DynamicOrOrdered) { 2704 // Emit "LB = LB + Stride", "UB = UB + Stride". 2705 EmitIgnoredExpr(LoopArgs.NextLB); 2706 EmitIgnoredExpr(LoopArgs.NextUB); 2707 } 2708 2709 EmitBranch(CondBlock); 2710 OMPLoopNestStack.clear(); 2711 LoopStack.pop(); 2712 // Emit the fall-through block. 2713 EmitBlock(LoopExit.getBlock()); 2714 2715 // Tell the runtime we are done. 2716 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) { 2717 if (!DynamicOrOrdered) 2718 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 2719 S.getDirectiveKind()); 2720 }; 2721 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 2722 } 2723 2724 void CodeGenFunction::EmitOMPForOuterLoop( 2725 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic, 2726 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 2727 const OMPLoopArguments &LoopArgs, 2728 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 2729 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2730 2731 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 2732 const bool DynamicOrOrdered = 2733 Ordered || RT.isDynamic(ScheduleKind.Schedule); 2734 2735 assert((Ordered || 2736 !RT.isStaticNonchunked(ScheduleKind.Schedule, 2737 LoopArgs.Chunk != nullptr)) && 2738 "static non-chunked schedule does not need outer loop"); 2739 2740 // Emit outer loop. 2741 // 2742 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2743 // When schedule(dynamic,chunk_size) is specified, the iterations are 2744 // distributed to threads in the team in chunks as the threads request them. 2745 // Each thread executes a chunk of iterations, then requests another chunk, 2746 // until no chunks remain to be distributed. Each chunk contains chunk_size 2747 // iterations, except for the last chunk to be distributed, which may have 2748 // fewer iterations. When no chunk_size is specified, it defaults to 1. 2749 // 2750 // When schedule(guided,chunk_size) is specified, the iterations are assigned 2751 // to threads in the team in chunks as the executing threads request them. 2752 // Each thread executes a chunk of iterations, then requests another chunk, 2753 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 2754 // each chunk is proportional to the number of unassigned iterations divided 2755 // by the number of threads in the team, decreasing to 1. For a chunk_size 2756 // with value k (greater than 1), the size of each chunk is determined in the 2757 // same way, with the restriction that the chunks do not contain fewer than k 2758 // iterations (except for the last chunk to be assigned, which may have fewer 2759 // than k iterations). 2760 // 2761 // When schedule(auto) is specified, the decision regarding scheduling is 2762 // delegated to the compiler and/or runtime system. The programmer gives the 2763 // implementation the freedom to choose any possible mapping of iterations to 2764 // threads in the team. 2765 // 2766 // When schedule(runtime) is specified, the decision regarding scheduling is 2767 // deferred until run time, and the schedule and chunk size are taken from the 2768 // run-sched-var ICV. If the ICV is set to auto, the schedule is 2769 // implementation defined 2770 // 2771 // while(__kmpc_dispatch_next(&LB, &UB)) { 2772 // idx = LB; 2773 // while (idx <= UB) { BODY; ++idx; 2774 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 2775 // } // inner loop 2776 // } 2777 // 2778 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2779 // When schedule(static, chunk_size) is specified, iterations are divided into 2780 // chunks of size chunk_size, and the chunks are assigned to the threads in 2781 // the team in a round-robin fashion in the order of the thread number. 2782 // 2783 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 2784 // while (idx <= UB) { BODY; ++idx; } // inner loop 2785 // LB = LB + ST; 2786 // UB = UB + ST; 2787 // } 2788 // 2789 2790 const Expr *IVExpr = S.getIterationVariable(); 2791 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2792 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2793 2794 if (DynamicOrOrdered) { 2795 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds = 2796 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB); 2797 llvm::Value *LBVal = DispatchBounds.first; 2798 llvm::Value *UBVal = DispatchBounds.second; 2799 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal, 2800 LoopArgs.Chunk}; 2801 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize, 2802 IVSigned, Ordered, DipatchRTInputValues); 2803 } else { 2804 CGOpenMPRuntime::StaticRTInput StaticInit( 2805 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB, 2806 LoopArgs.ST, LoopArgs.Chunk); 2807 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(), 2808 ScheduleKind, StaticInit); 2809 } 2810 2811 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc, 2812 const unsigned IVSize, 2813 const bool IVSigned) { 2814 if (Ordered) { 2815 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize, 2816 IVSigned); 2817 } 2818 }; 2819 2820 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST, 2821 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB); 2822 OuterLoopArgs.IncExpr = S.getInc(); 2823 OuterLoopArgs.Init = S.getInit(); 2824 OuterLoopArgs.Cond = S.getCond(); 2825 OuterLoopArgs.NextLB = S.getNextLowerBound(); 2826 OuterLoopArgs.NextUB = S.getNextUpperBound(); 2827 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs, 2828 emitOMPLoopBodyWithStopPoint, CodeGenOrdered); 2829 } 2830 2831 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc, 2832 const unsigned IVSize, const bool IVSigned) {} 2833 2834 void CodeGenFunction::EmitOMPDistributeOuterLoop( 2835 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S, 2836 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs, 2837 const CodeGenLoopTy &CodeGenLoopContent) { 2838 2839 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2840 2841 // Emit outer loop. 2842 // Same behavior as a OMPForOuterLoop, except that schedule cannot be 2843 // dynamic 2844 // 2845 2846 const Expr *IVExpr = S.getIterationVariable(); 2847 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2848 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2849 2850 CGOpenMPRuntime::StaticRTInput StaticInit( 2851 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB, 2852 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk); 2853 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit); 2854 2855 // for combined 'distribute' and 'for' the increment expression of distribute 2856 // is stored in DistInc. For 'distribute' alone, it is in Inc. 2857 Expr *IncExpr; 2858 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())) 2859 IncExpr = S.getDistInc(); 2860 else 2861 IncExpr = S.getInc(); 2862 2863 // this routine is shared by 'omp distribute parallel for' and 2864 // 'omp distribute': select the right EUB expression depending on the 2865 // directive 2866 OMPLoopArguments OuterLoopArgs; 2867 OuterLoopArgs.LB = LoopArgs.LB; 2868 OuterLoopArgs.UB = LoopArgs.UB; 2869 OuterLoopArgs.ST = LoopArgs.ST; 2870 OuterLoopArgs.IL = LoopArgs.IL; 2871 OuterLoopArgs.Chunk = LoopArgs.Chunk; 2872 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2873 ? S.getCombinedEnsureUpperBound() 2874 : S.getEnsureUpperBound(); 2875 OuterLoopArgs.IncExpr = IncExpr; 2876 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2877 ? S.getCombinedInit() 2878 : S.getInit(); 2879 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2880 ? S.getCombinedCond() 2881 : S.getCond(); 2882 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2883 ? S.getCombinedNextLowerBound() 2884 : S.getNextLowerBound(); 2885 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2886 ? S.getCombinedNextUpperBound() 2887 : S.getNextUpperBound(); 2888 2889 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S, 2890 LoopScope, OuterLoopArgs, CodeGenLoopContent, 2891 emitEmptyOrdered); 2892 } 2893 2894 static std::pair<LValue, LValue> 2895 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF, 2896 const OMPExecutableDirective &S) { 2897 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2898 LValue LB = 2899 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 2900 LValue UB = 2901 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 2902 2903 // When composing 'distribute' with 'for' (e.g. as in 'distribute 2904 // parallel for') we need to use the 'distribute' 2905 // chunk lower and upper bounds rather than the whole loop iteration 2906 // space. These are parameters to the outlined function for 'parallel' 2907 // and we copy the bounds of the previous schedule into the 2908 // the current ones. 2909 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable()); 2910 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable()); 2911 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar( 2912 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc()); 2913 PrevLBVal = CGF.EmitScalarConversion( 2914 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(), 2915 LS.getIterationVariable()->getType(), 2916 LS.getPrevLowerBoundVariable()->getExprLoc()); 2917 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar( 2918 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc()); 2919 PrevUBVal = CGF.EmitScalarConversion( 2920 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(), 2921 LS.getIterationVariable()->getType(), 2922 LS.getPrevUpperBoundVariable()->getExprLoc()); 2923 2924 CGF.EmitStoreOfScalar(PrevLBVal, LB); 2925 CGF.EmitStoreOfScalar(PrevUBVal, UB); 2926 2927 return {LB, UB}; 2928 } 2929 2930 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then 2931 /// we need to use the LB and UB expressions generated by the worksharing 2932 /// code generation support, whereas in non combined situations we would 2933 /// just emit 0 and the LastIteration expression 2934 /// This function is necessary due to the difference of the LB and UB 2935 /// types for the RT emission routines for 'for_static_init' and 2936 /// 'for_dispatch_init' 2937 static std::pair<llvm::Value *, llvm::Value *> 2938 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF, 2939 const OMPExecutableDirective &S, 2940 Address LB, Address UB) { 2941 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2942 const Expr *IVExpr = LS.getIterationVariable(); 2943 // when implementing a dynamic schedule for a 'for' combined with a 2944 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop 2945 // is not normalized as each team only executes its own assigned 2946 // distribute chunk 2947 QualType IteratorTy = IVExpr->getType(); 2948 llvm::Value *LBVal = 2949 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 2950 llvm::Value *UBVal = 2951 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 2952 return {LBVal, UBVal}; 2953 } 2954 2955 static void emitDistributeParallelForDistributeInnerBoundParams( 2956 CodeGenFunction &CGF, const OMPExecutableDirective &S, 2957 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) { 2958 const auto &Dir = cast<OMPLoopDirective>(S); 2959 LValue LB = 2960 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable())); 2961 llvm::Value *LBCast = 2962 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)), 2963 CGF.SizeTy, /*isSigned=*/false); 2964 CapturedVars.push_back(LBCast); 2965 LValue UB = 2966 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable())); 2967 2968 llvm::Value *UBCast = 2969 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)), 2970 CGF.SizeTy, /*isSigned=*/false); 2971 CapturedVars.push_back(UBCast); 2972 } 2973 2974 static void 2975 emitInnerParallelForWhenCombined(CodeGenFunction &CGF, 2976 const OMPLoopDirective &S, 2977 CodeGenFunction::JumpDest LoopExit) { 2978 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF, 2979 PrePostActionTy &Action) { 2980 Action.Enter(CGF); 2981 bool HasCancel = false; 2982 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2983 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S)) 2984 HasCancel = D->hasCancel(); 2985 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S)) 2986 HasCancel = D->hasCancel(); 2987 else if (const auto *D = 2988 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S)) 2989 HasCancel = D->hasCancel(); 2990 } 2991 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(), 2992 HasCancel); 2993 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(), 2994 emitDistributeParallelForInnerBounds, 2995 emitDistributeParallelForDispatchBounds); 2996 }; 2997 2998 emitCommonOMPParallelDirective( 2999 CGF, S, 3000 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for, 3001 CGInlinedWorksharingLoop, 3002 emitDistributeParallelForDistributeInnerBoundParams); 3003 } 3004 3005 void CodeGenFunction::EmitOMPDistributeParallelForDirective( 3006 const OMPDistributeParallelForDirective &S) { 3007 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3008 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 3009 S.getDistInc()); 3010 }; 3011 OMPLexicalScope Scope(*this, S, OMPD_parallel); 3012 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 3013 } 3014 3015 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective( 3016 const OMPDistributeParallelForSimdDirective &S) { 3017 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3018 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 3019 S.getDistInc()); 3020 }; 3021 OMPLexicalScope Scope(*this, S, OMPD_parallel); 3022 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 3023 } 3024 3025 void CodeGenFunction::EmitOMPDistributeSimdDirective( 3026 const OMPDistributeSimdDirective &S) { 3027 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3028 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 3029 }; 3030 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3031 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 3032 } 3033 3034 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction( 3035 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) { 3036 // Emit SPMD target parallel for region as a standalone region. 3037 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3038 emitOMPSimdRegion(CGF, S, Action); 3039 }; 3040 llvm::Function *Fn; 3041 llvm::Constant *Addr; 3042 // Emit target region as a standalone region. 3043 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 3044 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 3045 assert(Fn && Addr && "Target device function emission failed."); 3046 } 3047 3048 void CodeGenFunction::EmitOMPTargetSimdDirective( 3049 const OMPTargetSimdDirective &S) { 3050 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3051 emitOMPSimdRegion(CGF, S, Action); 3052 }; 3053 emitCommonOMPTargetDirective(*this, S, CodeGen); 3054 } 3055 3056 namespace { 3057 struct ScheduleKindModifiersTy { 3058 OpenMPScheduleClauseKind Kind; 3059 OpenMPScheduleClauseModifier M1; 3060 OpenMPScheduleClauseModifier M2; 3061 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind, 3062 OpenMPScheduleClauseModifier M1, 3063 OpenMPScheduleClauseModifier M2) 3064 : Kind(Kind), M1(M1), M2(M2) {} 3065 }; 3066 } // namespace 3067 3068 bool CodeGenFunction::EmitOMPWorksharingLoop( 3069 const OMPLoopDirective &S, Expr *EUB, 3070 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 3071 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 3072 // Emit the loop iteration variable. 3073 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 3074 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 3075 EmitVarDecl(*IVDecl); 3076 3077 // Emit the iterations count variable. 3078 // If it is not a variable, Sema decided to calculate iterations count on each 3079 // iteration (e.g., it is foldable into a constant). 3080 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 3081 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 3082 // Emit calculation of the iterations count. 3083 EmitIgnoredExpr(S.getCalcLastIteration()); 3084 } 3085 3086 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 3087 3088 bool HasLastprivateClause; 3089 // Check pre-condition. 3090 { 3091 OMPLoopScope PreInitScope(*this, S); 3092 // Skip the entire loop if we don't meet the precondition. 3093 // If the condition constant folds and can be elided, avoid emitting the 3094 // whole loop. 3095 bool CondConstant; 3096 llvm::BasicBlock *ContBlock = nullptr; 3097 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 3098 if (!CondConstant) 3099 return false; 3100 } else { 3101 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 3102 ContBlock = createBasicBlock("omp.precond.end"); 3103 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 3104 getProfileCount(&S)); 3105 EmitBlock(ThenBlock); 3106 incrementProfileCounter(&S); 3107 } 3108 3109 RunCleanupsScope DoacrossCleanupScope(*this); 3110 bool Ordered = false; 3111 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) { 3112 if (OrderedClause->getNumForLoops()) 3113 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations()); 3114 else 3115 Ordered = true; 3116 } 3117 3118 llvm::DenseSet<const Expr *> EmittedFinals; 3119 emitAlignedClause(*this, S); 3120 bool HasLinears = EmitOMPLinearClauseInit(S); 3121 // Emit helper vars inits. 3122 3123 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S); 3124 LValue LB = Bounds.first; 3125 LValue UB = Bounds.second; 3126 LValue ST = 3127 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 3128 LValue IL = 3129 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 3130 3131 // Emit 'then' code. 3132 { 3133 OMPPrivateScope LoopScope(*this); 3134 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) { 3135 // Emit implicit barrier to synchronize threads and avoid data races on 3136 // initialization of firstprivate variables and post-update of 3137 // lastprivate variables. 3138 CGM.getOpenMPRuntime().emitBarrierCall( 3139 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3140 /*ForceSimpleCall=*/true); 3141 } 3142 EmitOMPPrivateClause(S, LoopScope); 3143 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 3144 *this, S, EmitLValue(S.getIterationVariable())); 3145 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 3146 EmitOMPReductionClauseInit(S, LoopScope); 3147 EmitOMPPrivateLoopCounters(S, LoopScope); 3148 EmitOMPLinearClause(S, LoopScope); 3149 (void)LoopScope.Privatize(); 3150 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3151 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 3152 3153 // Detect the loop schedule kind and chunk. 3154 const Expr *ChunkExpr = nullptr; 3155 OpenMPScheduleTy ScheduleKind; 3156 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) { 3157 ScheduleKind.Schedule = C->getScheduleKind(); 3158 ScheduleKind.M1 = C->getFirstScheduleModifier(); 3159 ScheduleKind.M2 = C->getSecondScheduleModifier(); 3160 ChunkExpr = C->getChunkSize(); 3161 } else { 3162 // Default behaviour for schedule clause. 3163 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk( 3164 *this, S, ScheduleKind.Schedule, ChunkExpr); 3165 } 3166 bool HasChunkSizeOne = false; 3167 llvm::Value *Chunk = nullptr; 3168 if (ChunkExpr) { 3169 Chunk = EmitScalarExpr(ChunkExpr); 3170 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(), 3171 S.getIterationVariable()->getType(), 3172 S.getBeginLoc()); 3173 Expr::EvalResult Result; 3174 if (ChunkExpr->EvaluateAsInt(Result, getContext())) { 3175 llvm::APSInt EvaluatedChunk = Result.Val.getInt(); 3176 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1); 3177 } 3178 } 3179 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 3180 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 3181 // OpenMP 4.5, 2.7.1 Loop Construct, Description. 3182 // If the static schedule kind is specified or if the ordered clause is 3183 // specified, and if no monotonic modifier is specified, the effect will 3184 // be as if the monotonic modifier was specified. 3185 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule, 3186 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne && 3187 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 3188 bool IsMonotonic = 3189 Ordered || 3190 ((ScheduleKind.Schedule == OMPC_SCHEDULE_static || 3191 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown) && 3192 !(ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 3193 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)) || 3194 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic || 3195 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic; 3196 if ((RT.isStaticNonchunked(ScheduleKind.Schedule, 3197 /* Chunked */ Chunk != nullptr) || 3198 StaticChunkedOne) && 3199 !Ordered) { 3200 JumpDest LoopExit = 3201 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 3202 emitCommonSimdLoop( 3203 *this, S, 3204 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) { 3205 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 3206 CGF.EmitOMPSimdInit(S, IsMonotonic); 3207 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) { 3208 if (C->getKind() == OMPC_ORDER_concurrent) 3209 CGF.LoopStack.setParallel(/*Enable=*/true); 3210 } 3211 }, 3212 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk, 3213 &S, ScheduleKind, LoopExit, 3214 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 3215 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 3216 // When no chunk_size is specified, the iteration space is divided 3217 // into chunks that are approximately equal in size, and at most 3218 // one chunk is distributed to each thread. Note that the size of 3219 // the chunks is unspecified in this case. 3220 CGOpenMPRuntime::StaticRTInput StaticInit( 3221 IVSize, IVSigned, Ordered, IL.getAddress(CGF), 3222 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF), 3223 StaticChunkedOne ? Chunk : nullptr); 3224 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 3225 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, 3226 StaticInit); 3227 // UB = min(UB, GlobalUB); 3228 if (!StaticChunkedOne) 3229 CGF.EmitIgnoredExpr(S.getEnsureUpperBound()); 3230 // IV = LB; 3231 CGF.EmitIgnoredExpr(S.getInit()); 3232 // For unchunked static schedule generate: 3233 // 3234 // while (idx <= UB) { 3235 // BODY; 3236 // ++idx; 3237 // } 3238 // 3239 // For static schedule with chunk one: 3240 // 3241 // while (IV <= PrevUB) { 3242 // BODY; 3243 // IV += ST; 3244 // } 3245 CGF.EmitOMPInnerLoop( 3246 S, LoopScope.requiresCleanups(), 3247 StaticChunkedOne ? S.getCombinedParForInDistCond() 3248 : S.getCond(), 3249 StaticChunkedOne ? S.getDistInc() : S.getInc(), 3250 [&S, LoopExit](CodeGenFunction &CGF) { 3251 emitOMPLoopBodyWithStopPoint(CGF, S, LoopExit); 3252 }, 3253 [](CodeGenFunction &) {}); 3254 }); 3255 EmitBlock(LoopExit.getBlock()); 3256 // Tell the runtime we are done. 3257 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3258 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3259 S.getDirectiveKind()); 3260 }; 3261 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 3262 } else { 3263 // Emit the outer loop, which requests its work chunk [LB..UB] from 3264 // runtime and runs the inner loop to process it. 3265 const OMPLoopArguments LoopArguments( 3266 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 3267 IL.getAddress(*this), Chunk, EUB); 3268 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered, 3269 LoopArguments, CGDispatchBounds); 3270 } 3271 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 3272 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 3273 return CGF.Builder.CreateIsNotNull( 3274 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3275 }); 3276 } 3277 EmitOMPReductionClauseFinal( 3278 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind()) 3279 ? /*Parallel and Simd*/ OMPD_parallel_for_simd 3280 : /*Parallel only*/ OMPD_parallel); 3281 // Emit post-update of the reduction variables if IsLastIter != 0. 3282 emitPostUpdateForReductionClause( 3283 *this, S, [IL, &S](CodeGenFunction &CGF) { 3284 return CGF.Builder.CreateIsNotNull( 3285 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3286 }); 3287 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3288 if (HasLastprivateClause) 3289 EmitOMPLastprivateClauseFinal( 3290 S, isOpenMPSimdDirective(S.getDirectiveKind()), 3291 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 3292 } 3293 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) { 3294 return CGF.Builder.CreateIsNotNull( 3295 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3296 }); 3297 DoacrossCleanupScope.ForceCleanup(); 3298 // We're now done with the loop, so jump to the continuation block. 3299 if (ContBlock) { 3300 EmitBranch(ContBlock); 3301 EmitBlock(ContBlock, /*IsFinished=*/true); 3302 } 3303 } 3304 return HasLastprivateClause; 3305 } 3306 3307 /// The following two functions generate expressions for the loop lower 3308 /// and upper bounds in case of static and dynamic (dispatch) schedule 3309 /// of the associated 'for' or 'distribute' loop. 3310 static std::pair<LValue, LValue> 3311 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 3312 const auto &LS = cast<OMPLoopDirective>(S); 3313 LValue LB = 3314 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 3315 LValue UB = 3316 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 3317 return {LB, UB}; 3318 } 3319 3320 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not 3321 /// consider the lower and upper bound expressions generated by the 3322 /// worksharing loop support, but we use 0 and the iteration space size as 3323 /// constants 3324 static std::pair<llvm::Value *, llvm::Value *> 3325 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, 3326 Address LB, Address UB) { 3327 const auto &LS = cast<OMPLoopDirective>(S); 3328 const Expr *IVExpr = LS.getIterationVariable(); 3329 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType()); 3330 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0); 3331 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration()); 3332 return {LBVal, UBVal}; 3333 } 3334 3335 /// Emits internal temp array declarations for the directive with inscan 3336 /// reductions. 3337 /// The code is the following: 3338 /// \code 3339 /// size num_iters = <num_iters>; 3340 /// <type> buffer[num_iters]; 3341 /// \endcode 3342 static void emitScanBasedDirectiveDecls( 3343 CodeGenFunction &CGF, const OMPLoopDirective &S, 3344 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) { 3345 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast( 3346 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false); 3347 SmallVector<const Expr *, 4> Shareds; 3348 SmallVector<const Expr *, 4> Privates; 3349 SmallVector<const Expr *, 4> ReductionOps; 3350 SmallVector<const Expr *, 4> CopyArrayTemps; 3351 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 3352 assert(C->getModifier() == OMPC_REDUCTION_inscan && 3353 "Only inscan reductions are expected."); 3354 Shareds.append(C->varlist_begin(), C->varlist_end()); 3355 Privates.append(C->privates().begin(), C->privates().end()); 3356 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 3357 CopyArrayTemps.append(C->copy_array_temps().begin(), 3358 C->copy_array_temps().end()); 3359 } 3360 { 3361 // Emit buffers for each reduction variables. 3362 // ReductionCodeGen is required to emit correctly the code for array 3363 // reductions. 3364 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps); 3365 unsigned Count = 0; 3366 auto *ITA = CopyArrayTemps.begin(); 3367 for (const Expr *IRef : Privates) { 3368 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 3369 // Emit variably modified arrays, used for arrays/array sections 3370 // reductions. 3371 if (PrivateVD->getType()->isVariablyModifiedType()) { 3372 RedCG.emitSharedOrigLValue(CGF, Count); 3373 RedCG.emitAggregateType(CGF, Count); 3374 } 3375 CodeGenFunction::OpaqueValueMapping DimMapping( 3376 CGF, 3377 cast<OpaqueValueExpr>( 3378 cast<VariableArrayType>((*ITA)->getType()->getAsArrayTypeUnsafe()) 3379 ->getSizeExpr()), 3380 RValue::get(OMPScanNumIterations)); 3381 // Emit temp buffer. 3382 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(*ITA)->getDecl())); 3383 ++ITA; 3384 ++Count; 3385 } 3386 } 3387 } 3388 3389 /// Emits the code for the directive with inscan reductions. 3390 /// The code is the following: 3391 /// \code 3392 /// #pragma omp ... 3393 /// for (i: 0..<num_iters>) { 3394 /// <input phase>; 3395 /// buffer[i] = red; 3396 /// } 3397 /// #pragma omp master // in parallel region 3398 /// for (int k = 0; k != ceil(log2(num_iters)); ++k) 3399 /// for (size cnt = last_iter; cnt >= pow(2, k); --k) 3400 /// buffer[i] op= buffer[i-pow(2,k)]; 3401 /// #pragma omp barrier // in parallel region 3402 /// #pragma omp ... 3403 /// for (0..<num_iters>) { 3404 /// red = InclusiveScan ? buffer[i] : buffer[i-1]; 3405 /// <scan phase>; 3406 /// } 3407 /// \endcode 3408 static void emitScanBasedDirective( 3409 CodeGenFunction &CGF, const OMPLoopDirective &S, 3410 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen, 3411 llvm::function_ref<void(CodeGenFunction &)> FirstGen, 3412 llvm::function_ref<void(CodeGenFunction &)> SecondGen) { 3413 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast( 3414 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false); 3415 SmallVector<const Expr *, 4> Privates; 3416 SmallVector<const Expr *, 4> ReductionOps; 3417 SmallVector<const Expr *, 4> LHSs; 3418 SmallVector<const Expr *, 4> RHSs; 3419 SmallVector<const Expr *, 4> CopyArrayElems; 3420 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 3421 assert(C->getModifier() == OMPC_REDUCTION_inscan && 3422 "Only inscan reductions are expected."); 3423 Privates.append(C->privates().begin(), C->privates().end()); 3424 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 3425 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 3426 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 3427 CopyArrayElems.append(C->copy_array_elems().begin(), 3428 C->copy_array_elems().end()); 3429 } 3430 CodeGenFunction::ParentLoopDirectiveForScanRegion ScanRegion(CGF, S); 3431 { 3432 // Emit loop with input phase: 3433 // #pragma omp ... 3434 // for (i: 0..<num_iters>) { 3435 // <input phase>; 3436 // buffer[i] = red; 3437 // } 3438 CGF.OMPFirstScanLoop = true; 3439 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 3440 FirstGen(CGF); 3441 } 3442 // #pragma omp barrier // in parallel region 3443 auto &&CodeGen = [&S, OMPScanNumIterations, &LHSs, &RHSs, &CopyArrayElems, 3444 &ReductionOps, 3445 &Privates](CodeGenFunction &CGF, PrePostActionTy &Action) { 3446 Action.Enter(CGF); 3447 // Emit prefix reduction: 3448 // #pragma omp master // in parallel region 3449 // for (int k = 0; k <= ceil(log2(n)); ++k) 3450 llvm::BasicBlock *InputBB = CGF.Builder.GetInsertBlock(); 3451 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.outer.log.scan.body"); 3452 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.outer.log.scan.exit"); 3453 llvm::Function *F = 3454 CGF.CGM.getIntrinsic(llvm::Intrinsic::log2, CGF.DoubleTy); 3455 llvm::Value *Arg = 3456 CGF.Builder.CreateUIToFP(OMPScanNumIterations, CGF.DoubleTy); 3457 llvm::Value *LogVal = CGF.EmitNounwindRuntimeCall(F, Arg); 3458 F = CGF.CGM.getIntrinsic(llvm::Intrinsic::ceil, CGF.DoubleTy); 3459 LogVal = CGF.EmitNounwindRuntimeCall(F, LogVal); 3460 LogVal = CGF.Builder.CreateFPToUI(LogVal, CGF.IntTy); 3461 llvm::Value *NMin1 = CGF.Builder.CreateNUWSub( 3462 OMPScanNumIterations, llvm::ConstantInt::get(CGF.SizeTy, 1)); 3463 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getBeginLoc()); 3464 CGF.EmitBlock(LoopBB); 3465 auto *Counter = CGF.Builder.CreatePHI(CGF.IntTy, 2); 3466 // size pow2k = 1; 3467 auto *Pow2K = CGF.Builder.CreatePHI(CGF.SizeTy, 2); 3468 Counter->addIncoming(llvm::ConstantInt::get(CGF.IntTy, 0), InputBB); 3469 Pow2K->addIncoming(llvm::ConstantInt::get(CGF.SizeTy, 1), InputBB); 3470 // for (size i = n - 1; i >= 2 ^ k; --i) 3471 // tmp[i] op= tmp[i-pow2k]; 3472 llvm::BasicBlock *InnerLoopBB = 3473 CGF.createBasicBlock("omp.inner.log.scan.body"); 3474 llvm::BasicBlock *InnerExitBB = 3475 CGF.createBasicBlock("omp.inner.log.scan.exit"); 3476 llvm::Value *CmpI = CGF.Builder.CreateICmpUGE(NMin1, Pow2K); 3477 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB); 3478 CGF.EmitBlock(InnerLoopBB); 3479 auto *IVal = CGF.Builder.CreatePHI(CGF.SizeTy, 2); 3480 IVal->addIncoming(NMin1, LoopBB); 3481 { 3482 CodeGenFunction::OMPPrivateScope PrivScope(CGF); 3483 auto *ILHS = LHSs.begin(); 3484 auto *IRHS = RHSs.begin(); 3485 for (const Expr *CopyArrayElem : CopyArrayElems) { 3486 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 3487 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 3488 Address LHSAddr = Address::invalid(); 3489 { 3490 CodeGenFunction::OpaqueValueMapping IdxMapping( 3491 CGF, 3492 cast<OpaqueValueExpr>( 3493 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 3494 RValue::get(IVal)); 3495 LHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF); 3496 } 3497 PrivScope.addPrivate(LHSVD, [LHSAddr]() { return LHSAddr; }); 3498 Address RHSAddr = Address::invalid(); 3499 { 3500 llvm::Value *OffsetIVal = CGF.Builder.CreateNUWSub(IVal, Pow2K); 3501 CodeGenFunction::OpaqueValueMapping IdxMapping( 3502 CGF, 3503 cast<OpaqueValueExpr>( 3504 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 3505 RValue::get(OffsetIVal)); 3506 RHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF); 3507 } 3508 PrivScope.addPrivate(RHSVD, [RHSAddr]() { return RHSAddr; }); 3509 ++ILHS; 3510 ++IRHS; 3511 } 3512 PrivScope.Privatize(); 3513 CGF.CGM.getOpenMPRuntime().emitReduction( 3514 CGF, S.getEndLoc(), Privates, LHSs, RHSs, ReductionOps, 3515 {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_unknown}); 3516 } 3517 llvm::Value *NextIVal = 3518 CGF.Builder.CreateNUWSub(IVal, llvm::ConstantInt::get(CGF.SizeTy, 1)); 3519 IVal->addIncoming(NextIVal, CGF.Builder.GetInsertBlock()); 3520 CmpI = CGF.Builder.CreateICmpUGE(NextIVal, Pow2K); 3521 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB); 3522 CGF.EmitBlock(InnerExitBB); 3523 llvm::Value *Next = 3524 CGF.Builder.CreateNUWAdd(Counter, llvm::ConstantInt::get(CGF.IntTy, 1)); 3525 Counter->addIncoming(Next, CGF.Builder.GetInsertBlock()); 3526 // pow2k <<= 1; 3527 llvm::Value *NextPow2K = 3528 CGF.Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true); 3529 Pow2K->addIncoming(NextPow2K, CGF.Builder.GetInsertBlock()); 3530 llvm::Value *Cmp = CGF.Builder.CreateICmpNE(Next, LogVal); 3531 CGF.Builder.CreateCondBr(Cmp, LoopBB, ExitBB); 3532 auto DL1 = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getEndLoc()); 3533 CGF.EmitBlock(ExitBB); 3534 }; 3535 if (isOpenMPParallelDirective(S.getDirectiveKind())) { 3536 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc()); 3537 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3538 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3539 /*ForceSimpleCall=*/true); 3540 } else { 3541 RegionCodeGenTy RCG(CodeGen); 3542 RCG(CGF); 3543 } 3544 3545 CGF.OMPFirstScanLoop = false; 3546 SecondGen(CGF); 3547 } 3548 3549 static bool emitWorksharingDirective(CodeGenFunction &CGF, 3550 const OMPLoopDirective &S, 3551 bool HasCancel) { 3552 bool HasLastprivates; 3553 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(), 3554 [](const OMPReductionClause *C) { 3555 return C->getModifier() == OMPC_REDUCTION_inscan; 3556 })) { 3557 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) { 3558 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 3559 OMPLoopScope LoopScope(CGF, S); 3560 return CGF.EmitScalarExpr(S.getNumIterations()); 3561 }; 3562 const auto &&FirstGen = [&S, HasCancel](CodeGenFunction &CGF) { 3563 CodeGenFunction::OMPCancelStackRAII CancelRegion( 3564 CGF, S.getDirectiveKind(), HasCancel); 3565 (void)CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3566 emitForLoopBounds, 3567 emitDispatchForLoopBounds); 3568 // Emit an implicit barrier at the end. 3569 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(), 3570 OMPD_for); 3571 }; 3572 const auto &&SecondGen = [&S, HasCancel, 3573 &HasLastprivates](CodeGenFunction &CGF) { 3574 CodeGenFunction::OMPCancelStackRAII CancelRegion( 3575 CGF, S.getDirectiveKind(), HasCancel); 3576 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3577 emitForLoopBounds, 3578 emitDispatchForLoopBounds); 3579 }; 3580 if (!isOpenMPParallelDirective(S.getDirectiveKind())) 3581 emitScanBasedDirectiveDecls(CGF, S, NumIteratorsGen); 3582 emitScanBasedDirective(CGF, S, NumIteratorsGen, FirstGen, SecondGen); 3583 } else { 3584 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(), 3585 HasCancel); 3586 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3587 emitForLoopBounds, 3588 emitDispatchForLoopBounds); 3589 } 3590 return HasLastprivates; 3591 } 3592 3593 static bool isSupportedByOpenMPIRBuilder(const OMPForDirective &S) { 3594 if (S.hasCancel()) 3595 return false; 3596 for (OMPClause *C : S.clauses()) 3597 if (!isa<OMPNowaitClause>(C)) 3598 return false; 3599 3600 return true; 3601 } 3602 3603 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 3604 bool HasLastprivates = false; 3605 bool UseOMPIRBuilder = 3606 CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S); 3607 auto &&CodeGen = [this, &S, &HasLastprivates, 3608 UseOMPIRBuilder](CodeGenFunction &CGF, PrePostActionTy &) { 3609 // Use the OpenMPIRBuilder if enabled. 3610 if (UseOMPIRBuilder) { 3611 // Emit the associated statement and get its loop representation. 3612 const Stmt *Inner = S.getRawStmt(); 3613 llvm::CanonicalLoopInfo *CLI = 3614 EmitOMPCollapsedCanonicalLoopNest(Inner, 1); 3615 3616 bool NeedsBarrier = !S.getSingleClause<OMPNowaitClause>(); 3617 llvm::OpenMPIRBuilder &OMPBuilder = 3618 CGM.getOpenMPRuntime().getOMPBuilder(); 3619 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP( 3620 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator()); 3621 OMPBuilder.createWorkshareLoop(Builder, CLI, AllocaIP, NeedsBarrier); 3622 return; 3623 } 3624 3625 HasLastprivates = emitWorksharingDirective(CGF, S, S.hasCancel()); 3626 }; 3627 { 3628 auto LPCRegion = 3629 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3630 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3631 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen, 3632 S.hasCancel()); 3633 } 3634 3635 if (!UseOMPIRBuilder) { 3636 // Emit an implicit barrier at the end. 3637 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 3638 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 3639 } 3640 // Check for outer lastprivate conditional update. 3641 checkForLastprivateConditionalUpdate(*this, S); 3642 } 3643 3644 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) { 3645 bool HasLastprivates = false; 3646 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 3647 PrePostActionTy &) { 3648 HasLastprivates = emitWorksharingDirective(CGF, S, /*HasCancel=*/false); 3649 }; 3650 { 3651 auto LPCRegion = 3652 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3653 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3654 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 3655 } 3656 3657 // Emit an implicit barrier at the end. 3658 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 3659 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 3660 // Check for outer lastprivate conditional update. 3661 checkForLastprivateConditionalUpdate(*this, S); 3662 } 3663 3664 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 3665 const Twine &Name, 3666 llvm::Value *Init = nullptr) { 3667 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 3668 if (Init) 3669 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true); 3670 return LVal; 3671 } 3672 3673 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) { 3674 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt(); 3675 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt); 3676 bool HasLastprivates = false; 3677 auto &&CodeGen = [&S, CapturedStmt, CS, 3678 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) { 3679 const ASTContext &C = CGF.getContext(); 3680 QualType KmpInt32Ty = 3681 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 3682 // Emit helper vars inits. 3683 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 3684 CGF.Builder.getInt32(0)); 3685 llvm::ConstantInt *GlobalUBVal = CS != nullptr 3686 ? CGF.Builder.getInt32(CS->size() - 1) 3687 : CGF.Builder.getInt32(0); 3688 LValue UB = 3689 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 3690 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 3691 CGF.Builder.getInt32(1)); 3692 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 3693 CGF.Builder.getInt32(0)); 3694 // Loop counter. 3695 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 3696 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 3697 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 3698 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 3699 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 3700 // Generate condition for loop. 3701 BinaryOperator *Cond = BinaryOperator::Create( 3702 C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_PRValue, OK_Ordinary, 3703 S.getBeginLoc(), FPOptionsOverride()); 3704 // Increment for loop counter. 3705 UnaryOperator *Inc = UnaryOperator::Create( 3706 C, &IVRefExpr, UO_PreInc, KmpInt32Ty, VK_PRValue, OK_Ordinary, 3707 S.getBeginLoc(), true, FPOptionsOverride()); 3708 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) { 3709 // Iterate through all sections and emit a switch construct: 3710 // switch (IV) { 3711 // case 0: 3712 // <SectionStmt[0]>; 3713 // break; 3714 // ... 3715 // case <NumSection> - 1: 3716 // <SectionStmt[<NumSection> - 1]>; 3717 // break; 3718 // } 3719 // .omp.sections.exit: 3720 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 3721 llvm::SwitchInst *SwitchStmt = 3722 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()), 3723 ExitBB, CS == nullptr ? 1 : CS->size()); 3724 if (CS) { 3725 unsigned CaseNumber = 0; 3726 for (const Stmt *SubStmt : CS->children()) { 3727 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 3728 CGF.EmitBlock(CaseBB); 3729 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 3730 CGF.EmitStmt(SubStmt); 3731 CGF.EmitBranch(ExitBB); 3732 ++CaseNumber; 3733 } 3734 } else { 3735 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case"); 3736 CGF.EmitBlock(CaseBB); 3737 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB); 3738 CGF.EmitStmt(CapturedStmt); 3739 CGF.EmitBranch(ExitBB); 3740 } 3741 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 3742 }; 3743 3744 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 3745 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 3746 // Emit implicit barrier to synchronize threads and avoid data races on 3747 // initialization of firstprivate variables and post-update of lastprivate 3748 // variables. 3749 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3750 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3751 /*ForceSimpleCall=*/true); 3752 } 3753 CGF.EmitOMPPrivateClause(S, LoopScope); 3754 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV); 3755 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 3756 CGF.EmitOMPReductionClauseInit(S, LoopScope); 3757 (void)LoopScope.Privatize(); 3758 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3759 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 3760 3761 // Emit static non-chunked loop. 3762 OpenMPScheduleTy ScheduleKind; 3763 ScheduleKind.Schedule = OMPC_SCHEDULE_static; 3764 CGOpenMPRuntime::StaticRTInput StaticInit( 3765 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF), 3766 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF)); 3767 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 3768 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit); 3769 // UB = min(UB, GlobalUB); 3770 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc()); 3771 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect( 3772 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 3773 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 3774 // IV = LB; 3775 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV); 3776 // while (idx <= UB) { BODY; ++idx; } 3777 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, Inc, BodyGen, 3778 [](CodeGenFunction &) {}); 3779 // Tell the runtime we are done. 3780 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3781 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3782 S.getDirectiveKind()); 3783 }; 3784 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen); 3785 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3786 // Emit post-update of the reduction variables if IsLastIter != 0. 3787 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) { 3788 return CGF.Builder.CreateIsNotNull( 3789 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3790 }); 3791 3792 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3793 if (HasLastprivates) 3794 CGF.EmitOMPLastprivateClauseFinal( 3795 S, /*NoFinals=*/false, 3796 CGF.Builder.CreateIsNotNull( 3797 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()))); 3798 }; 3799 3800 bool HasCancel = false; 3801 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S)) 3802 HasCancel = OSD->hasCancel(); 3803 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S)) 3804 HasCancel = OPSD->hasCancel(); 3805 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel); 3806 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen, 3807 HasCancel); 3808 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 3809 // clause. Otherwise the barrier will be generated by the codegen for the 3810 // directive. 3811 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) { 3812 // Emit implicit barrier to synchronize threads and avoid data races on 3813 // initialization of firstprivate variables. 3814 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3815 OMPD_unknown); 3816 } 3817 } 3818 3819 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 3820 if (CGM.getLangOpts().OpenMPIRBuilder) { 3821 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 3822 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3823 using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy; 3824 3825 auto FiniCB = [this](InsertPointTy IP) { 3826 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3827 }; 3828 3829 const CapturedStmt *ICS = S.getInnermostCapturedStmt(); 3830 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt(); 3831 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt); 3832 llvm::SmallVector<BodyGenCallbackTy, 4> SectionCBVector; 3833 if (CS) { 3834 for (const Stmt *SubStmt : CS->children()) { 3835 auto SectionCB = [this, SubStmt](InsertPointTy AllocaIP, 3836 InsertPointTy CodeGenIP, 3837 llvm::BasicBlock &FiniBB) { 3838 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, 3839 FiniBB); 3840 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SubStmt, CodeGenIP, 3841 FiniBB); 3842 }; 3843 SectionCBVector.push_back(SectionCB); 3844 } 3845 } else { 3846 auto SectionCB = [this, CapturedStmt](InsertPointTy AllocaIP, 3847 InsertPointTy CodeGenIP, 3848 llvm::BasicBlock &FiniBB) { 3849 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3850 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CapturedStmt, CodeGenIP, 3851 FiniBB); 3852 }; 3853 SectionCBVector.push_back(SectionCB); 3854 } 3855 3856 // Privatization callback that performs appropriate action for 3857 // shared/private/firstprivate/lastprivate/copyin/... variables. 3858 // 3859 // TODO: This defaults to shared right now. 3860 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 3861 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) { 3862 // The next line is appropriate only for variables (Val) with the 3863 // data-sharing attribute "shared". 3864 ReplVal = &Val; 3865 3866 return CodeGenIP; 3867 }; 3868 3869 CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP); 3870 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 3871 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP( 3872 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator()); 3873 Builder.restoreIP(OMPBuilder.createSections( 3874 Builder, AllocaIP, SectionCBVector, PrivCB, FiniCB, S.hasCancel(), 3875 S.getSingleClause<OMPNowaitClause>())); 3876 return; 3877 } 3878 { 3879 auto LPCRegion = 3880 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3881 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3882 EmitSections(S); 3883 } 3884 // Emit an implicit barrier at the end. 3885 if (!S.getSingleClause<OMPNowaitClause>()) { 3886 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3887 OMPD_sections); 3888 } 3889 // Check for outer lastprivate conditional update. 3890 checkForLastprivateConditionalUpdate(*this, S); 3891 } 3892 3893 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 3894 if (CGM.getLangOpts().OpenMPIRBuilder) { 3895 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 3896 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3897 3898 const Stmt *SectionRegionBodyStmt = S.getAssociatedStmt(); 3899 auto FiniCB = [this](InsertPointTy IP) { 3900 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3901 }; 3902 3903 auto BodyGenCB = [SectionRegionBodyStmt, this](InsertPointTy AllocaIP, 3904 InsertPointTy CodeGenIP, 3905 llvm::BasicBlock &FiniBB) { 3906 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3907 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SectionRegionBodyStmt, 3908 CodeGenIP, FiniBB); 3909 }; 3910 3911 LexicalScope Scope(*this, S.getSourceRange()); 3912 EmitStopPoint(&S); 3913 Builder.restoreIP(OMPBuilder.createSection(Builder, BodyGenCB, FiniCB)); 3914 3915 return; 3916 } 3917 LexicalScope Scope(*this, S.getSourceRange()); 3918 EmitStopPoint(&S); 3919 EmitStmt(S.getAssociatedStmt()); 3920 } 3921 3922 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 3923 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 3924 llvm::SmallVector<const Expr *, 8> DestExprs; 3925 llvm::SmallVector<const Expr *, 8> SrcExprs; 3926 llvm::SmallVector<const Expr *, 8> AssignmentOps; 3927 // Check if there are any 'copyprivate' clauses associated with this 3928 // 'single' construct. 3929 // Build a list of copyprivate variables along with helper expressions 3930 // (<source>, <destination>, <destination>=<source> expressions) 3931 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) { 3932 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 3933 DestExprs.append(C->destination_exprs().begin(), 3934 C->destination_exprs().end()); 3935 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 3936 AssignmentOps.append(C->assignment_ops().begin(), 3937 C->assignment_ops().end()); 3938 } 3939 // Emit code for 'single' region along with 'copyprivate' clauses 3940 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3941 Action.Enter(CGF); 3942 OMPPrivateScope SingleScope(CGF); 3943 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope); 3944 CGF.EmitOMPPrivateClause(S, SingleScope); 3945 (void)SingleScope.Privatize(); 3946 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3947 }; 3948 { 3949 auto LPCRegion = 3950 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3951 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3952 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(), 3953 CopyprivateVars, DestExprs, 3954 SrcExprs, AssignmentOps); 3955 } 3956 // Emit an implicit barrier at the end (to avoid data race on firstprivate 3957 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 3958 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) { 3959 CGM.getOpenMPRuntime().emitBarrierCall( 3960 *this, S.getBeginLoc(), 3961 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single); 3962 } 3963 // Check for outer lastprivate conditional update. 3964 checkForLastprivateConditionalUpdate(*this, S); 3965 } 3966 3967 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 3968 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3969 Action.Enter(CGF); 3970 CGF.EmitStmt(S.getRawStmt()); 3971 }; 3972 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc()); 3973 } 3974 3975 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 3976 if (CGM.getLangOpts().OpenMPIRBuilder) { 3977 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 3978 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3979 3980 const Stmt *MasterRegionBodyStmt = S.getAssociatedStmt(); 3981 3982 auto FiniCB = [this](InsertPointTy IP) { 3983 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3984 }; 3985 3986 auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP, 3987 InsertPointTy CodeGenIP, 3988 llvm::BasicBlock &FiniBB) { 3989 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3990 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MasterRegionBodyStmt, 3991 CodeGenIP, FiniBB); 3992 }; 3993 3994 LexicalScope Scope(*this, S.getSourceRange()); 3995 EmitStopPoint(&S); 3996 Builder.restoreIP(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB)); 3997 3998 return; 3999 } 4000 LexicalScope Scope(*this, S.getSourceRange()); 4001 EmitStopPoint(&S); 4002 emitMaster(*this, S); 4003 } 4004 4005 static void emitMasked(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 4006 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4007 Action.Enter(CGF); 4008 CGF.EmitStmt(S.getRawStmt()); 4009 }; 4010 Expr *Filter = nullptr; 4011 if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>()) 4012 Filter = FilterClause->getThreadID(); 4013 CGF.CGM.getOpenMPRuntime().emitMaskedRegion(CGF, CodeGen, S.getBeginLoc(), 4014 Filter); 4015 } 4016 4017 void CodeGenFunction::EmitOMPMaskedDirective(const OMPMaskedDirective &S) { 4018 if (CGM.getLangOpts().OpenMPIRBuilder) { 4019 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 4020 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 4021 4022 const Stmt *MaskedRegionBodyStmt = S.getAssociatedStmt(); 4023 const Expr *Filter = nullptr; 4024 if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>()) 4025 Filter = FilterClause->getThreadID(); 4026 llvm::Value *FilterVal = Filter 4027 ? EmitScalarExpr(Filter, CGM.Int32Ty) 4028 : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0); 4029 4030 auto FiniCB = [this](InsertPointTy IP) { 4031 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 4032 }; 4033 4034 auto BodyGenCB = [MaskedRegionBodyStmt, this](InsertPointTy AllocaIP, 4035 InsertPointTy CodeGenIP, 4036 llvm::BasicBlock &FiniBB) { 4037 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 4038 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MaskedRegionBodyStmt, 4039 CodeGenIP, FiniBB); 4040 }; 4041 4042 LexicalScope Scope(*this, S.getSourceRange()); 4043 EmitStopPoint(&S); 4044 Builder.restoreIP( 4045 OMPBuilder.createMasked(Builder, BodyGenCB, FiniCB, FilterVal)); 4046 4047 return; 4048 } 4049 LexicalScope Scope(*this, S.getSourceRange()); 4050 EmitStopPoint(&S); 4051 emitMasked(*this, S); 4052 } 4053 4054 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 4055 if (CGM.getLangOpts().OpenMPIRBuilder) { 4056 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 4057 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 4058 4059 const Stmt *CriticalRegionBodyStmt = S.getAssociatedStmt(); 4060 const Expr *Hint = nullptr; 4061 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 4062 Hint = HintClause->getHint(); 4063 4064 // TODO: This is slightly different from what's currently being done in 4065 // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything 4066 // about typing is final. 4067 llvm::Value *HintInst = nullptr; 4068 if (Hint) 4069 HintInst = 4070 Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false); 4071 4072 auto FiniCB = [this](InsertPointTy IP) { 4073 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 4074 }; 4075 4076 auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP, 4077 InsertPointTy CodeGenIP, 4078 llvm::BasicBlock &FiniBB) { 4079 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 4080 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CriticalRegionBodyStmt, 4081 CodeGenIP, FiniBB); 4082 }; 4083 4084 LexicalScope Scope(*this, S.getSourceRange()); 4085 EmitStopPoint(&S); 4086 Builder.restoreIP(OMPBuilder.createCritical( 4087 Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(), 4088 HintInst)); 4089 4090 return; 4091 } 4092 4093 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4094 Action.Enter(CGF); 4095 CGF.EmitStmt(S.getAssociatedStmt()); 4096 }; 4097 const Expr *Hint = nullptr; 4098 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 4099 Hint = HintClause->getHint(); 4100 LexicalScope Scope(*this, S.getSourceRange()); 4101 EmitStopPoint(&S); 4102 CGM.getOpenMPRuntime().emitCriticalRegion(*this, 4103 S.getDirectiveName().getAsString(), 4104 CodeGen, S.getBeginLoc(), Hint); 4105 } 4106 4107 void CodeGenFunction::EmitOMPParallelForDirective( 4108 const OMPParallelForDirective &S) { 4109 // Emit directive as a combined directive that consists of two implicit 4110 // directives: 'parallel' with 'for' directive. 4111 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4112 Action.Enter(CGF); 4113 (void)emitWorksharingDirective(CGF, S, S.hasCancel()); 4114 }; 4115 { 4116 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(), 4117 [](const OMPReductionClause *C) { 4118 return C->getModifier() == OMPC_REDUCTION_inscan; 4119 })) { 4120 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) { 4121 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 4122 CGCapturedStmtInfo CGSI(CR_OpenMP); 4123 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI); 4124 OMPLoopScope LoopScope(CGF, S); 4125 return CGF.EmitScalarExpr(S.getNumIterations()); 4126 }; 4127 emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen); 4128 } 4129 auto LPCRegion = 4130 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4131 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen, 4132 emitEmptyBoundParameters); 4133 } 4134 // Check for outer lastprivate conditional update. 4135 checkForLastprivateConditionalUpdate(*this, S); 4136 } 4137 4138 void CodeGenFunction::EmitOMPParallelForSimdDirective( 4139 const OMPParallelForSimdDirective &S) { 4140 // Emit directive as a combined directive that consists of two implicit 4141 // directives: 'parallel' with 'for' directive. 4142 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4143 Action.Enter(CGF); 4144 (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false); 4145 }; 4146 { 4147 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(), 4148 [](const OMPReductionClause *C) { 4149 return C->getModifier() == OMPC_REDUCTION_inscan; 4150 })) { 4151 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) { 4152 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 4153 CGCapturedStmtInfo CGSI(CR_OpenMP); 4154 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI); 4155 OMPLoopScope LoopScope(CGF, S); 4156 return CGF.EmitScalarExpr(S.getNumIterations()); 4157 }; 4158 emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen); 4159 } 4160 auto LPCRegion = 4161 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4162 emitCommonOMPParallelDirective(*this, S, OMPD_for_simd, CodeGen, 4163 emitEmptyBoundParameters); 4164 } 4165 // Check for outer lastprivate conditional update. 4166 checkForLastprivateConditionalUpdate(*this, S); 4167 } 4168 4169 void CodeGenFunction::EmitOMPParallelMasterDirective( 4170 const OMPParallelMasterDirective &S) { 4171 // Emit directive as a combined directive that consists of two implicit 4172 // directives: 'parallel' with 'master' directive. 4173 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4174 Action.Enter(CGF); 4175 OMPPrivateScope PrivateScope(CGF); 4176 bool Copyins = CGF.EmitOMPCopyinClause(S); 4177 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4178 if (Copyins) { 4179 // Emit implicit barrier to synchronize threads and avoid data races on 4180 // propagation master's thread values of threadprivate variables to local 4181 // instances of that variables of all other implicit threads. 4182 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 4183 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 4184 /*ForceSimpleCall=*/true); 4185 } 4186 CGF.EmitOMPPrivateClause(S, PrivateScope); 4187 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4188 (void)PrivateScope.Privatize(); 4189 emitMaster(CGF, S); 4190 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 4191 }; 4192 { 4193 auto LPCRegion = 4194 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4195 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen, 4196 emitEmptyBoundParameters); 4197 emitPostUpdateForReductionClause(*this, S, 4198 [](CodeGenFunction &) { return nullptr; }); 4199 } 4200 // Check for outer lastprivate conditional update. 4201 checkForLastprivateConditionalUpdate(*this, S); 4202 } 4203 4204 void CodeGenFunction::EmitOMPParallelSectionsDirective( 4205 const OMPParallelSectionsDirective &S) { 4206 // Emit directive as a combined directive that consists of two implicit 4207 // directives: 'parallel' with 'sections' directive. 4208 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4209 Action.Enter(CGF); 4210 CGF.EmitSections(S); 4211 }; 4212 { 4213 auto LPCRegion = 4214 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4215 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen, 4216 emitEmptyBoundParameters); 4217 } 4218 // Check for outer lastprivate conditional update. 4219 checkForLastprivateConditionalUpdate(*this, S); 4220 } 4221 4222 namespace { 4223 /// Get the list of variables declared in the context of the untied tasks. 4224 class CheckVarsEscapingUntiedTaskDeclContext final 4225 : public ConstStmtVisitor<CheckVarsEscapingUntiedTaskDeclContext> { 4226 llvm::SmallVector<const VarDecl *, 4> PrivateDecls; 4227 4228 public: 4229 explicit CheckVarsEscapingUntiedTaskDeclContext() = default; 4230 virtual ~CheckVarsEscapingUntiedTaskDeclContext() = default; 4231 void VisitDeclStmt(const DeclStmt *S) { 4232 if (!S) 4233 return; 4234 // Need to privatize only local vars, static locals can be processed as is. 4235 for (const Decl *D : S->decls()) { 4236 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) 4237 if (VD->hasLocalStorage()) 4238 PrivateDecls.push_back(VD); 4239 } 4240 } 4241 void VisitOMPExecutableDirective(const OMPExecutableDirective *) { return; } 4242 void VisitCapturedStmt(const CapturedStmt *) { return; } 4243 void VisitLambdaExpr(const LambdaExpr *) { return; } 4244 void VisitBlockExpr(const BlockExpr *) { return; } 4245 void VisitStmt(const Stmt *S) { 4246 if (!S) 4247 return; 4248 for (const Stmt *Child : S->children()) 4249 if (Child) 4250 Visit(Child); 4251 } 4252 4253 /// Swaps list of vars with the provided one. 4254 ArrayRef<const VarDecl *> getPrivateDecls() const { return PrivateDecls; } 4255 }; 4256 } // anonymous namespace 4257 4258 void CodeGenFunction::EmitOMPTaskBasedDirective( 4259 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion, 4260 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen, 4261 OMPTaskDataTy &Data) { 4262 // Emit outlined function for task construct. 4263 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion); 4264 auto I = CS->getCapturedDecl()->param_begin(); 4265 auto PartId = std::next(I); 4266 auto TaskT = std::next(I, 4); 4267 // Check if the task is final 4268 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) { 4269 // If the condition constant folds and can be elided, try to avoid emitting 4270 // the condition and the dead arm of the if/else. 4271 const Expr *Cond = Clause->getCondition(); 4272 bool CondConstant; 4273 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 4274 Data.Final.setInt(CondConstant); 4275 else 4276 Data.Final.setPointer(EvaluateExprAsBool(Cond)); 4277 } else { 4278 // By default the task is not final. 4279 Data.Final.setInt(/*IntVal=*/false); 4280 } 4281 // Check if the task has 'priority' clause. 4282 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) { 4283 const Expr *Prio = Clause->getPriority(); 4284 Data.Priority.setInt(/*IntVal=*/true); 4285 Data.Priority.setPointer(EmitScalarConversion( 4286 EmitScalarExpr(Prio), Prio->getType(), 4287 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), 4288 Prio->getExprLoc())); 4289 } 4290 // The first function argument for tasks is a thread id, the second one is a 4291 // part id (0 for tied tasks, >=0 for untied task). 4292 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 4293 // Get list of private variables. 4294 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) { 4295 auto IRef = C->varlist_begin(); 4296 for (const Expr *IInit : C->private_copies()) { 4297 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4298 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4299 Data.PrivateVars.push_back(*IRef); 4300 Data.PrivateCopies.push_back(IInit); 4301 } 4302 ++IRef; 4303 } 4304 } 4305 EmittedAsPrivate.clear(); 4306 // Get list of firstprivate variables. 4307 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 4308 auto IRef = C->varlist_begin(); 4309 auto IElemInitRef = C->inits().begin(); 4310 for (const Expr *IInit : C->private_copies()) { 4311 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4312 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4313 Data.FirstprivateVars.push_back(*IRef); 4314 Data.FirstprivateCopies.push_back(IInit); 4315 Data.FirstprivateInits.push_back(*IElemInitRef); 4316 } 4317 ++IRef; 4318 ++IElemInitRef; 4319 } 4320 } 4321 // Get list of lastprivate variables (for taskloops). 4322 llvm::MapVector<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs; 4323 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 4324 auto IRef = C->varlist_begin(); 4325 auto ID = C->destination_exprs().begin(); 4326 for (const Expr *IInit : C->private_copies()) { 4327 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4328 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4329 Data.LastprivateVars.push_back(*IRef); 4330 Data.LastprivateCopies.push_back(IInit); 4331 } 4332 LastprivateDstsOrigs.insert( 4333 std::make_pair(cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()), 4334 cast<DeclRefExpr>(*IRef))); 4335 ++IRef; 4336 ++ID; 4337 } 4338 } 4339 SmallVector<const Expr *, 4> LHSs; 4340 SmallVector<const Expr *, 4> RHSs; 4341 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 4342 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end()); 4343 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 4344 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 4345 Data.ReductionOps.append(C->reduction_ops().begin(), 4346 C->reduction_ops().end()); 4347 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 4348 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 4349 } 4350 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit( 4351 *this, S.getBeginLoc(), LHSs, RHSs, Data); 4352 // Build list of dependences. 4353 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 4354 OMPTaskDataTy::DependData &DD = 4355 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 4356 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 4357 } 4358 // Get list of local vars for untied tasks. 4359 if (!Data.Tied) { 4360 CheckVarsEscapingUntiedTaskDeclContext Checker; 4361 Checker.Visit(S.getInnermostCapturedStmt()->getCapturedStmt()); 4362 Data.PrivateLocals.append(Checker.getPrivateDecls().begin(), 4363 Checker.getPrivateDecls().end()); 4364 } 4365 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs, 4366 CapturedRegion](CodeGenFunction &CGF, 4367 PrePostActionTy &Action) { 4368 llvm::MapVector<CanonicalDeclPtr<const VarDecl>, 4369 std::pair<Address, Address>> 4370 UntiedLocalVars; 4371 // Set proper addresses for generated private copies. 4372 OMPPrivateScope Scope(CGF); 4373 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> FirstprivatePtrs; 4374 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() || 4375 !Data.LastprivateVars.empty() || !Data.PrivateLocals.empty()) { 4376 enum { PrivatesParam = 2, CopyFnParam = 3 }; 4377 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 4378 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 4379 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 4380 CS->getCapturedDecl()->getParam(PrivatesParam))); 4381 // Map privates. 4382 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 4383 llvm::SmallVector<llvm::Value *, 16> CallArgs; 4384 llvm::SmallVector<llvm::Type *, 4> ParamTypes; 4385 CallArgs.push_back(PrivatesPtr); 4386 ParamTypes.push_back(PrivatesPtr->getType()); 4387 for (const Expr *E : Data.PrivateVars) { 4388 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4389 Address PrivatePtr = CGF.CreateMemTemp( 4390 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr"); 4391 PrivatePtrs.emplace_back(VD, PrivatePtr); 4392 CallArgs.push_back(PrivatePtr.getPointer()); 4393 ParamTypes.push_back(PrivatePtr.getType()); 4394 } 4395 for (const Expr *E : Data.FirstprivateVars) { 4396 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4397 Address PrivatePtr = 4398 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4399 ".firstpriv.ptr.addr"); 4400 PrivatePtrs.emplace_back(VD, PrivatePtr); 4401 FirstprivatePtrs.emplace_back(VD, PrivatePtr); 4402 CallArgs.push_back(PrivatePtr.getPointer()); 4403 ParamTypes.push_back(PrivatePtr.getType()); 4404 } 4405 for (const Expr *E : Data.LastprivateVars) { 4406 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4407 Address PrivatePtr = 4408 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4409 ".lastpriv.ptr.addr"); 4410 PrivatePtrs.emplace_back(VD, PrivatePtr); 4411 CallArgs.push_back(PrivatePtr.getPointer()); 4412 ParamTypes.push_back(PrivatePtr.getType()); 4413 } 4414 for (const VarDecl *VD : Data.PrivateLocals) { 4415 QualType Ty = VD->getType().getNonReferenceType(); 4416 if (VD->getType()->isLValueReferenceType()) 4417 Ty = CGF.getContext().getPointerType(Ty); 4418 if (isAllocatableDecl(VD)) 4419 Ty = CGF.getContext().getPointerType(Ty); 4420 Address PrivatePtr = CGF.CreateMemTemp( 4421 CGF.getContext().getPointerType(Ty), ".local.ptr.addr"); 4422 auto Result = UntiedLocalVars.insert( 4423 std::make_pair(VD, std::make_pair(PrivatePtr, Address::invalid()))); 4424 // If key exists update in place. 4425 if (Result.second == false) 4426 *Result.first = std::make_pair( 4427 VD, std::make_pair(PrivatePtr, Address::invalid())); 4428 CallArgs.push_back(PrivatePtr.getPointer()); 4429 ParamTypes.push_back(PrivatePtr.getType()); 4430 } 4431 auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(), 4432 ParamTypes, /*isVarArg=*/false); 4433 CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4434 CopyFn, CopyFnTy->getPointerTo()); 4435 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 4436 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 4437 for (const auto &Pair : LastprivateDstsOrigs) { 4438 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl()); 4439 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD), 4440 /*RefersToEnclosingVariableOrCapture=*/ 4441 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr, 4442 Pair.second->getType(), VK_LValue, 4443 Pair.second->getExprLoc()); 4444 Scope.addPrivate(Pair.first, [&CGF, &DRE]() { 4445 return CGF.EmitLValue(&DRE).getAddress(CGF); 4446 }); 4447 } 4448 for (const auto &Pair : PrivatePtrs) { 4449 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 4450 CGF.getContext().getDeclAlign(Pair.first)); 4451 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 4452 } 4453 // Adjust mapping for internal locals by mapping actual memory instead of 4454 // a pointer to this memory. 4455 for (auto &Pair : UntiedLocalVars) { 4456 if (isAllocatableDecl(Pair.first)) { 4457 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first); 4458 Address Replacement(Ptr, CGF.getPointerAlign()); 4459 Pair.second.first = Replacement; 4460 Ptr = CGF.Builder.CreateLoad(Replacement); 4461 Replacement = Address(Ptr, CGF.getContext().getDeclAlign(Pair.first)); 4462 Pair.second.second = Replacement; 4463 } else { 4464 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first); 4465 Address Replacement(Ptr, CGF.getContext().getDeclAlign(Pair.first)); 4466 Pair.second.first = Replacement; 4467 } 4468 } 4469 } 4470 if (Data.Reductions) { 4471 OMPPrivateScope FirstprivateScope(CGF); 4472 for (const auto &Pair : FirstprivatePtrs) { 4473 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 4474 CGF.getContext().getDeclAlign(Pair.first)); 4475 FirstprivateScope.addPrivate(Pair.first, 4476 [Replacement]() { return Replacement; }); 4477 } 4478 (void)FirstprivateScope.Privatize(); 4479 OMPLexicalScope LexScope(CGF, S, CapturedRegion); 4480 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars, 4481 Data.ReductionCopies, Data.ReductionOps); 4482 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad( 4483 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9))); 4484 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) { 4485 RedCG.emitSharedOrigLValue(CGF, Cnt); 4486 RedCG.emitAggregateType(CGF, Cnt); 4487 // FIXME: This must removed once the runtime library is fixed. 4488 // Emit required threadprivate variables for 4489 // initializer/combiner/finalizer. 4490 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 4491 RedCG, Cnt); 4492 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 4493 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 4494 Replacement = 4495 Address(CGF.EmitScalarConversion( 4496 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 4497 CGF.getContext().getPointerType( 4498 Data.ReductionCopies[Cnt]->getType()), 4499 Data.ReductionCopies[Cnt]->getExprLoc()), 4500 Replacement.getAlignment()); 4501 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 4502 Scope.addPrivate(RedCG.getBaseDecl(Cnt), 4503 [Replacement]() { return Replacement; }); 4504 } 4505 } 4506 // Privatize all private variables except for in_reduction items. 4507 (void)Scope.Privatize(); 4508 SmallVector<const Expr *, 4> InRedVars; 4509 SmallVector<const Expr *, 4> InRedPrivs; 4510 SmallVector<const Expr *, 4> InRedOps; 4511 SmallVector<const Expr *, 4> TaskgroupDescriptors; 4512 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) { 4513 auto IPriv = C->privates().begin(); 4514 auto IRed = C->reduction_ops().begin(); 4515 auto ITD = C->taskgroup_descriptors().begin(); 4516 for (const Expr *Ref : C->varlists()) { 4517 InRedVars.emplace_back(Ref); 4518 InRedPrivs.emplace_back(*IPriv); 4519 InRedOps.emplace_back(*IRed); 4520 TaskgroupDescriptors.emplace_back(*ITD); 4521 std::advance(IPriv, 1); 4522 std::advance(IRed, 1); 4523 std::advance(ITD, 1); 4524 } 4525 } 4526 // Privatize in_reduction items here, because taskgroup descriptors must be 4527 // privatized earlier. 4528 OMPPrivateScope InRedScope(CGF); 4529 if (!InRedVars.empty()) { 4530 ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps); 4531 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) { 4532 RedCG.emitSharedOrigLValue(CGF, Cnt); 4533 RedCG.emitAggregateType(CGF, Cnt); 4534 // The taskgroup descriptor variable is always implicit firstprivate and 4535 // privatized already during processing of the firstprivates. 4536 // FIXME: This must removed once the runtime library is fixed. 4537 // Emit required threadprivate variables for 4538 // initializer/combiner/finalizer. 4539 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 4540 RedCG, Cnt); 4541 llvm::Value *ReductionsPtr; 4542 if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) { 4543 ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr), 4544 TRExpr->getExprLoc()); 4545 } else { 4546 ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 4547 } 4548 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 4549 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 4550 Replacement = Address( 4551 CGF.EmitScalarConversion( 4552 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 4553 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()), 4554 InRedPrivs[Cnt]->getExprLoc()), 4555 Replacement.getAlignment()); 4556 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 4557 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), 4558 [Replacement]() { return Replacement; }); 4559 } 4560 } 4561 (void)InRedScope.Privatize(); 4562 4563 CGOpenMPRuntime::UntiedTaskLocalDeclsRAII LocalVarsScope(CGF, 4564 UntiedLocalVars); 4565 Action.Enter(CGF); 4566 BodyGen(CGF); 4567 }; 4568 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 4569 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied, 4570 Data.NumberOfParts); 4571 OMPLexicalScope Scope(*this, S, llvm::None, 4572 !isOpenMPParallelDirective(S.getDirectiveKind()) && 4573 !isOpenMPSimdDirective(S.getDirectiveKind())); 4574 TaskGen(*this, OutlinedFn, Data); 4575 } 4576 4577 static ImplicitParamDecl * 4578 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data, 4579 QualType Ty, CapturedDecl *CD, 4580 SourceLocation Loc) { 4581 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 4582 ImplicitParamDecl::Other); 4583 auto *OrigRef = DeclRefExpr::Create( 4584 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD, 4585 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 4586 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 4587 ImplicitParamDecl::Other); 4588 auto *PrivateRef = DeclRefExpr::Create( 4589 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD, 4590 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 4591 QualType ElemType = C.getBaseElementType(Ty); 4592 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType, 4593 ImplicitParamDecl::Other); 4594 auto *InitRef = DeclRefExpr::Create( 4595 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD, 4596 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue); 4597 PrivateVD->setInitStyle(VarDecl::CInit); 4598 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue, 4599 InitRef, /*BasePath=*/nullptr, 4600 VK_PRValue, FPOptionsOverride())); 4601 Data.FirstprivateVars.emplace_back(OrigRef); 4602 Data.FirstprivateCopies.emplace_back(PrivateRef); 4603 Data.FirstprivateInits.emplace_back(InitRef); 4604 return OrigVD; 4605 } 4606 4607 void CodeGenFunction::EmitOMPTargetTaskBasedDirective( 4608 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen, 4609 OMPTargetDataInfo &InputInfo) { 4610 // Emit outlined function for task construct. 4611 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 4612 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 4613 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 4614 auto I = CS->getCapturedDecl()->param_begin(); 4615 auto PartId = std::next(I); 4616 auto TaskT = std::next(I, 4); 4617 OMPTaskDataTy Data; 4618 // The task is not final. 4619 Data.Final.setInt(/*IntVal=*/false); 4620 // Get list of firstprivate variables. 4621 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 4622 auto IRef = C->varlist_begin(); 4623 auto IElemInitRef = C->inits().begin(); 4624 for (auto *IInit : C->private_copies()) { 4625 Data.FirstprivateVars.push_back(*IRef); 4626 Data.FirstprivateCopies.push_back(IInit); 4627 Data.FirstprivateInits.push_back(*IElemInitRef); 4628 ++IRef; 4629 ++IElemInitRef; 4630 } 4631 } 4632 OMPPrivateScope TargetScope(*this); 4633 VarDecl *BPVD = nullptr; 4634 VarDecl *PVD = nullptr; 4635 VarDecl *SVD = nullptr; 4636 VarDecl *MVD = nullptr; 4637 if (InputInfo.NumberOfTargetItems > 0) { 4638 auto *CD = CapturedDecl::Create( 4639 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0); 4640 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems); 4641 QualType BaseAndPointerAndMapperType = getContext().getConstantArrayType( 4642 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal, 4643 /*IndexTypeQuals=*/0); 4644 BPVD = createImplicitFirstprivateForType( 4645 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4646 PVD = createImplicitFirstprivateForType( 4647 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4648 QualType SizesType = getContext().getConstantArrayType( 4649 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1), 4650 ArrSize, nullptr, ArrayType::Normal, 4651 /*IndexTypeQuals=*/0); 4652 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD, 4653 S.getBeginLoc()); 4654 TargetScope.addPrivate( 4655 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; }); 4656 TargetScope.addPrivate(PVD, 4657 [&InputInfo]() { return InputInfo.PointersArray; }); 4658 TargetScope.addPrivate(SVD, 4659 [&InputInfo]() { return InputInfo.SizesArray; }); 4660 // If there is no user-defined mapper, the mapper array will be nullptr. In 4661 // this case, we don't need to privatize it. 4662 if (!dyn_cast_or_null<llvm::ConstantPointerNull>( 4663 InputInfo.MappersArray.getPointer())) { 4664 MVD = createImplicitFirstprivateForType( 4665 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4666 TargetScope.addPrivate(MVD, 4667 [&InputInfo]() { return InputInfo.MappersArray; }); 4668 } 4669 } 4670 (void)TargetScope.Privatize(); 4671 // Build list of dependences. 4672 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 4673 OMPTaskDataTy::DependData &DD = 4674 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 4675 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 4676 } 4677 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, MVD, 4678 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) { 4679 // Set proper addresses for generated private copies. 4680 OMPPrivateScope Scope(CGF); 4681 if (!Data.FirstprivateVars.empty()) { 4682 enum { PrivatesParam = 2, CopyFnParam = 3 }; 4683 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 4684 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 4685 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 4686 CS->getCapturedDecl()->getParam(PrivatesParam))); 4687 // Map privates. 4688 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 4689 llvm::SmallVector<llvm::Value *, 16> CallArgs; 4690 llvm::SmallVector<llvm::Type *, 4> ParamTypes; 4691 CallArgs.push_back(PrivatesPtr); 4692 ParamTypes.push_back(PrivatesPtr->getType()); 4693 for (const Expr *E : Data.FirstprivateVars) { 4694 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4695 Address PrivatePtr = 4696 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4697 ".firstpriv.ptr.addr"); 4698 PrivatePtrs.emplace_back(VD, PrivatePtr); 4699 CallArgs.push_back(PrivatePtr.getPointer()); 4700 ParamTypes.push_back(PrivatePtr.getType()); 4701 } 4702 auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(), 4703 ParamTypes, /*isVarArg=*/false); 4704 CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4705 CopyFn, CopyFnTy->getPointerTo()); 4706 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 4707 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 4708 for (const auto &Pair : PrivatePtrs) { 4709 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 4710 CGF.getContext().getDeclAlign(Pair.first)); 4711 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 4712 } 4713 } 4714 // Privatize all private variables except for in_reduction items. 4715 (void)Scope.Privatize(); 4716 if (InputInfo.NumberOfTargetItems > 0) { 4717 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP( 4718 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0); 4719 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP( 4720 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0); 4721 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP( 4722 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0); 4723 // If MVD is nullptr, the mapper array is not privatized 4724 if (MVD) 4725 InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP( 4726 CGF.GetAddrOfLocalVar(MVD), /*Index=*/0); 4727 } 4728 4729 Action.Enter(CGF); 4730 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false); 4731 BodyGen(CGF); 4732 }; 4733 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 4734 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true, 4735 Data.NumberOfParts); 4736 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0); 4737 IntegerLiteral IfCond(getContext(), TrueOrFalse, 4738 getContext().getIntTypeForBitwidth(32, /*Signed=*/0), 4739 SourceLocation()); 4740 4741 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn, 4742 SharedsTy, CapturedStruct, &IfCond, Data); 4743 } 4744 4745 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 4746 // Emit outlined function for task construct. 4747 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 4748 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 4749 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 4750 const Expr *IfCond = nullptr; 4751 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 4752 if (C->getNameModifier() == OMPD_unknown || 4753 C->getNameModifier() == OMPD_task) { 4754 IfCond = C->getCondition(); 4755 break; 4756 } 4757 } 4758 4759 OMPTaskDataTy Data; 4760 // Check if we should emit tied or untied task. 4761 Data.Tied = !S.getSingleClause<OMPUntiedClause>(); 4762 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) { 4763 CGF.EmitStmt(CS->getCapturedStmt()); 4764 }; 4765 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 4766 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 4767 const OMPTaskDataTy &Data) { 4768 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn, 4769 SharedsTy, CapturedStruct, IfCond, 4770 Data); 4771 }; 4772 auto LPCRegion = 4773 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4774 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data); 4775 } 4776 4777 void CodeGenFunction::EmitOMPTaskyieldDirective( 4778 const OMPTaskyieldDirective &S) { 4779 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc()); 4780 } 4781 4782 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 4783 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier); 4784 } 4785 4786 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 4787 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc()); 4788 } 4789 4790 void CodeGenFunction::EmitOMPTaskgroupDirective( 4791 const OMPTaskgroupDirective &S) { 4792 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4793 Action.Enter(CGF); 4794 if (const Expr *E = S.getReductionRef()) { 4795 SmallVector<const Expr *, 4> LHSs; 4796 SmallVector<const Expr *, 4> RHSs; 4797 OMPTaskDataTy Data; 4798 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) { 4799 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end()); 4800 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 4801 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 4802 Data.ReductionOps.append(C->reduction_ops().begin(), 4803 C->reduction_ops().end()); 4804 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 4805 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 4806 } 4807 llvm::Value *ReductionDesc = 4808 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(), 4809 LHSs, RHSs, Data); 4810 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4811 CGF.EmitVarDecl(*VD); 4812 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD), 4813 /*Volatile=*/false, E->getType()); 4814 } 4815 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 4816 }; 4817 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4818 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc()); 4819 } 4820 4821 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 4822 llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>() 4823 ? llvm::AtomicOrdering::NotAtomic 4824 : llvm::AtomicOrdering::AcquireRelease; 4825 CGM.getOpenMPRuntime().emitFlush( 4826 *this, 4827 [&S]() -> ArrayRef<const Expr *> { 4828 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) 4829 return llvm::makeArrayRef(FlushClause->varlist_begin(), 4830 FlushClause->varlist_end()); 4831 return llvm::None; 4832 }(), 4833 S.getBeginLoc(), AO); 4834 } 4835 4836 void CodeGenFunction::EmitOMPDepobjDirective(const OMPDepobjDirective &S) { 4837 const auto *DO = S.getSingleClause<OMPDepobjClause>(); 4838 LValue DOLVal = EmitLValue(DO->getDepobj()); 4839 if (const auto *DC = S.getSingleClause<OMPDependClause>()) { 4840 OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(), 4841 DC->getModifier()); 4842 Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end()); 4843 Address DepAddr = CGM.getOpenMPRuntime().emitDepobjDependClause( 4844 *this, Dependencies, DC->getBeginLoc()); 4845 EmitStoreOfScalar(DepAddr.getPointer(), DOLVal); 4846 return; 4847 } 4848 if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) { 4849 CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc()); 4850 return; 4851 } 4852 if (const auto *UC = S.getSingleClause<OMPUpdateClause>()) { 4853 CGM.getOpenMPRuntime().emitUpdateClause( 4854 *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc()); 4855 return; 4856 } 4857 } 4858 4859 void CodeGenFunction::EmitOMPScanDirective(const OMPScanDirective &S) { 4860 if (!OMPParentLoopDirectiveForScan) 4861 return; 4862 const OMPExecutableDirective &ParentDir = *OMPParentLoopDirectiveForScan; 4863 bool IsInclusive = S.hasClausesOfKind<OMPInclusiveClause>(); 4864 SmallVector<const Expr *, 4> Shareds; 4865 SmallVector<const Expr *, 4> Privates; 4866 SmallVector<const Expr *, 4> LHSs; 4867 SmallVector<const Expr *, 4> RHSs; 4868 SmallVector<const Expr *, 4> ReductionOps; 4869 SmallVector<const Expr *, 4> CopyOps; 4870 SmallVector<const Expr *, 4> CopyArrayTemps; 4871 SmallVector<const Expr *, 4> CopyArrayElems; 4872 for (const auto *C : ParentDir.getClausesOfKind<OMPReductionClause>()) { 4873 if (C->getModifier() != OMPC_REDUCTION_inscan) 4874 continue; 4875 Shareds.append(C->varlist_begin(), C->varlist_end()); 4876 Privates.append(C->privates().begin(), C->privates().end()); 4877 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 4878 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 4879 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 4880 CopyOps.append(C->copy_ops().begin(), C->copy_ops().end()); 4881 CopyArrayTemps.append(C->copy_array_temps().begin(), 4882 C->copy_array_temps().end()); 4883 CopyArrayElems.append(C->copy_array_elems().begin(), 4884 C->copy_array_elems().end()); 4885 } 4886 if (ParentDir.getDirectiveKind() == OMPD_simd || 4887 (getLangOpts().OpenMPSimd && 4888 isOpenMPSimdDirective(ParentDir.getDirectiveKind()))) { 4889 // For simd directive and simd-based directives in simd only mode, use the 4890 // following codegen: 4891 // int x = 0; 4892 // #pragma omp simd reduction(inscan, +: x) 4893 // for (..) { 4894 // <first part> 4895 // #pragma omp scan inclusive(x) 4896 // <second part> 4897 // } 4898 // is transformed to: 4899 // int x = 0; 4900 // for (..) { 4901 // int x_priv = 0; 4902 // <first part> 4903 // x = x_priv + x; 4904 // x_priv = x; 4905 // <second part> 4906 // } 4907 // and 4908 // int x = 0; 4909 // #pragma omp simd reduction(inscan, +: x) 4910 // for (..) { 4911 // <first part> 4912 // #pragma omp scan exclusive(x) 4913 // <second part> 4914 // } 4915 // to 4916 // int x = 0; 4917 // for (..) { 4918 // int x_priv = 0; 4919 // <second part> 4920 // int temp = x; 4921 // x = x_priv + x; 4922 // x_priv = temp; 4923 // <first part> 4924 // } 4925 llvm::BasicBlock *OMPScanReduce = createBasicBlock("omp.inscan.reduce"); 4926 EmitBranch(IsInclusive 4927 ? OMPScanReduce 4928 : BreakContinueStack.back().ContinueBlock.getBlock()); 4929 EmitBlock(OMPScanDispatch); 4930 { 4931 // New scope for correct construction/destruction of temp variables for 4932 // exclusive scan. 4933 LexicalScope Scope(*this, S.getSourceRange()); 4934 EmitBranch(IsInclusive ? OMPBeforeScanBlock : OMPAfterScanBlock); 4935 EmitBlock(OMPScanReduce); 4936 if (!IsInclusive) { 4937 // Create temp var and copy LHS value to this temp value. 4938 // TMP = LHS; 4939 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 4940 const Expr *PrivateExpr = Privates[I]; 4941 const Expr *TempExpr = CopyArrayTemps[I]; 4942 EmitAutoVarDecl( 4943 *cast<VarDecl>(cast<DeclRefExpr>(TempExpr)->getDecl())); 4944 LValue DestLVal = EmitLValue(TempExpr); 4945 LValue SrcLVal = EmitLValue(LHSs[I]); 4946 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 4947 SrcLVal.getAddress(*this), 4948 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 4949 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 4950 CopyOps[I]); 4951 } 4952 } 4953 CGM.getOpenMPRuntime().emitReduction( 4954 *this, ParentDir.getEndLoc(), Privates, LHSs, RHSs, ReductionOps, 4955 {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_simd}); 4956 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 4957 const Expr *PrivateExpr = Privates[I]; 4958 LValue DestLVal; 4959 LValue SrcLVal; 4960 if (IsInclusive) { 4961 DestLVal = EmitLValue(RHSs[I]); 4962 SrcLVal = EmitLValue(LHSs[I]); 4963 } else { 4964 const Expr *TempExpr = CopyArrayTemps[I]; 4965 DestLVal = EmitLValue(RHSs[I]); 4966 SrcLVal = EmitLValue(TempExpr); 4967 } 4968 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 4969 SrcLVal.getAddress(*this), 4970 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 4971 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 4972 CopyOps[I]); 4973 } 4974 } 4975 EmitBranch(IsInclusive ? OMPAfterScanBlock : OMPBeforeScanBlock); 4976 OMPScanExitBlock = IsInclusive 4977 ? BreakContinueStack.back().ContinueBlock.getBlock() 4978 : OMPScanReduce; 4979 EmitBlock(OMPAfterScanBlock); 4980 return; 4981 } 4982 if (!IsInclusive) { 4983 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 4984 EmitBlock(OMPScanExitBlock); 4985 } 4986 if (OMPFirstScanLoop) { 4987 // Emit buffer[i] = red; at the end of the input phase. 4988 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir) 4989 .getIterationVariable() 4990 ->IgnoreParenImpCasts(); 4991 LValue IdxLVal = EmitLValue(IVExpr); 4992 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc()); 4993 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false); 4994 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 4995 const Expr *PrivateExpr = Privates[I]; 4996 const Expr *OrigExpr = Shareds[I]; 4997 const Expr *CopyArrayElem = CopyArrayElems[I]; 4998 OpaqueValueMapping IdxMapping( 4999 *this, 5000 cast<OpaqueValueExpr>( 5001 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 5002 RValue::get(IdxVal)); 5003 LValue DestLVal = EmitLValue(CopyArrayElem); 5004 LValue SrcLVal = EmitLValue(OrigExpr); 5005 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 5006 SrcLVal.getAddress(*this), 5007 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 5008 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 5009 CopyOps[I]); 5010 } 5011 } 5012 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 5013 if (IsInclusive) { 5014 EmitBlock(OMPScanExitBlock); 5015 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 5016 } 5017 EmitBlock(OMPScanDispatch); 5018 if (!OMPFirstScanLoop) { 5019 // Emit red = buffer[i]; at the entrance to the scan phase. 5020 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir) 5021 .getIterationVariable() 5022 ->IgnoreParenImpCasts(); 5023 LValue IdxLVal = EmitLValue(IVExpr); 5024 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc()); 5025 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false); 5026 llvm::BasicBlock *ExclusiveExitBB = nullptr; 5027 if (!IsInclusive) { 5028 llvm::BasicBlock *ContBB = createBasicBlock("omp.exclusive.dec"); 5029 ExclusiveExitBB = createBasicBlock("omp.exclusive.copy.exit"); 5030 llvm::Value *Cmp = Builder.CreateIsNull(IdxVal); 5031 Builder.CreateCondBr(Cmp, ExclusiveExitBB, ContBB); 5032 EmitBlock(ContBB); 5033 // Use idx - 1 iteration for exclusive scan. 5034 IdxVal = Builder.CreateNUWSub(IdxVal, llvm::ConstantInt::get(SizeTy, 1)); 5035 } 5036 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 5037 const Expr *PrivateExpr = Privates[I]; 5038 const Expr *OrigExpr = Shareds[I]; 5039 const Expr *CopyArrayElem = CopyArrayElems[I]; 5040 OpaqueValueMapping IdxMapping( 5041 *this, 5042 cast<OpaqueValueExpr>( 5043 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 5044 RValue::get(IdxVal)); 5045 LValue SrcLVal = EmitLValue(CopyArrayElem); 5046 LValue DestLVal = EmitLValue(OrigExpr); 5047 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 5048 SrcLVal.getAddress(*this), 5049 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 5050 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 5051 CopyOps[I]); 5052 } 5053 if (!IsInclusive) { 5054 EmitBlock(ExclusiveExitBB); 5055 } 5056 } 5057 EmitBranch((OMPFirstScanLoop == IsInclusive) ? OMPBeforeScanBlock 5058 : OMPAfterScanBlock); 5059 EmitBlock(OMPAfterScanBlock); 5060 } 5061 5062 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S, 5063 const CodeGenLoopTy &CodeGenLoop, 5064 Expr *IncExpr) { 5065 // Emit the loop iteration variable. 5066 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 5067 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 5068 EmitVarDecl(*IVDecl); 5069 5070 // Emit the iterations count variable. 5071 // If it is not a variable, Sema decided to calculate iterations count on each 5072 // iteration (e.g., it is foldable into a constant). 5073 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 5074 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 5075 // Emit calculation of the iterations count. 5076 EmitIgnoredExpr(S.getCalcLastIteration()); 5077 } 5078 5079 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 5080 5081 bool HasLastprivateClause = false; 5082 // Check pre-condition. 5083 { 5084 OMPLoopScope PreInitScope(*this, S); 5085 // Skip the entire loop if we don't meet the precondition. 5086 // If the condition constant folds and can be elided, avoid emitting the 5087 // whole loop. 5088 bool CondConstant; 5089 llvm::BasicBlock *ContBlock = nullptr; 5090 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 5091 if (!CondConstant) 5092 return; 5093 } else { 5094 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 5095 ContBlock = createBasicBlock("omp.precond.end"); 5096 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 5097 getProfileCount(&S)); 5098 EmitBlock(ThenBlock); 5099 incrementProfileCounter(&S); 5100 } 5101 5102 emitAlignedClause(*this, S); 5103 // Emit 'then' code. 5104 { 5105 // Emit helper vars inits. 5106 5107 LValue LB = EmitOMPHelperVar( 5108 *this, cast<DeclRefExpr>( 5109 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5110 ? S.getCombinedLowerBoundVariable() 5111 : S.getLowerBoundVariable()))); 5112 LValue UB = EmitOMPHelperVar( 5113 *this, cast<DeclRefExpr>( 5114 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5115 ? S.getCombinedUpperBoundVariable() 5116 : S.getUpperBoundVariable()))); 5117 LValue ST = 5118 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 5119 LValue IL = 5120 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 5121 5122 OMPPrivateScope LoopScope(*this); 5123 if (EmitOMPFirstprivateClause(S, LoopScope)) { 5124 // Emit implicit barrier to synchronize threads and avoid data races 5125 // on initialization of firstprivate variables and post-update of 5126 // lastprivate variables. 5127 CGM.getOpenMPRuntime().emitBarrierCall( 5128 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 5129 /*ForceSimpleCall=*/true); 5130 } 5131 EmitOMPPrivateClause(S, LoopScope); 5132 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 5133 !isOpenMPParallelDirective(S.getDirectiveKind()) && 5134 !isOpenMPTeamsDirective(S.getDirectiveKind())) 5135 EmitOMPReductionClauseInit(S, LoopScope); 5136 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 5137 EmitOMPPrivateLoopCounters(S, LoopScope); 5138 (void)LoopScope.Privatize(); 5139 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 5140 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 5141 5142 // Detect the distribute schedule kind and chunk. 5143 llvm::Value *Chunk = nullptr; 5144 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown; 5145 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) { 5146 ScheduleKind = C->getDistScheduleKind(); 5147 if (const Expr *Ch = C->getChunkSize()) { 5148 Chunk = EmitScalarExpr(Ch); 5149 Chunk = EmitScalarConversion(Chunk, Ch->getType(), 5150 S.getIterationVariable()->getType(), 5151 S.getBeginLoc()); 5152 } 5153 } else { 5154 // Default behaviour for dist_schedule clause. 5155 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk( 5156 *this, S, ScheduleKind, Chunk); 5157 } 5158 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 5159 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 5160 5161 // OpenMP [2.10.8, distribute Construct, Description] 5162 // If dist_schedule is specified, kind must be static. If specified, 5163 // iterations are divided into chunks of size chunk_size, chunks are 5164 // assigned to the teams of the league in a round-robin fashion in the 5165 // order of the team number. When no chunk_size is specified, the 5166 // iteration space is divided into chunks that are approximately equal 5167 // in size, and at most one chunk is distributed to each team of the 5168 // league. The size of the chunks is unspecified in this case. 5169 bool StaticChunked = RT.isStaticChunked( 5170 ScheduleKind, /* Chunked */ Chunk != nullptr) && 5171 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 5172 if (RT.isStaticNonchunked(ScheduleKind, 5173 /* Chunked */ Chunk != nullptr) || 5174 StaticChunked) { 5175 CGOpenMPRuntime::StaticRTInput StaticInit( 5176 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this), 5177 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 5178 StaticChunked ? Chunk : nullptr); 5179 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, 5180 StaticInit); 5181 JumpDest LoopExit = 5182 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 5183 // UB = min(UB, GlobalUB); 5184 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5185 ? S.getCombinedEnsureUpperBound() 5186 : S.getEnsureUpperBound()); 5187 // IV = LB; 5188 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5189 ? S.getCombinedInit() 5190 : S.getInit()); 5191 5192 const Expr *Cond = 5193 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5194 ? S.getCombinedCond() 5195 : S.getCond(); 5196 5197 if (StaticChunked) 5198 Cond = S.getCombinedDistCond(); 5199 5200 // For static unchunked schedules generate: 5201 // 5202 // 1. For distribute alone, codegen 5203 // while (idx <= UB) { 5204 // BODY; 5205 // ++idx; 5206 // } 5207 // 5208 // 2. When combined with 'for' (e.g. as in 'distribute parallel for') 5209 // while (idx <= UB) { 5210 // <CodeGen rest of pragma>(LB, UB); 5211 // idx += ST; 5212 // } 5213 // 5214 // For static chunk one schedule generate: 5215 // 5216 // while (IV <= GlobalUB) { 5217 // <CodeGen rest of pragma>(LB, UB); 5218 // LB += ST; 5219 // UB += ST; 5220 // UB = min(UB, GlobalUB); 5221 // IV = LB; 5222 // } 5223 // 5224 emitCommonSimdLoop( 5225 *this, S, 5226 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5227 if (isOpenMPSimdDirective(S.getDirectiveKind())) 5228 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true); 5229 }, 5230 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop, 5231 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) { 5232 CGF.EmitOMPInnerLoop( 5233 S, LoopScope.requiresCleanups(), Cond, IncExpr, 5234 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 5235 CodeGenLoop(CGF, S, LoopExit); 5236 }, 5237 [&S, StaticChunked](CodeGenFunction &CGF) { 5238 if (StaticChunked) { 5239 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound()); 5240 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound()); 5241 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound()); 5242 CGF.EmitIgnoredExpr(S.getCombinedInit()); 5243 } 5244 }); 5245 }); 5246 EmitBlock(LoopExit.getBlock()); 5247 // Tell the runtime we are done. 5248 RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind()); 5249 } else { 5250 // Emit the outer loop, which requests its work chunk [LB..UB] from 5251 // runtime and runs the inner loop to process it. 5252 const OMPLoopArguments LoopArguments = { 5253 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 5254 IL.getAddress(*this), Chunk}; 5255 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments, 5256 CodeGenLoop); 5257 } 5258 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 5259 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 5260 return CGF.Builder.CreateIsNotNull( 5261 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 5262 }); 5263 } 5264 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 5265 !isOpenMPParallelDirective(S.getDirectiveKind()) && 5266 !isOpenMPTeamsDirective(S.getDirectiveKind())) { 5267 EmitOMPReductionClauseFinal(S, OMPD_simd); 5268 // Emit post-update of the reduction variables if IsLastIter != 0. 5269 emitPostUpdateForReductionClause( 5270 *this, S, [IL, &S](CodeGenFunction &CGF) { 5271 return CGF.Builder.CreateIsNotNull( 5272 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 5273 }); 5274 } 5275 // Emit final copy of the lastprivate variables if IsLastIter != 0. 5276 if (HasLastprivateClause) { 5277 EmitOMPLastprivateClauseFinal( 5278 S, /*NoFinals=*/false, 5279 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 5280 } 5281 } 5282 5283 // We're now done with the loop, so jump to the continuation block. 5284 if (ContBlock) { 5285 EmitBranch(ContBlock); 5286 EmitBlock(ContBlock, true); 5287 } 5288 } 5289 } 5290 5291 void CodeGenFunction::EmitOMPDistributeDirective( 5292 const OMPDistributeDirective &S) { 5293 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5294 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5295 }; 5296 OMPLexicalScope Scope(*this, S, OMPD_unknown); 5297 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 5298 } 5299 5300 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM, 5301 const CapturedStmt *S, 5302 SourceLocation Loc) { 5303 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); 5304 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo; 5305 CGF.CapturedStmtInfo = &CapStmtInfo; 5306 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc); 5307 Fn->setDoesNotRecurse(); 5308 return Fn; 5309 } 5310 5311 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 5312 if (S.hasClausesOfKind<OMPDependClause>()) { 5313 assert(!S.hasAssociatedStmt() && 5314 "No associated statement must be in ordered depend construct."); 5315 for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) 5316 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC); 5317 return; 5318 } 5319 const auto *C = S.getSingleClause<OMPSIMDClause>(); 5320 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF, 5321 PrePostActionTy &Action) { 5322 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 5323 if (C) { 5324 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 5325 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 5326 llvm::Function *OutlinedFn = 5327 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc()); 5328 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(), 5329 OutlinedFn, CapturedVars); 5330 } else { 5331 Action.Enter(CGF); 5332 CGF.EmitStmt(CS->getCapturedStmt()); 5333 } 5334 }; 5335 OMPLexicalScope Scope(*this, S, OMPD_unknown); 5336 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C); 5337 } 5338 5339 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 5340 QualType SrcType, QualType DestType, 5341 SourceLocation Loc) { 5342 assert(CGF.hasScalarEvaluationKind(DestType) && 5343 "DestType must have scalar evaluation kind."); 5344 assert(!Val.isAggregate() && "Must be a scalar or complex."); 5345 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, 5346 DestType, Loc) 5347 : CGF.EmitComplexToScalarConversion( 5348 Val.getComplexVal(), SrcType, DestType, Loc); 5349 } 5350 5351 static CodeGenFunction::ComplexPairTy 5352 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 5353 QualType DestType, SourceLocation Loc) { 5354 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 5355 "DestType must have complex evaluation kind."); 5356 CodeGenFunction::ComplexPairTy ComplexVal; 5357 if (Val.isScalar()) { 5358 // Convert the input element to the element type of the complex. 5359 QualType DestElementType = 5360 DestType->castAs<ComplexType>()->getElementType(); 5361 llvm::Value *ScalarVal = CGF.EmitScalarConversion( 5362 Val.getScalarVal(), SrcType, DestElementType, Loc); 5363 ComplexVal = CodeGenFunction::ComplexPairTy( 5364 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 5365 } else { 5366 assert(Val.isComplex() && "Must be a scalar or complex."); 5367 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 5368 QualType DestElementType = 5369 DestType->castAs<ComplexType>()->getElementType(); 5370 ComplexVal.first = CGF.EmitScalarConversion( 5371 Val.getComplexVal().first, SrcElementType, DestElementType, Loc); 5372 ComplexVal.second = CGF.EmitScalarConversion( 5373 Val.getComplexVal().second, SrcElementType, DestElementType, Loc); 5374 } 5375 return ComplexVal; 5376 } 5377 5378 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 5379 LValue LVal, RValue RVal) { 5380 if (LVal.isGlobalReg()) 5381 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 5382 else 5383 CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false); 5384 } 5385 5386 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF, 5387 llvm::AtomicOrdering AO, LValue LVal, 5388 SourceLocation Loc) { 5389 if (LVal.isGlobalReg()) 5390 return CGF.EmitLoadOfLValue(LVal, Loc); 5391 return CGF.EmitAtomicLoad( 5392 LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO), 5393 LVal.isVolatile()); 5394 } 5395 5396 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal, 5397 QualType RValTy, SourceLocation Loc) { 5398 switch (getEvaluationKind(LVal.getType())) { 5399 case TEK_Scalar: 5400 EmitStoreThroughLValue(RValue::get(convertToScalarValue( 5401 *this, RVal, RValTy, LVal.getType(), Loc)), 5402 LVal); 5403 break; 5404 case TEK_Complex: 5405 EmitStoreOfComplex( 5406 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal, 5407 /*isInit=*/false); 5408 break; 5409 case TEK_Aggregate: 5410 llvm_unreachable("Must be a scalar or complex."); 5411 } 5412 } 5413 5414 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 5415 const Expr *X, const Expr *V, 5416 SourceLocation Loc) { 5417 // v = x; 5418 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 5419 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 5420 LValue XLValue = CGF.EmitLValue(X); 5421 LValue VLValue = CGF.EmitLValue(V); 5422 RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc); 5423 // OpenMP, 2.17.7, atomic Construct 5424 // If the read or capture clause is specified and the acquire, acq_rel, or 5425 // seq_cst clause is specified then the strong flush on exit from the atomic 5426 // operation is also an acquire flush. 5427 switch (AO) { 5428 case llvm::AtomicOrdering::Acquire: 5429 case llvm::AtomicOrdering::AcquireRelease: 5430 case llvm::AtomicOrdering::SequentiallyConsistent: 5431 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5432 llvm::AtomicOrdering::Acquire); 5433 break; 5434 case llvm::AtomicOrdering::Monotonic: 5435 case llvm::AtomicOrdering::Release: 5436 break; 5437 case llvm::AtomicOrdering::NotAtomic: 5438 case llvm::AtomicOrdering::Unordered: 5439 llvm_unreachable("Unexpected ordering."); 5440 } 5441 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc); 5442 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 5443 } 5444 5445 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, 5446 llvm::AtomicOrdering AO, const Expr *X, 5447 const Expr *E, SourceLocation Loc) { 5448 // x = expr; 5449 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 5450 emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 5451 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5452 // OpenMP, 2.17.7, atomic Construct 5453 // If the write, update, or capture clause is specified and the release, 5454 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 5455 // the atomic operation is also a release flush. 5456 switch (AO) { 5457 case llvm::AtomicOrdering::Release: 5458 case llvm::AtomicOrdering::AcquireRelease: 5459 case llvm::AtomicOrdering::SequentiallyConsistent: 5460 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5461 llvm::AtomicOrdering::Release); 5462 break; 5463 case llvm::AtomicOrdering::Acquire: 5464 case llvm::AtomicOrdering::Monotonic: 5465 break; 5466 case llvm::AtomicOrdering::NotAtomic: 5467 case llvm::AtomicOrdering::Unordered: 5468 llvm_unreachable("Unexpected ordering."); 5469 } 5470 } 5471 5472 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 5473 RValue Update, 5474 BinaryOperatorKind BO, 5475 llvm::AtomicOrdering AO, 5476 bool IsXLHSInRHSPart) { 5477 ASTContext &Context = CGF.getContext(); 5478 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 5479 // expression is simple and atomic is allowed for the given type for the 5480 // target platform. 5481 if (BO == BO_Comma || !Update.isScalar() || 5482 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() || 5483 (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 5484 (Update.getScalarVal()->getType() != 5485 X.getAddress(CGF).getElementType())) || 5486 !X.getAddress(CGF).getElementType()->isIntegerTy() || 5487 !Context.getTargetInfo().hasBuiltinAtomic( 5488 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 5489 return std::make_pair(false, RValue::get(nullptr)); 5490 5491 llvm::AtomicRMWInst::BinOp RMWOp; 5492 switch (BO) { 5493 case BO_Add: 5494 RMWOp = llvm::AtomicRMWInst::Add; 5495 break; 5496 case BO_Sub: 5497 if (!IsXLHSInRHSPart) 5498 return std::make_pair(false, RValue::get(nullptr)); 5499 RMWOp = llvm::AtomicRMWInst::Sub; 5500 break; 5501 case BO_And: 5502 RMWOp = llvm::AtomicRMWInst::And; 5503 break; 5504 case BO_Or: 5505 RMWOp = llvm::AtomicRMWInst::Or; 5506 break; 5507 case BO_Xor: 5508 RMWOp = llvm::AtomicRMWInst::Xor; 5509 break; 5510 case BO_LT: 5511 RMWOp = X.getType()->hasSignedIntegerRepresentation() 5512 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 5513 : llvm::AtomicRMWInst::Max) 5514 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 5515 : llvm::AtomicRMWInst::UMax); 5516 break; 5517 case BO_GT: 5518 RMWOp = X.getType()->hasSignedIntegerRepresentation() 5519 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 5520 : llvm::AtomicRMWInst::Min) 5521 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 5522 : llvm::AtomicRMWInst::UMin); 5523 break; 5524 case BO_Assign: 5525 RMWOp = llvm::AtomicRMWInst::Xchg; 5526 break; 5527 case BO_Mul: 5528 case BO_Div: 5529 case BO_Rem: 5530 case BO_Shl: 5531 case BO_Shr: 5532 case BO_LAnd: 5533 case BO_LOr: 5534 return std::make_pair(false, RValue::get(nullptr)); 5535 case BO_PtrMemD: 5536 case BO_PtrMemI: 5537 case BO_LE: 5538 case BO_GE: 5539 case BO_EQ: 5540 case BO_NE: 5541 case BO_Cmp: 5542 case BO_AddAssign: 5543 case BO_SubAssign: 5544 case BO_AndAssign: 5545 case BO_OrAssign: 5546 case BO_XorAssign: 5547 case BO_MulAssign: 5548 case BO_DivAssign: 5549 case BO_RemAssign: 5550 case BO_ShlAssign: 5551 case BO_ShrAssign: 5552 case BO_Comma: 5553 llvm_unreachable("Unsupported atomic update operation"); 5554 } 5555 llvm::Value *UpdateVal = Update.getScalarVal(); 5556 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 5557 UpdateVal = CGF.Builder.CreateIntCast( 5558 IC, X.getAddress(CGF).getElementType(), 5559 X.getType()->hasSignedIntegerRepresentation()); 5560 } 5561 llvm::Value *Res = 5562 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO); 5563 return std::make_pair(true, RValue::get(Res)); 5564 } 5565 5566 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 5567 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 5568 llvm::AtomicOrdering AO, SourceLocation Loc, 5569 const llvm::function_ref<RValue(RValue)> CommonGen) { 5570 // Update expressions are allowed to have the following forms: 5571 // x binop= expr; -> xrval + expr; 5572 // x++, ++x -> xrval + 1; 5573 // x--, --x -> xrval - 1; 5574 // x = x binop expr; -> xrval binop expr 5575 // x = expr Op x; - > expr binop xrval; 5576 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 5577 if (!Res.first) { 5578 if (X.isGlobalReg()) { 5579 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 5580 // 'xrval'. 5581 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 5582 } else { 5583 // Perform compare-and-swap procedure. 5584 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 5585 } 5586 } 5587 return Res; 5588 } 5589 5590 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, 5591 llvm::AtomicOrdering AO, const Expr *X, 5592 const Expr *E, const Expr *UE, 5593 bool IsXLHSInRHSPart, SourceLocation Loc) { 5594 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 5595 "Update expr in 'atomic update' must be a binary operator."); 5596 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 5597 // Update expressions are allowed to have the following forms: 5598 // x binop= expr; -> xrval + expr; 5599 // x++, ++x -> xrval + 1; 5600 // x--, --x -> xrval - 1; 5601 // x = x binop expr; -> xrval binop expr 5602 // x = expr Op x; - > expr binop xrval; 5603 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 5604 LValue XLValue = CGF.EmitLValue(X); 5605 RValue ExprRValue = CGF.EmitAnyExpr(E); 5606 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 5607 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 5608 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 5609 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 5610 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) { 5611 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5612 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 5613 return CGF.EmitAnyExpr(UE); 5614 }; 5615 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 5616 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 5617 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5618 // OpenMP, 2.17.7, atomic Construct 5619 // If the write, update, or capture clause is specified and the release, 5620 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 5621 // the atomic operation is also a release flush. 5622 switch (AO) { 5623 case llvm::AtomicOrdering::Release: 5624 case llvm::AtomicOrdering::AcquireRelease: 5625 case llvm::AtomicOrdering::SequentiallyConsistent: 5626 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5627 llvm::AtomicOrdering::Release); 5628 break; 5629 case llvm::AtomicOrdering::Acquire: 5630 case llvm::AtomicOrdering::Monotonic: 5631 break; 5632 case llvm::AtomicOrdering::NotAtomic: 5633 case llvm::AtomicOrdering::Unordered: 5634 llvm_unreachable("Unexpected ordering."); 5635 } 5636 } 5637 5638 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 5639 QualType SourceType, QualType ResType, 5640 SourceLocation Loc) { 5641 switch (CGF.getEvaluationKind(ResType)) { 5642 case TEK_Scalar: 5643 return RValue::get( 5644 convertToScalarValue(CGF, Value, SourceType, ResType, Loc)); 5645 case TEK_Complex: { 5646 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc); 5647 return RValue::getComplex(Res.first, Res.second); 5648 } 5649 case TEK_Aggregate: 5650 break; 5651 } 5652 llvm_unreachable("Must be a scalar or complex."); 5653 } 5654 5655 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, 5656 llvm::AtomicOrdering AO, 5657 bool IsPostfixUpdate, const Expr *V, 5658 const Expr *X, const Expr *E, 5659 const Expr *UE, bool IsXLHSInRHSPart, 5660 SourceLocation Loc) { 5661 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 5662 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 5663 RValue NewVVal; 5664 LValue VLValue = CGF.EmitLValue(V); 5665 LValue XLValue = CGF.EmitLValue(X); 5666 RValue ExprRValue = CGF.EmitAnyExpr(E); 5667 QualType NewVValType; 5668 if (UE) { 5669 // 'x' is updated with some additional value. 5670 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 5671 "Update expr in 'atomic capture' must be a binary operator."); 5672 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 5673 // Update expressions are allowed to have the following forms: 5674 // x binop= expr; -> xrval + expr; 5675 // x++, ++x -> xrval + 1; 5676 // x--, --x -> xrval - 1; 5677 // x = x binop expr; -> xrval binop expr 5678 // x = expr Op x; - > expr binop xrval; 5679 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 5680 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 5681 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 5682 NewVValType = XRValExpr->getType(); 5683 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 5684 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 5685 IsPostfixUpdate](RValue XRValue) { 5686 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5687 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 5688 RValue Res = CGF.EmitAnyExpr(UE); 5689 NewVVal = IsPostfixUpdate ? XRValue : Res; 5690 return Res; 5691 }; 5692 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 5693 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 5694 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5695 if (Res.first) { 5696 // 'atomicrmw' instruction was generated. 5697 if (IsPostfixUpdate) { 5698 // Use old value from 'atomicrmw'. 5699 NewVVal = Res.second; 5700 } else { 5701 // 'atomicrmw' does not provide new value, so evaluate it using old 5702 // value of 'x'. 5703 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5704 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 5705 NewVVal = CGF.EmitAnyExpr(UE); 5706 } 5707 } 5708 } else { 5709 // 'x' is simply rewritten with some 'expr'. 5710 NewVValType = X->getType().getNonReferenceType(); 5711 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 5712 X->getType().getNonReferenceType(), Loc); 5713 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) { 5714 NewVVal = XRValue; 5715 return ExprRValue; 5716 }; 5717 // Try to perform atomicrmw xchg, otherwise simple exchange. 5718 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 5719 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 5720 Loc, Gen); 5721 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5722 if (Res.first) { 5723 // 'atomicrmw' instruction was generated. 5724 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 5725 } 5726 } 5727 // Emit post-update store to 'v' of old/new 'x' value. 5728 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc); 5729 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 5730 // OpenMP, 2.17.7, atomic Construct 5731 // If the write, update, or capture clause is specified and the release, 5732 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 5733 // the atomic operation is also a release flush. 5734 // If the read or capture clause is specified and the acquire, acq_rel, or 5735 // seq_cst clause is specified then the strong flush on exit from the atomic 5736 // operation is also an acquire flush. 5737 switch (AO) { 5738 case llvm::AtomicOrdering::Release: 5739 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5740 llvm::AtomicOrdering::Release); 5741 break; 5742 case llvm::AtomicOrdering::Acquire: 5743 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5744 llvm::AtomicOrdering::Acquire); 5745 break; 5746 case llvm::AtomicOrdering::AcquireRelease: 5747 case llvm::AtomicOrdering::SequentiallyConsistent: 5748 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5749 llvm::AtomicOrdering::AcquireRelease); 5750 break; 5751 case llvm::AtomicOrdering::Monotonic: 5752 break; 5753 case llvm::AtomicOrdering::NotAtomic: 5754 case llvm::AtomicOrdering::Unordered: 5755 llvm_unreachable("Unexpected ordering."); 5756 } 5757 } 5758 5759 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 5760 llvm::AtomicOrdering AO, bool IsPostfixUpdate, 5761 const Expr *X, const Expr *V, const Expr *E, 5762 const Expr *UE, bool IsXLHSInRHSPart, 5763 SourceLocation Loc) { 5764 switch (Kind) { 5765 case OMPC_read: 5766 emitOMPAtomicReadExpr(CGF, AO, X, V, Loc); 5767 break; 5768 case OMPC_write: 5769 emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc); 5770 break; 5771 case OMPC_unknown: 5772 case OMPC_update: 5773 emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc); 5774 break; 5775 case OMPC_capture: 5776 emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE, 5777 IsXLHSInRHSPart, Loc); 5778 break; 5779 case OMPC_if: 5780 case OMPC_final: 5781 case OMPC_num_threads: 5782 case OMPC_private: 5783 case OMPC_firstprivate: 5784 case OMPC_lastprivate: 5785 case OMPC_reduction: 5786 case OMPC_task_reduction: 5787 case OMPC_in_reduction: 5788 case OMPC_safelen: 5789 case OMPC_simdlen: 5790 case OMPC_sizes: 5791 case OMPC_full: 5792 case OMPC_partial: 5793 case OMPC_allocator: 5794 case OMPC_allocate: 5795 case OMPC_collapse: 5796 case OMPC_default: 5797 case OMPC_seq_cst: 5798 case OMPC_acq_rel: 5799 case OMPC_acquire: 5800 case OMPC_release: 5801 case OMPC_relaxed: 5802 case OMPC_shared: 5803 case OMPC_linear: 5804 case OMPC_aligned: 5805 case OMPC_copyin: 5806 case OMPC_copyprivate: 5807 case OMPC_flush: 5808 case OMPC_depobj: 5809 case OMPC_proc_bind: 5810 case OMPC_schedule: 5811 case OMPC_ordered: 5812 case OMPC_nowait: 5813 case OMPC_untied: 5814 case OMPC_threadprivate: 5815 case OMPC_depend: 5816 case OMPC_mergeable: 5817 case OMPC_device: 5818 case OMPC_threads: 5819 case OMPC_simd: 5820 case OMPC_map: 5821 case OMPC_num_teams: 5822 case OMPC_thread_limit: 5823 case OMPC_priority: 5824 case OMPC_grainsize: 5825 case OMPC_nogroup: 5826 case OMPC_num_tasks: 5827 case OMPC_hint: 5828 case OMPC_dist_schedule: 5829 case OMPC_defaultmap: 5830 case OMPC_uniform: 5831 case OMPC_to: 5832 case OMPC_from: 5833 case OMPC_use_device_ptr: 5834 case OMPC_use_device_addr: 5835 case OMPC_is_device_ptr: 5836 case OMPC_unified_address: 5837 case OMPC_unified_shared_memory: 5838 case OMPC_reverse_offload: 5839 case OMPC_dynamic_allocators: 5840 case OMPC_atomic_default_mem_order: 5841 case OMPC_device_type: 5842 case OMPC_match: 5843 case OMPC_nontemporal: 5844 case OMPC_order: 5845 case OMPC_destroy: 5846 case OMPC_detach: 5847 case OMPC_inclusive: 5848 case OMPC_exclusive: 5849 case OMPC_uses_allocators: 5850 case OMPC_affinity: 5851 case OMPC_init: 5852 case OMPC_inbranch: 5853 case OMPC_notinbranch: 5854 case OMPC_link: 5855 case OMPC_use: 5856 case OMPC_novariants: 5857 case OMPC_nocontext: 5858 case OMPC_filter: 5859 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 5860 } 5861 } 5862 5863 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 5864 llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic; 5865 bool MemOrderingSpecified = false; 5866 if (S.getSingleClause<OMPSeqCstClause>()) { 5867 AO = llvm::AtomicOrdering::SequentiallyConsistent; 5868 MemOrderingSpecified = true; 5869 } else if (S.getSingleClause<OMPAcqRelClause>()) { 5870 AO = llvm::AtomicOrdering::AcquireRelease; 5871 MemOrderingSpecified = true; 5872 } else if (S.getSingleClause<OMPAcquireClause>()) { 5873 AO = llvm::AtomicOrdering::Acquire; 5874 MemOrderingSpecified = true; 5875 } else if (S.getSingleClause<OMPReleaseClause>()) { 5876 AO = llvm::AtomicOrdering::Release; 5877 MemOrderingSpecified = true; 5878 } else if (S.getSingleClause<OMPRelaxedClause>()) { 5879 AO = llvm::AtomicOrdering::Monotonic; 5880 MemOrderingSpecified = true; 5881 } 5882 OpenMPClauseKind Kind = OMPC_unknown; 5883 for (const OMPClause *C : S.clauses()) { 5884 // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause, 5885 // if it is first). 5886 if (C->getClauseKind() != OMPC_seq_cst && 5887 C->getClauseKind() != OMPC_acq_rel && 5888 C->getClauseKind() != OMPC_acquire && 5889 C->getClauseKind() != OMPC_release && 5890 C->getClauseKind() != OMPC_relaxed && C->getClauseKind() != OMPC_hint) { 5891 Kind = C->getClauseKind(); 5892 break; 5893 } 5894 } 5895 if (!MemOrderingSpecified) { 5896 llvm::AtomicOrdering DefaultOrder = 5897 CGM.getOpenMPRuntime().getDefaultMemoryOrdering(); 5898 if (DefaultOrder == llvm::AtomicOrdering::Monotonic || 5899 DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent || 5900 (DefaultOrder == llvm::AtomicOrdering::AcquireRelease && 5901 Kind == OMPC_capture)) { 5902 AO = DefaultOrder; 5903 } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) { 5904 if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) { 5905 AO = llvm::AtomicOrdering::Release; 5906 } else if (Kind == OMPC_read) { 5907 assert(Kind == OMPC_read && "Unexpected atomic kind."); 5908 AO = llvm::AtomicOrdering::Acquire; 5909 } 5910 } 5911 } 5912 5913 LexicalScope Scope(*this, S.getSourceRange()); 5914 EmitStopPoint(S.getAssociatedStmt()); 5915 emitOMPAtomicExpr(*this, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(), 5916 S.getExpr(), S.getUpdateExpr(), S.isXLHSInRHSPart(), 5917 S.getBeginLoc()); 5918 } 5919 5920 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 5921 const OMPExecutableDirective &S, 5922 const RegionCodeGenTy &CodeGen) { 5923 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind())); 5924 CodeGenModule &CGM = CGF.CGM; 5925 5926 // On device emit this construct as inlined code. 5927 if (CGM.getLangOpts().OpenMPIsDevice) { 5928 OMPLexicalScope Scope(CGF, S, OMPD_target); 5929 CGM.getOpenMPRuntime().emitInlinedDirective( 5930 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5931 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 5932 }); 5933 return; 5934 } 5935 5936 auto LPCRegion = 5937 CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S); 5938 llvm::Function *Fn = nullptr; 5939 llvm::Constant *FnID = nullptr; 5940 5941 const Expr *IfCond = nullptr; 5942 // Check for the at most one if clause associated with the target region. 5943 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 5944 if (C->getNameModifier() == OMPD_unknown || 5945 C->getNameModifier() == OMPD_target) { 5946 IfCond = C->getCondition(); 5947 break; 5948 } 5949 } 5950 5951 // Check if we have any device clause associated with the directive. 5952 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device( 5953 nullptr, OMPC_DEVICE_unknown); 5954 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 5955 Device.setPointerAndInt(C->getDevice(), C->getModifier()); 5956 5957 // Check if we have an if clause whose conditional always evaluates to false 5958 // or if we do not have any targets specified. If so the target region is not 5959 // an offload entry point. 5960 bool IsOffloadEntry = true; 5961 if (IfCond) { 5962 bool Val; 5963 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val) 5964 IsOffloadEntry = false; 5965 } 5966 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5967 IsOffloadEntry = false; 5968 5969 assert(CGF.CurFuncDecl && "No parent declaration for target region!"); 5970 StringRef ParentName; 5971 // In case we have Ctors/Dtors we use the complete type variant to produce 5972 // the mangling of the device outlined kernel. 5973 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl)) 5974 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete)); 5975 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl)) 5976 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete)); 5977 else 5978 ParentName = 5979 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl))); 5980 5981 // Emit target region as a standalone region. 5982 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID, 5983 IsOffloadEntry, CodeGen); 5984 OMPLexicalScope Scope(CGF, S, OMPD_task); 5985 auto &&SizeEmitter = 5986 [IsOffloadEntry](CodeGenFunction &CGF, 5987 const OMPLoopDirective &D) -> llvm::Value * { 5988 if (IsOffloadEntry) { 5989 OMPLoopScope(CGF, D); 5990 // Emit calculation of the iterations count. 5991 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations()); 5992 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty, 5993 /*isSigned=*/false); 5994 return NumIterations; 5995 } 5996 return nullptr; 5997 }; 5998 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device, 5999 SizeEmitter); 6000 } 6001 6002 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S, 6003 PrePostActionTy &Action) { 6004 Action.Enter(CGF); 6005 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6006 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 6007 CGF.EmitOMPPrivateClause(S, PrivateScope); 6008 (void)PrivateScope.Privatize(); 6009 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 6010 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 6011 6012 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt()); 6013 CGF.EnsureInsertPoint(); 6014 } 6015 6016 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 6017 StringRef ParentName, 6018 const OMPTargetDirective &S) { 6019 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6020 emitTargetRegion(CGF, S, Action); 6021 }; 6022 llvm::Function *Fn; 6023 llvm::Constant *Addr; 6024 // Emit target region as a standalone region. 6025 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6026 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6027 assert(Fn && Addr && "Target device function emission failed."); 6028 } 6029 6030 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) { 6031 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6032 emitTargetRegion(CGF, S, Action); 6033 }; 6034 emitCommonOMPTargetDirective(*this, S, CodeGen); 6035 } 6036 6037 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, 6038 const OMPExecutableDirective &S, 6039 OpenMPDirectiveKind InnermostKind, 6040 const RegionCodeGenTy &CodeGen) { 6041 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams); 6042 llvm::Function *OutlinedFn = 6043 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction( 6044 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 6045 6046 const auto *NT = S.getSingleClause<OMPNumTeamsClause>(); 6047 const auto *TL = S.getSingleClause<OMPThreadLimitClause>(); 6048 if (NT || TL) { 6049 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr; 6050 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr; 6051 6052 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit, 6053 S.getBeginLoc()); 6054 } 6055 6056 OMPTeamsScope Scope(CGF, S); 6057 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 6058 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 6059 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn, 6060 CapturedVars); 6061 } 6062 6063 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) { 6064 // Emit teams region as a standalone region. 6065 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6066 Action.Enter(CGF); 6067 OMPPrivateScope PrivateScope(CGF); 6068 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 6069 CGF.EmitOMPPrivateClause(S, PrivateScope); 6070 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6071 (void)PrivateScope.Privatize(); 6072 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt()); 6073 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6074 }; 6075 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 6076 emitPostUpdateForReductionClause(*this, S, 6077 [](CodeGenFunction &) { return nullptr; }); 6078 } 6079 6080 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 6081 const OMPTargetTeamsDirective &S) { 6082 auto *CS = S.getCapturedStmt(OMPD_teams); 6083 Action.Enter(CGF); 6084 // Emit teams region as a standalone region. 6085 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 6086 Action.Enter(CGF); 6087 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6088 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 6089 CGF.EmitOMPPrivateClause(S, PrivateScope); 6090 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6091 (void)PrivateScope.Privatize(); 6092 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 6093 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 6094 CGF.EmitStmt(CS->getCapturedStmt()); 6095 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6096 }; 6097 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen); 6098 emitPostUpdateForReductionClause(CGF, S, 6099 [](CodeGenFunction &) { return nullptr; }); 6100 } 6101 6102 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction( 6103 CodeGenModule &CGM, StringRef ParentName, 6104 const OMPTargetTeamsDirective &S) { 6105 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6106 emitTargetTeamsRegion(CGF, Action, S); 6107 }; 6108 llvm::Function *Fn; 6109 llvm::Constant *Addr; 6110 // Emit target region as a standalone region. 6111 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6112 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6113 assert(Fn && Addr && "Target device function emission failed."); 6114 } 6115 6116 void CodeGenFunction::EmitOMPTargetTeamsDirective( 6117 const OMPTargetTeamsDirective &S) { 6118 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6119 emitTargetTeamsRegion(CGF, Action, S); 6120 }; 6121 emitCommonOMPTargetDirective(*this, S, CodeGen); 6122 } 6123 6124 static void 6125 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 6126 const OMPTargetTeamsDistributeDirective &S) { 6127 Action.Enter(CGF); 6128 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6129 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 6130 }; 6131 6132 // Emit teams region as a standalone region. 6133 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6134 PrePostActionTy &Action) { 6135 Action.Enter(CGF); 6136 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6137 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6138 (void)PrivateScope.Privatize(); 6139 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6140 CodeGenDistribute); 6141 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6142 }; 6143 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen); 6144 emitPostUpdateForReductionClause(CGF, S, 6145 [](CodeGenFunction &) { return nullptr; }); 6146 } 6147 6148 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction( 6149 CodeGenModule &CGM, StringRef ParentName, 6150 const OMPTargetTeamsDistributeDirective &S) { 6151 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6152 emitTargetTeamsDistributeRegion(CGF, Action, S); 6153 }; 6154 llvm::Function *Fn; 6155 llvm::Constant *Addr; 6156 // Emit target region as a standalone region. 6157 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6158 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6159 assert(Fn && Addr && "Target device function emission failed."); 6160 } 6161 6162 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective( 6163 const OMPTargetTeamsDistributeDirective &S) { 6164 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6165 emitTargetTeamsDistributeRegion(CGF, Action, S); 6166 }; 6167 emitCommonOMPTargetDirective(*this, S, CodeGen); 6168 } 6169 6170 static void emitTargetTeamsDistributeSimdRegion( 6171 CodeGenFunction &CGF, PrePostActionTy &Action, 6172 const OMPTargetTeamsDistributeSimdDirective &S) { 6173 Action.Enter(CGF); 6174 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6175 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 6176 }; 6177 6178 // Emit teams region as a standalone region. 6179 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6180 PrePostActionTy &Action) { 6181 Action.Enter(CGF); 6182 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6183 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6184 (void)PrivateScope.Privatize(); 6185 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6186 CodeGenDistribute); 6187 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6188 }; 6189 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen); 6190 emitPostUpdateForReductionClause(CGF, S, 6191 [](CodeGenFunction &) { return nullptr; }); 6192 } 6193 6194 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction( 6195 CodeGenModule &CGM, StringRef ParentName, 6196 const OMPTargetTeamsDistributeSimdDirective &S) { 6197 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6198 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 6199 }; 6200 llvm::Function *Fn; 6201 llvm::Constant *Addr; 6202 // Emit target region as a standalone region. 6203 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6204 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6205 assert(Fn && Addr && "Target device function emission failed."); 6206 } 6207 6208 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective( 6209 const OMPTargetTeamsDistributeSimdDirective &S) { 6210 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6211 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 6212 }; 6213 emitCommonOMPTargetDirective(*this, S, CodeGen); 6214 } 6215 6216 void CodeGenFunction::EmitOMPTeamsDistributeDirective( 6217 const OMPTeamsDistributeDirective &S) { 6218 6219 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6220 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 6221 }; 6222 6223 // Emit teams region as a standalone region. 6224 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6225 PrePostActionTy &Action) { 6226 Action.Enter(CGF); 6227 OMPPrivateScope PrivateScope(CGF); 6228 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6229 (void)PrivateScope.Privatize(); 6230 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6231 CodeGenDistribute); 6232 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6233 }; 6234 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 6235 emitPostUpdateForReductionClause(*this, S, 6236 [](CodeGenFunction &) { return nullptr; }); 6237 } 6238 6239 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective( 6240 const OMPTeamsDistributeSimdDirective &S) { 6241 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6242 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 6243 }; 6244 6245 // Emit teams region as a standalone region. 6246 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6247 PrePostActionTy &Action) { 6248 Action.Enter(CGF); 6249 OMPPrivateScope PrivateScope(CGF); 6250 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6251 (void)PrivateScope.Privatize(); 6252 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd, 6253 CodeGenDistribute); 6254 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6255 }; 6256 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen); 6257 emitPostUpdateForReductionClause(*this, S, 6258 [](CodeGenFunction &) { return nullptr; }); 6259 } 6260 6261 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective( 6262 const OMPTeamsDistributeParallelForDirective &S) { 6263 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6264 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6265 S.getDistInc()); 6266 }; 6267 6268 // Emit teams region as a standalone region. 6269 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6270 PrePostActionTy &Action) { 6271 Action.Enter(CGF); 6272 OMPPrivateScope PrivateScope(CGF); 6273 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6274 (void)PrivateScope.Privatize(); 6275 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6276 CodeGenDistribute); 6277 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6278 }; 6279 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen); 6280 emitPostUpdateForReductionClause(*this, S, 6281 [](CodeGenFunction &) { return nullptr; }); 6282 } 6283 6284 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective( 6285 const OMPTeamsDistributeParallelForSimdDirective &S) { 6286 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6287 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6288 S.getDistInc()); 6289 }; 6290 6291 // Emit teams region as a standalone region. 6292 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6293 PrePostActionTy &Action) { 6294 Action.Enter(CGF); 6295 OMPPrivateScope PrivateScope(CGF); 6296 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6297 (void)PrivateScope.Privatize(); 6298 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6299 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6300 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6301 }; 6302 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd, 6303 CodeGen); 6304 emitPostUpdateForReductionClause(*this, S, 6305 [](CodeGenFunction &) { return nullptr; }); 6306 } 6307 6308 static void emitTargetTeamsDistributeParallelForRegion( 6309 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S, 6310 PrePostActionTy &Action) { 6311 Action.Enter(CGF); 6312 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6313 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6314 S.getDistInc()); 6315 }; 6316 6317 // Emit teams region as a standalone region. 6318 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6319 PrePostActionTy &Action) { 6320 Action.Enter(CGF); 6321 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6322 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6323 (void)PrivateScope.Privatize(); 6324 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6325 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6326 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6327 }; 6328 6329 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for, 6330 CodeGenTeams); 6331 emitPostUpdateForReductionClause(CGF, S, 6332 [](CodeGenFunction &) { return nullptr; }); 6333 } 6334 6335 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 6336 CodeGenModule &CGM, StringRef ParentName, 6337 const OMPTargetTeamsDistributeParallelForDirective &S) { 6338 // Emit SPMD target teams distribute parallel for region as a standalone 6339 // region. 6340 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6341 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 6342 }; 6343 llvm::Function *Fn; 6344 llvm::Constant *Addr; 6345 // Emit target region as a standalone region. 6346 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6347 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6348 assert(Fn && Addr && "Target device function emission failed."); 6349 } 6350 6351 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective( 6352 const OMPTargetTeamsDistributeParallelForDirective &S) { 6353 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6354 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 6355 }; 6356 emitCommonOMPTargetDirective(*this, S, CodeGen); 6357 } 6358 6359 static void emitTargetTeamsDistributeParallelForSimdRegion( 6360 CodeGenFunction &CGF, 6361 const OMPTargetTeamsDistributeParallelForSimdDirective &S, 6362 PrePostActionTy &Action) { 6363 Action.Enter(CGF); 6364 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6365 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6366 S.getDistInc()); 6367 }; 6368 6369 // Emit teams region as a standalone region. 6370 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6371 PrePostActionTy &Action) { 6372 Action.Enter(CGF); 6373 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6374 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6375 (void)PrivateScope.Privatize(); 6376 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6377 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6378 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6379 }; 6380 6381 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd, 6382 CodeGenTeams); 6383 emitPostUpdateForReductionClause(CGF, S, 6384 [](CodeGenFunction &) { return nullptr; }); 6385 } 6386 6387 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 6388 CodeGenModule &CGM, StringRef ParentName, 6389 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 6390 // Emit SPMD target teams distribute parallel for simd region as a standalone 6391 // region. 6392 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6393 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 6394 }; 6395 llvm::Function *Fn; 6396 llvm::Constant *Addr; 6397 // Emit target region as a standalone region. 6398 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6399 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6400 assert(Fn && Addr && "Target device function emission failed."); 6401 } 6402 6403 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective( 6404 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 6405 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6406 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 6407 }; 6408 emitCommonOMPTargetDirective(*this, S, CodeGen); 6409 } 6410 6411 void CodeGenFunction::EmitOMPCancellationPointDirective( 6412 const OMPCancellationPointDirective &S) { 6413 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(), 6414 S.getCancelRegion()); 6415 } 6416 6417 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) { 6418 const Expr *IfCond = nullptr; 6419 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 6420 if (C->getNameModifier() == OMPD_unknown || 6421 C->getNameModifier() == OMPD_cancel) { 6422 IfCond = C->getCondition(); 6423 break; 6424 } 6425 } 6426 if (CGM.getLangOpts().OpenMPIRBuilder) { 6427 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 6428 // TODO: This check is necessary as we only generate `omp parallel` through 6429 // the OpenMPIRBuilder for now. 6430 if (S.getCancelRegion() == OMPD_parallel || 6431 S.getCancelRegion() == OMPD_sections || 6432 S.getCancelRegion() == OMPD_section) { 6433 llvm::Value *IfCondition = nullptr; 6434 if (IfCond) 6435 IfCondition = EmitScalarExpr(IfCond, 6436 /*IgnoreResultAssign=*/true); 6437 return Builder.restoreIP( 6438 OMPBuilder.createCancel(Builder, IfCondition, S.getCancelRegion())); 6439 } 6440 } 6441 6442 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond, 6443 S.getCancelRegion()); 6444 } 6445 6446 CodeGenFunction::JumpDest 6447 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) { 6448 if (Kind == OMPD_parallel || Kind == OMPD_task || 6449 Kind == OMPD_target_parallel || Kind == OMPD_taskloop || 6450 Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop) 6451 return ReturnBlock; 6452 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections || 6453 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for || 6454 Kind == OMPD_distribute_parallel_for || 6455 Kind == OMPD_target_parallel_for || 6456 Kind == OMPD_teams_distribute_parallel_for || 6457 Kind == OMPD_target_teams_distribute_parallel_for); 6458 return OMPCancelStack.getExitBlock(); 6459 } 6460 6461 void CodeGenFunction::EmitOMPUseDevicePtrClause( 6462 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope, 6463 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 6464 auto OrigVarIt = C.varlist_begin(); 6465 auto InitIt = C.inits().begin(); 6466 for (const Expr *PvtVarIt : C.private_copies()) { 6467 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl()); 6468 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl()); 6469 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl()); 6470 6471 // In order to identify the right initializer we need to match the 6472 // declaration used by the mapping logic. In some cases we may get 6473 // OMPCapturedExprDecl that refers to the original declaration. 6474 const ValueDecl *MatchingVD = OrigVD; 6475 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 6476 // OMPCapturedExprDecl are used to privative fields of the current 6477 // structure. 6478 const auto *ME = cast<MemberExpr>(OED->getInit()); 6479 assert(isa<CXXThisExpr>(ME->getBase()) && 6480 "Base should be the current struct!"); 6481 MatchingVD = ME->getMemberDecl(); 6482 } 6483 6484 // If we don't have information about the current list item, move on to 6485 // the next one. 6486 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 6487 if (InitAddrIt == CaptureDeviceAddrMap.end()) 6488 continue; 6489 6490 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD, 6491 InitAddrIt, InitVD, 6492 PvtVD]() { 6493 // Initialize the temporary initialization variable with the address we 6494 // get from the runtime library. We have to cast the source address 6495 // because it is always a void *. References are materialized in the 6496 // privatization scope, so the initialization here disregards the fact 6497 // the original variable is a reference. 6498 QualType AddrQTy = 6499 getContext().getPointerType(OrigVD->getType().getNonReferenceType()); 6500 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy); 6501 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy); 6502 setAddrOfLocalVar(InitVD, InitAddr); 6503 6504 // Emit private declaration, it will be initialized by the value we 6505 // declaration we just added to the local declarations map. 6506 EmitDecl(*PvtVD); 6507 6508 // The initialization variables reached its purpose in the emission 6509 // of the previous declaration, so we don't need it anymore. 6510 LocalDeclMap.erase(InitVD); 6511 6512 // Return the address of the private variable. 6513 return GetAddrOfLocalVar(PvtVD); 6514 }); 6515 assert(IsRegistered && "firstprivate var already registered as private"); 6516 // Silence the warning about unused variable. 6517 (void)IsRegistered; 6518 6519 ++OrigVarIt; 6520 ++InitIt; 6521 } 6522 } 6523 6524 static const VarDecl *getBaseDecl(const Expr *Ref) { 6525 const Expr *Base = Ref->IgnoreParenImpCasts(); 6526 while (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Base)) 6527 Base = OASE->getBase()->IgnoreParenImpCasts(); 6528 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Base)) 6529 Base = ASE->getBase()->IgnoreParenImpCasts(); 6530 return cast<VarDecl>(cast<DeclRefExpr>(Base)->getDecl()); 6531 } 6532 6533 void CodeGenFunction::EmitOMPUseDeviceAddrClause( 6534 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope, 6535 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 6536 llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed; 6537 for (const Expr *Ref : C.varlists()) { 6538 const VarDecl *OrigVD = getBaseDecl(Ref); 6539 if (!Processed.insert(OrigVD).second) 6540 continue; 6541 // In order to identify the right initializer we need to match the 6542 // declaration used by the mapping logic. In some cases we may get 6543 // OMPCapturedExprDecl that refers to the original declaration. 6544 const ValueDecl *MatchingVD = OrigVD; 6545 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 6546 // OMPCapturedExprDecl are used to privative fields of the current 6547 // structure. 6548 const auto *ME = cast<MemberExpr>(OED->getInit()); 6549 assert(isa<CXXThisExpr>(ME->getBase()) && 6550 "Base should be the current struct!"); 6551 MatchingVD = ME->getMemberDecl(); 6552 } 6553 6554 // If we don't have information about the current list item, move on to 6555 // the next one. 6556 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 6557 if (InitAddrIt == CaptureDeviceAddrMap.end()) 6558 continue; 6559 6560 Address PrivAddr = InitAddrIt->getSecond(); 6561 // For declrefs and variable length array need to load the pointer for 6562 // correct mapping, since the pointer to the data was passed to the runtime. 6563 if (isa<DeclRefExpr>(Ref->IgnoreParenImpCasts()) || 6564 MatchingVD->getType()->isArrayType()) 6565 PrivAddr = 6566 EmitLoadOfPointer(PrivAddr, getContext() 6567 .getPointerType(OrigVD->getType()) 6568 ->castAs<PointerType>()); 6569 llvm::Type *RealTy = 6570 ConvertTypeForMem(OrigVD->getType().getNonReferenceType()) 6571 ->getPointerTo(); 6572 PrivAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(PrivAddr, RealTy); 6573 6574 (void)PrivateScope.addPrivate(OrigVD, [PrivAddr]() { return PrivAddr; }); 6575 } 6576 } 6577 6578 // Generate the instructions for '#pragma omp target data' directive. 6579 void CodeGenFunction::EmitOMPTargetDataDirective( 6580 const OMPTargetDataDirective &S) { 6581 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true, 6582 /*SeparateBeginEndCalls=*/true); 6583 6584 // Create a pre/post action to signal the privatization of the device pointer. 6585 // This action can be replaced by the OpenMP runtime code generation to 6586 // deactivate privatization. 6587 bool PrivatizeDevicePointers = false; 6588 class DevicePointerPrivActionTy : public PrePostActionTy { 6589 bool &PrivatizeDevicePointers; 6590 6591 public: 6592 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers) 6593 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {} 6594 void Enter(CodeGenFunction &CGF) override { 6595 PrivatizeDevicePointers = true; 6596 } 6597 }; 6598 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers); 6599 6600 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers]( 6601 CodeGenFunction &CGF, PrePostActionTy &Action) { 6602 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6603 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 6604 }; 6605 6606 // Codegen that selects whether to generate the privatization code or not. 6607 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers, 6608 &InnermostCodeGen](CodeGenFunction &CGF, 6609 PrePostActionTy &Action) { 6610 RegionCodeGenTy RCG(InnermostCodeGen); 6611 PrivatizeDevicePointers = false; 6612 6613 // Call the pre-action to change the status of PrivatizeDevicePointers if 6614 // needed. 6615 Action.Enter(CGF); 6616 6617 if (PrivatizeDevicePointers) { 6618 OMPPrivateScope PrivateScope(CGF); 6619 // Emit all instances of the use_device_ptr clause. 6620 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>()) 6621 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope, 6622 Info.CaptureDeviceAddrMap); 6623 for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>()) 6624 CGF.EmitOMPUseDeviceAddrClause(*C, PrivateScope, 6625 Info.CaptureDeviceAddrMap); 6626 (void)PrivateScope.Privatize(); 6627 RCG(CGF); 6628 } else { 6629 OMPLexicalScope Scope(CGF, S, OMPD_unknown); 6630 RCG(CGF); 6631 } 6632 }; 6633 6634 // Forward the provided action to the privatization codegen. 6635 RegionCodeGenTy PrivRCG(PrivCodeGen); 6636 PrivRCG.setAction(Action); 6637 6638 // Notwithstanding the body of the region is emitted as inlined directive, 6639 // we don't use an inline scope as changes in the references inside the 6640 // region are expected to be visible outside, so we do not privative them. 6641 OMPLexicalScope Scope(CGF, S); 6642 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, 6643 PrivRCG); 6644 }; 6645 6646 RegionCodeGenTy RCG(CodeGen); 6647 6648 // If we don't have target devices, don't bother emitting the data mapping 6649 // code. 6650 if (CGM.getLangOpts().OMPTargetTriples.empty()) { 6651 RCG(*this); 6652 return; 6653 } 6654 6655 // Check if we have any if clause associated with the directive. 6656 const Expr *IfCond = nullptr; 6657 if (const auto *C = S.getSingleClause<OMPIfClause>()) 6658 IfCond = C->getCondition(); 6659 6660 // Check if we have any device clause associated with the directive. 6661 const Expr *Device = nullptr; 6662 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 6663 Device = C->getDevice(); 6664 6665 // Set the action to signal privatization of device pointers. 6666 RCG.setAction(PrivAction); 6667 6668 // Emit region code. 6669 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG, 6670 Info); 6671 } 6672 6673 void CodeGenFunction::EmitOMPTargetEnterDataDirective( 6674 const OMPTargetEnterDataDirective &S) { 6675 // If we don't have target devices, don't bother emitting the data mapping 6676 // code. 6677 if (CGM.getLangOpts().OMPTargetTriples.empty()) 6678 return; 6679 6680 // Check if we have any if clause associated with the directive. 6681 const Expr *IfCond = nullptr; 6682 if (const auto *C = S.getSingleClause<OMPIfClause>()) 6683 IfCond = C->getCondition(); 6684 6685 // Check if we have any device clause associated with the directive. 6686 const Expr *Device = nullptr; 6687 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 6688 Device = C->getDevice(); 6689 6690 OMPLexicalScope Scope(*this, S, OMPD_task); 6691 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 6692 } 6693 6694 void CodeGenFunction::EmitOMPTargetExitDataDirective( 6695 const OMPTargetExitDataDirective &S) { 6696 // If we don't have target devices, don't bother emitting the data mapping 6697 // code. 6698 if (CGM.getLangOpts().OMPTargetTriples.empty()) 6699 return; 6700 6701 // Check if we have any if clause associated with the directive. 6702 const Expr *IfCond = nullptr; 6703 if (const auto *C = S.getSingleClause<OMPIfClause>()) 6704 IfCond = C->getCondition(); 6705 6706 // Check if we have any device clause associated with the directive. 6707 const Expr *Device = nullptr; 6708 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 6709 Device = C->getDevice(); 6710 6711 OMPLexicalScope Scope(*this, S, OMPD_task); 6712 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 6713 } 6714 6715 static void emitTargetParallelRegion(CodeGenFunction &CGF, 6716 const OMPTargetParallelDirective &S, 6717 PrePostActionTy &Action) { 6718 // Get the captured statement associated with the 'parallel' region. 6719 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 6720 Action.Enter(CGF); 6721 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 6722 Action.Enter(CGF); 6723 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6724 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 6725 CGF.EmitOMPPrivateClause(S, PrivateScope); 6726 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6727 (void)PrivateScope.Privatize(); 6728 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 6729 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 6730 // TODO: Add support for clauses. 6731 CGF.EmitStmt(CS->getCapturedStmt()); 6732 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 6733 }; 6734 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen, 6735 emitEmptyBoundParameters); 6736 emitPostUpdateForReductionClause(CGF, S, 6737 [](CodeGenFunction &) { return nullptr; }); 6738 } 6739 6740 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction( 6741 CodeGenModule &CGM, StringRef ParentName, 6742 const OMPTargetParallelDirective &S) { 6743 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6744 emitTargetParallelRegion(CGF, S, Action); 6745 }; 6746 llvm::Function *Fn; 6747 llvm::Constant *Addr; 6748 // Emit target region as a standalone region. 6749 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6750 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6751 assert(Fn && Addr && "Target device function emission failed."); 6752 } 6753 6754 void CodeGenFunction::EmitOMPTargetParallelDirective( 6755 const OMPTargetParallelDirective &S) { 6756 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6757 emitTargetParallelRegion(CGF, S, Action); 6758 }; 6759 emitCommonOMPTargetDirective(*this, S, CodeGen); 6760 } 6761 6762 static void emitTargetParallelForRegion(CodeGenFunction &CGF, 6763 const OMPTargetParallelForDirective &S, 6764 PrePostActionTy &Action) { 6765 Action.Enter(CGF); 6766 // Emit directive as a combined directive that consists of two implicit 6767 // directives: 'parallel' with 'for' directive. 6768 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6769 Action.Enter(CGF); 6770 CodeGenFunction::OMPCancelStackRAII CancelRegion( 6771 CGF, OMPD_target_parallel_for, S.hasCancel()); 6772 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 6773 emitDispatchForLoopBounds); 6774 }; 6775 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen, 6776 emitEmptyBoundParameters); 6777 } 6778 6779 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction( 6780 CodeGenModule &CGM, StringRef ParentName, 6781 const OMPTargetParallelForDirective &S) { 6782 // Emit SPMD target parallel for region as a standalone region. 6783 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6784 emitTargetParallelForRegion(CGF, S, Action); 6785 }; 6786 llvm::Function *Fn; 6787 llvm::Constant *Addr; 6788 // Emit target region as a standalone region. 6789 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6790 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6791 assert(Fn && Addr && "Target device function emission failed."); 6792 } 6793 6794 void CodeGenFunction::EmitOMPTargetParallelForDirective( 6795 const OMPTargetParallelForDirective &S) { 6796 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6797 emitTargetParallelForRegion(CGF, S, Action); 6798 }; 6799 emitCommonOMPTargetDirective(*this, S, CodeGen); 6800 } 6801 6802 static void 6803 emitTargetParallelForSimdRegion(CodeGenFunction &CGF, 6804 const OMPTargetParallelForSimdDirective &S, 6805 PrePostActionTy &Action) { 6806 Action.Enter(CGF); 6807 // Emit directive as a combined directive that consists of two implicit 6808 // directives: 'parallel' with 'for' directive. 6809 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6810 Action.Enter(CGF); 6811 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 6812 emitDispatchForLoopBounds); 6813 }; 6814 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen, 6815 emitEmptyBoundParameters); 6816 } 6817 6818 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction( 6819 CodeGenModule &CGM, StringRef ParentName, 6820 const OMPTargetParallelForSimdDirective &S) { 6821 // Emit SPMD target parallel for region as a standalone region. 6822 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6823 emitTargetParallelForSimdRegion(CGF, S, Action); 6824 }; 6825 llvm::Function *Fn; 6826 llvm::Constant *Addr; 6827 // Emit target region as a standalone region. 6828 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6829 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6830 assert(Fn && Addr && "Target device function emission failed."); 6831 } 6832 6833 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective( 6834 const OMPTargetParallelForSimdDirective &S) { 6835 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6836 emitTargetParallelForSimdRegion(CGF, S, Action); 6837 }; 6838 emitCommonOMPTargetDirective(*this, S, CodeGen); 6839 } 6840 6841 /// Emit a helper variable and return corresponding lvalue. 6842 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, 6843 const ImplicitParamDecl *PVD, 6844 CodeGenFunction::OMPPrivateScope &Privates) { 6845 const auto *VDecl = cast<VarDecl>(Helper->getDecl()); 6846 Privates.addPrivate(VDecl, 6847 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); }); 6848 } 6849 6850 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) { 6851 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind())); 6852 // Emit outlined function for task construct. 6853 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop); 6854 Address CapturedStruct = Address::invalid(); 6855 { 6856 OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 6857 CapturedStruct = GenerateCapturedStmtArgument(*CS); 6858 } 6859 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 6860 const Expr *IfCond = nullptr; 6861 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 6862 if (C->getNameModifier() == OMPD_unknown || 6863 C->getNameModifier() == OMPD_taskloop) { 6864 IfCond = C->getCondition(); 6865 break; 6866 } 6867 } 6868 6869 OMPTaskDataTy Data; 6870 // Check if taskloop must be emitted without taskgroup. 6871 Data.Nogroup = S.getSingleClause<OMPNogroupClause>(); 6872 // TODO: Check if we should emit tied or untied task. 6873 Data.Tied = true; 6874 // Set scheduling for taskloop 6875 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) { 6876 // grainsize clause 6877 Data.Schedule.setInt(/*IntVal=*/false); 6878 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize())); 6879 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) { 6880 // num_tasks clause 6881 Data.Schedule.setInt(/*IntVal=*/true); 6882 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks())); 6883 } 6884 6885 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) { 6886 // if (PreCond) { 6887 // for (IV in 0..LastIteration) BODY; 6888 // <Final counter/linear vars updates>; 6889 // } 6890 // 6891 6892 // Emit: if (PreCond) - begin. 6893 // If the condition constant folds and can be elided, avoid emitting the 6894 // whole loop. 6895 bool CondConstant; 6896 llvm::BasicBlock *ContBlock = nullptr; 6897 OMPLoopScope PreInitScope(CGF, S); 6898 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 6899 if (!CondConstant) 6900 return; 6901 } else { 6902 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then"); 6903 ContBlock = CGF.createBasicBlock("taskloop.if.end"); 6904 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 6905 CGF.getProfileCount(&S)); 6906 CGF.EmitBlock(ThenBlock); 6907 CGF.incrementProfileCounter(&S); 6908 } 6909 6910 (void)CGF.EmitOMPLinearClauseInit(S); 6911 6912 OMPPrivateScope LoopScope(CGF); 6913 // Emit helper vars inits. 6914 enum { LowerBound = 5, UpperBound, Stride, LastIter }; 6915 auto *I = CS->getCapturedDecl()->param_begin(); 6916 auto *LBP = std::next(I, LowerBound); 6917 auto *UBP = std::next(I, UpperBound); 6918 auto *STP = std::next(I, Stride); 6919 auto *LIP = std::next(I, LastIter); 6920 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP, 6921 LoopScope); 6922 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP, 6923 LoopScope); 6924 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope); 6925 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP, 6926 LoopScope); 6927 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 6928 CGF.EmitOMPLinearClause(S, LoopScope); 6929 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 6930 (void)LoopScope.Privatize(); 6931 // Emit the loop iteration variable. 6932 const Expr *IVExpr = S.getIterationVariable(); 6933 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 6934 CGF.EmitVarDecl(*IVDecl); 6935 CGF.EmitIgnoredExpr(S.getInit()); 6936 6937 // Emit the iterations count variable. 6938 // If it is not a variable, Sema decided to calculate iterations count on 6939 // each iteration (e.g., it is foldable into a constant). 6940 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 6941 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 6942 // Emit calculation of the iterations count. 6943 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 6944 } 6945 6946 { 6947 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 6948 emitCommonSimdLoop( 6949 CGF, S, 6950 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6951 if (isOpenMPSimdDirective(S.getDirectiveKind())) 6952 CGF.EmitOMPSimdInit(S); 6953 }, 6954 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 6955 CGF.EmitOMPInnerLoop( 6956 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 6957 [&S](CodeGenFunction &CGF) { 6958 emitOMPLoopBodyWithStopPoint(CGF, S, 6959 CodeGenFunction::JumpDest()); 6960 }, 6961 [](CodeGenFunction &) {}); 6962 }); 6963 } 6964 // Emit: if (PreCond) - end. 6965 if (ContBlock) { 6966 CGF.EmitBranch(ContBlock); 6967 CGF.EmitBlock(ContBlock, true); 6968 } 6969 // Emit final copy of the lastprivate variables if IsLastIter != 0. 6970 if (HasLastprivateClause) { 6971 CGF.EmitOMPLastprivateClauseFinal( 6972 S, isOpenMPSimdDirective(S.getDirectiveKind()), 6973 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar( 6974 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 6975 (*LIP)->getType(), S.getBeginLoc()))); 6976 } 6977 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) { 6978 return CGF.Builder.CreateIsNotNull( 6979 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 6980 (*LIP)->getType(), S.getBeginLoc())); 6981 }); 6982 }; 6983 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 6984 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 6985 const OMPTaskDataTy &Data) { 6986 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond, 6987 &Data](CodeGenFunction &CGF, PrePostActionTy &) { 6988 OMPLoopScope PreInitScope(CGF, S); 6989 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S, 6990 OutlinedFn, SharedsTy, 6991 CapturedStruct, IfCond, Data); 6992 }; 6993 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop, 6994 CodeGen); 6995 }; 6996 if (Data.Nogroup) { 6997 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data); 6998 } else { 6999 CGM.getOpenMPRuntime().emitTaskgroupRegion( 7000 *this, 7001 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF, 7002 PrePostActionTy &Action) { 7003 Action.Enter(CGF); 7004 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, 7005 Data); 7006 }, 7007 S.getBeginLoc()); 7008 } 7009 } 7010 7011 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) { 7012 auto LPCRegion = 7013 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7014 EmitOMPTaskLoopBasedDirective(S); 7015 } 7016 7017 void CodeGenFunction::EmitOMPTaskLoopSimdDirective( 7018 const OMPTaskLoopSimdDirective &S) { 7019 auto LPCRegion = 7020 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7021 OMPLexicalScope Scope(*this, S); 7022 EmitOMPTaskLoopBasedDirective(S); 7023 } 7024 7025 void CodeGenFunction::EmitOMPMasterTaskLoopDirective( 7026 const OMPMasterTaskLoopDirective &S) { 7027 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7028 Action.Enter(CGF); 7029 EmitOMPTaskLoopBasedDirective(S); 7030 }; 7031 auto LPCRegion = 7032 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7033 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false); 7034 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 7035 } 7036 7037 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective( 7038 const OMPMasterTaskLoopSimdDirective &S) { 7039 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7040 Action.Enter(CGF); 7041 EmitOMPTaskLoopBasedDirective(S); 7042 }; 7043 auto LPCRegion = 7044 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7045 OMPLexicalScope Scope(*this, S); 7046 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 7047 } 7048 7049 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective( 7050 const OMPParallelMasterTaskLoopDirective &S) { 7051 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7052 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 7053 PrePostActionTy &Action) { 7054 Action.Enter(CGF); 7055 CGF.EmitOMPTaskLoopBasedDirective(S); 7056 }; 7057 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 7058 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 7059 S.getBeginLoc()); 7060 }; 7061 auto LPCRegion = 7062 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7063 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen, 7064 emitEmptyBoundParameters); 7065 } 7066 7067 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective( 7068 const OMPParallelMasterTaskLoopSimdDirective &S) { 7069 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7070 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 7071 PrePostActionTy &Action) { 7072 Action.Enter(CGF); 7073 CGF.EmitOMPTaskLoopBasedDirective(S); 7074 }; 7075 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 7076 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 7077 S.getBeginLoc()); 7078 }; 7079 auto LPCRegion = 7080 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7081 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen, 7082 emitEmptyBoundParameters); 7083 } 7084 7085 // Generate the instructions for '#pragma omp target update' directive. 7086 void CodeGenFunction::EmitOMPTargetUpdateDirective( 7087 const OMPTargetUpdateDirective &S) { 7088 // If we don't have target devices, don't bother emitting the data mapping 7089 // code. 7090 if (CGM.getLangOpts().OMPTargetTriples.empty()) 7091 return; 7092 7093 // Check if we have any if clause associated with the directive. 7094 const Expr *IfCond = nullptr; 7095 if (const auto *C = S.getSingleClause<OMPIfClause>()) 7096 IfCond = C->getCondition(); 7097 7098 // Check if we have any device clause associated with the directive. 7099 const Expr *Device = nullptr; 7100 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 7101 Device = C->getDevice(); 7102 7103 OMPLexicalScope Scope(*this, S, OMPD_task); 7104 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 7105 } 7106 7107 void CodeGenFunction::EmitSimpleOMPExecutableDirective( 7108 const OMPExecutableDirective &D) { 7109 if (const auto *SD = dyn_cast<OMPScanDirective>(&D)) { 7110 EmitOMPScanDirective(*SD); 7111 return; 7112 } 7113 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt()) 7114 return; 7115 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) { 7116 OMPPrivateScope GlobalsScope(CGF); 7117 if (isOpenMPTaskingDirective(D.getDirectiveKind())) { 7118 // Capture global firstprivates to avoid crash. 7119 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 7120 for (const Expr *Ref : C->varlists()) { 7121 const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 7122 if (!DRE) 7123 continue; 7124 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7125 if (!VD || VD->hasLocalStorage()) 7126 continue; 7127 if (!CGF.LocalDeclMap.count(VD)) { 7128 LValue GlobLVal = CGF.EmitLValue(Ref); 7129 GlobalsScope.addPrivate( 7130 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); }); 7131 } 7132 } 7133 } 7134 } 7135 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 7136 (void)GlobalsScope.Privatize(); 7137 ParentLoopDirectiveForScanRegion ScanRegion(CGF, D); 7138 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action); 7139 } else { 7140 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) { 7141 for (const Expr *E : LD->counters()) { 7142 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 7143 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) { 7144 LValue GlobLVal = CGF.EmitLValue(E); 7145 GlobalsScope.addPrivate( 7146 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); }); 7147 } 7148 if (isa<OMPCapturedExprDecl>(VD)) { 7149 // Emit only those that were not explicitly referenced in clauses. 7150 if (!CGF.LocalDeclMap.count(VD)) 7151 CGF.EmitVarDecl(*VD); 7152 } 7153 } 7154 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) { 7155 if (!C->getNumForLoops()) 7156 continue; 7157 for (unsigned I = LD->getLoopsNumber(), 7158 E = C->getLoopNumIterations().size(); 7159 I < E; ++I) { 7160 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>( 7161 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) { 7162 // Emit only those that were not explicitly referenced in clauses. 7163 if (!CGF.LocalDeclMap.count(VD)) 7164 CGF.EmitVarDecl(*VD); 7165 } 7166 } 7167 } 7168 } 7169 (void)GlobalsScope.Privatize(); 7170 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt()); 7171 } 7172 }; 7173 if (D.getDirectiveKind() == OMPD_atomic || 7174 D.getDirectiveKind() == OMPD_critical || 7175 D.getDirectiveKind() == OMPD_section || 7176 D.getDirectiveKind() == OMPD_master || 7177 D.getDirectiveKind() == OMPD_masked) { 7178 EmitStmt(D.getAssociatedStmt()); 7179 } else { 7180 auto LPCRegion = 7181 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D); 7182 OMPSimdLexicalScope Scope(*this, D); 7183 CGM.getOpenMPRuntime().emitInlinedDirective( 7184 *this, 7185 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd 7186 : D.getDirectiveKind(), 7187 CodeGen); 7188 } 7189 // Check for outer lastprivate conditional update. 7190 checkForLastprivateConditionalUpdate(*this, D); 7191 } 7192