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