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