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