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