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