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 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 1454 }; 1455 1456 // Privatization callback that performs appropriate action for 1457 // shared/private/firstprivate/lastprivate/copyin/... variables. 1458 // 1459 // TODO: This defaults to shared right now. 1460 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1461 llvm::Value &Val, llvm::Value *&ReplVal) { 1462 // The next line is appropriate only for variables (Val) with the 1463 // data-sharing attribute "shared". 1464 ReplVal = &Val; 1465 1466 return CodeGenIP; 1467 }; 1468 1469 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1470 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt(); 1471 1472 auto BodyGenCB = [ParallelRegionBodyStmt, 1473 this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1474 llvm::BasicBlock &ContinuationBB) { 1475 OMPBuilderCBHelpers::OutlinedRegionBodyRAII ORB(*this, AllocaIP, 1476 ContinuationBB); 1477 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, ParallelRegionBodyStmt, 1478 CodeGenIP, ContinuationBB); 1479 }; 1480 1481 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 1482 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 1483 Builder.restoreIP(OMPBuilder->CreateParallel(Builder, BodyGenCB, PrivCB, 1484 FiniCB, IfCond, NumThreads, 1485 ProcBind, S.hasCancel())); 1486 return; 1487 } 1488 1489 // Emit parallel region as a standalone region. 1490 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 1491 Action.Enter(CGF); 1492 OMPPrivateScope PrivateScope(CGF); 1493 bool Copyins = CGF.EmitOMPCopyinClause(S); 1494 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 1495 if (Copyins) { 1496 // Emit implicit barrier to synchronize threads and avoid data races on 1497 // propagation master's thread values of threadprivate variables to local 1498 // instances of that variables of all other implicit threads. 1499 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 1500 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 1501 /*ForceSimpleCall=*/true); 1502 } 1503 CGF.EmitOMPPrivateClause(S, PrivateScope); 1504 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 1505 (void)PrivateScope.Privatize(); 1506 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt()); 1507 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 1508 }; 1509 { 1510 auto LPCRegion = 1511 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 1512 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen, 1513 emitEmptyBoundParameters); 1514 emitPostUpdateForReductionClause(*this, S, 1515 [](CodeGenFunction &) { return nullptr; }); 1516 } 1517 // Check for outer lastprivate conditional update. 1518 checkForLastprivateConditionalUpdate(*this, S); 1519 } 1520 1521 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop, 1522 int MaxLevel, int Level = 0) { 1523 assert(Level < MaxLevel && "Too deep lookup during loop body codegen."); 1524 const Stmt *SimplifiedS = S->IgnoreContainers(); 1525 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) { 1526 PrettyStackTraceLoc CrashInfo( 1527 CGF.getContext().getSourceManager(), CS->getLBracLoc(), 1528 "LLVM IR generation of compound statement ('{}')"); 1529 1530 // Keep track of the current cleanup stack depth, including debug scopes. 1531 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange()); 1532 for (const Stmt *CurStmt : CS->body()) 1533 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level); 1534 return; 1535 } 1536 if (SimplifiedS == NextLoop) { 1537 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) { 1538 S = For->getBody(); 1539 } else { 1540 assert(isa<CXXForRangeStmt>(SimplifiedS) && 1541 "Expected canonical for loop or range-based for loop."); 1542 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS); 1543 CGF.EmitStmt(CXXFor->getLoopVarStmt()); 1544 S = CXXFor->getBody(); 1545 } 1546 if (Level + 1 < MaxLevel) { 1547 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop( 1548 S, /*TryImperfectlyNestedLoops=*/true); 1549 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1); 1550 return; 1551 } 1552 } 1553 CGF.EmitStmt(S); 1554 } 1555 1556 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D, 1557 JumpDest LoopExit) { 1558 RunCleanupsScope BodyScope(*this); 1559 // Update counters values on current iteration. 1560 for (const Expr *UE : D.updates()) 1561 EmitIgnoredExpr(UE); 1562 // Update the linear variables. 1563 // In distribute directives only loop counters may be marked as linear, no 1564 // need to generate the code for them. 1565 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) { 1566 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1567 for (const Expr *UE : C->updates()) 1568 EmitIgnoredExpr(UE); 1569 } 1570 } 1571 1572 // On a continue in the body, jump to the end. 1573 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue"); 1574 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1575 for (const Expr *E : D.finals_conditions()) { 1576 if (!E) 1577 continue; 1578 // Check that loop counter in non-rectangular nest fits into the iteration 1579 // space. 1580 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next"); 1581 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(), 1582 getProfileCount(D.getBody())); 1583 EmitBlock(NextBB); 1584 } 1585 // Emit loop variables for C++ range loops. 1586 const Stmt *Body = 1587 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(); 1588 // Emit loop body. 1589 emitBody(*this, Body, 1590 OMPLoopDirective::tryToFindNextInnerLoop( 1591 Body, /*TryImperfectlyNestedLoops=*/true), 1592 D.getCollapsedNumber()); 1593 1594 // The end (updates/cleanups). 1595 EmitBlock(Continue.getBlock()); 1596 BreakContinueStack.pop_back(); 1597 } 1598 1599 void CodeGenFunction::EmitOMPInnerLoop( 1600 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 1601 const Expr *IncExpr, 1602 const llvm::function_ref<void(CodeGenFunction &)> BodyGen, 1603 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) { 1604 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end"); 1605 1606 // Start the loop with a block that tests the condition. 1607 auto CondBlock = createBasicBlock("omp.inner.for.cond"); 1608 EmitBlock(CondBlock); 1609 const SourceRange R = S.getSourceRange(); 1610 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 1611 SourceLocToDebugLoc(R.getEnd())); 1612 1613 // If there are any cleanups between here and the loop-exit scope, 1614 // create a block to stage a loop exit along. 1615 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 1616 if (RequiresCleanup) 1617 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup"); 1618 1619 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body"); 1620 1621 // Emit condition. 1622 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S)); 1623 if (ExitBlock != LoopExit.getBlock()) { 1624 EmitBlock(ExitBlock); 1625 EmitBranchThroughCleanup(LoopExit); 1626 } 1627 1628 EmitBlock(LoopBody); 1629 incrementProfileCounter(&S); 1630 1631 // Create a block for the increment. 1632 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc"); 1633 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1634 1635 BodyGen(*this); 1636 1637 // Emit "IV = IV + 1" and a back-edge to the condition block. 1638 EmitBlock(Continue.getBlock()); 1639 EmitIgnoredExpr(IncExpr); 1640 PostIncGen(*this); 1641 BreakContinueStack.pop_back(); 1642 EmitBranch(CondBlock); 1643 LoopStack.pop(); 1644 // Emit the fall-through block. 1645 EmitBlock(LoopExit.getBlock()); 1646 } 1647 1648 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) { 1649 if (!HaveInsertPoint()) 1650 return false; 1651 // Emit inits for the linear variables. 1652 bool HasLinears = false; 1653 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1654 for (const Expr *Init : C->inits()) { 1655 HasLinears = true; 1656 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl()); 1657 if (const auto *Ref = 1658 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) { 1659 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 1660 const auto *OrigVD = cast<VarDecl>(Ref->getDecl()); 1661 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 1662 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1663 VD->getInit()->getType(), VK_LValue, 1664 VD->getInit()->getExprLoc()); 1665 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(), 1666 VD->getType()), 1667 /*capturedByInit=*/false); 1668 EmitAutoVarCleanups(Emission); 1669 } else { 1670 EmitVarDecl(*VD); 1671 } 1672 } 1673 // Emit the linear steps for the linear clauses. 1674 // If a step is not constant, it is pre-calculated before the loop. 1675 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep())) 1676 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) { 1677 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl())); 1678 // Emit calculation of the linear step. 1679 EmitIgnoredExpr(CS); 1680 } 1681 } 1682 return HasLinears; 1683 } 1684 1685 void CodeGenFunction::EmitOMPLinearClauseFinal( 1686 const OMPLoopDirective &D, 1687 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 1688 if (!HaveInsertPoint()) 1689 return; 1690 llvm::BasicBlock *DoneBB = nullptr; 1691 // Emit the final values of the linear variables. 1692 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1693 auto IC = C->varlist_begin(); 1694 for (const Expr *F : C->finals()) { 1695 if (!DoneBB) { 1696 if (llvm::Value *Cond = CondGen(*this)) { 1697 // If the first post-update expression is found, emit conditional 1698 // block if it was requested. 1699 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu"); 1700 DoneBB = createBasicBlock(".omp.linear.pu.done"); 1701 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1702 EmitBlock(ThenBB); 1703 } 1704 } 1705 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl()); 1706 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 1707 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1708 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 1709 Address OrigAddr = EmitLValue(&DRE).getAddress(*this); 1710 CodeGenFunction::OMPPrivateScope VarScope(*this); 1711 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; }); 1712 (void)VarScope.Privatize(); 1713 EmitIgnoredExpr(F); 1714 ++IC; 1715 } 1716 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 1717 EmitIgnoredExpr(PostUpdate); 1718 } 1719 if (DoneBB) 1720 EmitBlock(DoneBB, /*IsFinished=*/true); 1721 } 1722 1723 static void emitAlignedClause(CodeGenFunction &CGF, 1724 const OMPExecutableDirective &D) { 1725 if (!CGF.HaveInsertPoint()) 1726 return; 1727 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) { 1728 llvm::APInt ClauseAlignment(64, 0); 1729 if (const Expr *AlignmentExpr = Clause->getAlignment()) { 1730 auto *AlignmentCI = 1731 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr)); 1732 ClauseAlignment = AlignmentCI->getValue(); 1733 } 1734 for (const Expr *E : Clause->varlists()) { 1735 llvm::APInt Alignment(ClauseAlignment); 1736 if (Alignment == 0) { 1737 // OpenMP [2.8.1, Description] 1738 // If no optional parameter is specified, implementation-defined default 1739 // alignments for SIMD instructions on the target platforms are assumed. 1740 Alignment = 1741 CGF.getContext() 1742 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 1743 E->getType()->getPointeeType())) 1744 .getQuantity(); 1745 } 1746 assert((Alignment == 0 || Alignment.isPowerOf2()) && 1747 "alignment is not power of 2"); 1748 if (Alignment != 0) { 1749 llvm::Value *PtrValue = CGF.EmitScalarExpr(E); 1750 CGF.emitAlignmentAssumption( 1751 PtrValue, E, /*No second loc needed*/ SourceLocation(), 1752 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment)); 1753 } 1754 } 1755 } 1756 } 1757 1758 void CodeGenFunction::EmitOMPPrivateLoopCounters( 1759 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) { 1760 if (!HaveInsertPoint()) 1761 return; 1762 auto I = S.private_counters().begin(); 1763 for (const Expr *E : S.counters()) { 1764 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1765 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()); 1766 // Emit var without initialization. 1767 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD); 1768 EmitAutoVarCleanups(VarEmission); 1769 LocalDeclMap.erase(PrivateVD); 1770 (void)LoopScope.addPrivate(VD, [&VarEmission]() { 1771 return VarEmission.getAllocatedAddress(); 1772 }); 1773 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) || 1774 VD->hasGlobalStorage()) { 1775 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() { 1776 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), 1777 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD), 1778 E->getType(), VK_LValue, E->getExprLoc()); 1779 return EmitLValue(&DRE).getAddress(*this); 1780 }); 1781 } else { 1782 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() { 1783 return VarEmission.getAllocatedAddress(); 1784 }); 1785 } 1786 ++I; 1787 } 1788 // Privatize extra loop counters used in loops for ordered(n) clauses. 1789 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) { 1790 if (!C->getNumForLoops()) 1791 continue; 1792 for (unsigned I = S.getCollapsedNumber(), 1793 E = C->getLoopNumIterations().size(); 1794 I < E; ++I) { 1795 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I)); 1796 const auto *VD = cast<VarDecl>(DRE->getDecl()); 1797 // Override only those variables that can be captured to avoid re-emission 1798 // of the variables declared within the loops. 1799 if (DRE->refersToEnclosingVariableOrCapture()) { 1800 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() { 1801 return CreateMemTemp(DRE->getType(), VD->getName()); 1802 }); 1803 } 1804 } 1805 } 1806 } 1807 1808 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, 1809 const Expr *Cond, llvm::BasicBlock *TrueBlock, 1810 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) { 1811 if (!CGF.HaveInsertPoint()) 1812 return; 1813 { 1814 CodeGenFunction::OMPPrivateScope PreCondScope(CGF); 1815 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope); 1816 (void)PreCondScope.Privatize(); 1817 // Get initial values of real counters. 1818 for (const Expr *I : S.inits()) { 1819 CGF.EmitIgnoredExpr(I); 1820 } 1821 } 1822 // Create temp loop control variables with their init values to support 1823 // non-rectangular loops. 1824 CodeGenFunction::OMPMapVars PreCondVars; 1825 for (const Expr * E: S.dependent_counters()) { 1826 if (!E) 1827 continue; 1828 assert(!E->getType().getNonReferenceType()->isRecordType() && 1829 "dependent counter must not be an iterator."); 1830 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1831 Address CounterAddr = 1832 CGF.CreateMemTemp(VD->getType().getNonReferenceType()); 1833 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr); 1834 } 1835 (void)PreCondVars.apply(CGF); 1836 for (const Expr *E : S.dependent_inits()) { 1837 if (!E) 1838 continue; 1839 CGF.EmitIgnoredExpr(E); 1840 } 1841 // Check that loop is executed at least one time. 1842 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 1843 PreCondVars.restore(CGF); 1844 } 1845 1846 void CodeGenFunction::EmitOMPLinearClause( 1847 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) { 1848 if (!HaveInsertPoint()) 1849 return; 1850 llvm::DenseSet<const VarDecl *> SIMDLCVs; 1851 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 1852 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 1853 for (const Expr *C : LoopDirective->counters()) { 1854 SIMDLCVs.insert( 1855 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 1856 } 1857 } 1858 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1859 auto CurPrivate = C->privates().begin(); 1860 for (const Expr *E : C->varlists()) { 1861 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1862 const auto *PrivateVD = 1863 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl()); 1864 if (!SIMDLCVs.count(VD->getCanonicalDecl())) { 1865 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() { 1866 // Emit private VarDecl with copy init. 1867 EmitVarDecl(*PrivateVD); 1868 return GetAddrOfLocalVar(PrivateVD); 1869 }); 1870 assert(IsRegistered && "linear var already registered as private"); 1871 // Silence the warning about unused variable. 1872 (void)IsRegistered; 1873 } else { 1874 EmitVarDecl(*PrivateVD); 1875 } 1876 ++CurPrivate; 1877 } 1878 } 1879 } 1880 1881 static void emitSimdlenSafelenClause(CodeGenFunction &CGF, 1882 const OMPExecutableDirective &D, 1883 bool IsMonotonic) { 1884 if (!CGF.HaveInsertPoint()) 1885 return; 1886 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) { 1887 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(), 1888 /*ignoreResult=*/true); 1889 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 1890 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 1891 // In presence of finite 'safelen', it may be unsafe to mark all 1892 // the memory instructions parallel, because loop-carried 1893 // dependences of 'safelen' iterations are possible. 1894 if (!IsMonotonic) 1895 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>()); 1896 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) { 1897 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(), 1898 /*ignoreResult=*/true); 1899 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 1900 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 1901 // In presence of finite 'safelen', it may be unsafe to mark all 1902 // the memory instructions parallel, because loop-carried 1903 // dependences of 'safelen' iterations are possible. 1904 CGF.LoopStack.setParallel(/*Enable=*/false); 1905 } 1906 } 1907 1908 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D, 1909 bool IsMonotonic) { 1910 // Walk clauses and process safelen/lastprivate. 1911 LoopStack.setParallel(!IsMonotonic); 1912 LoopStack.setVectorizeEnable(); 1913 emitSimdlenSafelenClause(*this, D, IsMonotonic); 1914 if (const auto *C = D.getSingleClause<OMPOrderClause>()) 1915 if (C->getKind() == OMPC_ORDER_concurrent) 1916 LoopStack.setParallel(/*Enable=*/true); 1917 } 1918 1919 void CodeGenFunction::EmitOMPSimdFinal( 1920 const OMPLoopDirective &D, 1921 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 1922 if (!HaveInsertPoint()) 1923 return; 1924 llvm::BasicBlock *DoneBB = nullptr; 1925 auto IC = D.counters().begin(); 1926 auto IPC = D.private_counters().begin(); 1927 for (const Expr *F : D.finals()) { 1928 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 1929 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl()); 1930 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD); 1931 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) || 1932 OrigVD->hasGlobalStorage() || CED) { 1933 if (!DoneBB) { 1934 if (llvm::Value *Cond = CondGen(*this)) { 1935 // If the first post-update expression is found, emit conditional 1936 // block if it was requested. 1937 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then"); 1938 DoneBB = createBasicBlock(".omp.final.done"); 1939 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1940 EmitBlock(ThenBB); 1941 } 1942 } 1943 Address OrigAddr = Address::invalid(); 1944 if (CED) { 1945 OrigAddr = 1946 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this); 1947 } else { 1948 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD), 1949 /*RefersToEnclosingVariableOrCapture=*/false, 1950 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc()); 1951 OrigAddr = EmitLValue(&DRE).getAddress(*this); 1952 } 1953 OMPPrivateScope VarScope(*this); 1954 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; }); 1955 (void)VarScope.Privatize(); 1956 EmitIgnoredExpr(F); 1957 } 1958 ++IC; 1959 ++IPC; 1960 } 1961 if (DoneBB) 1962 EmitBlock(DoneBB, /*IsFinished=*/true); 1963 } 1964 1965 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF, 1966 const OMPLoopDirective &S, 1967 CodeGenFunction::JumpDest LoopExit) { 1968 CGF.EmitOMPLoopBody(S, LoopExit); 1969 CGF.EmitStopPoint(&S); 1970 } 1971 1972 /// Emit a helper variable and return corresponding lvalue. 1973 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 1974 const DeclRefExpr *Helper) { 1975 auto VDecl = cast<VarDecl>(Helper->getDecl()); 1976 CGF.EmitVarDecl(*VDecl); 1977 return CGF.EmitLValue(Helper); 1978 } 1979 1980 static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S, 1981 const RegionCodeGenTy &SimdInitGen, 1982 const RegionCodeGenTy &BodyCodeGen) { 1983 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF, 1984 PrePostActionTy &) { 1985 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S); 1986 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 1987 SimdInitGen(CGF); 1988 1989 BodyCodeGen(CGF); 1990 }; 1991 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) { 1992 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 1993 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false); 1994 1995 BodyCodeGen(CGF); 1996 }; 1997 const Expr *IfCond = nullptr; 1998 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 1999 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 2000 if (CGF.getLangOpts().OpenMP >= 50 && 2001 (C->getNameModifier() == OMPD_unknown || 2002 C->getNameModifier() == OMPD_simd)) { 2003 IfCond = C->getCondition(); 2004 break; 2005 } 2006 } 2007 } 2008 if (IfCond) { 2009 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen); 2010 } else { 2011 RegionCodeGenTy ThenRCG(ThenGen); 2012 ThenRCG(CGF); 2013 } 2014 } 2015 2016 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S, 2017 PrePostActionTy &Action) { 2018 Action.Enter(CGF); 2019 assert(isOpenMPSimdDirective(S.getDirectiveKind()) && 2020 "Expected simd directive"); 2021 OMPLoopScope PreInitScope(CGF, S); 2022 // if (PreCond) { 2023 // for (IV in 0..LastIteration) BODY; 2024 // <Final counter/linear vars updates>; 2025 // } 2026 // 2027 if (isOpenMPDistributeDirective(S.getDirectiveKind()) || 2028 isOpenMPWorksharingDirective(S.getDirectiveKind()) || 2029 isOpenMPTaskLoopDirective(S.getDirectiveKind())) { 2030 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable())); 2031 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable())); 2032 } 2033 2034 // Emit: if (PreCond) - begin. 2035 // If the condition constant folds and can be elided, avoid emitting the 2036 // whole loop. 2037 bool CondConstant; 2038 llvm::BasicBlock *ContBlock = nullptr; 2039 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2040 if (!CondConstant) 2041 return; 2042 } else { 2043 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then"); 2044 ContBlock = CGF.createBasicBlock("simd.if.end"); 2045 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 2046 CGF.getProfileCount(&S)); 2047 CGF.EmitBlock(ThenBlock); 2048 CGF.incrementProfileCounter(&S); 2049 } 2050 2051 // Emit the loop iteration variable. 2052 const Expr *IVExpr = S.getIterationVariable(); 2053 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 2054 CGF.EmitVarDecl(*IVDecl); 2055 CGF.EmitIgnoredExpr(S.getInit()); 2056 2057 // Emit the iterations count variable. 2058 // If it is not a variable, Sema decided to calculate iterations count on 2059 // each iteration (e.g., it is foldable into a constant). 2060 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2061 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2062 // Emit calculation of the iterations count. 2063 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 2064 } 2065 2066 emitAlignedClause(CGF, S); 2067 (void)CGF.EmitOMPLinearClauseInit(S); 2068 { 2069 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2070 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 2071 CGF.EmitOMPLinearClause(S, LoopScope); 2072 CGF.EmitOMPPrivateClause(S, LoopScope); 2073 CGF.EmitOMPReductionClauseInit(S, LoopScope); 2074 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 2075 CGF, S, CGF.EmitLValue(S.getIterationVariable())); 2076 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 2077 (void)LoopScope.Privatize(); 2078 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2079 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 2080 2081 emitCommonSimdLoop( 2082 CGF, S, 2083 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2084 CGF.EmitOMPSimdInit(S); 2085 }, 2086 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2087 CGF.EmitOMPInnerLoop( 2088 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 2089 [&S](CodeGenFunction &CGF) { 2090 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest()); 2091 CGF.EmitStopPoint(&S); 2092 }, 2093 [](CodeGenFunction &) {}); 2094 }); 2095 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; }); 2096 // Emit final copy of the lastprivate variables at the end of loops. 2097 if (HasLastprivateClause) 2098 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true); 2099 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd); 2100 emitPostUpdateForReductionClause(CGF, S, 2101 [](CodeGenFunction &) { return nullptr; }); 2102 } 2103 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; }); 2104 // Emit: if (PreCond) - end. 2105 if (ContBlock) { 2106 CGF.EmitBranch(ContBlock); 2107 CGF.EmitBlock(ContBlock, true); 2108 } 2109 } 2110 2111 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 2112 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2113 emitOMPSimdRegion(CGF, S, Action); 2114 }; 2115 { 2116 auto LPCRegion = 2117 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2118 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2119 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2120 } 2121 // Check for outer lastprivate conditional update. 2122 checkForLastprivateConditionalUpdate(*this, S); 2123 } 2124 2125 void CodeGenFunction::EmitOMPOuterLoop( 2126 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S, 2127 CodeGenFunction::OMPPrivateScope &LoopScope, 2128 const CodeGenFunction::OMPLoopArguments &LoopArgs, 2129 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop, 2130 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) { 2131 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2132 2133 const Expr *IVExpr = S.getIterationVariable(); 2134 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2135 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2136 2137 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 2138 2139 // Start the loop with a block that tests the condition. 2140 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond"); 2141 EmitBlock(CondBlock); 2142 const SourceRange R = S.getSourceRange(); 2143 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 2144 SourceLocToDebugLoc(R.getEnd())); 2145 2146 llvm::Value *BoolCondVal = nullptr; 2147 if (!DynamicOrOrdered) { 2148 // UB = min(UB, GlobalUB) or 2149 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g. 2150 // 'distribute parallel for') 2151 EmitIgnoredExpr(LoopArgs.EUB); 2152 // IV = LB 2153 EmitIgnoredExpr(LoopArgs.Init); 2154 // IV < UB 2155 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond); 2156 } else { 2157 BoolCondVal = 2158 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL, 2159 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST); 2160 } 2161 2162 // If there are any cleanups between here and the loop-exit scope, 2163 // create a block to stage a loop exit along. 2164 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 2165 if (LoopScope.requiresCleanups()) 2166 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 2167 2168 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body"); 2169 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 2170 if (ExitBlock != LoopExit.getBlock()) { 2171 EmitBlock(ExitBlock); 2172 EmitBranchThroughCleanup(LoopExit); 2173 } 2174 EmitBlock(LoopBody); 2175 2176 // Emit "IV = LB" (in case of static schedule, we have already calculated new 2177 // LB for loop condition and emitted it above). 2178 if (DynamicOrOrdered) 2179 EmitIgnoredExpr(LoopArgs.Init); 2180 2181 // Create a block for the increment. 2182 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 2183 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 2184 2185 emitCommonSimdLoop( 2186 *this, S, 2187 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) { 2188 // Generate !llvm.loop.parallel metadata for loads and stores for loops 2189 // with dynamic/guided scheduling and without ordered clause. 2190 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2191 CGF.LoopStack.setParallel(!IsMonotonic); 2192 if (const auto *C = S.getSingleClause<OMPOrderClause>()) 2193 if (C->getKind() == OMPC_ORDER_concurrent) 2194 CGF.LoopStack.setParallel(/*Enable=*/true); 2195 } else { 2196 CGF.EmitOMPSimdInit(S, IsMonotonic); 2197 } 2198 }, 2199 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered, 2200 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2201 SourceLocation Loc = S.getBeginLoc(); 2202 // when 'distribute' is not combined with a 'for': 2203 // while (idx <= UB) { BODY; ++idx; } 2204 // when 'distribute' is combined with a 'for' 2205 // (e.g. 'distribute parallel for') 2206 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; } 2207 CGF.EmitOMPInnerLoop( 2208 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr, 2209 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 2210 CodeGenLoop(CGF, S, LoopExit); 2211 }, 2212 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) { 2213 CodeGenOrdered(CGF, Loc, IVSize, IVSigned); 2214 }); 2215 }); 2216 2217 EmitBlock(Continue.getBlock()); 2218 BreakContinueStack.pop_back(); 2219 if (!DynamicOrOrdered) { 2220 // Emit "LB = LB + Stride", "UB = UB + Stride". 2221 EmitIgnoredExpr(LoopArgs.NextLB); 2222 EmitIgnoredExpr(LoopArgs.NextUB); 2223 } 2224 2225 EmitBranch(CondBlock); 2226 LoopStack.pop(); 2227 // Emit the fall-through block. 2228 EmitBlock(LoopExit.getBlock()); 2229 2230 // Tell the runtime we are done. 2231 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) { 2232 if (!DynamicOrOrdered) 2233 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 2234 S.getDirectiveKind()); 2235 }; 2236 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 2237 } 2238 2239 void CodeGenFunction::EmitOMPForOuterLoop( 2240 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic, 2241 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 2242 const OMPLoopArguments &LoopArgs, 2243 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 2244 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2245 2246 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 2247 const bool DynamicOrOrdered = 2248 Ordered || RT.isDynamic(ScheduleKind.Schedule); 2249 2250 assert((Ordered || 2251 !RT.isStaticNonchunked(ScheduleKind.Schedule, 2252 LoopArgs.Chunk != nullptr)) && 2253 "static non-chunked schedule does not need outer loop"); 2254 2255 // Emit outer loop. 2256 // 2257 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2258 // When schedule(dynamic,chunk_size) is specified, the iterations are 2259 // distributed to threads in the team in chunks as the threads request them. 2260 // Each thread executes a chunk of iterations, then requests another chunk, 2261 // until no chunks remain to be distributed. Each chunk contains chunk_size 2262 // iterations, except for the last chunk to be distributed, which may have 2263 // fewer iterations. When no chunk_size is specified, it defaults to 1. 2264 // 2265 // When schedule(guided,chunk_size) is specified, the iterations are assigned 2266 // to threads in the team in chunks as the executing threads request them. 2267 // Each thread executes a chunk of iterations, then requests another chunk, 2268 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 2269 // each chunk is proportional to the number of unassigned iterations divided 2270 // by the number of threads in the team, decreasing to 1. For a chunk_size 2271 // with value k (greater than 1), the size of each chunk is determined in the 2272 // same way, with the restriction that the chunks do not contain fewer than k 2273 // iterations (except for the last chunk to be assigned, which may have fewer 2274 // than k iterations). 2275 // 2276 // When schedule(auto) is specified, the decision regarding scheduling is 2277 // delegated to the compiler and/or runtime system. The programmer gives the 2278 // implementation the freedom to choose any possible mapping of iterations to 2279 // threads in the team. 2280 // 2281 // When schedule(runtime) is specified, the decision regarding scheduling is 2282 // deferred until run time, and the schedule and chunk size are taken from the 2283 // run-sched-var ICV. If the ICV is set to auto, the schedule is 2284 // implementation defined 2285 // 2286 // while(__kmpc_dispatch_next(&LB, &UB)) { 2287 // idx = LB; 2288 // while (idx <= UB) { BODY; ++idx; 2289 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 2290 // } // inner loop 2291 // } 2292 // 2293 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2294 // When schedule(static, chunk_size) is specified, iterations are divided into 2295 // chunks of size chunk_size, and the chunks are assigned to the threads in 2296 // the team in a round-robin fashion in the order of the thread number. 2297 // 2298 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 2299 // while (idx <= UB) { BODY; ++idx; } // inner loop 2300 // LB = LB + ST; 2301 // UB = UB + ST; 2302 // } 2303 // 2304 2305 const Expr *IVExpr = S.getIterationVariable(); 2306 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2307 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2308 2309 if (DynamicOrOrdered) { 2310 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds = 2311 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB); 2312 llvm::Value *LBVal = DispatchBounds.first; 2313 llvm::Value *UBVal = DispatchBounds.second; 2314 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal, 2315 LoopArgs.Chunk}; 2316 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize, 2317 IVSigned, Ordered, DipatchRTInputValues); 2318 } else { 2319 CGOpenMPRuntime::StaticRTInput StaticInit( 2320 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB, 2321 LoopArgs.ST, LoopArgs.Chunk); 2322 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(), 2323 ScheduleKind, StaticInit); 2324 } 2325 2326 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc, 2327 const unsigned IVSize, 2328 const bool IVSigned) { 2329 if (Ordered) { 2330 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize, 2331 IVSigned); 2332 } 2333 }; 2334 2335 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST, 2336 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB); 2337 OuterLoopArgs.IncExpr = S.getInc(); 2338 OuterLoopArgs.Init = S.getInit(); 2339 OuterLoopArgs.Cond = S.getCond(); 2340 OuterLoopArgs.NextLB = S.getNextLowerBound(); 2341 OuterLoopArgs.NextUB = S.getNextUpperBound(); 2342 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs, 2343 emitOMPLoopBodyWithStopPoint, CodeGenOrdered); 2344 } 2345 2346 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc, 2347 const unsigned IVSize, const bool IVSigned) {} 2348 2349 void CodeGenFunction::EmitOMPDistributeOuterLoop( 2350 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S, 2351 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs, 2352 const CodeGenLoopTy &CodeGenLoopContent) { 2353 2354 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2355 2356 // Emit outer loop. 2357 // Same behavior as a OMPForOuterLoop, except that schedule cannot be 2358 // dynamic 2359 // 2360 2361 const Expr *IVExpr = S.getIterationVariable(); 2362 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2363 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2364 2365 CGOpenMPRuntime::StaticRTInput StaticInit( 2366 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB, 2367 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk); 2368 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit); 2369 2370 // for combined 'distribute' and 'for' the increment expression of distribute 2371 // is stored in DistInc. For 'distribute' alone, it is in Inc. 2372 Expr *IncExpr; 2373 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())) 2374 IncExpr = S.getDistInc(); 2375 else 2376 IncExpr = S.getInc(); 2377 2378 // this routine is shared by 'omp distribute parallel for' and 2379 // 'omp distribute': select the right EUB expression depending on the 2380 // directive 2381 OMPLoopArguments OuterLoopArgs; 2382 OuterLoopArgs.LB = LoopArgs.LB; 2383 OuterLoopArgs.UB = LoopArgs.UB; 2384 OuterLoopArgs.ST = LoopArgs.ST; 2385 OuterLoopArgs.IL = LoopArgs.IL; 2386 OuterLoopArgs.Chunk = LoopArgs.Chunk; 2387 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2388 ? S.getCombinedEnsureUpperBound() 2389 : S.getEnsureUpperBound(); 2390 OuterLoopArgs.IncExpr = IncExpr; 2391 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2392 ? S.getCombinedInit() 2393 : S.getInit(); 2394 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2395 ? S.getCombinedCond() 2396 : S.getCond(); 2397 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2398 ? S.getCombinedNextLowerBound() 2399 : S.getNextLowerBound(); 2400 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2401 ? S.getCombinedNextUpperBound() 2402 : S.getNextUpperBound(); 2403 2404 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S, 2405 LoopScope, OuterLoopArgs, CodeGenLoopContent, 2406 emitEmptyOrdered); 2407 } 2408 2409 static std::pair<LValue, LValue> 2410 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF, 2411 const OMPExecutableDirective &S) { 2412 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2413 LValue LB = 2414 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 2415 LValue UB = 2416 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 2417 2418 // When composing 'distribute' with 'for' (e.g. as in 'distribute 2419 // parallel for') we need to use the 'distribute' 2420 // chunk lower and upper bounds rather than the whole loop iteration 2421 // space. These are parameters to the outlined function for 'parallel' 2422 // and we copy the bounds of the previous schedule into the 2423 // the current ones. 2424 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable()); 2425 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable()); 2426 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar( 2427 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc()); 2428 PrevLBVal = CGF.EmitScalarConversion( 2429 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(), 2430 LS.getIterationVariable()->getType(), 2431 LS.getPrevLowerBoundVariable()->getExprLoc()); 2432 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar( 2433 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc()); 2434 PrevUBVal = CGF.EmitScalarConversion( 2435 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(), 2436 LS.getIterationVariable()->getType(), 2437 LS.getPrevUpperBoundVariable()->getExprLoc()); 2438 2439 CGF.EmitStoreOfScalar(PrevLBVal, LB); 2440 CGF.EmitStoreOfScalar(PrevUBVal, UB); 2441 2442 return {LB, UB}; 2443 } 2444 2445 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then 2446 /// we need to use the LB and UB expressions generated by the worksharing 2447 /// code generation support, whereas in non combined situations we would 2448 /// just emit 0 and the LastIteration expression 2449 /// This function is necessary due to the difference of the LB and UB 2450 /// types for the RT emission routines for 'for_static_init' and 2451 /// 'for_dispatch_init' 2452 static std::pair<llvm::Value *, llvm::Value *> 2453 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF, 2454 const OMPExecutableDirective &S, 2455 Address LB, Address UB) { 2456 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2457 const Expr *IVExpr = LS.getIterationVariable(); 2458 // when implementing a dynamic schedule for a 'for' combined with a 2459 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop 2460 // is not normalized as each team only executes its own assigned 2461 // distribute chunk 2462 QualType IteratorTy = IVExpr->getType(); 2463 llvm::Value *LBVal = 2464 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 2465 llvm::Value *UBVal = 2466 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 2467 return {LBVal, UBVal}; 2468 } 2469 2470 static void emitDistributeParallelForDistributeInnerBoundParams( 2471 CodeGenFunction &CGF, const OMPExecutableDirective &S, 2472 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) { 2473 const auto &Dir = cast<OMPLoopDirective>(S); 2474 LValue LB = 2475 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable())); 2476 llvm::Value *LBCast = 2477 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)), 2478 CGF.SizeTy, /*isSigned=*/false); 2479 CapturedVars.push_back(LBCast); 2480 LValue UB = 2481 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable())); 2482 2483 llvm::Value *UBCast = 2484 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)), 2485 CGF.SizeTy, /*isSigned=*/false); 2486 CapturedVars.push_back(UBCast); 2487 } 2488 2489 static void 2490 emitInnerParallelForWhenCombined(CodeGenFunction &CGF, 2491 const OMPLoopDirective &S, 2492 CodeGenFunction::JumpDest LoopExit) { 2493 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF, 2494 PrePostActionTy &Action) { 2495 Action.Enter(CGF); 2496 bool HasCancel = false; 2497 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2498 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S)) 2499 HasCancel = D->hasCancel(); 2500 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S)) 2501 HasCancel = D->hasCancel(); 2502 else if (const auto *D = 2503 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S)) 2504 HasCancel = D->hasCancel(); 2505 } 2506 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(), 2507 HasCancel); 2508 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(), 2509 emitDistributeParallelForInnerBounds, 2510 emitDistributeParallelForDispatchBounds); 2511 }; 2512 2513 emitCommonOMPParallelDirective( 2514 CGF, S, 2515 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for, 2516 CGInlinedWorksharingLoop, 2517 emitDistributeParallelForDistributeInnerBoundParams); 2518 } 2519 2520 void CodeGenFunction::EmitOMPDistributeParallelForDirective( 2521 const OMPDistributeParallelForDirective &S) { 2522 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2523 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 2524 S.getDistInc()); 2525 }; 2526 OMPLexicalScope Scope(*this, S, OMPD_parallel); 2527 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 2528 } 2529 2530 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective( 2531 const OMPDistributeParallelForSimdDirective &S) { 2532 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2533 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 2534 S.getDistInc()); 2535 }; 2536 OMPLexicalScope Scope(*this, S, OMPD_parallel); 2537 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 2538 } 2539 2540 void CodeGenFunction::EmitOMPDistributeSimdDirective( 2541 const OMPDistributeSimdDirective &S) { 2542 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2543 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 2544 }; 2545 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2546 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2547 } 2548 2549 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction( 2550 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) { 2551 // Emit SPMD target parallel for region as a standalone region. 2552 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2553 emitOMPSimdRegion(CGF, S, Action); 2554 }; 2555 llvm::Function *Fn; 2556 llvm::Constant *Addr; 2557 // Emit target region as a standalone region. 2558 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 2559 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 2560 assert(Fn && Addr && "Target device function emission failed."); 2561 } 2562 2563 void CodeGenFunction::EmitOMPTargetSimdDirective( 2564 const OMPTargetSimdDirective &S) { 2565 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2566 emitOMPSimdRegion(CGF, S, Action); 2567 }; 2568 emitCommonOMPTargetDirective(*this, S, CodeGen); 2569 } 2570 2571 namespace { 2572 struct ScheduleKindModifiersTy { 2573 OpenMPScheduleClauseKind Kind; 2574 OpenMPScheduleClauseModifier M1; 2575 OpenMPScheduleClauseModifier M2; 2576 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind, 2577 OpenMPScheduleClauseModifier M1, 2578 OpenMPScheduleClauseModifier M2) 2579 : Kind(Kind), M1(M1), M2(M2) {} 2580 }; 2581 } // namespace 2582 2583 bool CodeGenFunction::EmitOMPWorksharingLoop( 2584 const OMPLoopDirective &S, Expr *EUB, 2585 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 2586 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 2587 // Emit the loop iteration variable. 2588 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 2589 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 2590 EmitVarDecl(*IVDecl); 2591 2592 // Emit the iterations count variable. 2593 // If it is not a variable, Sema decided to calculate iterations count on each 2594 // iteration (e.g., it is foldable into a constant). 2595 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2596 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2597 // Emit calculation of the iterations count. 2598 EmitIgnoredExpr(S.getCalcLastIteration()); 2599 } 2600 2601 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2602 2603 bool HasLastprivateClause; 2604 // Check pre-condition. 2605 { 2606 OMPLoopScope PreInitScope(*this, S); 2607 // Skip the entire loop if we don't meet the precondition. 2608 // If the condition constant folds and can be elided, avoid emitting the 2609 // whole loop. 2610 bool CondConstant; 2611 llvm::BasicBlock *ContBlock = nullptr; 2612 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2613 if (!CondConstant) 2614 return false; 2615 } else { 2616 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 2617 ContBlock = createBasicBlock("omp.precond.end"); 2618 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 2619 getProfileCount(&S)); 2620 EmitBlock(ThenBlock); 2621 incrementProfileCounter(&S); 2622 } 2623 2624 RunCleanupsScope DoacrossCleanupScope(*this); 2625 bool Ordered = false; 2626 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) { 2627 if (OrderedClause->getNumForLoops()) 2628 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations()); 2629 else 2630 Ordered = true; 2631 } 2632 2633 llvm::DenseSet<const Expr *> EmittedFinals; 2634 emitAlignedClause(*this, S); 2635 bool HasLinears = EmitOMPLinearClauseInit(S); 2636 // Emit helper vars inits. 2637 2638 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S); 2639 LValue LB = Bounds.first; 2640 LValue UB = Bounds.second; 2641 LValue ST = 2642 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 2643 LValue IL = 2644 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 2645 2646 // Emit 'then' code. 2647 { 2648 OMPPrivateScope LoopScope(*this); 2649 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) { 2650 // Emit implicit barrier to synchronize threads and avoid data races on 2651 // initialization of firstprivate variables and post-update of 2652 // lastprivate variables. 2653 CGM.getOpenMPRuntime().emitBarrierCall( 2654 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 2655 /*ForceSimpleCall=*/true); 2656 } 2657 EmitOMPPrivateClause(S, LoopScope); 2658 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 2659 *this, S, EmitLValue(S.getIterationVariable())); 2660 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 2661 EmitOMPReductionClauseInit(S, LoopScope); 2662 EmitOMPPrivateLoopCounters(S, LoopScope); 2663 EmitOMPLinearClause(S, LoopScope); 2664 (void)LoopScope.Privatize(); 2665 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2666 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 2667 2668 // Detect the loop schedule kind and chunk. 2669 const Expr *ChunkExpr = nullptr; 2670 OpenMPScheduleTy ScheduleKind; 2671 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) { 2672 ScheduleKind.Schedule = C->getScheduleKind(); 2673 ScheduleKind.M1 = C->getFirstScheduleModifier(); 2674 ScheduleKind.M2 = C->getSecondScheduleModifier(); 2675 ChunkExpr = C->getChunkSize(); 2676 } else { 2677 // Default behaviour for schedule clause. 2678 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk( 2679 *this, S, ScheduleKind.Schedule, ChunkExpr); 2680 } 2681 bool HasChunkSizeOne = false; 2682 llvm::Value *Chunk = nullptr; 2683 if (ChunkExpr) { 2684 Chunk = EmitScalarExpr(ChunkExpr); 2685 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(), 2686 S.getIterationVariable()->getType(), 2687 S.getBeginLoc()); 2688 Expr::EvalResult Result; 2689 if (ChunkExpr->EvaluateAsInt(Result, getContext())) { 2690 llvm::APSInt EvaluatedChunk = Result.Val.getInt(); 2691 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1); 2692 } 2693 } 2694 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2695 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2696 // OpenMP 4.5, 2.7.1 Loop Construct, Description. 2697 // If the static schedule kind is specified or if the ordered clause is 2698 // specified, and if no monotonic modifier is specified, the effect will 2699 // be as if the monotonic modifier was specified. 2700 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule, 2701 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne && 2702 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 2703 if ((RT.isStaticNonchunked(ScheduleKind.Schedule, 2704 /* Chunked */ Chunk != nullptr) || 2705 StaticChunkedOne) && 2706 !Ordered) { 2707 JumpDest LoopExit = 2708 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 2709 emitCommonSimdLoop( 2710 *this, S, 2711 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2712 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2713 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true); 2714 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) { 2715 if (C->getKind() == OMPC_ORDER_concurrent) 2716 CGF.LoopStack.setParallel(/*Enable=*/true); 2717 } 2718 }, 2719 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk, 2720 &S, ScheduleKind, LoopExit, 2721 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2722 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2723 // When no chunk_size is specified, the iteration space is divided 2724 // into chunks that are approximately equal in size, and at most 2725 // one chunk is distributed to each thread. Note that the size of 2726 // the chunks is unspecified in this case. 2727 CGOpenMPRuntime::StaticRTInput StaticInit( 2728 IVSize, IVSigned, Ordered, IL.getAddress(CGF), 2729 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF), 2730 StaticChunkedOne ? Chunk : nullptr); 2731 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 2732 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, 2733 StaticInit); 2734 // UB = min(UB, GlobalUB); 2735 if (!StaticChunkedOne) 2736 CGF.EmitIgnoredExpr(S.getEnsureUpperBound()); 2737 // IV = LB; 2738 CGF.EmitIgnoredExpr(S.getInit()); 2739 // For unchunked static schedule generate: 2740 // 2741 // while (idx <= UB) { 2742 // BODY; 2743 // ++idx; 2744 // } 2745 // 2746 // For static schedule with chunk one: 2747 // 2748 // while (IV <= PrevUB) { 2749 // BODY; 2750 // IV += ST; 2751 // } 2752 CGF.EmitOMPInnerLoop( 2753 S, LoopScope.requiresCleanups(), 2754 StaticChunkedOne ? S.getCombinedParForInDistCond() 2755 : S.getCond(), 2756 StaticChunkedOne ? S.getDistInc() : S.getInc(), 2757 [&S, LoopExit](CodeGenFunction &CGF) { 2758 CGF.EmitOMPLoopBody(S, LoopExit); 2759 CGF.EmitStopPoint(&S); 2760 }, 2761 [](CodeGenFunction &) {}); 2762 }); 2763 EmitBlock(LoopExit.getBlock()); 2764 // Tell the runtime we are done. 2765 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 2766 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 2767 S.getDirectiveKind()); 2768 }; 2769 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 2770 } else { 2771 const bool IsMonotonic = 2772 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static || 2773 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown || 2774 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic || 2775 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic; 2776 // Emit the outer loop, which requests its work chunk [LB..UB] from 2777 // runtime and runs the inner loop to process it. 2778 const OMPLoopArguments LoopArguments( 2779 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 2780 IL.getAddress(*this), Chunk, EUB); 2781 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered, 2782 LoopArguments, CGDispatchBounds); 2783 } 2784 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2785 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 2786 return CGF.Builder.CreateIsNotNull( 2787 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 2788 }); 2789 } 2790 EmitOMPReductionClauseFinal( 2791 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind()) 2792 ? /*Parallel and Simd*/ OMPD_parallel_for_simd 2793 : /*Parallel only*/ OMPD_parallel); 2794 // Emit post-update of the reduction variables if IsLastIter != 0. 2795 emitPostUpdateForReductionClause( 2796 *this, S, [IL, &S](CodeGenFunction &CGF) { 2797 return CGF.Builder.CreateIsNotNull( 2798 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 2799 }); 2800 // Emit final copy of the lastprivate variables if IsLastIter != 0. 2801 if (HasLastprivateClause) 2802 EmitOMPLastprivateClauseFinal( 2803 S, isOpenMPSimdDirective(S.getDirectiveKind()), 2804 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 2805 } 2806 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) { 2807 return CGF.Builder.CreateIsNotNull( 2808 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 2809 }); 2810 DoacrossCleanupScope.ForceCleanup(); 2811 // We're now done with the loop, so jump to the continuation block. 2812 if (ContBlock) { 2813 EmitBranch(ContBlock); 2814 EmitBlock(ContBlock, /*IsFinished=*/true); 2815 } 2816 } 2817 return HasLastprivateClause; 2818 } 2819 2820 /// The following two functions generate expressions for the loop lower 2821 /// and upper bounds in case of static and dynamic (dispatch) schedule 2822 /// of the associated 'for' or 'distribute' loop. 2823 static std::pair<LValue, LValue> 2824 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 2825 const auto &LS = cast<OMPLoopDirective>(S); 2826 LValue LB = 2827 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 2828 LValue UB = 2829 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 2830 return {LB, UB}; 2831 } 2832 2833 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not 2834 /// consider the lower and upper bound expressions generated by the 2835 /// worksharing loop support, but we use 0 and the iteration space size as 2836 /// constants 2837 static std::pair<llvm::Value *, llvm::Value *> 2838 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, 2839 Address LB, Address UB) { 2840 const auto &LS = cast<OMPLoopDirective>(S); 2841 const Expr *IVExpr = LS.getIterationVariable(); 2842 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType()); 2843 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0); 2844 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration()); 2845 return {LBVal, UBVal}; 2846 } 2847 2848 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 2849 bool HasLastprivates = false; 2850 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 2851 PrePostActionTy &) { 2852 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel()); 2853 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 2854 emitForLoopBounds, 2855 emitDispatchForLoopBounds); 2856 }; 2857 { 2858 auto LPCRegion = 2859 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2860 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2861 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen, 2862 S.hasCancel()); 2863 } 2864 2865 // Emit an implicit barrier at the end. 2866 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 2867 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 2868 // Check for outer lastprivate conditional update. 2869 checkForLastprivateConditionalUpdate(*this, S); 2870 } 2871 2872 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) { 2873 bool HasLastprivates = false; 2874 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 2875 PrePostActionTy &) { 2876 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 2877 emitForLoopBounds, 2878 emitDispatchForLoopBounds); 2879 }; 2880 { 2881 auto LPCRegion = 2882 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2883 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2884 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2885 } 2886 2887 // Emit an implicit barrier at the end. 2888 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 2889 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 2890 // Check for outer lastprivate conditional update. 2891 checkForLastprivateConditionalUpdate(*this, S); 2892 } 2893 2894 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 2895 const Twine &Name, 2896 llvm::Value *Init = nullptr) { 2897 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 2898 if (Init) 2899 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true); 2900 return LVal; 2901 } 2902 2903 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) { 2904 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt(); 2905 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt); 2906 bool HasLastprivates = false; 2907 auto &&CodeGen = [&S, CapturedStmt, CS, 2908 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) { 2909 ASTContext &C = CGF.getContext(); 2910 QualType KmpInt32Ty = 2911 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 2912 // Emit helper vars inits. 2913 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 2914 CGF.Builder.getInt32(0)); 2915 llvm::ConstantInt *GlobalUBVal = CS != nullptr 2916 ? CGF.Builder.getInt32(CS->size() - 1) 2917 : CGF.Builder.getInt32(0); 2918 LValue UB = 2919 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 2920 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 2921 CGF.Builder.getInt32(1)); 2922 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 2923 CGF.Builder.getInt32(0)); 2924 // Loop counter. 2925 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 2926 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 2927 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 2928 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 2929 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 2930 // Generate condition for loop. 2931 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue, 2932 OK_Ordinary, S.getBeginLoc(), FPOptions()); 2933 // Increment for loop counter. 2934 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary, 2935 S.getBeginLoc(), true); 2936 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) { 2937 // Iterate through all sections and emit a switch construct: 2938 // switch (IV) { 2939 // case 0: 2940 // <SectionStmt[0]>; 2941 // break; 2942 // ... 2943 // case <NumSection> - 1: 2944 // <SectionStmt[<NumSection> - 1]>; 2945 // break; 2946 // } 2947 // .omp.sections.exit: 2948 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 2949 llvm::SwitchInst *SwitchStmt = 2950 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()), 2951 ExitBB, CS == nullptr ? 1 : CS->size()); 2952 if (CS) { 2953 unsigned CaseNumber = 0; 2954 for (const Stmt *SubStmt : CS->children()) { 2955 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 2956 CGF.EmitBlock(CaseBB); 2957 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 2958 CGF.EmitStmt(SubStmt); 2959 CGF.EmitBranch(ExitBB); 2960 ++CaseNumber; 2961 } 2962 } else { 2963 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case"); 2964 CGF.EmitBlock(CaseBB); 2965 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB); 2966 CGF.EmitStmt(CapturedStmt); 2967 CGF.EmitBranch(ExitBB); 2968 } 2969 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 2970 }; 2971 2972 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2973 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 2974 // Emit implicit barrier to synchronize threads and avoid data races on 2975 // initialization of firstprivate variables and post-update of lastprivate 2976 // variables. 2977 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 2978 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 2979 /*ForceSimpleCall=*/true); 2980 } 2981 CGF.EmitOMPPrivateClause(S, LoopScope); 2982 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV); 2983 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 2984 CGF.EmitOMPReductionClauseInit(S, LoopScope); 2985 (void)LoopScope.Privatize(); 2986 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2987 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 2988 2989 // Emit static non-chunked loop. 2990 OpenMPScheduleTy ScheduleKind; 2991 ScheduleKind.Schedule = OMPC_SCHEDULE_static; 2992 CGOpenMPRuntime::StaticRTInput StaticInit( 2993 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF), 2994 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF)); 2995 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 2996 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit); 2997 // UB = min(UB, GlobalUB); 2998 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc()); 2999 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect( 3000 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 3001 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 3002 // IV = LB; 3003 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV); 3004 // while (idx <= UB) { BODY; ++idx; } 3005 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen, 3006 [](CodeGenFunction &) {}); 3007 // Tell the runtime we are done. 3008 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3009 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3010 S.getDirectiveKind()); 3011 }; 3012 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen); 3013 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3014 // Emit post-update of the reduction variables if IsLastIter != 0. 3015 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) { 3016 return CGF.Builder.CreateIsNotNull( 3017 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3018 }); 3019 3020 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3021 if (HasLastprivates) 3022 CGF.EmitOMPLastprivateClauseFinal( 3023 S, /*NoFinals=*/false, 3024 CGF.Builder.CreateIsNotNull( 3025 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()))); 3026 }; 3027 3028 bool HasCancel = false; 3029 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S)) 3030 HasCancel = OSD->hasCancel(); 3031 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S)) 3032 HasCancel = OPSD->hasCancel(); 3033 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel); 3034 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen, 3035 HasCancel); 3036 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 3037 // clause. Otherwise the barrier will be generated by the codegen for the 3038 // directive. 3039 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) { 3040 // Emit implicit barrier to synchronize threads and avoid data races on 3041 // initialization of firstprivate variables. 3042 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3043 OMPD_unknown); 3044 } 3045 } 3046 3047 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 3048 { 3049 auto LPCRegion = 3050 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3051 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3052 EmitSections(S); 3053 } 3054 // Emit an implicit barrier at the end. 3055 if (!S.getSingleClause<OMPNowaitClause>()) { 3056 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3057 OMPD_sections); 3058 } 3059 // Check for outer lastprivate conditional update. 3060 checkForLastprivateConditionalUpdate(*this, S); 3061 } 3062 3063 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 3064 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3065 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3066 }; 3067 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3068 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen, 3069 S.hasCancel()); 3070 } 3071 3072 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 3073 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 3074 llvm::SmallVector<const Expr *, 8> DestExprs; 3075 llvm::SmallVector<const Expr *, 8> SrcExprs; 3076 llvm::SmallVector<const Expr *, 8> AssignmentOps; 3077 // Check if there are any 'copyprivate' clauses associated with this 3078 // 'single' construct. 3079 // Build a list of copyprivate variables along with helper expressions 3080 // (<source>, <destination>, <destination>=<source> expressions) 3081 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) { 3082 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 3083 DestExprs.append(C->destination_exprs().begin(), 3084 C->destination_exprs().end()); 3085 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 3086 AssignmentOps.append(C->assignment_ops().begin(), 3087 C->assignment_ops().end()); 3088 } 3089 // Emit code for 'single' region along with 'copyprivate' clauses 3090 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3091 Action.Enter(CGF); 3092 OMPPrivateScope SingleScope(CGF); 3093 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope); 3094 CGF.EmitOMPPrivateClause(S, SingleScope); 3095 (void)SingleScope.Privatize(); 3096 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3097 }; 3098 { 3099 auto LPCRegion = 3100 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3101 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3102 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(), 3103 CopyprivateVars, DestExprs, 3104 SrcExprs, AssignmentOps); 3105 } 3106 // Emit an implicit barrier at the end (to avoid data race on firstprivate 3107 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 3108 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) { 3109 CGM.getOpenMPRuntime().emitBarrierCall( 3110 *this, S.getBeginLoc(), 3111 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single); 3112 } 3113 // Check for outer lastprivate conditional update. 3114 checkForLastprivateConditionalUpdate(*this, S); 3115 } 3116 3117 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 3118 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3119 Action.Enter(CGF); 3120 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3121 }; 3122 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc()); 3123 } 3124 3125 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 3126 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) { 3127 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3128 3129 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 3130 const Stmt *MasterRegionBodyStmt = CS->getCapturedStmt(); 3131 3132 auto FiniCB = [this](InsertPointTy IP) { 3133 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3134 }; 3135 3136 auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP, 3137 InsertPointTy CodeGenIP, 3138 llvm::BasicBlock &FiniBB) { 3139 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3140 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MasterRegionBodyStmt, 3141 CodeGenIP, FiniBB); 3142 }; 3143 3144 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 3145 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 3146 Builder.restoreIP(OMPBuilder->CreateMaster(Builder, BodyGenCB, FiniCB)); 3147 3148 return; 3149 } 3150 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3151 emitMaster(*this, S); 3152 } 3153 3154 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 3155 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) { 3156 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3157 3158 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 3159 const Stmt *CriticalRegionBodyStmt = CS->getCapturedStmt(); 3160 const Expr *Hint = nullptr; 3161 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 3162 Hint = HintClause->getHint(); 3163 3164 // TODO: This is slightly different from what's currently being done in 3165 // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything 3166 // about typing is final. 3167 llvm::Value *HintInst = nullptr; 3168 if (Hint) 3169 HintInst = 3170 Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false); 3171 3172 auto FiniCB = [this](InsertPointTy IP) { 3173 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3174 }; 3175 3176 auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP, 3177 InsertPointTy CodeGenIP, 3178 llvm::BasicBlock &FiniBB) { 3179 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3180 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CriticalRegionBodyStmt, 3181 CodeGenIP, FiniBB); 3182 }; 3183 3184 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 3185 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 3186 Builder.restoreIP(OMPBuilder->CreateCritical( 3187 Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(), 3188 HintInst)); 3189 3190 return; 3191 } 3192 3193 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3194 Action.Enter(CGF); 3195 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3196 }; 3197 const Expr *Hint = nullptr; 3198 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 3199 Hint = HintClause->getHint(); 3200 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3201 CGM.getOpenMPRuntime().emitCriticalRegion(*this, 3202 S.getDirectiveName().getAsString(), 3203 CodeGen, S.getBeginLoc(), Hint); 3204 } 3205 3206 void CodeGenFunction::EmitOMPParallelForDirective( 3207 const OMPParallelForDirective &S) { 3208 // Emit directive as a combined directive that consists of two implicit 3209 // directives: 'parallel' with 'for' directive. 3210 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3211 Action.Enter(CGF); 3212 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel()); 3213 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 3214 emitDispatchForLoopBounds); 3215 }; 3216 { 3217 auto LPCRegion = 3218 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3219 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen, 3220 emitEmptyBoundParameters); 3221 } 3222 // Check for outer lastprivate conditional update. 3223 checkForLastprivateConditionalUpdate(*this, S); 3224 } 3225 3226 void CodeGenFunction::EmitOMPParallelForSimdDirective( 3227 const OMPParallelForSimdDirective &S) { 3228 // Emit directive as a combined directive that consists of two implicit 3229 // directives: 'parallel' with 'for' directive. 3230 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3231 Action.Enter(CGF); 3232 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 3233 emitDispatchForLoopBounds); 3234 }; 3235 { 3236 auto LPCRegion = 3237 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3238 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen, 3239 emitEmptyBoundParameters); 3240 } 3241 // Check for outer lastprivate conditional update. 3242 checkForLastprivateConditionalUpdate(*this, S); 3243 } 3244 3245 void CodeGenFunction::EmitOMPParallelMasterDirective( 3246 const OMPParallelMasterDirective &S) { 3247 // Emit directive as a combined directive that consists of two implicit 3248 // directives: 'parallel' with 'master' directive. 3249 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3250 Action.Enter(CGF); 3251 OMPPrivateScope PrivateScope(CGF); 3252 bool Copyins = CGF.EmitOMPCopyinClause(S); 3253 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 3254 if (Copyins) { 3255 // Emit implicit barrier to synchronize threads and avoid data races on 3256 // propagation master's thread values of threadprivate variables to local 3257 // instances of that variables of all other implicit threads. 3258 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3259 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3260 /*ForceSimpleCall=*/true); 3261 } 3262 CGF.EmitOMPPrivateClause(S, PrivateScope); 3263 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 3264 (void)PrivateScope.Privatize(); 3265 emitMaster(CGF, S); 3266 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3267 }; 3268 { 3269 auto LPCRegion = 3270 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3271 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen, 3272 emitEmptyBoundParameters); 3273 emitPostUpdateForReductionClause(*this, S, 3274 [](CodeGenFunction &) { return nullptr; }); 3275 } 3276 // Check for outer lastprivate conditional update. 3277 checkForLastprivateConditionalUpdate(*this, S); 3278 } 3279 3280 void CodeGenFunction::EmitOMPParallelSectionsDirective( 3281 const OMPParallelSectionsDirective &S) { 3282 // Emit directive as a combined directive that consists of two implicit 3283 // directives: 'parallel' with 'sections' directive. 3284 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3285 Action.Enter(CGF); 3286 CGF.EmitSections(S); 3287 }; 3288 { 3289 auto LPCRegion = 3290 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3291 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen, 3292 emitEmptyBoundParameters); 3293 } 3294 // Check for outer lastprivate conditional update. 3295 checkForLastprivateConditionalUpdate(*this, S); 3296 } 3297 3298 void CodeGenFunction::EmitOMPTaskBasedDirective( 3299 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion, 3300 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen, 3301 OMPTaskDataTy &Data) { 3302 // Emit outlined function for task construct. 3303 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion); 3304 auto I = CS->getCapturedDecl()->param_begin(); 3305 auto PartId = std::next(I); 3306 auto TaskT = std::next(I, 4); 3307 // Check if the task is final 3308 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) { 3309 // If the condition constant folds and can be elided, try to avoid emitting 3310 // the condition and the dead arm of the if/else. 3311 const Expr *Cond = Clause->getCondition(); 3312 bool CondConstant; 3313 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 3314 Data.Final.setInt(CondConstant); 3315 else 3316 Data.Final.setPointer(EvaluateExprAsBool(Cond)); 3317 } else { 3318 // By default the task is not final. 3319 Data.Final.setInt(/*IntVal=*/false); 3320 } 3321 // Check if the task has 'priority' clause. 3322 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) { 3323 const Expr *Prio = Clause->getPriority(); 3324 Data.Priority.setInt(/*IntVal=*/true); 3325 Data.Priority.setPointer(EmitScalarConversion( 3326 EmitScalarExpr(Prio), Prio->getType(), 3327 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), 3328 Prio->getExprLoc())); 3329 } 3330 // The first function argument for tasks is a thread id, the second one is a 3331 // part id (0 for tied tasks, >=0 for untied task). 3332 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 3333 // Get list of private variables. 3334 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) { 3335 auto IRef = C->varlist_begin(); 3336 for (const Expr *IInit : C->private_copies()) { 3337 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3338 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3339 Data.PrivateVars.push_back(*IRef); 3340 Data.PrivateCopies.push_back(IInit); 3341 } 3342 ++IRef; 3343 } 3344 } 3345 EmittedAsPrivate.clear(); 3346 // Get list of firstprivate variables. 3347 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 3348 auto IRef = C->varlist_begin(); 3349 auto IElemInitRef = C->inits().begin(); 3350 for (const Expr *IInit : C->private_copies()) { 3351 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3352 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3353 Data.FirstprivateVars.push_back(*IRef); 3354 Data.FirstprivateCopies.push_back(IInit); 3355 Data.FirstprivateInits.push_back(*IElemInitRef); 3356 } 3357 ++IRef; 3358 ++IElemInitRef; 3359 } 3360 } 3361 // Get list of lastprivate variables (for taskloops). 3362 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs; 3363 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 3364 auto IRef = C->varlist_begin(); 3365 auto ID = C->destination_exprs().begin(); 3366 for (const Expr *IInit : C->private_copies()) { 3367 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3368 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3369 Data.LastprivateVars.push_back(*IRef); 3370 Data.LastprivateCopies.push_back(IInit); 3371 } 3372 LastprivateDstsOrigs.insert( 3373 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()), 3374 cast<DeclRefExpr>(*IRef)}); 3375 ++IRef; 3376 ++ID; 3377 } 3378 } 3379 SmallVector<const Expr *, 4> LHSs; 3380 SmallVector<const Expr *, 4> RHSs; 3381 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 3382 auto IPriv = C->privates().begin(); 3383 auto IRed = C->reduction_ops().begin(); 3384 auto ILHS = C->lhs_exprs().begin(); 3385 auto IRHS = C->rhs_exprs().begin(); 3386 for (const Expr *Ref : C->varlists()) { 3387 Data.ReductionVars.emplace_back(Ref); 3388 Data.ReductionCopies.emplace_back(*IPriv); 3389 Data.ReductionOps.emplace_back(*IRed); 3390 LHSs.emplace_back(*ILHS); 3391 RHSs.emplace_back(*IRHS); 3392 std::advance(IPriv, 1); 3393 std::advance(IRed, 1); 3394 std::advance(ILHS, 1); 3395 std::advance(IRHS, 1); 3396 } 3397 } 3398 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit( 3399 *this, S.getBeginLoc(), LHSs, RHSs, Data); 3400 // Build list of dependences. 3401 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) 3402 for (const Expr *IRef : C->varlists()) 3403 Data.Dependences.emplace_back(C->getDependencyKind(), IRef); 3404 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs, 3405 CapturedRegion](CodeGenFunction &CGF, 3406 PrePostActionTy &Action) { 3407 // Set proper addresses for generated private copies. 3408 OMPPrivateScope Scope(CGF); 3409 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() || 3410 !Data.LastprivateVars.empty()) { 3411 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get( 3412 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true); 3413 enum { PrivatesParam = 2, CopyFnParam = 3 }; 3414 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 3415 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 3416 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 3417 CS->getCapturedDecl()->getParam(PrivatesParam))); 3418 // Map privates. 3419 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 3420 llvm::SmallVector<llvm::Value *, 16> CallArgs; 3421 CallArgs.push_back(PrivatesPtr); 3422 for (const Expr *E : Data.PrivateVars) { 3423 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3424 Address PrivatePtr = CGF.CreateMemTemp( 3425 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr"); 3426 PrivatePtrs.emplace_back(VD, PrivatePtr); 3427 CallArgs.push_back(PrivatePtr.getPointer()); 3428 } 3429 for (const Expr *E : Data.FirstprivateVars) { 3430 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3431 Address PrivatePtr = 3432 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3433 ".firstpriv.ptr.addr"); 3434 PrivatePtrs.emplace_back(VD, PrivatePtr); 3435 CallArgs.push_back(PrivatePtr.getPointer()); 3436 } 3437 for (const Expr *E : Data.LastprivateVars) { 3438 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3439 Address PrivatePtr = 3440 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3441 ".lastpriv.ptr.addr"); 3442 PrivatePtrs.emplace_back(VD, PrivatePtr); 3443 CallArgs.push_back(PrivatePtr.getPointer()); 3444 } 3445 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 3446 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 3447 for (const auto &Pair : LastprivateDstsOrigs) { 3448 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl()); 3449 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD), 3450 /*RefersToEnclosingVariableOrCapture=*/ 3451 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr, 3452 Pair.second->getType(), VK_LValue, 3453 Pair.second->getExprLoc()); 3454 Scope.addPrivate(Pair.first, [&CGF, &DRE]() { 3455 return CGF.EmitLValue(&DRE).getAddress(CGF); 3456 }); 3457 } 3458 for (const auto &Pair : PrivatePtrs) { 3459 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 3460 CGF.getContext().getDeclAlign(Pair.first)); 3461 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 3462 } 3463 } 3464 if (Data.Reductions) { 3465 OMPLexicalScope LexScope(CGF, S, CapturedRegion); 3466 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies, 3467 Data.ReductionOps); 3468 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad( 3469 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9))); 3470 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) { 3471 RedCG.emitSharedLValue(CGF, Cnt); 3472 RedCG.emitAggregateType(CGF, Cnt); 3473 // FIXME: This must removed once the runtime library is fixed. 3474 // Emit required threadprivate variables for 3475 // initializer/combiner/finalizer. 3476 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 3477 RedCG, Cnt); 3478 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 3479 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 3480 Replacement = 3481 Address(CGF.EmitScalarConversion( 3482 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 3483 CGF.getContext().getPointerType( 3484 Data.ReductionCopies[Cnt]->getType()), 3485 Data.ReductionCopies[Cnt]->getExprLoc()), 3486 Replacement.getAlignment()); 3487 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 3488 Scope.addPrivate(RedCG.getBaseDecl(Cnt), 3489 [Replacement]() { return Replacement; }); 3490 } 3491 } 3492 // Privatize all private variables except for in_reduction items. 3493 (void)Scope.Privatize(); 3494 SmallVector<const Expr *, 4> InRedVars; 3495 SmallVector<const Expr *, 4> InRedPrivs; 3496 SmallVector<const Expr *, 4> InRedOps; 3497 SmallVector<const Expr *, 4> TaskgroupDescriptors; 3498 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) { 3499 auto IPriv = C->privates().begin(); 3500 auto IRed = C->reduction_ops().begin(); 3501 auto ITD = C->taskgroup_descriptors().begin(); 3502 for (const Expr *Ref : C->varlists()) { 3503 InRedVars.emplace_back(Ref); 3504 InRedPrivs.emplace_back(*IPriv); 3505 InRedOps.emplace_back(*IRed); 3506 TaskgroupDescriptors.emplace_back(*ITD); 3507 std::advance(IPriv, 1); 3508 std::advance(IRed, 1); 3509 std::advance(ITD, 1); 3510 } 3511 } 3512 // Privatize in_reduction items here, because taskgroup descriptors must be 3513 // privatized earlier. 3514 OMPPrivateScope InRedScope(CGF); 3515 if (!InRedVars.empty()) { 3516 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps); 3517 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) { 3518 RedCG.emitSharedLValue(CGF, Cnt); 3519 RedCG.emitAggregateType(CGF, Cnt); 3520 // The taskgroup descriptor variable is always implicit firstprivate and 3521 // privatized already during processing of the firstprivates. 3522 // FIXME: This must removed once the runtime library is fixed. 3523 // Emit required threadprivate variables for 3524 // initializer/combiner/finalizer. 3525 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 3526 RedCG, Cnt); 3527 llvm::Value *ReductionsPtr = 3528 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]), 3529 TaskgroupDescriptors[Cnt]->getExprLoc()); 3530 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 3531 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 3532 Replacement = Address( 3533 CGF.EmitScalarConversion( 3534 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 3535 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()), 3536 InRedPrivs[Cnt]->getExprLoc()), 3537 Replacement.getAlignment()); 3538 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 3539 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), 3540 [Replacement]() { return Replacement; }); 3541 } 3542 } 3543 (void)InRedScope.Privatize(); 3544 3545 Action.Enter(CGF); 3546 BodyGen(CGF); 3547 }; 3548 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 3549 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied, 3550 Data.NumberOfParts); 3551 OMPLexicalScope Scope(*this, S, llvm::None, 3552 !isOpenMPParallelDirective(S.getDirectiveKind()) && 3553 !isOpenMPSimdDirective(S.getDirectiveKind())); 3554 TaskGen(*this, OutlinedFn, Data); 3555 } 3556 3557 static ImplicitParamDecl * 3558 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data, 3559 QualType Ty, CapturedDecl *CD, 3560 SourceLocation Loc) { 3561 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 3562 ImplicitParamDecl::Other); 3563 auto *OrigRef = DeclRefExpr::Create( 3564 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD, 3565 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 3566 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 3567 ImplicitParamDecl::Other); 3568 auto *PrivateRef = DeclRefExpr::Create( 3569 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD, 3570 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 3571 QualType ElemType = C.getBaseElementType(Ty); 3572 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType, 3573 ImplicitParamDecl::Other); 3574 auto *InitRef = DeclRefExpr::Create( 3575 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD, 3576 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue); 3577 PrivateVD->setInitStyle(VarDecl::CInit); 3578 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue, 3579 InitRef, /*BasePath=*/nullptr, 3580 VK_RValue)); 3581 Data.FirstprivateVars.emplace_back(OrigRef); 3582 Data.FirstprivateCopies.emplace_back(PrivateRef); 3583 Data.FirstprivateInits.emplace_back(InitRef); 3584 return OrigVD; 3585 } 3586 3587 void CodeGenFunction::EmitOMPTargetTaskBasedDirective( 3588 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen, 3589 OMPTargetDataInfo &InputInfo) { 3590 // Emit outlined function for task construct. 3591 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 3592 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 3593 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 3594 auto I = CS->getCapturedDecl()->param_begin(); 3595 auto PartId = std::next(I); 3596 auto TaskT = std::next(I, 4); 3597 OMPTaskDataTy Data; 3598 // The task is not final. 3599 Data.Final.setInt(/*IntVal=*/false); 3600 // Get list of firstprivate variables. 3601 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 3602 auto IRef = C->varlist_begin(); 3603 auto IElemInitRef = C->inits().begin(); 3604 for (auto *IInit : C->private_copies()) { 3605 Data.FirstprivateVars.push_back(*IRef); 3606 Data.FirstprivateCopies.push_back(IInit); 3607 Data.FirstprivateInits.push_back(*IElemInitRef); 3608 ++IRef; 3609 ++IElemInitRef; 3610 } 3611 } 3612 OMPPrivateScope TargetScope(*this); 3613 VarDecl *BPVD = nullptr; 3614 VarDecl *PVD = nullptr; 3615 VarDecl *SVD = nullptr; 3616 if (InputInfo.NumberOfTargetItems > 0) { 3617 auto *CD = CapturedDecl::Create( 3618 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0); 3619 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems); 3620 QualType BaseAndPointersType = getContext().getConstantArrayType( 3621 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal, 3622 /*IndexTypeQuals=*/0); 3623 BPVD = createImplicitFirstprivateForType( 3624 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc()); 3625 PVD = createImplicitFirstprivateForType( 3626 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc()); 3627 QualType SizesType = getContext().getConstantArrayType( 3628 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1), 3629 ArrSize, nullptr, ArrayType::Normal, 3630 /*IndexTypeQuals=*/0); 3631 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD, 3632 S.getBeginLoc()); 3633 TargetScope.addPrivate( 3634 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; }); 3635 TargetScope.addPrivate(PVD, 3636 [&InputInfo]() { return InputInfo.PointersArray; }); 3637 TargetScope.addPrivate(SVD, 3638 [&InputInfo]() { return InputInfo.SizesArray; }); 3639 } 3640 (void)TargetScope.Privatize(); 3641 // Build list of dependences. 3642 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) 3643 for (const Expr *IRef : C->varlists()) 3644 Data.Dependences.emplace_back(C->getDependencyKind(), IRef); 3645 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, 3646 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) { 3647 // Set proper addresses for generated private copies. 3648 OMPPrivateScope Scope(CGF); 3649 if (!Data.FirstprivateVars.empty()) { 3650 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get( 3651 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true); 3652 enum { PrivatesParam = 2, CopyFnParam = 3 }; 3653 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 3654 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 3655 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 3656 CS->getCapturedDecl()->getParam(PrivatesParam))); 3657 // Map privates. 3658 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 3659 llvm::SmallVector<llvm::Value *, 16> CallArgs; 3660 CallArgs.push_back(PrivatesPtr); 3661 for (const Expr *E : Data.FirstprivateVars) { 3662 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3663 Address PrivatePtr = 3664 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3665 ".firstpriv.ptr.addr"); 3666 PrivatePtrs.emplace_back(VD, PrivatePtr); 3667 CallArgs.push_back(PrivatePtr.getPointer()); 3668 } 3669 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 3670 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 3671 for (const auto &Pair : PrivatePtrs) { 3672 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 3673 CGF.getContext().getDeclAlign(Pair.first)); 3674 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 3675 } 3676 } 3677 // Privatize all private variables except for in_reduction items. 3678 (void)Scope.Privatize(); 3679 if (InputInfo.NumberOfTargetItems > 0) { 3680 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP( 3681 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0); 3682 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP( 3683 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0); 3684 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP( 3685 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0); 3686 } 3687 3688 Action.Enter(CGF); 3689 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false); 3690 BodyGen(CGF); 3691 }; 3692 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 3693 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true, 3694 Data.NumberOfParts); 3695 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0); 3696 IntegerLiteral IfCond(getContext(), TrueOrFalse, 3697 getContext().getIntTypeForBitwidth(32, /*Signed=*/0), 3698 SourceLocation()); 3699 3700 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn, 3701 SharedsTy, CapturedStruct, &IfCond, Data); 3702 } 3703 3704 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 3705 // Emit outlined function for task construct. 3706 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 3707 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 3708 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 3709 const Expr *IfCond = nullptr; 3710 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 3711 if (C->getNameModifier() == OMPD_unknown || 3712 C->getNameModifier() == OMPD_task) { 3713 IfCond = C->getCondition(); 3714 break; 3715 } 3716 } 3717 3718 OMPTaskDataTy Data; 3719 // Check if we should emit tied or untied task. 3720 Data.Tied = !S.getSingleClause<OMPUntiedClause>(); 3721 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) { 3722 CGF.EmitStmt(CS->getCapturedStmt()); 3723 }; 3724 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 3725 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 3726 const OMPTaskDataTy &Data) { 3727 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn, 3728 SharedsTy, CapturedStruct, IfCond, 3729 Data); 3730 }; 3731 auto LPCRegion = 3732 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3733 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data); 3734 } 3735 3736 void CodeGenFunction::EmitOMPTaskyieldDirective( 3737 const OMPTaskyieldDirective &S) { 3738 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc()); 3739 } 3740 3741 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 3742 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier); 3743 } 3744 3745 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 3746 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc()); 3747 } 3748 3749 void CodeGenFunction::EmitOMPTaskgroupDirective( 3750 const OMPTaskgroupDirective &S) { 3751 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3752 Action.Enter(CGF); 3753 if (const Expr *E = S.getReductionRef()) { 3754 SmallVector<const Expr *, 4> LHSs; 3755 SmallVector<const Expr *, 4> RHSs; 3756 OMPTaskDataTy Data; 3757 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) { 3758 auto IPriv = C->privates().begin(); 3759 auto IRed = C->reduction_ops().begin(); 3760 auto ILHS = C->lhs_exprs().begin(); 3761 auto IRHS = C->rhs_exprs().begin(); 3762 for (const Expr *Ref : C->varlists()) { 3763 Data.ReductionVars.emplace_back(Ref); 3764 Data.ReductionCopies.emplace_back(*IPriv); 3765 Data.ReductionOps.emplace_back(*IRed); 3766 LHSs.emplace_back(*ILHS); 3767 RHSs.emplace_back(*IRHS); 3768 std::advance(IPriv, 1); 3769 std::advance(IRed, 1); 3770 std::advance(ILHS, 1); 3771 std::advance(IRHS, 1); 3772 } 3773 } 3774 llvm::Value *ReductionDesc = 3775 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(), 3776 LHSs, RHSs, Data); 3777 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3778 CGF.EmitVarDecl(*VD); 3779 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD), 3780 /*Volatile=*/false, E->getType()); 3781 } 3782 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3783 }; 3784 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3785 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc()); 3786 } 3787 3788 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 3789 llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>() 3790 ? llvm::AtomicOrdering::NotAtomic 3791 : llvm::AtomicOrdering::AcquireRelease; 3792 CGM.getOpenMPRuntime().emitFlush( 3793 *this, 3794 [&S]() -> ArrayRef<const Expr *> { 3795 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) 3796 return llvm::makeArrayRef(FlushClause->varlist_begin(), 3797 FlushClause->varlist_end()); 3798 return llvm::None; 3799 }(), 3800 S.getBeginLoc(), AO); 3801 } 3802 3803 void CodeGenFunction::EmitOMPDepobjDirective(const OMPDepobjDirective &S) { 3804 const auto *DO = S.getSingleClause<OMPDepobjClause>(); 3805 LValue DOLVal = EmitLValue(DO->getDepobj()); 3806 if (const auto *DC = S.getSingleClause<OMPDependClause>()) { 3807 SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 4> 3808 Dependencies; 3809 for (const Expr *IRef : DC->varlists()) 3810 Dependencies.emplace_back(DC->getDependencyKind(), IRef); 3811 Address DepAddr = CGM.getOpenMPRuntime().emitDependClause( 3812 *this, Dependencies, /*ForDepobj=*/true, DC->getBeginLoc()); 3813 EmitStoreOfScalar(DepAddr.getPointer(), DOLVal); 3814 return; 3815 } 3816 if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) { 3817 CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc()); 3818 return; 3819 } 3820 } 3821 3822 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S, 3823 const CodeGenLoopTy &CodeGenLoop, 3824 Expr *IncExpr) { 3825 // Emit the loop iteration variable. 3826 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 3827 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 3828 EmitVarDecl(*IVDecl); 3829 3830 // Emit the iterations count variable. 3831 // If it is not a variable, Sema decided to calculate iterations count on each 3832 // iteration (e.g., it is foldable into a constant). 3833 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 3834 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 3835 // Emit calculation of the iterations count. 3836 EmitIgnoredExpr(S.getCalcLastIteration()); 3837 } 3838 3839 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 3840 3841 bool HasLastprivateClause = false; 3842 // Check pre-condition. 3843 { 3844 OMPLoopScope PreInitScope(*this, S); 3845 // Skip the entire loop if we don't meet the precondition. 3846 // If the condition constant folds and can be elided, avoid emitting the 3847 // whole loop. 3848 bool CondConstant; 3849 llvm::BasicBlock *ContBlock = nullptr; 3850 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 3851 if (!CondConstant) 3852 return; 3853 } else { 3854 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 3855 ContBlock = createBasicBlock("omp.precond.end"); 3856 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 3857 getProfileCount(&S)); 3858 EmitBlock(ThenBlock); 3859 incrementProfileCounter(&S); 3860 } 3861 3862 emitAlignedClause(*this, S); 3863 // Emit 'then' code. 3864 { 3865 // Emit helper vars inits. 3866 3867 LValue LB = EmitOMPHelperVar( 3868 *this, cast<DeclRefExpr>( 3869 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3870 ? S.getCombinedLowerBoundVariable() 3871 : S.getLowerBoundVariable()))); 3872 LValue UB = EmitOMPHelperVar( 3873 *this, cast<DeclRefExpr>( 3874 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3875 ? S.getCombinedUpperBoundVariable() 3876 : S.getUpperBoundVariable()))); 3877 LValue ST = 3878 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 3879 LValue IL = 3880 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 3881 3882 OMPPrivateScope LoopScope(*this); 3883 if (EmitOMPFirstprivateClause(S, LoopScope)) { 3884 // Emit implicit barrier to synchronize threads and avoid data races 3885 // on initialization of firstprivate variables and post-update of 3886 // lastprivate variables. 3887 CGM.getOpenMPRuntime().emitBarrierCall( 3888 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3889 /*ForceSimpleCall=*/true); 3890 } 3891 EmitOMPPrivateClause(S, LoopScope); 3892 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 3893 !isOpenMPParallelDirective(S.getDirectiveKind()) && 3894 !isOpenMPTeamsDirective(S.getDirectiveKind())) 3895 EmitOMPReductionClauseInit(S, LoopScope); 3896 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 3897 EmitOMPPrivateLoopCounters(S, LoopScope); 3898 (void)LoopScope.Privatize(); 3899 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3900 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 3901 3902 // Detect the distribute schedule kind and chunk. 3903 llvm::Value *Chunk = nullptr; 3904 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown; 3905 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) { 3906 ScheduleKind = C->getDistScheduleKind(); 3907 if (const Expr *Ch = C->getChunkSize()) { 3908 Chunk = EmitScalarExpr(Ch); 3909 Chunk = EmitScalarConversion(Chunk, Ch->getType(), 3910 S.getIterationVariable()->getType(), 3911 S.getBeginLoc()); 3912 } 3913 } else { 3914 // Default behaviour for dist_schedule clause. 3915 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk( 3916 *this, S, ScheduleKind, Chunk); 3917 } 3918 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 3919 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 3920 3921 // OpenMP [2.10.8, distribute Construct, Description] 3922 // If dist_schedule is specified, kind must be static. If specified, 3923 // iterations are divided into chunks of size chunk_size, chunks are 3924 // assigned to the teams of the league in a round-robin fashion in the 3925 // order of the team number. When no chunk_size is specified, the 3926 // iteration space is divided into chunks that are approximately equal 3927 // in size, and at most one chunk is distributed to each team of the 3928 // league. The size of the chunks is unspecified in this case. 3929 bool StaticChunked = RT.isStaticChunked( 3930 ScheduleKind, /* Chunked */ Chunk != nullptr) && 3931 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 3932 if (RT.isStaticNonchunked(ScheduleKind, 3933 /* Chunked */ Chunk != nullptr) || 3934 StaticChunked) { 3935 CGOpenMPRuntime::StaticRTInput StaticInit( 3936 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this), 3937 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 3938 StaticChunked ? Chunk : nullptr); 3939 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, 3940 StaticInit); 3941 JumpDest LoopExit = 3942 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 3943 // UB = min(UB, GlobalUB); 3944 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3945 ? S.getCombinedEnsureUpperBound() 3946 : S.getEnsureUpperBound()); 3947 // IV = LB; 3948 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3949 ? S.getCombinedInit() 3950 : S.getInit()); 3951 3952 const Expr *Cond = 3953 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3954 ? S.getCombinedCond() 3955 : S.getCond(); 3956 3957 if (StaticChunked) 3958 Cond = S.getCombinedDistCond(); 3959 3960 // For static unchunked schedules generate: 3961 // 3962 // 1. For distribute alone, codegen 3963 // while (idx <= UB) { 3964 // BODY; 3965 // ++idx; 3966 // } 3967 // 3968 // 2. When combined with 'for' (e.g. as in 'distribute parallel for') 3969 // while (idx <= UB) { 3970 // <CodeGen rest of pragma>(LB, UB); 3971 // idx += ST; 3972 // } 3973 // 3974 // For static chunk one schedule generate: 3975 // 3976 // while (IV <= GlobalUB) { 3977 // <CodeGen rest of pragma>(LB, UB); 3978 // LB += ST; 3979 // UB += ST; 3980 // UB = min(UB, GlobalUB); 3981 // IV = LB; 3982 // } 3983 // 3984 emitCommonSimdLoop( 3985 *this, S, 3986 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3987 if (isOpenMPSimdDirective(S.getDirectiveKind())) 3988 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true); 3989 }, 3990 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop, 3991 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) { 3992 CGF.EmitOMPInnerLoop( 3993 S, LoopScope.requiresCleanups(), Cond, IncExpr, 3994 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 3995 CodeGenLoop(CGF, S, LoopExit); 3996 }, 3997 [&S, StaticChunked](CodeGenFunction &CGF) { 3998 if (StaticChunked) { 3999 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound()); 4000 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound()); 4001 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound()); 4002 CGF.EmitIgnoredExpr(S.getCombinedInit()); 4003 } 4004 }); 4005 }); 4006 EmitBlock(LoopExit.getBlock()); 4007 // Tell the runtime we are done. 4008 RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind()); 4009 } else { 4010 // Emit the outer loop, which requests its work chunk [LB..UB] from 4011 // runtime and runs the inner loop to process it. 4012 const OMPLoopArguments LoopArguments = { 4013 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 4014 IL.getAddress(*this), Chunk}; 4015 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments, 4016 CodeGenLoop); 4017 } 4018 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 4019 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 4020 return CGF.Builder.CreateIsNotNull( 4021 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 4022 }); 4023 } 4024 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 4025 !isOpenMPParallelDirective(S.getDirectiveKind()) && 4026 !isOpenMPTeamsDirective(S.getDirectiveKind())) { 4027 EmitOMPReductionClauseFinal(S, OMPD_simd); 4028 // Emit post-update of the reduction variables if IsLastIter != 0. 4029 emitPostUpdateForReductionClause( 4030 *this, S, [IL, &S](CodeGenFunction &CGF) { 4031 return CGF.Builder.CreateIsNotNull( 4032 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 4033 }); 4034 } 4035 // Emit final copy of the lastprivate variables if IsLastIter != 0. 4036 if (HasLastprivateClause) { 4037 EmitOMPLastprivateClauseFinal( 4038 S, /*NoFinals=*/false, 4039 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 4040 } 4041 } 4042 4043 // We're now done with the loop, so jump to the continuation block. 4044 if (ContBlock) { 4045 EmitBranch(ContBlock); 4046 EmitBlock(ContBlock, true); 4047 } 4048 } 4049 } 4050 4051 void CodeGenFunction::EmitOMPDistributeDirective( 4052 const OMPDistributeDirective &S) { 4053 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4054 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4055 }; 4056 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4057 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 4058 } 4059 4060 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM, 4061 const CapturedStmt *S, 4062 SourceLocation Loc) { 4063 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); 4064 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo; 4065 CGF.CapturedStmtInfo = &CapStmtInfo; 4066 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc); 4067 Fn->setDoesNotRecurse(); 4068 return Fn; 4069 } 4070 4071 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 4072 if (S.hasClausesOfKind<OMPDependClause>()) { 4073 assert(!S.getAssociatedStmt() && 4074 "No associated statement must be in ordered depend construct."); 4075 for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) 4076 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC); 4077 return; 4078 } 4079 const auto *C = S.getSingleClause<OMPSIMDClause>(); 4080 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF, 4081 PrePostActionTy &Action) { 4082 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 4083 if (C) { 4084 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 4085 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 4086 llvm::Function *OutlinedFn = 4087 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc()); 4088 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(), 4089 OutlinedFn, CapturedVars); 4090 } else { 4091 Action.Enter(CGF); 4092 CGF.EmitStmt(CS->getCapturedStmt()); 4093 } 4094 }; 4095 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4096 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C); 4097 } 4098 4099 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 4100 QualType SrcType, QualType DestType, 4101 SourceLocation Loc) { 4102 assert(CGF.hasScalarEvaluationKind(DestType) && 4103 "DestType must have scalar evaluation kind."); 4104 assert(!Val.isAggregate() && "Must be a scalar or complex."); 4105 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, 4106 DestType, Loc) 4107 : CGF.EmitComplexToScalarConversion( 4108 Val.getComplexVal(), SrcType, DestType, Loc); 4109 } 4110 4111 static CodeGenFunction::ComplexPairTy 4112 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 4113 QualType DestType, SourceLocation Loc) { 4114 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 4115 "DestType must have complex evaluation kind."); 4116 CodeGenFunction::ComplexPairTy ComplexVal; 4117 if (Val.isScalar()) { 4118 // Convert the input element to the element type of the complex. 4119 QualType DestElementType = 4120 DestType->castAs<ComplexType>()->getElementType(); 4121 llvm::Value *ScalarVal = CGF.EmitScalarConversion( 4122 Val.getScalarVal(), SrcType, DestElementType, Loc); 4123 ComplexVal = CodeGenFunction::ComplexPairTy( 4124 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 4125 } else { 4126 assert(Val.isComplex() && "Must be a scalar or complex."); 4127 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 4128 QualType DestElementType = 4129 DestType->castAs<ComplexType>()->getElementType(); 4130 ComplexVal.first = CGF.EmitScalarConversion( 4131 Val.getComplexVal().first, SrcElementType, DestElementType, Loc); 4132 ComplexVal.second = CGF.EmitScalarConversion( 4133 Val.getComplexVal().second, SrcElementType, DestElementType, Loc); 4134 } 4135 return ComplexVal; 4136 } 4137 4138 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 4139 LValue LVal, RValue RVal) { 4140 if (LVal.isGlobalReg()) 4141 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 4142 else 4143 CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false); 4144 } 4145 4146 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF, 4147 llvm::AtomicOrdering AO, LValue LVal, 4148 SourceLocation Loc) { 4149 if (LVal.isGlobalReg()) 4150 return CGF.EmitLoadOfLValue(LVal, Loc); 4151 return CGF.EmitAtomicLoad( 4152 LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO), 4153 LVal.isVolatile()); 4154 } 4155 4156 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal, 4157 QualType RValTy, SourceLocation Loc) { 4158 switch (getEvaluationKind(LVal.getType())) { 4159 case TEK_Scalar: 4160 EmitStoreThroughLValue(RValue::get(convertToScalarValue( 4161 *this, RVal, RValTy, LVal.getType(), Loc)), 4162 LVal); 4163 break; 4164 case TEK_Complex: 4165 EmitStoreOfComplex( 4166 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal, 4167 /*isInit=*/false); 4168 break; 4169 case TEK_Aggregate: 4170 llvm_unreachable("Must be a scalar or complex."); 4171 } 4172 } 4173 4174 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 4175 const Expr *X, const Expr *V, 4176 SourceLocation Loc) { 4177 // v = x; 4178 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 4179 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 4180 LValue XLValue = CGF.EmitLValue(X); 4181 LValue VLValue = CGF.EmitLValue(V); 4182 RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc); 4183 // OpenMP, 2.17.7, atomic Construct 4184 // If the read or capture clause is specified and the acquire, acq_rel, or 4185 // seq_cst clause is specified then the strong flush on exit from the atomic 4186 // operation is also an acquire flush. 4187 switch (AO) { 4188 case llvm::AtomicOrdering::Acquire: 4189 case llvm::AtomicOrdering::AcquireRelease: 4190 case llvm::AtomicOrdering::SequentiallyConsistent: 4191 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4192 llvm::AtomicOrdering::Acquire); 4193 break; 4194 case llvm::AtomicOrdering::Monotonic: 4195 case llvm::AtomicOrdering::Release: 4196 break; 4197 case llvm::AtomicOrdering::NotAtomic: 4198 case llvm::AtomicOrdering::Unordered: 4199 llvm_unreachable("Unexpected ordering."); 4200 } 4201 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc); 4202 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 4203 } 4204 4205 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, 4206 llvm::AtomicOrdering AO, const Expr *X, 4207 const Expr *E, SourceLocation Loc) { 4208 // x = expr; 4209 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 4210 emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 4211 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4212 // OpenMP, 2.17.7, atomic Construct 4213 // If the write, update, or capture clause is specified and the release, 4214 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4215 // the atomic operation is also a release flush. 4216 switch (AO) { 4217 case llvm::AtomicOrdering::Release: 4218 case llvm::AtomicOrdering::AcquireRelease: 4219 case llvm::AtomicOrdering::SequentiallyConsistent: 4220 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4221 llvm::AtomicOrdering::Release); 4222 break; 4223 case llvm::AtomicOrdering::Acquire: 4224 case llvm::AtomicOrdering::Monotonic: 4225 break; 4226 case llvm::AtomicOrdering::NotAtomic: 4227 case llvm::AtomicOrdering::Unordered: 4228 llvm_unreachable("Unexpected ordering."); 4229 } 4230 } 4231 4232 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 4233 RValue Update, 4234 BinaryOperatorKind BO, 4235 llvm::AtomicOrdering AO, 4236 bool IsXLHSInRHSPart) { 4237 ASTContext &Context = CGF.getContext(); 4238 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 4239 // expression is simple and atomic is allowed for the given type for the 4240 // target platform. 4241 if (BO == BO_Comma || !Update.isScalar() || 4242 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() || 4243 (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 4244 (Update.getScalarVal()->getType() != 4245 X.getAddress(CGF).getElementType())) || 4246 !X.getAddress(CGF).getElementType()->isIntegerTy() || 4247 !Context.getTargetInfo().hasBuiltinAtomic( 4248 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 4249 return std::make_pair(false, RValue::get(nullptr)); 4250 4251 llvm::AtomicRMWInst::BinOp RMWOp; 4252 switch (BO) { 4253 case BO_Add: 4254 RMWOp = llvm::AtomicRMWInst::Add; 4255 break; 4256 case BO_Sub: 4257 if (!IsXLHSInRHSPart) 4258 return std::make_pair(false, RValue::get(nullptr)); 4259 RMWOp = llvm::AtomicRMWInst::Sub; 4260 break; 4261 case BO_And: 4262 RMWOp = llvm::AtomicRMWInst::And; 4263 break; 4264 case BO_Or: 4265 RMWOp = llvm::AtomicRMWInst::Or; 4266 break; 4267 case BO_Xor: 4268 RMWOp = llvm::AtomicRMWInst::Xor; 4269 break; 4270 case BO_LT: 4271 RMWOp = X.getType()->hasSignedIntegerRepresentation() 4272 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 4273 : llvm::AtomicRMWInst::Max) 4274 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 4275 : llvm::AtomicRMWInst::UMax); 4276 break; 4277 case BO_GT: 4278 RMWOp = X.getType()->hasSignedIntegerRepresentation() 4279 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 4280 : llvm::AtomicRMWInst::Min) 4281 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 4282 : llvm::AtomicRMWInst::UMin); 4283 break; 4284 case BO_Assign: 4285 RMWOp = llvm::AtomicRMWInst::Xchg; 4286 break; 4287 case BO_Mul: 4288 case BO_Div: 4289 case BO_Rem: 4290 case BO_Shl: 4291 case BO_Shr: 4292 case BO_LAnd: 4293 case BO_LOr: 4294 return std::make_pair(false, RValue::get(nullptr)); 4295 case BO_PtrMemD: 4296 case BO_PtrMemI: 4297 case BO_LE: 4298 case BO_GE: 4299 case BO_EQ: 4300 case BO_NE: 4301 case BO_Cmp: 4302 case BO_AddAssign: 4303 case BO_SubAssign: 4304 case BO_AndAssign: 4305 case BO_OrAssign: 4306 case BO_XorAssign: 4307 case BO_MulAssign: 4308 case BO_DivAssign: 4309 case BO_RemAssign: 4310 case BO_ShlAssign: 4311 case BO_ShrAssign: 4312 case BO_Comma: 4313 llvm_unreachable("Unsupported atomic update operation"); 4314 } 4315 llvm::Value *UpdateVal = Update.getScalarVal(); 4316 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 4317 UpdateVal = CGF.Builder.CreateIntCast( 4318 IC, X.getAddress(CGF).getElementType(), 4319 X.getType()->hasSignedIntegerRepresentation()); 4320 } 4321 llvm::Value *Res = 4322 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO); 4323 return std::make_pair(true, RValue::get(Res)); 4324 } 4325 4326 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 4327 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 4328 llvm::AtomicOrdering AO, SourceLocation Loc, 4329 const llvm::function_ref<RValue(RValue)> CommonGen) { 4330 // Update expressions are allowed to have the following forms: 4331 // x binop= expr; -> xrval + expr; 4332 // x++, ++x -> xrval + 1; 4333 // x--, --x -> xrval - 1; 4334 // x = x binop expr; -> xrval binop expr 4335 // x = expr Op x; - > expr binop xrval; 4336 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 4337 if (!Res.first) { 4338 if (X.isGlobalReg()) { 4339 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 4340 // 'xrval'. 4341 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 4342 } else { 4343 // Perform compare-and-swap procedure. 4344 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 4345 } 4346 } 4347 return Res; 4348 } 4349 4350 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, 4351 llvm::AtomicOrdering AO, const Expr *X, 4352 const Expr *E, const Expr *UE, 4353 bool IsXLHSInRHSPart, SourceLocation Loc) { 4354 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 4355 "Update expr in 'atomic update' must be a binary operator."); 4356 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 4357 // Update expressions are allowed to have the following forms: 4358 // x binop= expr; -> xrval + expr; 4359 // x++, ++x -> xrval + 1; 4360 // x--, --x -> xrval - 1; 4361 // x = x binop expr; -> xrval binop expr 4362 // x = expr Op x; - > expr binop xrval; 4363 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 4364 LValue XLValue = CGF.EmitLValue(X); 4365 RValue ExprRValue = CGF.EmitAnyExpr(E); 4366 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 4367 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 4368 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 4369 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 4370 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) { 4371 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4372 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 4373 return CGF.EmitAnyExpr(UE); 4374 }; 4375 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 4376 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 4377 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4378 // OpenMP, 2.17.7, atomic Construct 4379 // If the write, update, or capture clause is specified and the release, 4380 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4381 // the atomic operation is also a release flush. 4382 switch (AO) { 4383 case llvm::AtomicOrdering::Release: 4384 case llvm::AtomicOrdering::AcquireRelease: 4385 case llvm::AtomicOrdering::SequentiallyConsistent: 4386 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4387 llvm::AtomicOrdering::Release); 4388 break; 4389 case llvm::AtomicOrdering::Acquire: 4390 case llvm::AtomicOrdering::Monotonic: 4391 break; 4392 case llvm::AtomicOrdering::NotAtomic: 4393 case llvm::AtomicOrdering::Unordered: 4394 llvm_unreachable("Unexpected ordering."); 4395 } 4396 } 4397 4398 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 4399 QualType SourceType, QualType ResType, 4400 SourceLocation Loc) { 4401 switch (CGF.getEvaluationKind(ResType)) { 4402 case TEK_Scalar: 4403 return RValue::get( 4404 convertToScalarValue(CGF, Value, SourceType, ResType, Loc)); 4405 case TEK_Complex: { 4406 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc); 4407 return RValue::getComplex(Res.first, Res.second); 4408 } 4409 case TEK_Aggregate: 4410 break; 4411 } 4412 llvm_unreachable("Must be a scalar or complex."); 4413 } 4414 4415 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, 4416 llvm::AtomicOrdering AO, 4417 bool IsPostfixUpdate, const Expr *V, 4418 const Expr *X, const Expr *E, 4419 const Expr *UE, bool IsXLHSInRHSPart, 4420 SourceLocation Loc) { 4421 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 4422 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 4423 RValue NewVVal; 4424 LValue VLValue = CGF.EmitLValue(V); 4425 LValue XLValue = CGF.EmitLValue(X); 4426 RValue ExprRValue = CGF.EmitAnyExpr(E); 4427 QualType NewVValType; 4428 if (UE) { 4429 // 'x' is updated with some additional value. 4430 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 4431 "Update expr in 'atomic capture' must be a binary operator."); 4432 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 4433 // Update expressions are allowed to have the following forms: 4434 // x binop= expr; -> xrval + expr; 4435 // x++, ++x -> xrval + 1; 4436 // x--, --x -> xrval - 1; 4437 // x = x binop expr; -> xrval binop expr 4438 // x = expr Op x; - > expr binop xrval; 4439 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 4440 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 4441 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 4442 NewVValType = XRValExpr->getType(); 4443 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 4444 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 4445 IsPostfixUpdate](RValue XRValue) { 4446 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4447 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 4448 RValue Res = CGF.EmitAnyExpr(UE); 4449 NewVVal = IsPostfixUpdate ? XRValue : Res; 4450 return Res; 4451 }; 4452 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 4453 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 4454 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4455 if (Res.first) { 4456 // 'atomicrmw' instruction was generated. 4457 if (IsPostfixUpdate) { 4458 // Use old value from 'atomicrmw'. 4459 NewVVal = Res.second; 4460 } else { 4461 // 'atomicrmw' does not provide new value, so evaluate it using old 4462 // value of 'x'. 4463 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4464 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 4465 NewVVal = CGF.EmitAnyExpr(UE); 4466 } 4467 } 4468 } else { 4469 // 'x' is simply rewritten with some 'expr'. 4470 NewVValType = X->getType().getNonReferenceType(); 4471 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 4472 X->getType().getNonReferenceType(), Loc); 4473 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) { 4474 NewVVal = XRValue; 4475 return ExprRValue; 4476 }; 4477 // Try to perform atomicrmw xchg, otherwise simple exchange. 4478 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 4479 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 4480 Loc, Gen); 4481 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4482 if (Res.first) { 4483 // 'atomicrmw' instruction was generated. 4484 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 4485 } 4486 } 4487 // Emit post-update store to 'v' of old/new 'x' value. 4488 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc); 4489 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 4490 // OpenMP, 2.17.7, atomic Construct 4491 // If the write, update, or capture clause is specified and the release, 4492 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4493 // the atomic operation is also a release flush. 4494 // If the read or capture clause is specified and the acquire, acq_rel, or 4495 // seq_cst clause is specified then the strong flush on exit from the atomic 4496 // operation is also an acquire flush. 4497 switch (AO) { 4498 case llvm::AtomicOrdering::Release: 4499 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4500 llvm::AtomicOrdering::Release); 4501 break; 4502 case llvm::AtomicOrdering::Acquire: 4503 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4504 llvm::AtomicOrdering::Acquire); 4505 break; 4506 case llvm::AtomicOrdering::AcquireRelease: 4507 case llvm::AtomicOrdering::SequentiallyConsistent: 4508 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4509 llvm::AtomicOrdering::AcquireRelease); 4510 break; 4511 case llvm::AtomicOrdering::Monotonic: 4512 break; 4513 case llvm::AtomicOrdering::NotAtomic: 4514 case llvm::AtomicOrdering::Unordered: 4515 llvm_unreachable("Unexpected ordering."); 4516 } 4517 } 4518 4519 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 4520 llvm::AtomicOrdering AO, bool IsPostfixUpdate, 4521 const Expr *X, const Expr *V, const Expr *E, 4522 const Expr *UE, bool IsXLHSInRHSPart, 4523 SourceLocation Loc) { 4524 switch (Kind) { 4525 case OMPC_read: 4526 emitOMPAtomicReadExpr(CGF, AO, X, V, Loc); 4527 break; 4528 case OMPC_write: 4529 emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc); 4530 break; 4531 case OMPC_unknown: 4532 case OMPC_update: 4533 emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc); 4534 break; 4535 case OMPC_capture: 4536 emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE, 4537 IsXLHSInRHSPart, Loc); 4538 break; 4539 case OMPC_if: 4540 case OMPC_final: 4541 case OMPC_num_threads: 4542 case OMPC_private: 4543 case OMPC_firstprivate: 4544 case OMPC_lastprivate: 4545 case OMPC_reduction: 4546 case OMPC_task_reduction: 4547 case OMPC_in_reduction: 4548 case OMPC_safelen: 4549 case OMPC_simdlen: 4550 case OMPC_allocator: 4551 case OMPC_allocate: 4552 case OMPC_collapse: 4553 case OMPC_default: 4554 case OMPC_seq_cst: 4555 case OMPC_acq_rel: 4556 case OMPC_acquire: 4557 case OMPC_release: 4558 case OMPC_relaxed: 4559 case OMPC_shared: 4560 case OMPC_linear: 4561 case OMPC_aligned: 4562 case OMPC_copyin: 4563 case OMPC_copyprivate: 4564 case OMPC_flush: 4565 case OMPC_depobj: 4566 case OMPC_proc_bind: 4567 case OMPC_schedule: 4568 case OMPC_ordered: 4569 case OMPC_nowait: 4570 case OMPC_untied: 4571 case OMPC_threadprivate: 4572 case OMPC_depend: 4573 case OMPC_mergeable: 4574 case OMPC_device: 4575 case OMPC_threads: 4576 case OMPC_simd: 4577 case OMPC_map: 4578 case OMPC_num_teams: 4579 case OMPC_thread_limit: 4580 case OMPC_priority: 4581 case OMPC_grainsize: 4582 case OMPC_nogroup: 4583 case OMPC_num_tasks: 4584 case OMPC_hint: 4585 case OMPC_dist_schedule: 4586 case OMPC_defaultmap: 4587 case OMPC_uniform: 4588 case OMPC_to: 4589 case OMPC_from: 4590 case OMPC_use_device_ptr: 4591 case OMPC_is_device_ptr: 4592 case OMPC_unified_address: 4593 case OMPC_unified_shared_memory: 4594 case OMPC_reverse_offload: 4595 case OMPC_dynamic_allocators: 4596 case OMPC_atomic_default_mem_order: 4597 case OMPC_device_type: 4598 case OMPC_match: 4599 case OMPC_nontemporal: 4600 case OMPC_order: 4601 case OMPC_destroy: 4602 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 4603 } 4604 } 4605 4606 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 4607 llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic; 4608 bool MemOrderingSpecified = false; 4609 if (S.getSingleClause<OMPSeqCstClause>()) { 4610 AO = llvm::AtomicOrdering::SequentiallyConsistent; 4611 MemOrderingSpecified = true; 4612 } else if (S.getSingleClause<OMPAcqRelClause>()) { 4613 AO = llvm::AtomicOrdering::AcquireRelease; 4614 MemOrderingSpecified = true; 4615 } else if (S.getSingleClause<OMPAcquireClause>()) { 4616 AO = llvm::AtomicOrdering::Acquire; 4617 MemOrderingSpecified = true; 4618 } else if (S.getSingleClause<OMPReleaseClause>()) { 4619 AO = llvm::AtomicOrdering::Release; 4620 MemOrderingSpecified = true; 4621 } else if (S.getSingleClause<OMPRelaxedClause>()) { 4622 AO = llvm::AtomicOrdering::Monotonic; 4623 MemOrderingSpecified = true; 4624 } 4625 OpenMPClauseKind Kind = OMPC_unknown; 4626 for (const OMPClause *C : S.clauses()) { 4627 // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause, 4628 // if it is first). 4629 if (C->getClauseKind() != OMPC_seq_cst && 4630 C->getClauseKind() != OMPC_acq_rel && 4631 C->getClauseKind() != OMPC_acquire && 4632 C->getClauseKind() != OMPC_release && 4633 C->getClauseKind() != OMPC_relaxed) { 4634 Kind = C->getClauseKind(); 4635 break; 4636 } 4637 } 4638 if (!MemOrderingSpecified) { 4639 llvm::AtomicOrdering DefaultOrder = 4640 CGM.getOpenMPRuntime().getDefaultMemoryOrdering(); 4641 if (DefaultOrder == llvm::AtomicOrdering::Monotonic || 4642 DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent || 4643 (DefaultOrder == llvm::AtomicOrdering::AcquireRelease && 4644 Kind == OMPC_capture)) { 4645 AO = DefaultOrder; 4646 } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) { 4647 if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) { 4648 AO = llvm::AtomicOrdering::Release; 4649 } else if (Kind == OMPC_read) { 4650 assert(Kind == OMPC_read && "Unexpected atomic kind."); 4651 AO = llvm::AtomicOrdering::Acquire; 4652 } 4653 } 4654 } 4655 4656 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers(); 4657 if (const auto *FE = dyn_cast<FullExpr>(CS)) 4658 enterFullExpression(FE); 4659 // Processing for statements under 'atomic capture'. 4660 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) { 4661 for (const Stmt *C : Compound->body()) { 4662 if (const auto *FE = dyn_cast<FullExpr>(C)) 4663 enterFullExpression(FE); 4664 } 4665 } 4666 4667 auto &&CodeGen = [&S, Kind, AO, CS](CodeGenFunction &CGF, 4668 PrePostActionTy &) { 4669 CGF.EmitStopPoint(CS); 4670 emitOMPAtomicExpr(CGF, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(), 4671 S.getExpr(), S.getUpdateExpr(), S.isXLHSInRHSPart(), 4672 S.getBeginLoc()); 4673 }; 4674 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4675 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen); 4676 } 4677 4678 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 4679 const OMPExecutableDirective &S, 4680 const RegionCodeGenTy &CodeGen) { 4681 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind())); 4682 CodeGenModule &CGM = CGF.CGM; 4683 4684 // On device emit this construct as inlined code. 4685 if (CGM.getLangOpts().OpenMPIsDevice) { 4686 OMPLexicalScope Scope(CGF, S, OMPD_target); 4687 CGM.getOpenMPRuntime().emitInlinedDirective( 4688 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4689 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 4690 }); 4691 return; 4692 } 4693 4694 auto LPCRegion = 4695 CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S); 4696 llvm::Function *Fn = nullptr; 4697 llvm::Constant *FnID = nullptr; 4698 4699 const Expr *IfCond = nullptr; 4700 // Check for the at most one if clause associated with the target region. 4701 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 4702 if (C->getNameModifier() == OMPD_unknown || 4703 C->getNameModifier() == OMPD_target) { 4704 IfCond = C->getCondition(); 4705 break; 4706 } 4707 } 4708 4709 // Check if we have any device clause associated with the directive. 4710 const Expr *Device = nullptr; 4711 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 4712 Device = C->getDevice(); 4713 4714 // Check if we have an if clause whose conditional always evaluates to false 4715 // or if we do not have any targets specified. If so the target region is not 4716 // an offload entry point. 4717 bool IsOffloadEntry = true; 4718 if (IfCond) { 4719 bool Val; 4720 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val) 4721 IsOffloadEntry = false; 4722 } 4723 if (CGM.getLangOpts().OMPTargetTriples.empty()) 4724 IsOffloadEntry = false; 4725 4726 assert(CGF.CurFuncDecl && "No parent declaration for target region!"); 4727 StringRef ParentName; 4728 // In case we have Ctors/Dtors we use the complete type variant to produce 4729 // the mangling of the device outlined kernel. 4730 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl)) 4731 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete)); 4732 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl)) 4733 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete)); 4734 else 4735 ParentName = 4736 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl))); 4737 4738 // Emit target region as a standalone region. 4739 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID, 4740 IsOffloadEntry, CodeGen); 4741 OMPLexicalScope Scope(CGF, S, OMPD_task); 4742 auto &&SizeEmitter = 4743 [IsOffloadEntry](CodeGenFunction &CGF, 4744 const OMPLoopDirective &D) -> llvm::Value * { 4745 if (IsOffloadEntry) { 4746 OMPLoopScope(CGF, D); 4747 // Emit calculation of the iterations count. 4748 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations()); 4749 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty, 4750 /*isSigned=*/false); 4751 return NumIterations; 4752 } 4753 return nullptr; 4754 }; 4755 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device, 4756 SizeEmitter); 4757 } 4758 4759 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S, 4760 PrePostActionTy &Action) { 4761 Action.Enter(CGF); 4762 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4763 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4764 CGF.EmitOMPPrivateClause(S, PrivateScope); 4765 (void)PrivateScope.Privatize(); 4766 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 4767 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 4768 4769 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt()); 4770 } 4771 4772 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 4773 StringRef ParentName, 4774 const OMPTargetDirective &S) { 4775 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4776 emitTargetRegion(CGF, S, Action); 4777 }; 4778 llvm::Function *Fn; 4779 llvm::Constant *Addr; 4780 // Emit target region as a standalone region. 4781 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4782 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4783 assert(Fn && Addr && "Target device function emission failed."); 4784 } 4785 4786 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) { 4787 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4788 emitTargetRegion(CGF, S, Action); 4789 }; 4790 emitCommonOMPTargetDirective(*this, S, CodeGen); 4791 } 4792 4793 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, 4794 const OMPExecutableDirective &S, 4795 OpenMPDirectiveKind InnermostKind, 4796 const RegionCodeGenTy &CodeGen) { 4797 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams); 4798 llvm::Function *OutlinedFn = 4799 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction( 4800 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 4801 4802 const auto *NT = S.getSingleClause<OMPNumTeamsClause>(); 4803 const auto *TL = S.getSingleClause<OMPThreadLimitClause>(); 4804 if (NT || TL) { 4805 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr; 4806 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr; 4807 4808 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit, 4809 S.getBeginLoc()); 4810 } 4811 4812 OMPTeamsScope Scope(CGF, S); 4813 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 4814 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 4815 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn, 4816 CapturedVars); 4817 } 4818 4819 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) { 4820 // Emit teams region as a standalone region. 4821 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4822 Action.Enter(CGF); 4823 OMPPrivateScope PrivateScope(CGF); 4824 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4825 CGF.EmitOMPPrivateClause(S, PrivateScope); 4826 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4827 (void)PrivateScope.Privatize(); 4828 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt()); 4829 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4830 }; 4831 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 4832 emitPostUpdateForReductionClause(*this, S, 4833 [](CodeGenFunction &) { return nullptr; }); 4834 } 4835 4836 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 4837 const OMPTargetTeamsDirective &S) { 4838 auto *CS = S.getCapturedStmt(OMPD_teams); 4839 Action.Enter(CGF); 4840 // Emit teams region as a standalone region. 4841 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 4842 Action.Enter(CGF); 4843 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4844 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4845 CGF.EmitOMPPrivateClause(S, PrivateScope); 4846 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4847 (void)PrivateScope.Privatize(); 4848 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 4849 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 4850 CGF.EmitStmt(CS->getCapturedStmt()); 4851 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4852 }; 4853 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen); 4854 emitPostUpdateForReductionClause(CGF, S, 4855 [](CodeGenFunction &) { return nullptr; }); 4856 } 4857 4858 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction( 4859 CodeGenModule &CGM, StringRef ParentName, 4860 const OMPTargetTeamsDirective &S) { 4861 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4862 emitTargetTeamsRegion(CGF, Action, S); 4863 }; 4864 llvm::Function *Fn; 4865 llvm::Constant *Addr; 4866 // Emit target region as a standalone region. 4867 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4868 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4869 assert(Fn && Addr && "Target device function emission failed."); 4870 } 4871 4872 void CodeGenFunction::EmitOMPTargetTeamsDirective( 4873 const OMPTargetTeamsDirective &S) { 4874 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4875 emitTargetTeamsRegion(CGF, Action, S); 4876 }; 4877 emitCommonOMPTargetDirective(*this, S, CodeGen); 4878 } 4879 4880 static void 4881 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 4882 const OMPTargetTeamsDistributeDirective &S) { 4883 Action.Enter(CGF); 4884 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4885 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4886 }; 4887 4888 // Emit teams region as a standalone region. 4889 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4890 PrePostActionTy &Action) { 4891 Action.Enter(CGF); 4892 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4893 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4894 (void)PrivateScope.Privatize(); 4895 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4896 CodeGenDistribute); 4897 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4898 }; 4899 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen); 4900 emitPostUpdateForReductionClause(CGF, S, 4901 [](CodeGenFunction &) { return nullptr; }); 4902 } 4903 4904 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction( 4905 CodeGenModule &CGM, StringRef ParentName, 4906 const OMPTargetTeamsDistributeDirective &S) { 4907 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4908 emitTargetTeamsDistributeRegion(CGF, Action, S); 4909 }; 4910 llvm::Function *Fn; 4911 llvm::Constant *Addr; 4912 // Emit target region as a standalone region. 4913 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4914 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4915 assert(Fn && Addr && "Target device function emission failed."); 4916 } 4917 4918 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective( 4919 const OMPTargetTeamsDistributeDirective &S) { 4920 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4921 emitTargetTeamsDistributeRegion(CGF, Action, S); 4922 }; 4923 emitCommonOMPTargetDirective(*this, S, CodeGen); 4924 } 4925 4926 static void emitTargetTeamsDistributeSimdRegion( 4927 CodeGenFunction &CGF, PrePostActionTy &Action, 4928 const OMPTargetTeamsDistributeSimdDirective &S) { 4929 Action.Enter(CGF); 4930 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4931 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4932 }; 4933 4934 // Emit teams region as a standalone region. 4935 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4936 PrePostActionTy &Action) { 4937 Action.Enter(CGF); 4938 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4939 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4940 (void)PrivateScope.Privatize(); 4941 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4942 CodeGenDistribute); 4943 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4944 }; 4945 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen); 4946 emitPostUpdateForReductionClause(CGF, S, 4947 [](CodeGenFunction &) { return nullptr; }); 4948 } 4949 4950 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction( 4951 CodeGenModule &CGM, StringRef ParentName, 4952 const OMPTargetTeamsDistributeSimdDirective &S) { 4953 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4954 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 4955 }; 4956 llvm::Function *Fn; 4957 llvm::Constant *Addr; 4958 // Emit target region as a standalone region. 4959 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4960 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4961 assert(Fn && Addr && "Target device function emission failed."); 4962 } 4963 4964 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective( 4965 const OMPTargetTeamsDistributeSimdDirective &S) { 4966 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4967 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 4968 }; 4969 emitCommonOMPTargetDirective(*this, S, CodeGen); 4970 } 4971 4972 void CodeGenFunction::EmitOMPTeamsDistributeDirective( 4973 const OMPTeamsDistributeDirective &S) { 4974 4975 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4976 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4977 }; 4978 4979 // Emit teams region as a standalone region. 4980 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4981 PrePostActionTy &Action) { 4982 Action.Enter(CGF); 4983 OMPPrivateScope PrivateScope(CGF); 4984 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4985 (void)PrivateScope.Privatize(); 4986 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4987 CodeGenDistribute); 4988 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4989 }; 4990 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 4991 emitPostUpdateForReductionClause(*this, S, 4992 [](CodeGenFunction &) { return nullptr; }); 4993 } 4994 4995 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective( 4996 const OMPTeamsDistributeSimdDirective &S) { 4997 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4998 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4999 }; 5000 5001 // Emit teams region as a standalone region. 5002 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5003 PrePostActionTy &Action) { 5004 Action.Enter(CGF); 5005 OMPPrivateScope PrivateScope(CGF); 5006 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5007 (void)PrivateScope.Privatize(); 5008 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd, 5009 CodeGenDistribute); 5010 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5011 }; 5012 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen); 5013 emitPostUpdateForReductionClause(*this, S, 5014 [](CodeGenFunction &) { return nullptr; }); 5015 } 5016 5017 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective( 5018 const OMPTeamsDistributeParallelForDirective &S) { 5019 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5020 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5021 S.getDistInc()); 5022 }; 5023 5024 // Emit teams region as a standalone region. 5025 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5026 PrePostActionTy &Action) { 5027 Action.Enter(CGF); 5028 OMPPrivateScope PrivateScope(CGF); 5029 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5030 (void)PrivateScope.Privatize(); 5031 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 5032 CodeGenDistribute); 5033 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5034 }; 5035 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen); 5036 emitPostUpdateForReductionClause(*this, S, 5037 [](CodeGenFunction &) { return nullptr; }); 5038 } 5039 5040 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective( 5041 const OMPTeamsDistributeParallelForSimdDirective &S) { 5042 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5043 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5044 S.getDistInc()); 5045 }; 5046 5047 // Emit teams region as a standalone region. 5048 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5049 PrePostActionTy &Action) { 5050 Action.Enter(CGF); 5051 OMPPrivateScope PrivateScope(CGF); 5052 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5053 (void)PrivateScope.Privatize(); 5054 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 5055 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 5056 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5057 }; 5058 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd, 5059 CodeGen); 5060 emitPostUpdateForReductionClause(*this, S, 5061 [](CodeGenFunction &) { return nullptr; }); 5062 } 5063 5064 static void emitTargetTeamsDistributeParallelForRegion( 5065 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S, 5066 PrePostActionTy &Action) { 5067 Action.Enter(CGF); 5068 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5069 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5070 S.getDistInc()); 5071 }; 5072 5073 // Emit teams region as a standalone region. 5074 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5075 PrePostActionTy &Action) { 5076 Action.Enter(CGF); 5077 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5078 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5079 (void)PrivateScope.Privatize(); 5080 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 5081 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 5082 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5083 }; 5084 5085 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for, 5086 CodeGenTeams); 5087 emitPostUpdateForReductionClause(CGF, S, 5088 [](CodeGenFunction &) { return nullptr; }); 5089 } 5090 5091 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 5092 CodeGenModule &CGM, StringRef ParentName, 5093 const OMPTargetTeamsDistributeParallelForDirective &S) { 5094 // Emit SPMD target teams distribute parallel for region as a standalone 5095 // region. 5096 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5097 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 5098 }; 5099 llvm::Function *Fn; 5100 llvm::Constant *Addr; 5101 // Emit target region as a standalone region. 5102 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5103 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5104 assert(Fn && Addr && "Target device function emission failed."); 5105 } 5106 5107 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective( 5108 const OMPTargetTeamsDistributeParallelForDirective &S) { 5109 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5110 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 5111 }; 5112 emitCommonOMPTargetDirective(*this, S, CodeGen); 5113 } 5114 5115 static void emitTargetTeamsDistributeParallelForSimdRegion( 5116 CodeGenFunction &CGF, 5117 const OMPTargetTeamsDistributeParallelForSimdDirective &S, 5118 PrePostActionTy &Action) { 5119 Action.Enter(CGF); 5120 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5121 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5122 S.getDistInc()); 5123 }; 5124 5125 // Emit teams region as a standalone region. 5126 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5127 PrePostActionTy &Action) { 5128 Action.Enter(CGF); 5129 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5130 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5131 (void)PrivateScope.Privatize(); 5132 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 5133 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 5134 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5135 }; 5136 5137 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd, 5138 CodeGenTeams); 5139 emitPostUpdateForReductionClause(CGF, S, 5140 [](CodeGenFunction &) { return nullptr; }); 5141 } 5142 5143 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 5144 CodeGenModule &CGM, StringRef ParentName, 5145 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 5146 // Emit SPMD target teams distribute parallel for simd region as a standalone 5147 // region. 5148 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5149 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 5150 }; 5151 llvm::Function *Fn; 5152 llvm::Constant *Addr; 5153 // Emit target region as a standalone region. 5154 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5155 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5156 assert(Fn && Addr && "Target device function emission failed."); 5157 } 5158 5159 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective( 5160 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 5161 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5162 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 5163 }; 5164 emitCommonOMPTargetDirective(*this, S, CodeGen); 5165 } 5166 5167 void CodeGenFunction::EmitOMPCancellationPointDirective( 5168 const OMPCancellationPointDirective &S) { 5169 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(), 5170 S.getCancelRegion()); 5171 } 5172 5173 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) { 5174 const Expr *IfCond = nullptr; 5175 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 5176 if (C->getNameModifier() == OMPD_unknown || 5177 C->getNameModifier() == OMPD_cancel) { 5178 IfCond = C->getCondition(); 5179 break; 5180 } 5181 } 5182 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) { 5183 // TODO: This check is necessary as we only generate `omp parallel` through 5184 // the OpenMPIRBuilder for now. 5185 if (S.getCancelRegion() == OMPD_parallel) { 5186 llvm::Value *IfCondition = nullptr; 5187 if (IfCond) 5188 IfCondition = EmitScalarExpr(IfCond, 5189 /*IgnoreResultAssign=*/true); 5190 return Builder.restoreIP( 5191 OMPBuilder->CreateCancel(Builder, IfCondition, S.getCancelRegion())); 5192 } 5193 } 5194 5195 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond, 5196 S.getCancelRegion()); 5197 } 5198 5199 CodeGenFunction::JumpDest 5200 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) { 5201 if (Kind == OMPD_parallel || Kind == OMPD_task || 5202 Kind == OMPD_target_parallel || Kind == OMPD_taskloop || 5203 Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop) 5204 return ReturnBlock; 5205 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections || 5206 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for || 5207 Kind == OMPD_distribute_parallel_for || 5208 Kind == OMPD_target_parallel_for || 5209 Kind == OMPD_teams_distribute_parallel_for || 5210 Kind == OMPD_target_teams_distribute_parallel_for); 5211 return OMPCancelStack.getExitBlock(); 5212 } 5213 5214 void CodeGenFunction::EmitOMPUseDevicePtrClause( 5215 const OMPClause &NC, OMPPrivateScope &PrivateScope, 5216 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 5217 const auto &C = cast<OMPUseDevicePtrClause>(NC); 5218 auto OrigVarIt = C.varlist_begin(); 5219 auto InitIt = C.inits().begin(); 5220 for (const Expr *PvtVarIt : C.private_copies()) { 5221 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl()); 5222 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl()); 5223 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl()); 5224 5225 // In order to identify the right initializer we need to match the 5226 // declaration used by the mapping logic. In some cases we may get 5227 // OMPCapturedExprDecl that refers to the original declaration. 5228 const ValueDecl *MatchingVD = OrigVD; 5229 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 5230 // OMPCapturedExprDecl are used to privative fields of the current 5231 // structure. 5232 const auto *ME = cast<MemberExpr>(OED->getInit()); 5233 assert(isa<CXXThisExpr>(ME->getBase()) && 5234 "Base should be the current struct!"); 5235 MatchingVD = ME->getMemberDecl(); 5236 } 5237 5238 // If we don't have information about the current list item, move on to 5239 // the next one. 5240 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 5241 if (InitAddrIt == CaptureDeviceAddrMap.end()) 5242 continue; 5243 5244 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD, 5245 InitAddrIt, InitVD, 5246 PvtVD]() { 5247 // Initialize the temporary initialization variable with the address we 5248 // get from the runtime library. We have to cast the source address 5249 // because it is always a void *. References are materialized in the 5250 // privatization scope, so the initialization here disregards the fact 5251 // the original variable is a reference. 5252 QualType AddrQTy = 5253 getContext().getPointerType(OrigVD->getType().getNonReferenceType()); 5254 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy); 5255 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy); 5256 setAddrOfLocalVar(InitVD, InitAddr); 5257 5258 // Emit private declaration, it will be initialized by the value we 5259 // declaration we just added to the local declarations map. 5260 EmitDecl(*PvtVD); 5261 5262 // The initialization variables reached its purpose in the emission 5263 // of the previous declaration, so we don't need it anymore. 5264 LocalDeclMap.erase(InitVD); 5265 5266 // Return the address of the private variable. 5267 return GetAddrOfLocalVar(PvtVD); 5268 }); 5269 assert(IsRegistered && "firstprivate var already registered as private"); 5270 // Silence the warning about unused variable. 5271 (void)IsRegistered; 5272 5273 ++OrigVarIt; 5274 ++InitIt; 5275 } 5276 } 5277 5278 // Generate the instructions for '#pragma omp target data' directive. 5279 void CodeGenFunction::EmitOMPTargetDataDirective( 5280 const OMPTargetDataDirective &S) { 5281 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true); 5282 5283 // Create a pre/post action to signal the privatization of the device pointer. 5284 // This action can be replaced by the OpenMP runtime code generation to 5285 // deactivate privatization. 5286 bool PrivatizeDevicePointers = false; 5287 class DevicePointerPrivActionTy : public PrePostActionTy { 5288 bool &PrivatizeDevicePointers; 5289 5290 public: 5291 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers) 5292 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {} 5293 void Enter(CodeGenFunction &CGF) override { 5294 PrivatizeDevicePointers = true; 5295 } 5296 }; 5297 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers); 5298 5299 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers]( 5300 CodeGenFunction &CGF, PrePostActionTy &Action) { 5301 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5302 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 5303 }; 5304 5305 // Codegen that selects whether to generate the privatization code or not. 5306 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers, 5307 &InnermostCodeGen](CodeGenFunction &CGF, 5308 PrePostActionTy &Action) { 5309 RegionCodeGenTy RCG(InnermostCodeGen); 5310 PrivatizeDevicePointers = false; 5311 5312 // Call the pre-action to change the status of PrivatizeDevicePointers if 5313 // needed. 5314 Action.Enter(CGF); 5315 5316 if (PrivatizeDevicePointers) { 5317 OMPPrivateScope PrivateScope(CGF); 5318 // Emit all instances of the use_device_ptr clause. 5319 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>()) 5320 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope, 5321 Info.CaptureDeviceAddrMap); 5322 (void)PrivateScope.Privatize(); 5323 RCG(CGF); 5324 } else { 5325 RCG(CGF); 5326 } 5327 }; 5328 5329 // Forward the provided action to the privatization codegen. 5330 RegionCodeGenTy PrivRCG(PrivCodeGen); 5331 PrivRCG.setAction(Action); 5332 5333 // Notwithstanding the body of the region is emitted as inlined directive, 5334 // we don't use an inline scope as changes in the references inside the 5335 // region are expected to be visible outside, so we do not privative them. 5336 OMPLexicalScope Scope(CGF, S); 5337 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, 5338 PrivRCG); 5339 }; 5340 5341 RegionCodeGenTy RCG(CodeGen); 5342 5343 // If we don't have target devices, don't bother emitting the data mapping 5344 // code. 5345 if (CGM.getLangOpts().OMPTargetTriples.empty()) { 5346 RCG(*this); 5347 return; 5348 } 5349 5350 // Check if we have any if clause associated with the directive. 5351 const Expr *IfCond = nullptr; 5352 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5353 IfCond = C->getCondition(); 5354 5355 // Check if we have any device clause associated with the directive. 5356 const Expr *Device = nullptr; 5357 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5358 Device = C->getDevice(); 5359 5360 // Set the action to signal privatization of device pointers. 5361 RCG.setAction(PrivAction); 5362 5363 // Emit region code. 5364 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG, 5365 Info); 5366 } 5367 5368 void CodeGenFunction::EmitOMPTargetEnterDataDirective( 5369 const OMPTargetEnterDataDirective &S) { 5370 // If we don't have target devices, don't bother emitting the data mapping 5371 // code. 5372 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5373 return; 5374 5375 // Check if we have any if clause associated with the directive. 5376 const Expr *IfCond = nullptr; 5377 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5378 IfCond = C->getCondition(); 5379 5380 // Check if we have any device clause associated with the directive. 5381 const Expr *Device = nullptr; 5382 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5383 Device = C->getDevice(); 5384 5385 OMPLexicalScope Scope(*this, S, OMPD_task); 5386 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5387 } 5388 5389 void CodeGenFunction::EmitOMPTargetExitDataDirective( 5390 const OMPTargetExitDataDirective &S) { 5391 // If we don't have target devices, don't bother emitting the data mapping 5392 // code. 5393 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5394 return; 5395 5396 // Check if we have any if clause associated with the directive. 5397 const Expr *IfCond = nullptr; 5398 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5399 IfCond = C->getCondition(); 5400 5401 // Check if we have any device clause associated with the directive. 5402 const Expr *Device = nullptr; 5403 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5404 Device = C->getDevice(); 5405 5406 OMPLexicalScope Scope(*this, S, OMPD_task); 5407 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5408 } 5409 5410 static void emitTargetParallelRegion(CodeGenFunction &CGF, 5411 const OMPTargetParallelDirective &S, 5412 PrePostActionTy &Action) { 5413 // Get the captured statement associated with the 'parallel' region. 5414 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 5415 Action.Enter(CGF); 5416 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 5417 Action.Enter(CGF); 5418 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5419 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 5420 CGF.EmitOMPPrivateClause(S, PrivateScope); 5421 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5422 (void)PrivateScope.Privatize(); 5423 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 5424 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 5425 // TODO: Add support for clauses. 5426 CGF.EmitStmt(CS->getCapturedStmt()); 5427 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 5428 }; 5429 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen, 5430 emitEmptyBoundParameters); 5431 emitPostUpdateForReductionClause(CGF, S, 5432 [](CodeGenFunction &) { return nullptr; }); 5433 } 5434 5435 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction( 5436 CodeGenModule &CGM, StringRef ParentName, 5437 const OMPTargetParallelDirective &S) { 5438 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5439 emitTargetParallelRegion(CGF, S, Action); 5440 }; 5441 llvm::Function *Fn; 5442 llvm::Constant *Addr; 5443 // Emit target region as a standalone region. 5444 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5445 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5446 assert(Fn && Addr && "Target device function emission failed."); 5447 } 5448 5449 void CodeGenFunction::EmitOMPTargetParallelDirective( 5450 const OMPTargetParallelDirective &S) { 5451 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5452 emitTargetParallelRegion(CGF, S, Action); 5453 }; 5454 emitCommonOMPTargetDirective(*this, S, CodeGen); 5455 } 5456 5457 static void emitTargetParallelForRegion(CodeGenFunction &CGF, 5458 const OMPTargetParallelForDirective &S, 5459 PrePostActionTy &Action) { 5460 Action.Enter(CGF); 5461 // Emit directive as a combined directive that consists of two implicit 5462 // directives: 'parallel' with 'for' directive. 5463 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5464 Action.Enter(CGF); 5465 CodeGenFunction::OMPCancelStackRAII CancelRegion( 5466 CGF, OMPD_target_parallel_for, S.hasCancel()); 5467 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 5468 emitDispatchForLoopBounds); 5469 }; 5470 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen, 5471 emitEmptyBoundParameters); 5472 } 5473 5474 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction( 5475 CodeGenModule &CGM, StringRef ParentName, 5476 const OMPTargetParallelForDirective &S) { 5477 // Emit SPMD target parallel for region as a standalone region. 5478 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5479 emitTargetParallelForRegion(CGF, S, Action); 5480 }; 5481 llvm::Function *Fn; 5482 llvm::Constant *Addr; 5483 // Emit target region as a standalone region. 5484 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5485 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5486 assert(Fn && Addr && "Target device function emission failed."); 5487 } 5488 5489 void CodeGenFunction::EmitOMPTargetParallelForDirective( 5490 const OMPTargetParallelForDirective &S) { 5491 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5492 emitTargetParallelForRegion(CGF, S, Action); 5493 }; 5494 emitCommonOMPTargetDirective(*this, S, CodeGen); 5495 } 5496 5497 static void 5498 emitTargetParallelForSimdRegion(CodeGenFunction &CGF, 5499 const OMPTargetParallelForSimdDirective &S, 5500 PrePostActionTy &Action) { 5501 Action.Enter(CGF); 5502 // Emit directive as a combined directive that consists of two implicit 5503 // directives: 'parallel' with 'for' directive. 5504 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5505 Action.Enter(CGF); 5506 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 5507 emitDispatchForLoopBounds); 5508 }; 5509 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen, 5510 emitEmptyBoundParameters); 5511 } 5512 5513 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction( 5514 CodeGenModule &CGM, StringRef ParentName, 5515 const OMPTargetParallelForSimdDirective &S) { 5516 // Emit SPMD target parallel for region as a standalone region. 5517 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5518 emitTargetParallelForSimdRegion(CGF, S, Action); 5519 }; 5520 llvm::Function *Fn; 5521 llvm::Constant *Addr; 5522 // Emit target region as a standalone region. 5523 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5524 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5525 assert(Fn && Addr && "Target device function emission failed."); 5526 } 5527 5528 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective( 5529 const OMPTargetParallelForSimdDirective &S) { 5530 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5531 emitTargetParallelForSimdRegion(CGF, S, Action); 5532 }; 5533 emitCommonOMPTargetDirective(*this, S, CodeGen); 5534 } 5535 5536 /// Emit a helper variable and return corresponding lvalue. 5537 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, 5538 const ImplicitParamDecl *PVD, 5539 CodeGenFunction::OMPPrivateScope &Privates) { 5540 const auto *VDecl = cast<VarDecl>(Helper->getDecl()); 5541 Privates.addPrivate(VDecl, 5542 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); }); 5543 } 5544 5545 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) { 5546 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind())); 5547 // Emit outlined function for task construct. 5548 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop); 5549 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 5550 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 5551 const Expr *IfCond = nullptr; 5552 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 5553 if (C->getNameModifier() == OMPD_unknown || 5554 C->getNameModifier() == OMPD_taskloop) { 5555 IfCond = C->getCondition(); 5556 break; 5557 } 5558 } 5559 5560 OMPTaskDataTy Data; 5561 // Check if taskloop must be emitted without taskgroup. 5562 Data.Nogroup = S.getSingleClause<OMPNogroupClause>(); 5563 // TODO: Check if we should emit tied or untied task. 5564 Data.Tied = true; 5565 // Set scheduling for taskloop 5566 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) { 5567 // grainsize clause 5568 Data.Schedule.setInt(/*IntVal=*/false); 5569 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize())); 5570 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) { 5571 // num_tasks clause 5572 Data.Schedule.setInt(/*IntVal=*/true); 5573 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks())); 5574 } 5575 5576 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) { 5577 // if (PreCond) { 5578 // for (IV in 0..LastIteration) BODY; 5579 // <Final counter/linear vars updates>; 5580 // } 5581 // 5582 5583 // Emit: if (PreCond) - begin. 5584 // If the condition constant folds and can be elided, avoid emitting the 5585 // whole loop. 5586 bool CondConstant; 5587 llvm::BasicBlock *ContBlock = nullptr; 5588 OMPLoopScope PreInitScope(CGF, S); 5589 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 5590 if (!CondConstant) 5591 return; 5592 } else { 5593 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then"); 5594 ContBlock = CGF.createBasicBlock("taskloop.if.end"); 5595 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 5596 CGF.getProfileCount(&S)); 5597 CGF.EmitBlock(ThenBlock); 5598 CGF.incrementProfileCounter(&S); 5599 } 5600 5601 (void)CGF.EmitOMPLinearClauseInit(S); 5602 5603 OMPPrivateScope LoopScope(CGF); 5604 // Emit helper vars inits. 5605 enum { LowerBound = 5, UpperBound, Stride, LastIter }; 5606 auto *I = CS->getCapturedDecl()->param_begin(); 5607 auto *LBP = std::next(I, LowerBound); 5608 auto *UBP = std::next(I, UpperBound); 5609 auto *STP = std::next(I, Stride); 5610 auto *LIP = std::next(I, LastIter); 5611 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP, 5612 LoopScope); 5613 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP, 5614 LoopScope); 5615 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope); 5616 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP, 5617 LoopScope); 5618 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 5619 CGF.EmitOMPLinearClause(S, LoopScope); 5620 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 5621 (void)LoopScope.Privatize(); 5622 // Emit the loop iteration variable. 5623 const Expr *IVExpr = S.getIterationVariable(); 5624 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 5625 CGF.EmitVarDecl(*IVDecl); 5626 CGF.EmitIgnoredExpr(S.getInit()); 5627 5628 // Emit the iterations count variable. 5629 // If it is not a variable, Sema decided to calculate iterations count on 5630 // each iteration (e.g., it is foldable into a constant). 5631 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 5632 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 5633 // Emit calculation of the iterations count. 5634 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 5635 } 5636 5637 { 5638 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 5639 emitCommonSimdLoop( 5640 CGF, S, 5641 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5642 if (isOpenMPSimdDirective(S.getDirectiveKind())) 5643 CGF.EmitOMPSimdInit(S); 5644 }, 5645 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 5646 CGF.EmitOMPInnerLoop( 5647 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 5648 [&S](CodeGenFunction &CGF) { 5649 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest()); 5650 CGF.EmitStopPoint(&S); 5651 }, 5652 [](CodeGenFunction &) {}); 5653 }); 5654 } 5655 // Emit: if (PreCond) - end. 5656 if (ContBlock) { 5657 CGF.EmitBranch(ContBlock); 5658 CGF.EmitBlock(ContBlock, true); 5659 } 5660 // Emit final copy of the lastprivate variables if IsLastIter != 0. 5661 if (HasLastprivateClause) { 5662 CGF.EmitOMPLastprivateClauseFinal( 5663 S, isOpenMPSimdDirective(S.getDirectiveKind()), 5664 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar( 5665 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 5666 (*LIP)->getType(), S.getBeginLoc()))); 5667 } 5668 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) { 5669 return CGF.Builder.CreateIsNotNull( 5670 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 5671 (*LIP)->getType(), S.getBeginLoc())); 5672 }); 5673 }; 5674 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 5675 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 5676 const OMPTaskDataTy &Data) { 5677 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond, 5678 &Data](CodeGenFunction &CGF, PrePostActionTy &) { 5679 OMPLoopScope PreInitScope(CGF, S); 5680 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S, 5681 OutlinedFn, SharedsTy, 5682 CapturedStruct, IfCond, Data); 5683 }; 5684 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop, 5685 CodeGen); 5686 }; 5687 if (Data.Nogroup) { 5688 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data); 5689 } else { 5690 CGM.getOpenMPRuntime().emitTaskgroupRegion( 5691 *this, 5692 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF, 5693 PrePostActionTy &Action) { 5694 Action.Enter(CGF); 5695 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, 5696 Data); 5697 }, 5698 S.getBeginLoc()); 5699 } 5700 } 5701 5702 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) { 5703 auto LPCRegion = 5704 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5705 EmitOMPTaskLoopBasedDirective(S); 5706 } 5707 5708 void CodeGenFunction::EmitOMPTaskLoopSimdDirective( 5709 const OMPTaskLoopSimdDirective &S) { 5710 auto LPCRegion = 5711 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5712 OMPLexicalScope Scope(*this, S); 5713 EmitOMPTaskLoopBasedDirective(S); 5714 } 5715 5716 void CodeGenFunction::EmitOMPMasterTaskLoopDirective( 5717 const OMPMasterTaskLoopDirective &S) { 5718 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5719 Action.Enter(CGF); 5720 EmitOMPTaskLoopBasedDirective(S); 5721 }; 5722 auto LPCRegion = 5723 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5724 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false); 5725 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 5726 } 5727 5728 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective( 5729 const OMPMasterTaskLoopSimdDirective &S) { 5730 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5731 Action.Enter(CGF); 5732 EmitOMPTaskLoopBasedDirective(S); 5733 }; 5734 auto LPCRegion = 5735 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5736 OMPLexicalScope Scope(*this, S); 5737 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 5738 } 5739 5740 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective( 5741 const OMPParallelMasterTaskLoopDirective &S) { 5742 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5743 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 5744 PrePostActionTy &Action) { 5745 Action.Enter(CGF); 5746 CGF.EmitOMPTaskLoopBasedDirective(S); 5747 }; 5748 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 5749 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 5750 S.getBeginLoc()); 5751 }; 5752 auto LPCRegion = 5753 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5754 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen, 5755 emitEmptyBoundParameters); 5756 } 5757 5758 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective( 5759 const OMPParallelMasterTaskLoopSimdDirective &S) { 5760 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5761 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 5762 PrePostActionTy &Action) { 5763 Action.Enter(CGF); 5764 CGF.EmitOMPTaskLoopBasedDirective(S); 5765 }; 5766 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 5767 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 5768 S.getBeginLoc()); 5769 }; 5770 auto LPCRegion = 5771 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5772 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen, 5773 emitEmptyBoundParameters); 5774 } 5775 5776 // Generate the instructions for '#pragma omp target update' directive. 5777 void CodeGenFunction::EmitOMPTargetUpdateDirective( 5778 const OMPTargetUpdateDirective &S) { 5779 // If we don't have target devices, don't bother emitting the data mapping 5780 // code. 5781 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5782 return; 5783 5784 // Check if we have any if clause associated with the directive. 5785 const Expr *IfCond = nullptr; 5786 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5787 IfCond = C->getCondition(); 5788 5789 // Check if we have any device clause associated with the directive. 5790 const Expr *Device = nullptr; 5791 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5792 Device = C->getDevice(); 5793 5794 OMPLexicalScope Scope(*this, S, OMPD_task); 5795 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5796 } 5797 5798 void CodeGenFunction::EmitSimpleOMPExecutableDirective( 5799 const OMPExecutableDirective &D) { 5800 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt()) 5801 return; 5802 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) { 5803 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 5804 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action); 5805 } else { 5806 OMPPrivateScope LoopGlobals(CGF); 5807 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) { 5808 for (const Expr *E : LD->counters()) { 5809 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 5810 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) { 5811 LValue GlobLVal = CGF.EmitLValue(E); 5812 LoopGlobals.addPrivate( 5813 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); }); 5814 } 5815 if (isa<OMPCapturedExprDecl>(VD)) { 5816 // Emit only those that were not explicitly referenced in clauses. 5817 if (!CGF.LocalDeclMap.count(VD)) 5818 CGF.EmitVarDecl(*VD); 5819 } 5820 } 5821 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) { 5822 if (!C->getNumForLoops()) 5823 continue; 5824 for (unsigned I = LD->getCollapsedNumber(), 5825 E = C->getLoopNumIterations().size(); 5826 I < E; ++I) { 5827 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>( 5828 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) { 5829 // Emit only those that were not explicitly referenced in clauses. 5830 if (!CGF.LocalDeclMap.count(VD)) 5831 CGF.EmitVarDecl(*VD); 5832 } 5833 } 5834 } 5835 } 5836 LoopGlobals.Privatize(); 5837 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt()); 5838 } 5839 }; 5840 { 5841 auto LPCRegion = 5842 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D); 5843 OMPSimdLexicalScope Scope(*this, D); 5844 CGM.getOpenMPRuntime().emitInlinedDirective( 5845 *this, 5846 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd 5847 : D.getDirectiveKind(), 5848 CodeGen); 5849 } 5850 // Check for outer lastprivate conditional update. 5851 checkForLastprivateConditionalUpdate(*this, D); 5852 } 5853