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