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