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