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