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 final : 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(CodeGenFunction &CGF, const OMPExecutableDirective &S, 57 bool AsInlined = false) 58 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 59 InlinedShareds(CGF) { 60 emitPreInitStmt(CGF, S); 61 if (AsInlined) { 62 if (S.hasAssociatedStmt()) { 63 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt()); 64 for (auto &C : CS->captures()) { 65 if (C.capturesVariable() || C.capturesVariableByCopy()) { 66 auto *VD = C.getCapturedVar(); 67 DeclRefExpr DRE(const_cast<VarDecl *>(VD), 68 isCapturedVar(CGF, VD) || 69 (CGF.CapturedStmtInfo && 70 InlinedShareds.isGlobalVarCaptured(VD)), 71 VD->getType().getNonReferenceType(), VK_LValue, 72 SourceLocation()); 73 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address { 74 return CGF.EmitLValue(&DRE).getAddress(); 75 }); 76 } 77 } 78 (void)InlinedShareds.Privatize(); 79 } 80 } 81 } 82 }; 83 84 /// Private scope for OpenMP loop-based directives, that supports capturing 85 /// of used expression from loop statement. 86 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope { 87 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) { 88 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) { 89 if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) { 90 for (const auto *I : PreInits->decls()) 91 CGF.EmitVarDecl(cast<VarDecl>(*I)); 92 } 93 } 94 } 95 96 public: 97 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S) 98 : CodeGenFunction::RunCleanupsScope(CGF) { 99 emitPreInitStmt(CGF, S); 100 } 101 }; 102 103 } // namespace 104 105 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) { 106 auto &C = getContext(); 107 llvm::Value *Size = nullptr; 108 auto SizeInChars = C.getTypeSizeInChars(Ty); 109 if (SizeInChars.isZero()) { 110 // getTypeSizeInChars() returns 0 for a VLA. 111 while (auto *VAT = C.getAsVariableArrayType(Ty)) { 112 llvm::Value *ArraySize; 113 std::tie(ArraySize, Ty) = getVLASize(VAT); 114 Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize; 115 } 116 SizeInChars = C.getTypeSizeInChars(Ty); 117 if (SizeInChars.isZero()) 118 return llvm::ConstantInt::get(SizeTy, /*V=*/0); 119 Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars)); 120 } else 121 Size = CGM.getSize(SizeInChars); 122 return Size; 123 } 124 125 void CodeGenFunction::GenerateOpenMPCapturedVars( 126 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) { 127 const RecordDecl *RD = S.getCapturedRecordDecl(); 128 auto CurField = RD->field_begin(); 129 auto CurCap = S.captures().begin(); 130 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), 131 E = S.capture_init_end(); 132 I != E; ++I, ++CurField, ++CurCap) { 133 if (CurField->hasCapturedVLAType()) { 134 auto VAT = CurField->getCapturedVLAType(); 135 auto *Val = VLASizeMap[VAT->getSizeExpr()]; 136 CapturedVars.push_back(Val); 137 } else if (CurCap->capturesThis()) 138 CapturedVars.push_back(CXXThisValue); 139 else if (CurCap->capturesVariableByCopy()) { 140 llvm::Value *CV = 141 EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal(); 142 143 // If the field is not a pointer, we need to save the actual value 144 // and load it as a void pointer. 145 if (!CurField->getType()->isAnyPointerType()) { 146 auto &Ctx = getContext(); 147 auto DstAddr = CreateMemTemp( 148 Ctx.getUIntPtrType(), 149 Twine(CurCap->getCapturedVar()->getName()) + ".casted"); 150 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType()); 151 152 auto *SrcAddrVal = EmitScalarConversion( 153 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()), 154 Ctx.getPointerType(CurField->getType()), SourceLocation()); 155 LValue SrcLV = 156 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType()); 157 158 // Store the value using the source type pointer. 159 EmitStoreThroughLValue(RValue::get(CV), SrcLV); 160 161 // Load the value using the destination type pointer. 162 CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal(); 163 } 164 CapturedVars.push_back(CV); 165 } else { 166 assert(CurCap->capturesVariable() && "Expected capture by reference."); 167 CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer()); 168 } 169 } 170 } 171 172 static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType, 173 StringRef Name, LValue AddrLV, 174 bool isReferenceType = false) { 175 ASTContext &Ctx = CGF.getContext(); 176 177 auto *CastedPtr = CGF.EmitScalarConversion( 178 AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(), 179 Ctx.getPointerType(DstType), SourceLocation()); 180 auto TmpAddr = 181 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType)) 182 .getAddress(); 183 184 // If we are dealing with references we need to return the address of the 185 // reference instead of the reference of the value. 186 if (isReferenceType) { 187 QualType RefType = Ctx.getLValueReferenceType(DstType); 188 auto *RefVal = TmpAddr.getPointer(); 189 TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref"); 190 auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType); 191 CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true); 192 } 193 194 return TmpAddr; 195 } 196 197 llvm::Function * 198 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) { 199 assert( 200 CapturedStmtInfo && 201 "CapturedStmtInfo should be set when generating the captured function"); 202 const CapturedDecl *CD = S.getCapturedDecl(); 203 const RecordDecl *RD = S.getCapturedRecordDecl(); 204 assert(CD->hasBody() && "missing CapturedDecl body"); 205 206 // Build the argument list. 207 ASTContext &Ctx = CGM.getContext(); 208 FunctionArgList Args; 209 Args.append(CD->param_begin(), 210 std::next(CD->param_begin(), CD->getContextParamPosition())); 211 auto I = S.captures().begin(); 212 for (auto *FD : RD->fields()) { 213 QualType ArgType = FD->getType(); 214 IdentifierInfo *II = nullptr; 215 VarDecl *CapVar = nullptr; 216 217 // If this is a capture by copy and the type is not a pointer, the outlined 218 // function argument type should be uintptr and the value properly casted to 219 // uintptr. This is necessary given that the runtime library is only able to 220 // deal with pointers. We can pass in the same way the VLA type sizes to the 221 // outlined function. 222 if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) || 223 I->capturesVariableArrayType()) 224 ArgType = Ctx.getUIntPtrType(); 225 226 if (I->capturesVariable() || I->capturesVariableByCopy()) { 227 CapVar = I->getCapturedVar(); 228 II = CapVar->getIdentifier(); 229 } else if (I->capturesThis()) 230 II = &getContext().Idents.get("this"); 231 else { 232 assert(I->capturesVariableArrayType()); 233 II = &getContext().Idents.get("vla"); 234 } 235 if (ArgType->isVariablyModifiedType()) { 236 bool IsReference = ArgType->isLValueReferenceType(); 237 ArgType = 238 getContext().getCanonicalParamType(ArgType.getNonReferenceType()); 239 if (IsReference && !ArgType->isPointerType()) { 240 ArgType = getContext().getLValueReferenceType( 241 ArgType, /*SpelledAsLValue=*/false); 242 } 243 } 244 Args.push_back(ImplicitParamDecl::Create(getContext(), nullptr, 245 FD->getLocation(), II, ArgType)); 246 ++I; 247 } 248 Args.append( 249 std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 250 CD->param_end()); 251 252 // Create the function declaration. 253 FunctionType::ExtInfo ExtInfo; 254 const CGFunctionInfo &FuncInfo = 255 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args); 256 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 257 258 llvm::Function *F = llvm::Function::Create( 259 FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 260 CapturedStmtInfo->getHelperName(), &CGM.getModule()); 261 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 262 if (CD->isNothrow()) 263 F->addFnAttr(llvm::Attribute::NoUnwind); 264 265 // Generate the function. 266 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(), 267 CD->getBody()->getLocStart()); 268 unsigned Cnt = CD->getContextParamPosition(); 269 I = S.captures().begin(); 270 for (auto *FD : RD->fields()) { 271 // If we are capturing a pointer by copy we don't need to do anything, just 272 // use the value that we get from the arguments. 273 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) { 274 const VarDecl *CurVD = I->getCapturedVar(); 275 Address LocalAddr = GetAddrOfLocalVar(Args[Cnt]); 276 // If the variable is a reference we need to materialize it here. 277 if (CurVD->getType()->isReferenceType()) { 278 Address RefAddr = CreateMemTemp(CurVD->getType(), getPointerAlign(), 279 ".materialized_ref"); 280 EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, /*Volatile=*/false, 281 CurVD->getType()); 282 LocalAddr = RefAddr; 283 } 284 setAddrOfLocalVar(CurVD, LocalAddr); 285 ++Cnt; 286 ++I; 287 continue; 288 } 289 290 LValue ArgLVal = 291 MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(), 292 AlignmentSource::Decl); 293 if (FD->hasCapturedVLAType()) { 294 LValue CastedArgLVal = 295 MakeAddrLValue(castValueFromUintptr(*this, FD->getType(), 296 Args[Cnt]->getName(), ArgLVal), 297 FD->getType(), AlignmentSource::Decl); 298 auto *ExprArg = 299 EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal(); 300 auto VAT = FD->getCapturedVLAType(); 301 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 302 } else if (I->capturesVariable()) { 303 auto *Var = I->getCapturedVar(); 304 QualType VarTy = Var->getType(); 305 Address ArgAddr = ArgLVal.getAddress(); 306 if (!VarTy->isReferenceType()) { 307 if (ArgLVal.getType()->isLValueReferenceType()) { 308 ArgAddr = EmitLoadOfReference( 309 ArgAddr, ArgLVal.getType()->castAs<ReferenceType>()); 310 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) { 311 assert(ArgLVal.getType()->isPointerType()); 312 ArgAddr = EmitLoadOfPointer( 313 ArgAddr, ArgLVal.getType()->castAs<PointerType>()); 314 } 315 } 316 setAddrOfLocalVar( 317 Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var))); 318 } else if (I->capturesVariableByCopy()) { 319 assert(!FD->getType()->isAnyPointerType() && 320 "Not expecting a captured pointer."); 321 auto *Var = I->getCapturedVar(); 322 QualType VarTy = Var->getType(); 323 setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(), 324 Args[Cnt]->getName(), ArgLVal, 325 VarTy->isReferenceType())); 326 } else { 327 // If 'this' is captured, load it into CXXThisValue. 328 assert(I->capturesThis()); 329 CXXThisValue = 330 EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal(); 331 } 332 ++Cnt; 333 ++I; 334 } 335 336 PGO.assignRegionCounters(GlobalDecl(CD), F); 337 CapturedStmtInfo->EmitBody(*this, CD->getBody()); 338 FinishFunction(CD->getBodyRBrace()); 339 340 return F; 341 } 342 343 //===----------------------------------------------------------------------===// 344 // OpenMP Directive Emission 345 //===----------------------------------------------------------------------===// 346 void CodeGenFunction::EmitOMPAggregateAssign( 347 Address DestAddr, Address SrcAddr, QualType OriginalType, 348 const llvm::function_ref<void(Address, Address)> &CopyGen) { 349 // Perform element-by-element initialization. 350 QualType ElementTy; 351 352 // Drill down to the base element type on both arrays. 353 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe(); 354 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr); 355 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); 356 357 auto SrcBegin = SrcAddr.getPointer(); 358 auto DestBegin = DestAddr.getPointer(); 359 // Cast from pointer to array type to pointer to single element. 360 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements); 361 // The basic structure here is a while-do loop. 362 auto BodyBB = createBasicBlock("omp.arraycpy.body"); 363 auto DoneBB = createBasicBlock("omp.arraycpy.done"); 364 auto IsEmpty = 365 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty"); 366 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 367 368 // Enter the loop body, making that address the current address. 369 auto EntryBB = Builder.GetInsertBlock(); 370 EmitBlock(BodyBB); 371 372 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy); 373 374 llvm::PHINode *SrcElementPHI = 375 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 376 SrcElementPHI->addIncoming(SrcBegin, EntryBB); 377 Address SrcElementCurrent = 378 Address(SrcElementPHI, 379 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 380 381 llvm::PHINode *DestElementPHI = 382 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); 383 DestElementPHI->addIncoming(DestBegin, EntryBB); 384 Address DestElementCurrent = 385 Address(DestElementPHI, 386 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 387 388 // Emit copy. 389 CopyGen(DestElementCurrent, SrcElementCurrent); 390 391 // Shift the address forward by one element. 392 auto DestElementNext = Builder.CreateConstGEP1_32( 393 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 394 auto SrcElementNext = Builder.CreateConstGEP1_32( 395 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element"); 396 // Check whether we've reached the end. 397 auto Done = 398 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 399 Builder.CreateCondBr(Done, DoneBB, BodyBB); 400 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock()); 401 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock()); 402 403 // Done. 404 EmitBlock(DoneBB, /*IsFinished=*/true); 405 } 406 407 /// Check if the combiner is a call to UDR combiner and if it is so return the 408 /// UDR decl used for reduction. 409 static const OMPDeclareReductionDecl * 410 getReductionInit(const Expr *ReductionOp) { 411 if (auto *CE = dyn_cast<CallExpr>(ReductionOp)) 412 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) 413 if (auto *DRE = 414 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) 415 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) 416 return DRD; 417 return nullptr; 418 } 419 420 static void emitInitWithReductionInitializer(CodeGenFunction &CGF, 421 const OMPDeclareReductionDecl *DRD, 422 const Expr *InitOp, 423 Address Private, Address Original, 424 QualType Ty) { 425 if (DRD->getInitializer()) { 426 std::pair<llvm::Function *, llvm::Function *> Reduction = 427 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); 428 auto *CE = cast<CallExpr>(InitOp); 429 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee()); 430 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 431 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 432 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr()); 433 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr()); 434 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 435 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()), 436 [=]() -> Address { return Private; }); 437 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()), 438 [=]() -> Address { return Original; }); 439 (void)PrivateScope.Privatize(); 440 RValue Func = RValue::get(Reduction.second); 441 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); 442 CGF.EmitIgnoredExpr(InitOp); 443 } else { 444 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty); 445 auto *GV = new llvm::GlobalVariable( 446 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true, 447 llvm::GlobalValue::PrivateLinkage, Init, ".init"); 448 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty); 449 RValue InitRVal; 450 switch (CGF.getEvaluationKind(Ty)) { 451 case TEK_Scalar: 452 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation()); 453 break; 454 case TEK_Complex: 455 InitRVal = 456 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation())); 457 break; 458 case TEK_Aggregate: 459 InitRVal = RValue::getAggregate(LV.getAddress()); 460 break; 461 } 462 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue); 463 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal); 464 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(), 465 /*IsInitializer=*/false); 466 } 467 } 468 469 /// \brief Emit initialization of arrays of complex types. 470 /// \param DestAddr Address of the array. 471 /// \param Type Type of array. 472 /// \param Init Initial expression of array. 473 /// \param SrcAddr Address of the original array. 474 static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr, 475 QualType Type, const Expr *Init, 476 Address SrcAddr = Address::invalid()) { 477 auto *DRD = getReductionInit(Init); 478 // Perform element-by-element initialization. 479 QualType ElementTy; 480 481 // Drill down to the base element type on both arrays. 482 auto ArrayTy = Type->getAsArrayTypeUnsafe(); 483 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr); 484 DestAddr = 485 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType()); 486 if (DRD) 487 SrcAddr = 488 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); 489 490 llvm::Value *SrcBegin = nullptr; 491 if (DRD) 492 SrcBegin = SrcAddr.getPointer(); 493 auto DestBegin = DestAddr.getPointer(); 494 // Cast from pointer to array type to pointer to single element. 495 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements); 496 // The basic structure here is a while-do loop. 497 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body"); 498 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done"); 499 auto IsEmpty = 500 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty"); 501 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 502 503 // Enter the loop body, making that address the current address. 504 auto EntryBB = CGF.Builder.GetInsertBlock(); 505 CGF.EmitBlock(BodyBB); 506 507 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); 508 509 llvm::PHINode *SrcElementPHI = nullptr; 510 Address SrcElementCurrent = Address::invalid(); 511 if (DRD) { 512 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2, 513 "omp.arraycpy.srcElementPast"); 514 SrcElementPHI->addIncoming(SrcBegin, EntryBB); 515 SrcElementCurrent = 516 Address(SrcElementPHI, 517 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 518 } 519 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI( 520 DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); 521 DestElementPHI->addIncoming(DestBegin, EntryBB); 522 Address DestElementCurrent = 523 Address(DestElementPHI, 524 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 525 526 // Emit copy. 527 { 528 CodeGenFunction::RunCleanupsScope InitScope(CGF); 529 if (DRD && (DRD->getInitializer() || !Init)) { 530 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent, 531 SrcElementCurrent, ElementTy); 532 } else 533 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(), 534 /*IsInitializer=*/false); 535 } 536 537 if (DRD) { 538 // Shift the address forward by one element. 539 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32( 540 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 541 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock()); 542 } 543 544 // Shift the address forward by one element. 545 auto DestElementNext = CGF.Builder.CreateConstGEP1_32( 546 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 547 // Check whether we've reached the end. 548 auto Done = 549 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 550 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); 551 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock()); 552 553 // Done. 554 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 555 } 556 557 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr, 558 Address SrcAddr, const VarDecl *DestVD, 559 const VarDecl *SrcVD, const Expr *Copy) { 560 if (OriginalType->isArrayType()) { 561 auto *BO = dyn_cast<BinaryOperator>(Copy); 562 if (BO && BO->getOpcode() == BO_Assign) { 563 // Perform simple memcpy for simple copying. 564 EmitAggregateAssign(DestAddr, SrcAddr, OriginalType); 565 } else { 566 // For arrays with complex element types perform element by element 567 // copying. 568 EmitOMPAggregateAssign( 569 DestAddr, SrcAddr, OriginalType, 570 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) { 571 // Working with the single array element, so have to remap 572 // destination and source variables to corresponding array 573 // elements. 574 CodeGenFunction::OMPPrivateScope Remap(*this); 575 Remap.addPrivate(DestVD, [DestElement]() -> Address { 576 return DestElement; 577 }); 578 Remap.addPrivate( 579 SrcVD, [SrcElement]() -> Address { return SrcElement; }); 580 (void)Remap.Privatize(); 581 EmitIgnoredExpr(Copy); 582 }); 583 } 584 } else { 585 // Remap pseudo source variable to private copy. 586 CodeGenFunction::OMPPrivateScope Remap(*this); 587 Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; }); 588 Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; }); 589 (void)Remap.Privatize(); 590 // Emit copying of the whole variable. 591 EmitIgnoredExpr(Copy); 592 } 593 } 594 595 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 596 OMPPrivateScope &PrivateScope) { 597 if (!HaveInsertPoint()) 598 return false; 599 bool FirstprivateIsLastprivate = false; 600 llvm::DenseSet<const VarDecl *> Lastprivates; 601 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 602 for (const auto *D : C->varlists()) 603 Lastprivates.insert( 604 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl()); 605 } 606 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate; 607 CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt())); 608 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 609 auto IRef = C->varlist_begin(); 610 auto InitsRef = C->inits().begin(); 611 for (auto IInit : C->private_copies()) { 612 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 613 bool ThisFirstprivateIsLastprivate = 614 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0; 615 auto *CapFD = CapturesInfo.lookup(OrigVD); 616 auto *FD = CapturedStmtInfo->lookup(OrigVD); 617 if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) && 618 !FD->getType()->isReferenceType()) { 619 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()); 620 ++IRef; 621 ++InitsRef; 622 continue; 623 } 624 FirstprivateIsLastprivate = 625 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate; 626 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) { 627 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 628 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl()); 629 bool IsRegistered; 630 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 631 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr, 632 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 633 Address OriginalAddr = EmitLValue(&DRE).getAddress(); 634 QualType Type = VD->getType(); 635 if (Type->isArrayType()) { 636 // Emit VarDecl with copy init for arrays. 637 // Get the address of the original variable captured in current 638 // captured region. 639 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address { 640 auto Emission = EmitAutoVarAlloca(*VD); 641 auto *Init = VD->getInit(); 642 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) { 643 // Perform simple memcpy. 644 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr, 645 Type); 646 } else { 647 EmitOMPAggregateAssign( 648 Emission.getAllocatedAddress(), OriginalAddr, Type, 649 [this, VDInit, Init](Address DestElement, 650 Address SrcElement) { 651 // Clean up any temporaries needed by the initialization. 652 RunCleanupsScope InitScope(*this); 653 // Emit initialization for single element. 654 setAddrOfLocalVar(VDInit, SrcElement); 655 EmitAnyExprToMem(Init, DestElement, 656 Init->getType().getQualifiers(), 657 /*IsInitializer*/ false); 658 LocalDeclMap.erase(VDInit); 659 }); 660 } 661 EmitAutoVarCleanups(Emission); 662 return Emission.getAllocatedAddress(); 663 }); 664 } else { 665 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address { 666 // Emit private VarDecl with copy init. 667 // Remap temp VDInit variable to the address of the original 668 // variable 669 // (for proper handling of captured global variables). 670 setAddrOfLocalVar(VDInit, OriginalAddr); 671 EmitDecl(*VD); 672 LocalDeclMap.erase(VDInit); 673 return GetAddrOfLocalVar(VD); 674 }); 675 } 676 assert(IsRegistered && 677 "firstprivate var already registered as private"); 678 // Silence the warning about unused variable. 679 (void)IsRegistered; 680 } 681 ++IRef; 682 ++InitsRef; 683 } 684 } 685 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty(); 686 } 687 688 void CodeGenFunction::EmitOMPPrivateClause( 689 const OMPExecutableDirective &D, 690 CodeGenFunction::OMPPrivateScope &PrivateScope) { 691 if (!HaveInsertPoint()) 692 return; 693 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 694 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) { 695 auto IRef = C->varlist_begin(); 696 for (auto IInit : C->private_copies()) { 697 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 698 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 699 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 700 bool IsRegistered = 701 PrivateScope.addPrivate(OrigVD, [&]() -> Address { 702 // Emit private VarDecl with copy init. 703 EmitDecl(*VD); 704 return GetAddrOfLocalVar(VD); 705 }); 706 assert(IsRegistered && "private var already registered as private"); 707 // Silence the warning about unused variable. 708 (void)IsRegistered; 709 } 710 ++IRef; 711 } 712 } 713 } 714 715 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) { 716 if (!HaveInsertPoint()) 717 return false; 718 // threadprivate_var1 = master_threadprivate_var1; 719 // operator=(threadprivate_var2, master_threadprivate_var2); 720 // ... 721 // __kmpc_barrier(&loc, global_tid); 722 llvm::DenseSet<const VarDecl *> CopiedVars; 723 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr; 724 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) { 725 auto IRef = C->varlist_begin(); 726 auto ISrcRef = C->source_exprs().begin(); 727 auto IDestRef = C->destination_exprs().begin(); 728 for (auto *AssignOp : C->assignment_ops()) { 729 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 730 QualType Type = VD->getType(); 731 if (CopiedVars.insert(VD->getCanonicalDecl()).second) { 732 // Get the address of the master variable. If we are emitting code with 733 // TLS support, the address is passed from the master as field in the 734 // captured declaration. 735 Address MasterAddr = Address::invalid(); 736 if (getLangOpts().OpenMPUseTLS && 737 getContext().getTargetInfo().isTLSSupported()) { 738 assert(CapturedStmtInfo->lookup(VD) && 739 "Copyin threadprivates should have been captured!"); 740 DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(), 741 VK_LValue, (*IRef)->getExprLoc()); 742 MasterAddr = EmitLValue(&DRE).getAddress(); 743 LocalDeclMap.erase(VD); 744 } else { 745 MasterAddr = 746 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD) 747 : CGM.GetAddrOfGlobal(VD), 748 getContext().getDeclAlign(VD)); 749 } 750 // Get the address of the threadprivate variable. 751 Address PrivateAddr = EmitLValue(*IRef).getAddress(); 752 if (CopiedVars.size() == 1) { 753 // At first check if current thread is a master thread. If it is, no 754 // need to copy data. 755 CopyBegin = createBasicBlock("copyin.not.master"); 756 CopyEnd = createBasicBlock("copyin.not.master.end"); 757 Builder.CreateCondBr( 758 Builder.CreateICmpNE( 759 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy), 760 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)), 761 CopyBegin, CopyEnd); 762 EmitBlock(CopyBegin); 763 } 764 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 765 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 766 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp); 767 } 768 ++IRef; 769 ++ISrcRef; 770 ++IDestRef; 771 } 772 } 773 if (CopyEnd) { 774 // Exit out of copying procedure for non-master thread. 775 EmitBlock(CopyEnd, /*IsFinished=*/true); 776 return true; 777 } 778 return false; 779 } 780 781 bool CodeGenFunction::EmitOMPLastprivateClauseInit( 782 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) { 783 if (!HaveInsertPoint()) 784 return false; 785 bool HasAtLeastOneLastprivate = false; 786 llvm::DenseSet<const VarDecl *> SIMDLCVs; 787 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 788 auto *LoopDirective = cast<OMPLoopDirective>(&D); 789 for (auto *C : LoopDirective->counters()) { 790 SIMDLCVs.insert( 791 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 792 } 793 } 794 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 795 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 796 HasAtLeastOneLastprivate = true; 797 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) 798 break; 799 auto IRef = C->varlist_begin(); 800 auto IDestRef = C->destination_exprs().begin(); 801 for (auto *IInit : C->private_copies()) { 802 // Keep the address of the original variable for future update at the end 803 // of the loop. 804 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 805 // Taskloops do not require additional initialization, it is done in 806 // runtime support library. 807 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) { 808 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 809 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address { 810 DeclRefExpr DRE( 811 const_cast<VarDecl *>(OrigVD), 812 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup( 813 OrigVD) != nullptr, 814 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 815 return EmitLValue(&DRE).getAddress(); 816 }); 817 // Check if the variable is also a firstprivate: in this case IInit is 818 // not generated. Initialization of this variable will happen in codegen 819 // for 'firstprivate' clause. 820 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) { 821 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 822 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address { 823 // Emit private VarDecl with copy init. 824 EmitDecl(*VD); 825 return GetAddrOfLocalVar(VD); 826 }); 827 assert(IsRegistered && 828 "lastprivate var already registered as private"); 829 (void)IsRegistered; 830 } 831 } 832 ++IRef; 833 ++IDestRef; 834 } 835 } 836 return HasAtLeastOneLastprivate; 837 } 838 839 void CodeGenFunction::EmitOMPLastprivateClauseFinal( 840 const OMPExecutableDirective &D, bool NoFinals, 841 llvm::Value *IsLastIterCond) { 842 if (!HaveInsertPoint()) 843 return; 844 // Emit following code: 845 // if (<IsLastIterCond>) { 846 // orig_var1 = private_orig_var1; 847 // ... 848 // orig_varn = private_orig_varn; 849 // } 850 llvm::BasicBlock *ThenBB = nullptr; 851 llvm::BasicBlock *DoneBB = nullptr; 852 if (IsLastIterCond) { 853 ThenBB = createBasicBlock(".omp.lastprivate.then"); 854 DoneBB = createBasicBlock(".omp.lastprivate.done"); 855 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB); 856 EmitBlock(ThenBB); 857 } 858 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 859 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates; 860 if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) { 861 auto IC = LoopDirective->counters().begin(); 862 for (auto F : LoopDirective->finals()) { 863 auto *D = 864 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl(); 865 if (NoFinals) 866 AlreadyEmittedVars.insert(D); 867 else 868 LoopCountersAndUpdates[D] = F; 869 ++IC; 870 } 871 } 872 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 873 auto IRef = C->varlist_begin(); 874 auto ISrcRef = C->source_exprs().begin(); 875 auto IDestRef = C->destination_exprs().begin(); 876 for (auto *AssignOp : C->assignment_ops()) { 877 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 878 QualType Type = PrivateVD->getType(); 879 auto *CanonicalVD = PrivateVD->getCanonicalDecl(); 880 if (AlreadyEmittedVars.insert(CanonicalVD).second) { 881 // If lastprivate variable is a loop control variable for loop-based 882 // directive, update its value before copyin back to original 883 // variable. 884 if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) 885 EmitIgnoredExpr(FinalExpr); 886 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 887 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 888 // Get the address of the original variable. 889 Address OriginalAddr = GetAddrOfLocalVar(DestVD); 890 // Get the address of the private variable. 891 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD); 892 if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>()) 893 PrivateAddr = 894 Address(Builder.CreateLoad(PrivateAddr), 895 getNaturalTypeAlignment(RefTy->getPointeeType())); 896 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp); 897 } 898 ++IRef; 899 ++ISrcRef; 900 ++IDestRef; 901 } 902 if (auto *PostUpdate = C->getPostUpdateExpr()) 903 EmitIgnoredExpr(PostUpdate); 904 } 905 if (IsLastIterCond) 906 EmitBlock(DoneBB, /*IsFinished=*/true); 907 } 908 909 static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, 910 LValue BaseLV, llvm::Value *Addr) { 911 Address Tmp = Address::invalid(); 912 Address TopTmp = Address::invalid(); 913 Address MostTopTmp = Address::invalid(); 914 BaseTy = BaseTy.getNonReferenceType(); 915 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && 916 !CGF.getContext().hasSameType(BaseTy, ElTy)) { 917 Tmp = CGF.CreateMemTemp(BaseTy); 918 if (TopTmp.isValid()) 919 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp); 920 else 921 MostTopTmp = Tmp; 922 TopTmp = Tmp; 923 BaseTy = BaseTy->getPointeeType(); 924 } 925 llvm::Type *Ty = BaseLV.getPointer()->getType(); 926 if (Tmp.isValid()) 927 Ty = Tmp.getElementType(); 928 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty); 929 if (Tmp.isValid()) { 930 CGF.Builder.CreateStore(Addr, Tmp); 931 return MostTopTmp; 932 } 933 return Address(Addr, BaseLV.getAlignment()); 934 } 935 936 static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, 937 LValue BaseLV) { 938 BaseTy = BaseTy.getNonReferenceType(); 939 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && 940 !CGF.getContext().hasSameType(BaseTy, ElTy)) { 941 if (auto *PtrTy = BaseTy->getAs<PointerType>()) 942 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy); 943 else { 944 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(), 945 BaseTy->castAs<ReferenceType>()); 946 } 947 BaseTy = BaseTy->getPointeeType(); 948 } 949 return CGF.MakeAddrLValue( 950 Address( 951 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 952 BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()), 953 BaseLV.getAlignment()), 954 BaseLV.getType(), BaseLV.getAlignmentSource()); 955 } 956 957 void CodeGenFunction::EmitOMPReductionClauseInit( 958 const OMPExecutableDirective &D, 959 CodeGenFunction::OMPPrivateScope &PrivateScope) { 960 if (!HaveInsertPoint()) 961 return; 962 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 963 auto ILHS = C->lhs_exprs().begin(); 964 auto IRHS = C->rhs_exprs().begin(); 965 auto IPriv = C->privates().begin(); 966 auto IRed = C->reduction_ops().begin(); 967 for (auto IRef : C->varlists()) { 968 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 969 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 970 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl()); 971 auto *DRD = getReductionInit(*IRed); 972 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) { 973 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 974 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 975 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 976 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 977 Base = TempASE->getBase()->IgnoreParenImpCasts(); 978 auto *DE = cast<DeclRefExpr>(Base); 979 auto *OrigVD = cast<VarDecl>(DE->getDecl()); 980 auto OASELValueLB = EmitOMPArraySectionExpr(OASE); 981 auto OASELValueUB = 982 EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false); 983 auto OriginalBaseLValue = EmitLValue(DE); 984 LValue BaseLValue = 985 loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(), 986 OriginalBaseLValue); 987 // Store the address of the original variable associated with the LHS 988 // implicit variable. 989 PrivateScope.addPrivate(LHSVD, [this, OASELValueLB]() -> Address { 990 return OASELValueLB.getAddress(); 991 }); 992 // Emit reduction copy. 993 bool IsRegistered = PrivateScope.addPrivate( 994 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB, 995 OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address { 996 // Emit VarDecl with copy init for arrays. 997 // Get the address of the original variable captured in current 998 // captured region. 999 auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(), 1000 OASELValueLB.getPointer()); 1001 Size = Builder.CreateNUWAdd( 1002 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1)); 1003 CodeGenFunction::OpaqueValueMapping OpaqueMap( 1004 *this, cast<OpaqueValueExpr>( 1005 getContext() 1006 .getAsVariableArrayType(PrivateVD->getType()) 1007 ->getSizeExpr()), 1008 RValue::get(Size)); 1009 EmitVariablyModifiedType(PrivateVD->getType()); 1010 auto Emission = EmitAutoVarAlloca(*PrivateVD); 1011 auto Addr = Emission.getAllocatedAddress(); 1012 auto *Init = PrivateVD->getInit(); 1013 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), 1014 DRD ? *IRed : Init, 1015 OASELValueLB.getAddress()); 1016 EmitAutoVarCleanups(Emission); 1017 // Emit private VarDecl with reduction init. 1018 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(), 1019 OASELValueLB.getPointer()); 1020 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset); 1021 return castToBase(*this, OrigVD->getType(), 1022 OASELValueLB.getType(), OriginalBaseLValue, 1023 Ptr); 1024 }); 1025 assert(IsRegistered && "private var already registered as private"); 1026 // Silence the warning about unused variable. 1027 (void)IsRegistered; 1028 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address { 1029 return GetAddrOfLocalVar(PrivateVD); 1030 }); 1031 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) { 1032 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 1033 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 1034 Base = TempASE->getBase()->IgnoreParenImpCasts(); 1035 auto *DE = cast<DeclRefExpr>(Base); 1036 auto *OrigVD = cast<VarDecl>(DE->getDecl()); 1037 auto ASELValue = EmitLValue(ASE); 1038 auto OriginalBaseLValue = EmitLValue(DE); 1039 LValue BaseLValue = loadToBegin( 1040 *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue); 1041 // Store the address of the original variable associated with the LHS 1042 // implicit variable. 1043 PrivateScope.addPrivate(LHSVD, [this, ASELValue]() -> Address { 1044 return ASELValue.getAddress(); 1045 }); 1046 // Emit reduction copy. 1047 bool IsRegistered = PrivateScope.addPrivate( 1048 OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue, 1049 OriginalBaseLValue, DRD, IRed]() -> Address { 1050 // Emit private VarDecl with reduction init. 1051 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD); 1052 auto Addr = Emission.getAllocatedAddress(); 1053 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) { 1054 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr, 1055 ASELValue.getAddress(), 1056 ASELValue.getType()); 1057 } else 1058 EmitAutoVarInit(Emission); 1059 EmitAutoVarCleanups(Emission); 1060 auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(), 1061 ASELValue.getPointer()); 1062 auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset); 1063 return castToBase(*this, OrigVD->getType(), ASELValue.getType(), 1064 OriginalBaseLValue, Ptr); 1065 }); 1066 assert(IsRegistered && "private var already registered as private"); 1067 // Silence the warning about unused variable. 1068 (void)IsRegistered; 1069 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address { 1070 return Builder.CreateElementBitCast( 1071 GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()), 1072 "rhs.begin"); 1073 }); 1074 } else { 1075 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 1076 QualType Type = PrivateVD->getType(); 1077 if (getContext().getAsArrayType(Type)) { 1078 // Store the address of the original variable associated with the LHS 1079 // implicit variable. 1080 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 1081 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1082 IRef->getType(), VK_LValue, IRef->getExprLoc()); 1083 Address OriginalAddr = EmitLValue(&DRE).getAddress(); 1084 PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr, 1085 LHSVD]() -> Address { 1086 OriginalAddr = Builder.CreateElementBitCast( 1087 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin"); 1088 return OriginalAddr; 1089 }); 1090 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address { 1091 if (Type->isVariablyModifiedType()) { 1092 CodeGenFunction::OpaqueValueMapping OpaqueMap( 1093 *this, cast<OpaqueValueExpr>( 1094 getContext() 1095 .getAsVariableArrayType(PrivateVD->getType()) 1096 ->getSizeExpr()), 1097 RValue::get( 1098 getTypeSize(OrigVD->getType().getNonReferenceType()))); 1099 EmitVariablyModifiedType(Type); 1100 } 1101 auto Emission = EmitAutoVarAlloca(*PrivateVD); 1102 auto Addr = Emission.getAllocatedAddress(); 1103 auto *Init = PrivateVD->getInit(); 1104 EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(), 1105 DRD ? *IRed : Init, OriginalAddr); 1106 EmitAutoVarCleanups(Emission); 1107 return Emission.getAllocatedAddress(); 1108 }); 1109 assert(IsRegistered && "private var already registered as private"); 1110 // Silence the warning about unused variable. 1111 (void)IsRegistered; 1112 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address { 1113 return Builder.CreateElementBitCast( 1114 GetAddrOfLocalVar(PrivateVD), 1115 ConvertTypeForMem(RHSVD->getType()), "rhs.begin"); 1116 }); 1117 } else { 1118 // Store the address of the original variable associated with the LHS 1119 // implicit variable. 1120 Address OriginalAddr = Address::invalid(); 1121 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef, 1122 &OriginalAddr]() -> Address { 1123 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 1124 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1125 IRef->getType(), VK_LValue, IRef->getExprLoc()); 1126 OriginalAddr = EmitLValue(&DRE).getAddress(); 1127 return OriginalAddr; 1128 }); 1129 // Emit reduction copy. 1130 bool IsRegistered = PrivateScope.addPrivate( 1131 OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address { 1132 // Emit private VarDecl with reduction init. 1133 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD); 1134 auto Addr = Emission.getAllocatedAddress(); 1135 if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) { 1136 emitInitWithReductionInitializer(*this, DRD, *IRed, Addr, 1137 OriginalAddr, 1138 PrivateVD->getType()); 1139 } else 1140 EmitAutoVarInit(Emission); 1141 EmitAutoVarCleanups(Emission); 1142 return Addr; 1143 }); 1144 assert(IsRegistered && "private var already registered as private"); 1145 // Silence the warning about unused variable. 1146 (void)IsRegistered; 1147 PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address { 1148 return GetAddrOfLocalVar(PrivateVD); 1149 }); 1150 } 1151 } 1152 ++ILHS; 1153 ++IRHS; 1154 ++IPriv; 1155 ++IRed; 1156 } 1157 } 1158 } 1159 1160 void CodeGenFunction::EmitOMPReductionClauseFinal( 1161 const OMPExecutableDirective &D) { 1162 if (!HaveInsertPoint()) 1163 return; 1164 llvm::SmallVector<const Expr *, 8> Privates; 1165 llvm::SmallVector<const Expr *, 8> LHSExprs; 1166 llvm::SmallVector<const Expr *, 8> RHSExprs; 1167 llvm::SmallVector<const Expr *, 8> ReductionOps; 1168 bool HasAtLeastOneReduction = false; 1169 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1170 HasAtLeastOneReduction = true; 1171 Privates.append(C->privates().begin(), C->privates().end()); 1172 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1173 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1174 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 1175 } 1176 if (HasAtLeastOneReduction) { 1177 // Emit nowait reduction if nowait clause is present or directive is a 1178 // parallel directive (it always has implicit barrier). 1179 CGM.getOpenMPRuntime().emitReduction( 1180 *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps, 1181 D.getSingleClause<OMPNowaitClause>() || 1182 isOpenMPParallelDirective(D.getDirectiveKind()) || 1183 D.getDirectiveKind() == OMPD_simd, 1184 D.getDirectiveKind() == OMPD_simd); 1185 } 1186 } 1187 1188 static void emitPostUpdateForReductionClause( 1189 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1190 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) { 1191 if (!CGF.HaveInsertPoint()) 1192 return; 1193 llvm::BasicBlock *DoneBB = nullptr; 1194 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1195 if (auto *PostUpdate = C->getPostUpdateExpr()) { 1196 if (!DoneBB) { 1197 if (auto *Cond = CondGen(CGF)) { 1198 // If the first post-update expression is found, emit conditional 1199 // block if it was requested. 1200 auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu"); 1201 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done"); 1202 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1203 CGF.EmitBlock(ThenBB); 1204 } 1205 } 1206 CGF.EmitIgnoredExpr(PostUpdate); 1207 } 1208 } 1209 if (DoneBB) 1210 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 1211 } 1212 1213 static void emitCommonOMPParallelDirective(CodeGenFunction &CGF, 1214 const OMPExecutableDirective &S, 1215 OpenMPDirectiveKind InnermostKind, 1216 const RegionCodeGenTy &CodeGen) { 1217 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 1218 auto OutlinedFn = CGF.CGM.getOpenMPRuntime(). 1219 emitParallelOrTeamsOutlinedFunction(S, 1220 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 1221 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) { 1222 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 1223 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 1224 /*IgnoreResultAssign*/ true); 1225 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause( 1226 CGF, NumThreads, NumThreadsClause->getLocStart()); 1227 } 1228 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) { 1229 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF); 1230 CGF.CGM.getOpenMPRuntime().emitProcBindClause( 1231 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart()); 1232 } 1233 const Expr *IfCond = nullptr; 1234 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 1235 if (C->getNameModifier() == OMPD_unknown || 1236 C->getNameModifier() == OMPD_parallel) { 1237 IfCond = C->getCondition(); 1238 break; 1239 } 1240 } 1241 1242 OMPLexicalScope Scope(CGF, S); 1243 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 1244 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 1245 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn, 1246 CapturedVars, IfCond); 1247 } 1248 1249 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) { 1250 // Emit parallel region as a standalone region. 1251 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1252 OMPPrivateScope PrivateScope(CGF); 1253 bool Copyins = CGF.EmitOMPCopyinClause(S); 1254 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 1255 if (Copyins) { 1256 // Emit implicit barrier to synchronize threads and avoid data races on 1257 // propagation master's thread values of threadprivate variables to local 1258 // instances of that variables of all other implicit threads. 1259 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 1260 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false, 1261 /*ForceSimpleCall=*/true); 1262 } 1263 CGF.EmitOMPPrivateClause(S, PrivateScope); 1264 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 1265 (void)PrivateScope.Privatize(); 1266 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1267 CGF.EmitOMPReductionClauseFinal(S); 1268 }; 1269 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen); 1270 emitPostUpdateForReductionClause( 1271 *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; }); 1272 } 1273 1274 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D, 1275 JumpDest LoopExit) { 1276 RunCleanupsScope BodyScope(*this); 1277 // Update counters values on current iteration. 1278 for (auto I : D.updates()) { 1279 EmitIgnoredExpr(I); 1280 } 1281 // Update the linear variables. 1282 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1283 for (auto *U : C->updates()) 1284 EmitIgnoredExpr(U); 1285 } 1286 1287 // On a continue in the body, jump to the end. 1288 auto Continue = getJumpDestInCurrentScope("omp.body.continue"); 1289 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1290 // Emit loop body. 1291 EmitStmt(D.getBody()); 1292 // The end (updates/cleanups). 1293 EmitBlock(Continue.getBlock()); 1294 BreakContinueStack.pop_back(); 1295 } 1296 1297 void CodeGenFunction::EmitOMPInnerLoop( 1298 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 1299 const Expr *IncExpr, 1300 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen, 1301 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) { 1302 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end"); 1303 1304 // Start the loop with a block that tests the condition. 1305 auto CondBlock = createBasicBlock("omp.inner.for.cond"); 1306 EmitBlock(CondBlock); 1307 const SourceRange &R = S.getSourceRange(); 1308 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 1309 SourceLocToDebugLoc(R.getEnd())); 1310 1311 // If there are any cleanups between here and the loop-exit scope, 1312 // create a block to stage a loop exit along. 1313 auto ExitBlock = LoopExit.getBlock(); 1314 if (RequiresCleanup) 1315 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup"); 1316 1317 auto LoopBody = createBasicBlock("omp.inner.for.body"); 1318 1319 // Emit condition. 1320 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S)); 1321 if (ExitBlock != LoopExit.getBlock()) { 1322 EmitBlock(ExitBlock); 1323 EmitBranchThroughCleanup(LoopExit); 1324 } 1325 1326 EmitBlock(LoopBody); 1327 incrementProfileCounter(&S); 1328 1329 // Create a block for the increment. 1330 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc"); 1331 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1332 1333 BodyGen(*this); 1334 1335 // Emit "IV = IV + 1" and a back-edge to the condition block. 1336 EmitBlock(Continue.getBlock()); 1337 EmitIgnoredExpr(IncExpr); 1338 PostIncGen(*this); 1339 BreakContinueStack.pop_back(); 1340 EmitBranch(CondBlock); 1341 LoopStack.pop(); 1342 // Emit the fall-through block. 1343 EmitBlock(LoopExit.getBlock()); 1344 } 1345 1346 void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) { 1347 if (!HaveInsertPoint()) 1348 return; 1349 // Emit inits for the linear variables. 1350 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1351 for (auto *Init : C->inits()) { 1352 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl()); 1353 if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) { 1354 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 1355 auto *OrigVD = cast<VarDecl>(Ref->getDecl()); 1356 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 1357 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1358 VD->getInit()->getType(), VK_LValue, 1359 VD->getInit()->getExprLoc()); 1360 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(), 1361 VD->getType()), 1362 /*capturedByInit=*/false); 1363 EmitAutoVarCleanups(Emission); 1364 } else 1365 EmitVarDecl(*VD); 1366 } 1367 // Emit the linear steps for the linear clauses. 1368 // If a step is not constant, it is pre-calculated before the loop. 1369 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep())) 1370 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) { 1371 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl())); 1372 // Emit calculation of the linear step. 1373 EmitIgnoredExpr(CS); 1374 } 1375 } 1376 } 1377 1378 void CodeGenFunction::EmitOMPLinearClauseFinal( 1379 const OMPLoopDirective &D, 1380 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) { 1381 if (!HaveInsertPoint()) 1382 return; 1383 llvm::BasicBlock *DoneBB = nullptr; 1384 // Emit the final values of the linear variables. 1385 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1386 auto IC = C->varlist_begin(); 1387 for (auto *F : C->finals()) { 1388 if (!DoneBB) { 1389 if (auto *Cond = CondGen(*this)) { 1390 // If the first post-update expression is found, emit conditional 1391 // block if it was requested. 1392 auto *ThenBB = createBasicBlock(".omp.linear.pu"); 1393 DoneBB = createBasicBlock(".omp.linear.pu.done"); 1394 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1395 EmitBlock(ThenBB); 1396 } 1397 } 1398 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl()); 1399 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 1400 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1401 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 1402 Address OrigAddr = EmitLValue(&DRE).getAddress(); 1403 CodeGenFunction::OMPPrivateScope VarScope(*this); 1404 VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; }); 1405 (void)VarScope.Privatize(); 1406 EmitIgnoredExpr(F); 1407 ++IC; 1408 } 1409 if (auto *PostUpdate = C->getPostUpdateExpr()) 1410 EmitIgnoredExpr(PostUpdate); 1411 } 1412 if (DoneBB) 1413 EmitBlock(DoneBB, /*IsFinished=*/true); 1414 } 1415 1416 static void emitAlignedClause(CodeGenFunction &CGF, 1417 const OMPExecutableDirective &D) { 1418 if (!CGF.HaveInsertPoint()) 1419 return; 1420 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) { 1421 unsigned ClauseAlignment = 0; 1422 if (auto AlignmentExpr = Clause->getAlignment()) { 1423 auto AlignmentCI = 1424 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr)); 1425 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue()); 1426 } 1427 for (auto E : Clause->varlists()) { 1428 unsigned Alignment = ClauseAlignment; 1429 if (Alignment == 0) { 1430 // OpenMP [2.8.1, Description] 1431 // If no optional parameter is specified, implementation-defined default 1432 // alignments for SIMD instructions on the target platforms are assumed. 1433 Alignment = 1434 CGF.getContext() 1435 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 1436 E->getType()->getPointeeType())) 1437 .getQuantity(); 1438 } 1439 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) && 1440 "alignment is not power of 2"); 1441 if (Alignment != 0) { 1442 llvm::Value *PtrValue = CGF.EmitScalarExpr(E); 1443 CGF.EmitAlignmentAssumption(PtrValue, Alignment); 1444 } 1445 } 1446 } 1447 } 1448 1449 void CodeGenFunction::EmitOMPPrivateLoopCounters( 1450 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) { 1451 if (!HaveInsertPoint()) 1452 return; 1453 auto I = S.private_counters().begin(); 1454 for (auto *E : S.counters()) { 1455 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1456 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()); 1457 (void)LoopScope.addPrivate(VD, [&]() -> Address { 1458 // Emit var without initialization. 1459 if (!LocalDeclMap.count(PrivateVD)) { 1460 auto VarEmission = EmitAutoVarAlloca(*PrivateVD); 1461 EmitAutoVarCleanups(VarEmission); 1462 } 1463 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD), 1464 /*RefersToEnclosingVariableOrCapture=*/false, 1465 (*I)->getType(), VK_LValue, (*I)->getExprLoc()); 1466 return EmitLValue(&DRE).getAddress(); 1467 }); 1468 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) || 1469 VD->hasGlobalStorage()) { 1470 (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address { 1471 DeclRefExpr DRE(const_cast<VarDecl *>(VD), 1472 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD), 1473 E->getType(), VK_LValue, E->getExprLoc()); 1474 return EmitLValue(&DRE).getAddress(); 1475 }); 1476 } 1477 ++I; 1478 } 1479 } 1480 1481 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, 1482 const Expr *Cond, llvm::BasicBlock *TrueBlock, 1483 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) { 1484 if (!CGF.HaveInsertPoint()) 1485 return; 1486 { 1487 CodeGenFunction::OMPPrivateScope PreCondScope(CGF); 1488 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope); 1489 (void)PreCondScope.Privatize(); 1490 // Get initial values of real counters. 1491 for (auto I : S.inits()) { 1492 CGF.EmitIgnoredExpr(I); 1493 } 1494 } 1495 // Check that loop is executed at least one time. 1496 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 1497 } 1498 1499 void CodeGenFunction::EmitOMPLinearClause( 1500 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) { 1501 if (!HaveInsertPoint()) 1502 return; 1503 llvm::DenseSet<const VarDecl *> SIMDLCVs; 1504 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 1505 auto *LoopDirective = cast<OMPLoopDirective>(&D); 1506 for (auto *C : LoopDirective->counters()) { 1507 SIMDLCVs.insert( 1508 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 1509 } 1510 } 1511 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1512 auto CurPrivate = C->privates().begin(); 1513 for (auto *E : C->varlists()) { 1514 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1515 auto *PrivateVD = 1516 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl()); 1517 if (!SIMDLCVs.count(VD->getCanonicalDecl())) { 1518 bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address { 1519 // Emit private VarDecl with copy init. 1520 EmitVarDecl(*PrivateVD); 1521 return GetAddrOfLocalVar(PrivateVD); 1522 }); 1523 assert(IsRegistered && "linear var already registered as private"); 1524 // Silence the warning about unused variable. 1525 (void)IsRegistered; 1526 } else 1527 EmitVarDecl(*PrivateVD); 1528 ++CurPrivate; 1529 } 1530 } 1531 } 1532 1533 static void emitSimdlenSafelenClause(CodeGenFunction &CGF, 1534 const OMPExecutableDirective &D, 1535 bool IsMonotonic) { 1536 if (!CGF.HaveInsertPoint()) 1537 return; 1538 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) { 1539 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(), 1540 /*ignoreResult=*/true); 1541 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 1542 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 1543 // In presence of finite 'safelen', it may be unsafe to mark all 1544 // the memory instructions parallel, because loop-carried 1545 // dependences of 'safelen' iterations are possible. 1546 if (!IsMonotonic) 1547 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>()); 1548 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) { 1549 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(), 1550 /*ignoreResult=*/true); 1551 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 1552 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 1553 // In presence of finite 'safelen', it may be unsafe to mark all 1554 // the memory instructions parallel, because loop-carried 1555 // dependences of 'safelen' iterations are possible. 1556 CGF.LoopStack.setParallel(false); 1557 } 1558 } 1559 1560 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D, 1561 bool IsMonotonic) { 1562 // Walk clauses and process safelen/lastprivate. 1563 LoopStack.setParallel(!IsMonotonic); 1564 LoopStack.setVectorizeEnable(true); 1565 emitSimdlenSafelenClause(*this, D, IsMonotonic); 1566 } 1567 1568 void CodeGenFunction::EmitOMPSimdFinal( 1569 const OMPLoopDirective &D, 1570 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) { 1571 if (!HaveInsertPoint()) 1572 return; 1573 llvm::BasicBlock *DoneBB = nullptr; 1574 auto IC = D.counters().begin(); 1575 auto IPC = D.private_counters().begin(); 1576 for (auto F : D.finals()) { 1577 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 1578 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl()); 1579 auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD); 1580 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) || 1581 OrigVD->hasGlobalStorage() || CED) { 1582 if (!DoneBB) { 1583 if (auto *Cond = CondGen(*this)) { 1584 // If the first post-update expression is found, emit conditional 1585 // block if it was requested. 1586 auto *ThenBB = createBasicBlock(".omp.final.then"); 1587 DoneBB = createBasicBlock(".omp.final.done"); 1588 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1589 EmitBlock(ThenBB); 1590 } 1591 } 1592 Address OrigAddr = Address::invalid(); 1593 if (CED) 1594 OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(); 1595 else { 1596 DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD), 1597 /*RefersToEnclosingVariableOrCapture=*/false, 1598 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc()); 1599 OrigAddr = EmitLValue(&DRE).getAddress(); 1600 } 1601 OMPPrivateScope VarScope(*this); 1602 VarScope.addPrivate(OrigVD, 1603 [OrigAddr]() -> Address { return OrigAddr; }); 1604 (void)VarScope.Privatize(); 1605 EmitIgnoredExpr(F); 1606 } 1607 ++IC; 1608 ++IPC; 1609 } 1610 if (DoneBB) 1611 EmitBlock(DoneBB, /*IsFinished=*/true); 1612 } 1613 1614 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 1615 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1616 OMPLoopScope PreInitScope(CGF, S); 1617 // if (PreCond) { 1618 // for (IV in 0..LastIteration) BODY; 1619 // <Final counter/linear vars updates>; 1620 // } 1621 // 1622 1623 // Emit: if (PreCond) - begin. 1624 // If the condition constant folds and can be elided, avoid emitting the 1625 // whole loop. 1626 bool CondConstant; 1627 llvm::BasicBlock *ContBlock = nullptr; 1628 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 1629 if (!CondConstant) 1630 return; 1631 } else { 1632 auto *ThenBlock = CGF.createBasicBlock("simd.if.then"); 1633 ContBlock = CGF.createBasicBlock("simd.if.end"); 1634 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 1635 CGF.getProfileCount(&S)); 1636 CGF.EmitBlock(ThenBlock); 1637 CGF.incrementProfileCounter(&S); 1638 } 1639 1640 // Emit the loop iteration variable. 1641 const Expr *IVExpr = S.getIterationVariable(); 1642 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 1643 CGF.EmitVarDecl(*IVDecl); 1644 CGF.EmitIgnoredExpr(S.getInit()); 1645 1646 // Emit the iterations count variable. 1647 // If it is not a variable, Sema decided to calculate iterations count on 1648 // each iteration (e.g., it is foldable into a constant). 1649 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 1650 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 1651 // Emit calculation of the iterations count. 1652 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 1653 } 1654 1655 CGF.EmitOMPSimdInit(S); 1656 1657 emitAlignedClause(CGF, S); 1658 CGF.EmitOMPLinearClauseInit(S); 1659 { 1660 OMPPrivateScope LoopScope(CGF); 1661 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 1662 CGF.EmitOMPLinearClause(S, LoopScope); 1663 CGF.EmitOMPPrivateClause(S, LoopScope); 1664 CGF.EmitOMPReductionClauseInit(S, LoopScope); 1665 bool HasLastprivateClause = 1666 CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 1667 (void)LoopScope.Privatize(); 1668 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), 1669 S.getInc(), 1670 [&S](CodeGenFunction &CGF) { 1671 CGF.EmitOMPLoopBody(S, JumpDest()); 1672 CGF.EmitStopPoint(&S); 1673 }, 1674 [](CodeGenFunction &) {}); 1675 CGF.EmitOMPSimdFinal( 1676 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; }); 1677 // Emit final copy of the lastprivate variables at the end of loops. 1678 if (HasLastprivateClause) 1679 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true); 1680 CGF.EmitOMPReductionClauseFinal(S); 1681 emitPostUpdateForReductionClause( 1682 CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; }); 1683 } 1684 CGF.EmitOMPLinearClauseFinal( 1685 S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; }); 1686 // Emit: if (PreCond) - end. 1687 if (ContBlock) { 1688 CGF.EmitBranch(ContBlock); 1689 CGF.EmitBlock(ContBlock, true); 1690 } 1691 }; 1692 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1693 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 1694 } 1695 1696 void CodeGenFunction::EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic, 1697 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 1698 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) { 1699 auto &RT = CGM.getOpenMPRuntime(); 1700 1701 const Expr *IVExpr = S.getIterationVariable(); 1702 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 1703 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 1704 1705 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 1706 1707 // Start the loop with a block that tests the condition. 1708 auto CondBlock = createBasicBlock("omp.dispatch.cond"); 1709 EmitBlock(CondBlock); 1710 const SourceRange &R = S.getSourceRange(); 1711 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 1712 SourceLocToDebugLoc(R.getEnd())); 1713 1714 llvm::Value *BoolCondVal = nullptr; 1715 if (!DynamicOrOrdered) { 1716 // UB = min(UB, GlobalUB) 1717 EmitIgnoredExpr(S.getEnsureUpperBound()); 1718 // IV = LB 1719 EmitIgnoredExpr(S.getInit()); 1720 // IV < UB 1721 BoolCondVal = EvaluateExprAsBool(S.getCond()); 1722 } else { 1723 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, IL, 1724 LB, UB, ST); 1725 } 1726 1727 // If there are any cleanups between here and the loop-exit scope, 1728 // create a block to stage a loop exit along. 1729 auto ExitBlock = LoopExit.getBlock(); 1730 if (LoopScope.requiresCleanups()) 1731 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 1732 1733 auto LoopBody = createBasicBlock("omp.dispatch.body"); 1734 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 1735 if (ExitBlock != LoopExit.getBlock()) { 1736 EmitBlock(ExitBlock); 1737 EmitBranchThroughCleanup(LoopExit); 1738 } 1739 EmitBlock(LoopBody); 1740 1741 // Emit "IV = LB" (in case of static schedule, we have already calculated new 1742 // LB for loop condition and emitted it above). 1743 if (DynamicOrOrdered) 1744 EmitIgnoredExpr(S.getInit()); 1745 1746 // Create a block for the increment. 1747 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 1748 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1749 1750 // Generate !llvm.loop.parallel metadata for loads and stores for loops 1751 // with dynamic/guided scheduling and without ordered clause. 1752 if (!isOpenMPSimdDirective(S.getDirectiveKind())) 1753 LoopStack.setParallel(!IsMonotonic); 1754 else 1755 EmitOMPSimdInit(S, IsMonotonic); 1756 1757 SourceLocation Loc = S.getLocStart(); 1758 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 1759 [&S, LoopExit](CodeGenFunction &CGF) { 1760 CGF.EmitOMPLoopBody(S, LoopExit); 1761 CGF.EmitStopPoint(&S); 1762 }, 1763 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) { 1764 if (Ordered) { 1765 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd( 1766 CGF, Loc, IVSize, IVSigned); 1767 } 1768 }); 1769 1770 EmitBlock(Continue.getBlock()); 1771 BreakContinueStack.pop_back(); 1772 if (!DynamicOrOrdered) { 1773 // Emit "LB = LB + Stride", "UB = UB + Stride". 1774 EmitIgnoredExpr(S.getNextLowerBound()); 1775 EmitIgnoredExpr(S.getNextUpperBound()); 1776 } 1777 1778 EmitBranch(CondBlock); 1779 LoopStack.pop(); 1780 // Emit the fall-through block. 1781 EmitBlock(LoopExit.getBlock()); 1782 1783 // Tell the runtime we are done. 1784 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) { 1785 if (!DynamicOrOrdered) 1786 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd()); 1787 }; 1788 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 1789 } 1790 1791 void CodeGenFunction::EmitOMPForOuterLoop( 1792 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic, 1793 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 1794 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) { 1795 auto &RT = CGM.getOpenMPRuntime(); 1796 1797 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 1798 const bool DynamicOrOrdered = 1799 Ordered || RT.isDynamic(ScheduleKind.Schedule); 1800 1801 assert((Ordered || 1802 !RT.isStaticNonchunked(ScheduleKind.Schedule, 1803 /*Chunked=*/Chunk != nullptr)) && 1804 "static non-chunked schedule does not need outer loop"); 1805 1806 // Emit outer loop. 1807 // 1808 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 1809 // When schedule(dynamic,chunk_size) is specified, the iterations are 1810 // distributed to threads in the team in chunks as the threads request them. 1811 // Each thread executes a chunk of iterations, then requests another chunk, 1812 // until no chunks remain to be distributed. Each chunk contains chunk_size 1813 // iterations, except for the last chunk to be distributed, which may have 1814 // fewer iterations. When no chunk_size is specified, it defaults to 1. 1815 // 1816 // When schedule(guided,chunk_size) is specified, the iterations are assigned 1817 // to threads in the team in chunks as the executing threads request them. 1818 // Each thread executes a chunk of iterations, then requests another chunk, 1819 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 1820 // each chunk is proportional to the number of unassigned iterations divided 1821 // by the number of threads in the team, decreasing to 1. For a chunk_size 1822 // with value k (greater than 1), the size of each chunk is determined in the 1823 // same way, with the restriction that the chunks do not contain fewer than k 1824 // iterations (except for the last chunk to be assigned, which may have fewer 1825 // than k iterations). 1826 // 1827 // When schedule(auto) is specified, the decision regarding scheduling is 1828 // delegated to the compiler and/or runtime system. The programmer gives the 1829 // implementation the freedom to choose any possible mapping of iterations to 1830 // threads in the team. 1831 // 1832 // When schedule(runtime) is specified, the decision regarding scheduling is 1833 // deferred until run time, and the schedule and chunk size are taken from the 1834 // run-sched-var ICV. If the ICV is set to auto, the schedule is 1835 // implementation defined 1836 // 1837 // while(__kmpc_dispatch_next(&LB, &UB)) { 1838 // idx = LB; 1839 // while (idx <= UB) { BODY; ++idx; 1840 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 1841 // } // inner loop 1842 // } 1843 // 1844 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 1845 // When schedule(static, chunk_size) is specified, iterations are divided into 1846 // chunks of size chunk_size, and the chunks are assigned to the threads in 1847 // the team in a round-robin fashion in the order of the thread number. 1848 // 1849 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 1850 // while (idx <= UB) { BODY; ++idx; } // inner loop 1851 // LB = LB + ST; 1852 // UB = UB + ST; 1853 // } 1854 // 1855 1856 const Expr *IVExpr = S.getIterationVariable(); 1857 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 1858 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 1859 1860 if (DynamicOrOrdered) { 1861 llvm::Value *UBVal = EmitScalarExpr(S.getLastIteration()); 1862 RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize, 1863 IVSigned, Ordered, UBVal, Chunk); 1864 } else { 1865 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, 1866 Ordered, IL, LB, UB, ST, Chunk); 1867 } 1868 1869 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, Ordered, LB, UB, 1870 ST, IL, Chunk); 1871 } 1872 1873 void CodeGenFunction::EmitOMPDistributeOuterLoop( 1874 OpenMPDistScheduleClauseKind ScheduleKind, 1875 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope, 1876 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk) { 1877 1878 auto &RT = CGM.getOpenMPRuntime(); 1879 1880 // Emit outer loop. 1881 // Same behavior as a OMPForOuterLoop, except that schedule cannot be 1882 // dynamic 1883 // 1884 1885 const Expr *IVExpr = S.getIterationVariable(); 1886 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 1887 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 1888 1889 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, 1890 IVSize, IVSigned, /* Ordered = */ false, 1891 IL, LB, UB, ST, Chunk); 1892 1893 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, 1894 S, LoopScope, /* Ordered = */ false, LB, UB, ST, IL, Chunk); 1895 } 1896 1897 void CodeGenFunction::EmitOMPDistributeParallelForDirective( 1898 const OMPDistributeParallelForDirective &S) { 1899 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1900 CGM.getOpenMPRuntime().emitInlinedDirective( 1901 *this, OMPD_distribute_parallel_for, 1902 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1903 OMPLoopScope PreInitScope(CGF, S); 1904 OMPCancelStackRAII CancelRegion(CGF, OMPD_distribute_parallel_for, 1905 /*HasCancel=*/false); 1906 CGF.EmitStmt( 1907 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1908 }); 1909 } 1910 1911 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective( 1912 const OMPDistributeParallelForSimdDirective &S) { 1913 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1914 CGM.getOpenMPRuntime().emitInlinedDirective( 1915 *this, OMPD_distribute_parallel_for_simd, 1916 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1917 OMPLoopScope PreInitScope(CGF, S); 1918 CGF.EmitStmt( 1919 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1920 }); 1921 } 1922 1923 void CodeGenFunction::EmitOMPDistributeSimdDirective( 1924 const OMPDistributeSimdDirective &S) { 1925 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1926 CGM.getOpenMPRuntime().emitInlinedDirective( 1927 *this, OMPD_distribute_simd, 1928 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1929 OMPLoopScope PreInitScope(CGF, S); 1930 CGF.EmitStmt( 1931 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1932 }); 1933 } 1934 1935 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective( 1936 const OMPTargetParallelForSimdDirective &S) { 1937 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1938 CGM.getOpenMPRuntime().emitInlinedDirective( 1939 *this, OMPD_target_parallel_for_simd, 1940 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1941 OMPLoopScope PreInitScope(CGF, S); 1942 CGF.EmitStmt( 1943 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1944 }); 1945 } 1946 1947 void CodeGenFunction::EmitOMPTargetSimdDirective( 1948 const OMPTargetSimdDirective &S) { 1949 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1950 CGM.getOpenMPRuntime().emitInlinedDirective( 1951 *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1952 OMPLoopScope PreInitScope(CGF, S); 1953 CGF.EmitStmt( 1954 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1955 }); 1956 } 1957 1958 void CodeGenFunction::EmitOMPTeamsDistributeDirective( 1959 const OMPTeamsDistributeDirective &S) { 1960 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1961 CGM.getOpenMPRuntime().emitInlinedDirective( 1962 *this, OMPD_teams_distribute, 1963 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1964 OMPLoopScope PreInitScope(CGF, S); 1965 CGF.EmitStmt( 1966 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1967 }); 1968 } 1969 1970 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective( 1971 const OMPTeamsDistributeSimdDirective &S) { 1972 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1973 CGM.getOpenMPRuntime().emitInlinedDirective( 1974 *this, OMPD_teams_distribute_simd, 1975 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1976 OMPLoopScope PreInitScope(CGF, S); 1977 CGF.EmitStmt( 1978 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1979 }); 1980 } 1981 1982 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective( 1983 const OMPTeamsDistributeParallelForSimdDirective &S) { 1984 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1985 CGM.getOpenMPRuntime().emitInlinedDirective( 1986 *this, OMPD_teams_distribute_parallel_for_simd, 1987 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 1988 OMPLoopScope PreInitScope(CGF, S); 1989 CGF.EmitStmt( 1990 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1991 }); 1992 } 1993 1994 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective( 1995 const OMPTeamsDistributeParallelForDirective &S) { 1996 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 1997 CGM.getOpenMPRuntime().emitInlinedDirective( 1998 *this, OMPD_teams_distribute_parallel_for, 1999 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2000 OMPLoopScope PreInitScope(CGF, S); 2001 CGF.EmitStmt( 2002 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 2003 }); 2004 } 2005 2006 void CodeGenFunction::EmitOMPTargetTeamsDirective( 2007 const OMPTargetTeamsDirective &S) { 2008 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_target_teams, 2009 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2010 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 2011 }); 2012 } 2013 2014 /// \brief Emit a helper variable and return corresponding lvalue. 2015 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 2016 const DeclRefExpr *Helper) { 2017 auto VDecl = cast<VarDecl>(Helper->getDecl()); 2018 CGF.EmitVarDecl(*VDecl); 2019 return CGF.EmitLValue(Helper); 2020 } 2021 2022 namespace { 2023 struct ScheduleKindModifiersTy { 2024 OpenMPScheduleClauseKind Kind; 2025 OpenMPScheduleClauseModifier M1; 2026 OpenMPScheduleClauseModifier M2; 2027 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind, 2028 OpenMPScheduleClauseModifier M1, 2029 OpenMPScheduleClauseModifier M2) 2030 : Kind(Kind), M1(M1), M2(M2) {} 2031 }; 2032 } // namespace 2033 2034 bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) { 2035 // Emit the loop iteration variable. 2036 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 2037 auto IVDecl = cast<VarDecl>(IVExpr->getDecl()); 2038 EmitVarDecl(*IVDecl); 2039 2040 // Emit the iterations count variable. 2041 // If it is not a variable, Sema decided to calculate iterations count on each 2042 // iteration (e.g., it is foldable into a constant). 2043 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2044 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2045 // Emit calculation of the iterations count. 2046 EmitIgnoredExpr(S.getCalcLastIteration()); 2047 } 2048 2049 auto &RT = CGM.getOpenMPRuntime(); 2050 2051 bool HasLastprivateClause; 2052 // Check pre-condition. 2053 { 2054 OMPLoopScope PreInitScope(*this, S); 2055 // Skip the entire loop if we don't meet the precondition. 2056 // If the condition constant folds and can be elided, avoid emitting the 2057 // whole loop. 2058 bool CondConstant; 2059 llvm::BasicBlock *ContBlock = nullptr; 2060 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2061 if (!CondConstant) 2062 return false; 2063 } else { 2064 auto *ThenBlock = createBasicBlock("omp.precond.then"); 2065 ContBlock = createBasicBlock("omp.precond.end"); 2066 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 2067 getProfileCount(&S)); 2068 EmitBlock(ThenBlock); 2069 incrementProfileCounter(&S); 2070 } 2071 2072 bool Ordered = false; 2073 if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) { 2074 if (OrderedClause->getNumForLoops()) 2075 RT.emitDoacrossInit(*this, S); 2076 else 2077 Ordered = true; 2078 } 2079 2080 llvm::DenseSet<const Expr *> EmittedFinals; 2081 emitAlignedClause(*this, S); 2082 EmitOMPLinearClauseInit(S); 2083 // Emit helper vars inits. 2084 LValue LB = 2085 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable())); 2086 LValue UB = 2087 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable())); 2088 LValue ST = 2089 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 2090 LValue IL = 2091 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 2092 2093 // Emit 'then' code. 2094 { 2095 OMPPrivateScope LoopScope(*this); 2096 if (EmitOMPFirstprivateClause(S, LoopScope)) { 2097 // Emit implicit barrier to synchronize threads and avoid data races on 2098 // initialization of firstprivate variables and post-update of 2099 // lastprivate variables. 2100 CGM.getOpenMPRuntime().emitBarrierCall( 2101 *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false, 2102 /*ForceSimpleCall=*/true); 2103 } 2104 EmitOMPPrivateClause(S, LoopScope); 2105 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 2106 EmitOMPReductionClauseInit(S, LoopScope); 2107 EmitOMPPrivateLoopCounters(S, LoopScope); 2108 EmitOMPLinearClause(S, LoopScope); 2109 (void)LoopScope.Privatize(); 2110 2111 // Detect the loop schedule kind and chunk. 2112 llvm::Value *Chunk = nullptr; 2113 OpenMPScheduleTy ScheduleKind; 2114 if (auto *C = S.getSingleClause<OMPScheduleClause>()) { 2115 ScheduleKind.Schedule = C->getScheduleKind(); 2116 ScheduleKind.M1 = C->getFirstScheduleModifier(); 2117 ScheduleKind.M2 = C->getSecondScheduleModifier(); 2118 if (const auto *Ch = C->getChunkSize()) { 2119 Chunk = EmitScalarExpr(Ch); 2120 Chunk = EmitScalarConversion(Chunk, Ch->getType(), 2121 S.getIterationVariable()->getType(), 2122 S.getLocStart()); 2123 } 2124 } 2125 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2126 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2127 // OpenMP 4.5, 2.7.1 Loop Construct, Description. 2128 // If the static schedule kind is specified or if the ordered clause is 2129 // specified, and if no monotonic modifier is specified, the effect will 2130 // be as if the monotonic modifier was specified. 2131 if (RT.isStaticNonchunked(ScheduleKind.Schedule, 2132 /* Chunked */ Chunk != nullptr) && 2133 !Ordered) { 2134 if (isOpenMPSimdDirective(S.getDirectiveKind())) 2135 EmitOMPSimdInit(S, /*IsMonotonic=*/true); 2136 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2137 // When no chunk_size is specified, the iteration space is divided into 2138 // chunks that are approximately equal in size, and at most one chunk is 2139 // distributed to each thread. Note that the size of the chunks is 2140 // unspecified in this case. 2141 RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, 2142 IVSize, IVSigned, Ordered, 2143 IL.getAddress(), LB.getAddress(), 2144 UB.getAddress(), ST.getAddress()); 2145 auto LoopExit = 2146 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 2147 // UB = min(UB, GlobalUB); 2148 EmitIgnoredExpr(S.getEnsureUpperBound()); 2149 // IV = LB; 2150 EmitIgnoredExpr(S.getInit()); 2151 // while (idx <= UB) { BODY; ++idx; } 2152 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), 2153 S.getInc(), 2154 [&S, LoopExit](CodeGenFunction &CGF) { 2155 CGF.EmitOMPLoopBody(S, LoopExit); 2156 CGF.EmitStopPoint(&S); 2157 }, 2158 [](CodeGenFunction &) {}); 2159 EmitBlock(LoopExit.getBlock()); 2160 // Tell the runtime we are done. 2161 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 2162 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd()); 2163 }; 2164 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 2165 } else { 2166 const bool IsMonotonic = 2167 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static || 2168 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown || 2169 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic || 2170 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic; 2171 // Emit the outer loop, which requests its work chunk [LB..UB] from 2172 // runtime and runs the inner loop to process it. 2173 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered, 2174 LB.getAddress(), UB.getAddress(), ST.getAddress(), 2175 IL.getAddress(), Chunk); 2176 } 2177 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2178 EmitOMPSimdFinal(S, 2179 [&](CodeGenFunction &CGF) -> llvm::Value * { 2180 return CGF.Builder.CreateIsNotNull( 2181 CGF.EmitLoadOfScalar(IL, S.getLocStart())); 2182 }); 2183 } 2184 EmitOMPReductionClauseFinal(S); 2185 // Emit post-update of the reduction variables if IsLastIter != 0. 2186 emitPostUpdateForReductionClause( 2187 *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * { 2188 return CGF.Builder.CreateIsNotNull( 2189 CGF.EmitLoadOfScalar(IL, S.getLocStart())); 2190 }); 2191 // Emit final copy of the lastprivate variables if IsLastIter != 0. 2192 if (HasLastprivateClause) 2193 EmitOMPLastprivateClauseFinal( 2194 S, isOpenMPSimdDirective(S.getDirectiveKind()), 2195 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart()))); 2196 } 2197 EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * { 2198 return CGF.Builder.CreateIsNotNull( 2199 CGF.EmitLoadOfScalar(IL, S.getLocStart())); 2200 }); 2201 // We're now done with the loop, so jump to the continuation block. 2202 if (ContBlock) { 2203 EmitBranch(ContBlock); 2204 EmitBlock(ContBlock, true); 2205 } 2206 } 2207 return HasLastprivateClause; 2208 } 2209 2210 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 2211 bool HasLastprivates = false; 2212 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 2213 PrePostActionTy &) { 2214 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel()); 2215 HasLastprivates = CGF.EmitOMPWorksharingLoop(S); 2216 }; 2217 { 2218 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2219 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen, 2220 S.hasCancel()); 2221 } 2222 2223 // Emit an implicit barrier at the end. 2224 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) { 2225 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for); 2226 } 2227 } 2228 2229 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) { 2230 bool HasLastprivates = false; 2231 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 2232 PrePostActionTy &) { 2233 HasLastprivates = CGF.EmitOMPWorksharingLoop(S); 2234 }; 2235 { 2236 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2237 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2238 } 2239 2240 // Emit an implicit barrier at the end. 2241 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) { 2242 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for); 2243 } 2244 } 2245 2246 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 2247 const Twine &Name, 2248 llvm::Value *Init = nullptr) { 2249 auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 2250 if (Init) 2251 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true); 2252 return LVal; 2253 } 2254 2255 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) { 2256 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt(); 2257 auto *CS = dyn_cast<CompoundStmt>(Stmt); 2258 bool HasLastprivates = false; 2259 auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF, 2260 PrePostActionTy &) { 2261 auto &C = CGF.CGM.getContext(); 2262 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 2263 // Emit helper vars inits. 2264 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 2265 CGF.Builder.getInt32(0)); 2266 auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1) 2267 : CGF.Builder.getInt32(0); 2268 LValue UB = 2269 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 2270 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 2271 CGF.Builder.getInt32(1)); 2272 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 2273 CGF.Builder.getInt32(0)); 2274 // Loop counter. 2275 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 2276 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue); 2277 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 2278 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue); 2279 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 2280 // Generate condition for loop. 2281 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue, 2282 OK_Ordinary, S.getLocStart(), 2283 /*fpContractable=*/false); 2284 // Increment for loop counter. 2285 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary, 2286 S.getLocStart()); 2287 auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) { 2288 // Iterate through all sections and emit a switch construct: 2289 // switch (IV) { 2290 // case 0: 2291 // <SectionStmt[0]>; 2292 // break; 2293 // ... 2294 // case <NumSection> - 1: 2295 // <SectionStmt[<NumSection> - 1]>; 2296 // break; 2297 // } 2298 // .omp.sections.exit: 2299 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 2300 auto *SwitchStmt = CGF.Builder.CreateSwitch( 2301 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB, 2302 CS == nullptr ? 1 : CS->size()); 2303 if (CS) { 2304 unsigned CaseNumber = 0; 2305 for (auto *SubStmt : CS->children()) { 2306 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 2307 CGF.EmitBlock(CaseBB); 2308 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 2309 CGF.EmitStmt(SubStmt); 2310 CGF.EmitBranch(ExitBB); 2311 ++CaseNumber; 2312 } 2313 } else { 2314 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 2315 CGF.EmitBlock(CaseBB); 2316 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB); 2317 CGF.EmitStmt(Stmt); 2318 CGF.EmitBranch(ExitBB); 2319 } 2320 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 2321 }; 2322 2323 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2324 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 2325 // Emit implicit barrier to synchronize threads and avoid data races on 2326 // initialization of firstprivate variables and post-update of lastprivate 2327 // variables. 2328 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 2329 CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false, 2330 /*ForceSimpleCall=*/true); 2331 } 2332 CGF.EmitOMPPrivateClause(S, LoopScope); 2333 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 2334 CGF.EmitOMPReductionClauseInit(S, LoopScope); 2335 (void)LoopScope.Privatize(); 2336 2337 // Emit static non-chunked loop. 2338 OpenMPScheduleTy ScheduleKind; 2339 ScheduleKind.Schedule = OMPC_SCHEDULE_static; 2340 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 2341 CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32, 2342 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(), 2343 UB.getAddress(), ST.getAddress()); 2344 // UB = min(UB, GlobalUB); 2345 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart()); 2346 auto *MinUBGlobalUB = CGF.Builder.CreateSelect( 2347 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 2348 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 2349 // IV = LB; 2350 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV); 2351 // while (idx <= UB) { BODY; ++idx; } 2352 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen, 2353 [](CodeGenFunction &) {}); 2354 // Tell the runtime we are done. 2355 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 2356 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd()); 2357 }; 2358 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen); 2359 CGF.EmitOMPReductionClauseFinal(S); 2360 // Emit post-update of the reduction variables if IsLastIter != 0. 2361 emitPostUpdateForReductionClause( 2362 CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * { 2363 return CGF.Builder.CreateIsNotNull( 2364 CGF.EmitLoadOfScalar(IL, S.getLocStart())); 2365 }); 2366 2367 // Emit final copy of the lastprivate variables if IsLastIter != 0. 2368 if (HasLastprivates) 2369 CGF.EmitOMPLastprivateClauseFinal( 2370 S, /*NoFinals=*/false, 2371 CGF.Builder.CreateIsNotNull( 2372 CGF.EmitLoadOfScalar(IL, S.getLocStart()))); 2373 }; 2374 2375 bool HasCancel = false; 2376 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S)) 2377 HasCancel = OSD->hasCancel(); 2378 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S)) 2379 HasCancel = OPSD->hasCancel(); 2380 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel); 2381 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen, 2382 HasCancel); 2383 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 2384 // clause. Otherwise the barrier will be generated by the codegen for the 2385 // directive. 2386 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) { 2387 // Emit implicit barrier to synchronize threads and avoid data races on 2388 // initialization of firstprivate variables. 2389 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), 2390 OMPD_unknown); 2391 } 2392 } 2393 2394 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 2395 { 2396 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2397 EmitSections(S); 2398 } 2399 // Emit an implicit barrier at the end. 2400 if (!S.getSingleClause<OMPNowaitClause>()) { 2401 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), 2402 OMPD_sections); 2403 } 2404 } 2405 2406 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 2407 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2408 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 2409 }; 2410 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2411 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen, 2412 S.hasCancel()); 2413 } 2414 2415 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 2416 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 2417 llvm::SmallVector<const Expr *, 8> DestExprs; 2418 llvm::SmallVector<const Expr *, 8> SrcExprs; 2419 llvm::SmallVector<const Expr *, 8> AssignmentOps; 2420 // Check if there are any 'copyprivate' clauses associated with this 2421 // 'single' construct. 2422 // Build a list of copyprivate variables along with helper expressions 2423 // (<source>, <destination>, <destination>=<source> expressions) 2424 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) { 2425 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 2426 DestExprs.append(C->destination_exprs().begin(), 2427 C->destination_exprs().end()); 2428 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 2429 AssignmentOps.append(C->assignment_ops().begin(), 2430 C->assignment_ops().end()); 2431 } 2432 // Emit code for 'single' region along with 'copyprivate' clauses 2433 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2434 Action.Enter(CGF); 2435 OMPPrivateScope SingleScope(CGF); 2436 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope); 2437 CGF.EmitOMPPrivateClause(S, SingleScope); 2438 (void)SingleScope.Privatize(); 2439 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 2440 }; 2441 { 2442 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2443 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(), 2444 CopyprivateVars, DestExprs, 2445 SrcExprs, AssignmentOps); 2446 } 2447 // Emit an implicit barrier at the end (to avoid data race on firstprivate 2448 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 2449 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) { 2450 CGM.getOpenMPRuntime().emitBarrierCall( 2451 *this, S.getLocStart(), 2452 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single); 2453 } 2454 } 2455 2456 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 2457 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2458 Action.Enter(CGF); 2459 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 2460 }; 2461 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2462 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart()); 2463 } 2464 2465 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 2466 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2467 Action.Enter(CGF); 2468 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 2469 }; 2470 Expr *Hint = nullptr; 2471 if (auto *HintClause = S.getSingleClause<OMPHintClause>()) 2472 Hint = HintClause->getHint(); 2473 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2474 CGM.getOpenMPRuntime().emitCriticalRegion(*this, 2475 S.getDirectiveName().getAsString(), 2476 CodeGen, S.getLocStart(), Hint); 2477 } 2478 2479 void CodeGenFunction::EmitOMPParallelForDirective( 2480 const OMPParallelForDirective &S) { 2481 // Emit directive as a combined directive that consists of two implicit 2482 // directives: 'parallel' with 'for' directive. 2483 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2484 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel()); 2485 CGF.EmitOMPWorksharingLoop(S); 2486 }; 2487 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen); 2488 } 2489 2490 void CodeGenFunction::EmitOMPParallelForSimdDirective( 2491 const OMPParallelForSimdDirective &S) { 2492 // Emit directive as a combined directive that consists of two implicit 2493 // directives: 'parallel' with 'for' directive. 2494 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2495 CGF.EmitOMPWorksharingLoop(S); 2496 }; 2497 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen); 2498 } 2499 2500 void CodeGenFunction::EmitOMPParallelSectionsDirective( 2501 const OMPParallelSectionsDirective &S) { 2502 // Emit directive as a combined directive that consists of two implicit 2503 // directives: 'parallel' with 'sections' directive. 2504 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2505 CGF.EmitSections(S); 2506 }; 2507 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen); 2508 } 2509 2510 void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, 2511 const RegionCodeGenTy &BodyGen, 2512 const TaskGenTy &TaskGen, 2513 OMPTaskDataTy &Data) { 2514 // Emit outlined function for task construct. 2515 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 2516 auto *I = CS->getCapturedDecl()->param_begin(); 2517 auto *PartId = std::next(I); 2518 auto *TaskT = std::next(I, 4); 2519 // Check if the task is final 2520 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) { 2521 // If the condition constant folds and can be elided, try to avoid emitting 2522 // the condition and the dead arm of the if/else. 2523 auto *Cond = Clause->getCondition(); 2524 bool CondConstant; 2525 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 2526 Data.Final.setInt(CondConstant); 2527 else 2528 Data.Final.setPointer(EvaluateExprAsBool(Cond)); 2529 } else { 2530 // By default the task is not final. 2531 Data.Final.setInt(/*IntVal=*/false); 2532 } 2533 // Check if the task has 'priority' clause. 2534 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) { 2535 auto *Prio = Clause->getPriority(); 2536 Data.Priority.setInt(/*IntVal=*/true); 2537 Data.Priority.setPointer(EmitScalarConversion( 2538 EmitScalarExpr(Prio), Prio->getType(), 2539 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), 2540 Prio->getExprLoc())); 2541 } 2542 // The first function argument for tasks is a thread id, the second one is a 2543 // part id (0 for tied tasks, >=0 for untied task). 2544 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 2545 // Get list of private variables. 2546 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) { 2547 auto IRef = C->varlist_begin(); 2548 for (auto *IInit : C->private_copies()) { 2549 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 2550 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 2551 Data.PrivateVars.push_back(*IRef); 2552 Data.PrivateCopies.push_back(IInit); 2553 } 2554 ++IRef; 2555 } 2556 } 2557 EmittedAsPrivate.clear(); 2558 // Get list of firstprivate variables. 2559 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 2560 auto IRef = C->varlist_begin(); 2561 auto IElemInitRef = C->inits().begin(); 2562 for (auto *IInit : C->private_copies()) { 2563 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 2564 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 2565 Data.FirstprivateVars.push_back(*IRef); 2566 Data.FirstprivateCopies.push_back(IInit); 2567 Data.FirstprivateInits.push_back(*IElemInitRef); 2568 } 2569 ++IRef; 2570 ++IElemInitRef; 2571 } 2572 } 2573 // Get list of lastprivate variables (for taskloops). 2574 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs; 2575 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 2576 auto IRef = C->varlist_begin(); 2577 auto ID = C->destination_exprs().begin(); 2578 for (auto *IInit : C->private_copies()) { 2579 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 2580 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 2581 Data.LastprivateVars.push_back(*IRef); 2582 Data.LastprivateCopies.push_back(IInit); 2583 } 2584 LastprivateDstsOrigs.insert( 2585 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()), 2586 cast<DeclRefExpr>(*IRef)}); 2587 ++IRef; 2588 ++ID; 2589 } 2590 } 2591 // Build list of dependences. 2592 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) 2593 for (auto *IRef : C->varlists()) 2594 Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef)); 2595 auto &&CodeGen = [PartId, &S, &Data, CS, &BodyGen, &LastprivateDstsOrigs]( 2596 CodeGenFunction &CGF, PrePostActionTy &Action) { 2597 // Set proper addresses for generated private copies. 2598 OMPPrivateScope Scope(CGF); 2599 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() || 2600 !Data.LastprivateVars.empty()) { 2601 auto *CopyFn = CGF.Builder.CreateLoad( 2602 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3))); 2603 auto *PrivatesPtr = CGF.Builder.CreateLoad( 2604 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2))); 2605 // Map privates. 2606 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 2607 llvm::SmallVector<llvm::Value *, 16> CallArgs; 2608 CallArgs.push_back(PrivatesPtr); 2609 for (auto *E : Data.PrivateVars) { 2610 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2611 Address PrivatePtr = CGF.CreateMemTemp( 2612 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr"); 2613 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr)); 2614 CallArgs.push_back(PrivatePtr.getPointer()); 2615 } 2616 for (auto *E : Data.FirstprivateVars) { 2617 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2618 Address PrivatePtr = 2619 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 2620 ".firstpriv.ptr.addr"); 2621 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr)); 2622 CallArgs.push_back(PrivatePtr.getPointer()); 2623 } 2624 for (auto *E : Data.LastprivateVars) { 2625 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2626 Address PrivatePtr = 2627 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 2628 ".lastpriv.ptr.addr"); 2629 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr)); 2630 CallArgs.push_back(PrivatePtr.getPointer()); 2631 } 2632 CGF.EmitRuntimeCall(CopyFn, CallArgs); 2633 for (auto &&Pair : LastprivateDstsOrigs) { 2634 auto *OrigVD = cast<VarDecl>(Pair.second->getDecl()); 2635 DeclRefExpr DRE( 2636 const_cast<VarDecl *>(OrigVD), 2637 /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup( 2638 OrigVD) != nullptr, 2639 Pair.second->getType(), VK_LValue, Pair.second->getExprLoc()); 2640 Scope.addPrivate(Pair.first, [&CGF, &DRE]() { 2641 return CGF.EmitLValue(&DRE).getAddress(); 2642 }); 2643 } 2644 for (auto &&Pair : PrivatePtrs) { 2645 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 2646 CGF.getContext().getDeclAlign(Pair.first)); 2647 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 2648 } 2649 } 2650 (void)Scope.Privatize(); 2651 2652 Action.Enter(CGF); 2653 BodyGen(CGF); 2654 }; 2655 auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 2656 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied, 2657 Data.NumberOfParts); 2658 OMPLexicalScope Scope(*this, S); 2659 TaskGen(*this, OutlinedFn, Data); 2660 } 2661 2662 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 2663 // Emit outlined function for task construct. 2664 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 2665 auto CapturedStruct = GenerateCapturedStmtArgument(*CS); 2666 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 2667 const Expr *IfCond = nullptr; 2668 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 2669 if (C->getNameModifier() == OMPD_unknown || 2670 C->getNameModifier() == OMPD_task) { 2671 IfCond = C->getCondition(); 2672 break; 2673 } 2674 } 2675 2676 OMPTaskDataTy Data; 2677 // Check if we should emit tied or untied task. 2678 Data.Tied = !S.getSingleClause<OMPUntiedClause>(); 2679 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) { 2680 CGF.EmitStmt(CS->getCapturedStmt()); 2681 }; 2682 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 2683 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn, 2684 const OMPTaskDataTy &Data) { 2685 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn, 2686 SharedsTy, CapturedStruct, IfCond, 2687 Data); 2688 }; 2689 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data); 2690 } 2691 2692 void CodeGenFunction::EmitOMPTaskyieldDirective( 2693 const OMPTaskyieldDirective &S) { 2694 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart()); 2695 } 2696 2697 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 2698 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier); 2699 } 2700 2701 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 2702 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart()); 2703 } 2704 2705 void CodeGenFunction::EmitOMPTaskgroupDirective( 2706 const OMPTaskgroupDirective &S) { 2707 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2708 Action.Enter(CGF); 2709 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 2710 }; 2711 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2712 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart()); 2713 } 2714 2715 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 2716 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> { 2717 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) { 2718 return llvm::makeArrayRef(FlushClause->varlist_begin(), 2719 FlushClause->varlist_end()); 2720 } 2721 return llvm::None; 2722 }(), S.getLocStart()); 2723 } 2724 2725 void CodeGenFunction::EmitOMPDistributeLoop(const OMPDistributeDirective &S) { 2726 // Emit the loop iteration variable. 2727 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 2728 auto IVDecl = cast<VarDecl>(IVExpr->getDecl()); 2729 EmitVarDecl(*IVDecl); 2730 2731 // Emit the iterations count variable. 2732 // If it is not a variable, Sema decided to calculate iterations count on each 2733 // iteration (e.g., it is foldable into a constant). 2734 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2735 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2736 // Emit calculation of the iterations count. 2737 EmitIgnoredExpr(S.getCalcLastIteration()); 2738 } 2739 2740 auto &RT = CGM.getOpenMPRuntime(); 2741 2742 // Check pre-condition. 2743 { 2744 OMPLoopScope PreInitScope(*this, S); 2745 // Skip the entire loop if we don't meet the precondition. 2746 // If the condition constant folds and can be elided, avoid emitting the 2747 // whole loop. 2748 bool CondConstant; 2749 llvm::BasicBlock *ContBlock = nullptr; 2750 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2751 if (!CondConstant) 2752 return; 2753 } else { 2754 auto *ThenBlock = createBasicBlock("omp.precond.then"); 2755 ContBlock = createBasicBlock("omp.precond.end"); 2756 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 2757 getProfileCount(&S)); 2758 EmitBlock(ThenBlock); 2759 incrementProfileCounter(&S); 2760 } 2761 2762 // Emit 'then' code. 2763 { 2764 // Emit helper vars inits. 2765 LValue LB = 2766 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable())); 2767 LValue UB = 2768 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable())); 2769 LValue ST = 2770 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 2771 LValue IL = 2772 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 2773 2774 OMPPrivateScope LoopScope(*this); 2775 EmitOMPPrivateLoopCounters(S, LoopScope); 2776 (void)LoopScope.Privatize(); 2777 2778 // Detect the distribute schedule kind and chunk. 2779 llvm::Value *Chunk = nullptr; 2780 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown; 2781 if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) { 2782 ScheduleKind = C->getDistScheduleKind(); 2783 if (const auto *Ch = C->getChunkSize()) { 2784 Chunk = EmitScalarExpr(Ch); 2785 Chunk = EmitScalarConversion(Chunk, Ch->getType(), 2786 S.getIterationVariable()->getType(), 2787 S.getLocStart()); 2788 } 2789 } 2790 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2791 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2792 2793 // OpenMP [2.10.8, distribute Construct, Description] 2794 // If dist_schedule is specified, kind must be static. If specified, 2795 // iterations are divided into chunks of size chunk_size, chunks are 2796 // assigned to the teams of the league in a round-robin fashion in the 2797 // order of the team number. When no chunk_size is specified, the 2798 // iteration space is divided into chunks that are approximately equal 2799 // in size, and at most one chunk is distributed to each team of the 2800 // league. The size of the chunks is unspecified in this case. 2801 if (RT.isStaticNonchunked(ScheduleKind, 2802 /* Chunked */ Chunk != nullptr)) { 2803 RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, 2804 IVSize, IVSigned, /* Ordered = */ false, 2805 IL.getAddress(), LB.getAddress(), 2806 UB.getAddress(), ST.getAddress()); 2807 auto LoopExit = 2808 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 2809 // UB = min(UB, GlobalUB); 2810 EmitIgnoredExpr(S.getEnsureUpperBound()); 2811 // IV = LB; 2812 EmitIgnoredExpr(S.getInit()); 2813 // while (idx <= UB) { BODY; ++idx; } 2814 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), 2815 S.getInc(), 2816 [&S, LoopExit](CodeGenFunction &CGF) { 2817 CGF.EmitOMPLoopBody(S, LoopExit); 2818 CGF.EmitStopPoint(&S); 2819 }, 2820 [](CodeGenFunction &) {}); 2821 EmitBlock(LoopExit.getBlock()); 2822 // Tell the runtime we are done. 2823 RT.emitForStaticFinish(*this, S.getLocStart()); 2824 } else { 2825 // Emit the outer loop, which requests its work chunk [LB..UB] from 2826 // runtime and runs the inner loop to process it. 2827 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, 2828 LB.getAddress(), UB.getAddress(), ST.getAddress(), 2829 IL.getAddress(), Chunk); 2830 } 2831 } 2832 2833 // We're now done with the loop, so jump to the continuation block. 2834 if (ContBlock) { 2835 EmitBranch(ContBlock); 2836 EmitBlock(ContBlock, true); 2837 } 2838 } 2839 } 2840 2841 void CodeGenFunction::EmitOMPDistributeDirective( 2842 const OMPDistributeDirective &S) { 2843 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2844 CGF.EmitOMPDistributeLoop(S); 2845 }; 2846 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2847 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen, 2848 false); 2849 } 2850 2851 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM, 2852 const CapturedStmt *S) { 2853 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); 2854 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo; 2855 CGF.CapturedStmtInfo = &CapStmtInfo; 2856 auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S); 2857 Fn->addFnAttr(llvm::Attribute::NoInline); 2858 return Fn; 2859 } 2860 2861 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 2862 if (!S.getAssociatedStmt()) { 2863 for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) 2864 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC); 2865 return; 2866 } 2867 auto *C = S.getSingleClause<OMPSIMDClause>(); 2868 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF, 2869 PrePostActionTy &Action) { 2870 if (C) { 2871 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 2872 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 2873 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 2874 auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS); 2875 CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars); 2876 } else { 2877 Action.Enter(CGF); 2878 CGF.EmitStmt( 2879 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 2880 } 2881 }; 2882 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 2883 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C); 2884 } 2885 2886 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 2887 QualType SrcType, QualType DestType, 2888 SourceLocation Loc) { 2889 assert(CGF.hasScalarEvaluationKind(DestType) && 2890 "DestType must have scalar evaluation kind."); 2891 assert(!Val.isAggregate() && "Must be a scalar or complex."); 2892 return Val.isScalar() 2893 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType, 2894 Loc) 2895 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType, 2896 DestType, Loc); 2897 } 2898 2899 static CodeGenFunction::ComplexPairTy 2900 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 2901 QualType DestType, SourceLocation Loc) { 2902 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 2903 "DestType must have complex evaluation kind."); 2904 CodeGenFunction::ComplexPairTy ComplexVal; 2905 if (Val.isScalar()) { 2906 // Convert the input element to the element type of the complex. 2907 auto DestElementType = DestType->castAs<ComplexType>()->getElementType(); 2908 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, 2909 DestElementType, Loc); 2910 ComplexVal = CodeGenFunction::ComplexPairTy( 2911 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 2912 } else { 2913 assert(Val.isComplex() && "Must be a scalar or complex."); 2914 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 2915 auto DestElementType = DestType->castAs<ComplexType>()->getElementType(); 2916 ComplexVal.first = CGF.EmitScalarConversion( 2917 Val.getComplexVal().first, SrcElementType, DestElementType, Loc); 2918 ComplexVal.second = CGF.EmitScalarConversion( 2919 Val.getComplexVal().second, SrcElementType, DestElementType, Loc); 2920 } 2921 return ComplexVal; 2922 } 2923 2924 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst, 2925 LValue LVal, RValue RVal) { 2926 if (LVal.isGlobalReg()) { 2927 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 2928 } else { 2929 CGF.EmitAtomicStore(RVal, LVal, 2930 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent 2931 : llvm::AtomicOrdering::Monotonic, 2932 LVal.isVolatile(), /*IsInit=*/false); 2933 } 2934 } 2935 2936 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal, 2937 QualType RValTy, SourceLocation Loc) { 2938 switch (getEvaluationKind(LVal.getType())) { 2939 case TEK_Scalar: 2940 EmitStoreThroughLValue(RValue::get(convertToScalarValue( 2941 *this, RVal, RValTy, LVal.getType(), Loc)), 2942 LVal); 2943 break; 2944 case TEK_Complex: 2945 EmitStoreOfComplex( 2946 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal, 2947 /*isInit=*/false); 2948 break; 2949 case TEK_Aggregate: 2950 llvm_unreachable("Must be a scalar or complex."); 2951 } 2952 } 2953 2954 static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst, 2955 const Expr *X, const Expr *V, 2956 SourceLocation Loc) { 2957 // v = x; 2958 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 2959 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 2960 LValue XLValue = CGF.EmitLValue(X); 2961 LValue VLValue = CGF.EmitLValue(V); 2962 RValue Res = XLValue.isGlobalReg() 2963 ? CGF.EmitLoadOfLValue(XLValue, Loc) 2964 : CGF.EmitAtomicLoad( 2965 XLValue, Loc, 2966 IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent 2967 : llvm::AtomicOrdering::Monotonic, 2968 XLValue.isVolatile()); 2969 // OpenMP, 2.12.6, atomic Construct 2970 // Any atomic construct with a seq_cst clause forces the atomically 2971 // performed operation to include an implicit flush operation without a 2972 // list. 2973 if (IsSeqCst) 2974 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 2975 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc); 2976 } 2977 2978 static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst, 2979 const Expr *X, const Expr *E, 2980 SourceLocation Loc) { 2981 // x = expr; 2982 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 2983 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 2984 // OpenMP, 2.12.6, atomic Construct 2985 // Any atomic construct with a seq_cst clause forces the atomically 2986 // performed operation to include an implicit flush operation without a 2987 // list. 2988 if (IsSeqCst) 2989 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 2990 } 2991 2992 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 2993 RValue Update, 2994 BinaryOperatorKind BO, 2995 llvm::AtomicOrdering AO, 2996 bool IsXLHSInRHSPart) { 2997 auto &Context = CGF.CGM.getContext(); 2998 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 2999 // expression is simple and atomic is allowed for the given type for the 3000 // target platform. 3001 if (BO == BO_Comma || !Update.isScalar() || 3002 !Update.getScalarVal()->getType()->isIntegerTy() || 3003 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 3004 (Update.getScalarVal()->getType() != 3005 X.getAddress().getElementType())) || 3006 !X.getAddress().getElementType()->isIntegerTy() || 3007 !Context.getTargetInfo().hasBuiltinAtomic( 3008 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 3009 return std::make_pair(false, RValue::get(nullptr)); 3010 3011 llvm::AtomicRMWInst::BinOp RMWOp; 3012 switch (BO) { 3013 case BO_Add: 3014 RMWOp = llvm::AtomicRMWInst::Add; 3015 break; 3016 case BO_Sub: 3017 if (!IsXLHSInRHSPart) 3018 return std::make_pair(false, RValue::get(nullptr)); 3019 RMWOp = llvm::AtomicRMWInst::Sub; 3020 break; 3021 case BO_And: 3022 RMWOp = llvm::AtomicRMWInst::And; 3023 break; 3024 case BO_Or: 3025 RMWOp = llvm::AtomicRMWInst::Or; 3026 break; 3027 case BO_Xor: 3028 RMWOp = llvm::AtomicRMWInst::Xor; 3029 break; 3030 case BO_LT: 3031 RMWOp = X.getType()->hasSignedIntegerRepresentation() 3032 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 3033 : llvm::AtomicRMWInst::Max) 3034 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 3035 : llvm::AtomicRMWInst::UMax); 3036 break; 3037 case BO_GT: 3038 RMWOp = X.getType()->hasSignedIntegerRepresentation() 3039 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 3040 : llvm::AtomicRMWInst::Min) 3041 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 3042 : llvm::AtomicRMWInst::UMin); 3043 break; 3044 case BO_Assign: 3045 RMWOp = llvm::AtomicRMWInst::Xchg; 3046 break; 3047 case BO_Mul: 3048 case BO_Div: 3049 case BO_Rem: 3050 case BO_Shl: 3051 case BO_Shr: 3052 case BO_LAnd: 3053 case BO_LOr: 3054 return std::make_pair(false, RValue::get(nullptr)); 3055 case BO_PtrMemD: 3056 case BO_PtrMemI: 3057 case BO_LE: 3058 case BO_GE: 3059 case BO_EQ: 3060 case BO_NE: 3061 case BO_AddAssign: 3062 case BO_SubAssign: 3063 case BO_AndAssign: 3064 case BO_OrAssign: 3065 case BO_XorAssign: 3066 case BO_MulAssign: 3067 case BO_DivAssign: 3068 case BO_RemAssign: 3069 case BO_ShlAssign: 3070 case BO_ShrAssign: 3071 case BO_Comma: 3072 llvm_unreachable("Unsupported atomic update operation"); 3073 } 3074 auto *UpdateVal = Update.getScalarVal(); 3075 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 3076 UpdateVal = CGF.Builder.CreateIntCast( 3077 IC, X.getAddress().getElementType(), 3078 X.getType()->hasSignedIntegerRepresentation()); 3079 } 3080 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO); 3081 return std::make_pair(true, RValue::get(Res)); 3082 } 3083 3084 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 3085 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 3086 llvm::AtomicOrdering AO, SourceLocation Loc, 3087 const llvm::function_ref<RValue(RValue)> &CommonGen) { 3088 // Update expressions are allowed to have the following forms: 3089 // x binop= expr; -> xrval + expr; 3090 // x++, ++x -> xrval + 1; 3091 // x--, --x -> xrval - 1; 3092 // x = x binop expr; -> xrval binop expr 3093 // x = expr Op x; - > expr binop xrval; 3094 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 3095 if (!Res.first) { 3096 if (X.isGlobalReg()) { 3097 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 3098 // 'xrval'. 3099 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 3100 } else { 3101 // Perform compare-and-swap procedure. 3102 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 3103 } 3104 } 3105 return Res; 3106 } 3107 3108 static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst, 3109 const Expr *X, const Expr *E, 3110 const Expr *UE, bool IsXLHSInRHSPart, 3111 SourceLocation Loc) { 3112 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 3113 "Update expr in 'atomic update' must be a binary operator."); 3114 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 3115 // Update expressions are allowed to have the following forms: 3116 // x binop= expr; -> xrval + expr; 3117 // x++, ++x -> xrval + 1; 3118 // x--, --x -> xrval - 1; 3119 // x = x binop expr; -> xrval binop expr 3120 // x = expr Op x; - > expr binop xrval; 3121 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 3122 LValue XLValue = CGF.EmitLValue(X); 3123 RValue ExprRValue = CGF.EmitAnyExpr(E); 3124 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent 3125 : llvm::AtomicOrdering::Monotonic; 3126 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 3127 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 3128 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 3129 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 3130 auto Gen = 3131 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue { 3132 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 3133 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 3134 return CGF.EmitAnyExpr(UE); 3135 }; 3136 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 3137 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 3138 // OpenMP, 2.12.6, atomic Construct 3139 // Any atomic construct with a seq_cst clause forces the atomically 3140 // performed operation to include an implicit flush operation without a 3141 // list. 3142 if (IsSeqCst) 3143 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 3144 } 3145 3146 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 3147 QualType SourceType, QualType ResType, 3148 SourceLocation Loc) { 3149 switch (CGF.getEvaluationKind(ResType)) { 3150 case TEK_Scalar: 3151 return RValue::get( 3152 convertToScalarValue(CGF, Value, SourceType, ResType, Loc)); 3153 case TEK_Complex: { 3154 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc); 3155 return RValue::getComplex(Res.first, Res.second); 3156 } 3157 case TEK_Aggregate: 3158 break; 3159 } 3160 llvm_unreachable("Must be a scalar or complex."); 3161 } 3162 3163 static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst, 3164 bool IsPostfixUpdate, const Expr *V, 3165 const Expr *X, const Expr *E, 3166 const Expr *UE, bool IsXLHSInRHSPart, 3167 SourceLocation Loc) { 3168 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 3169 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 3170 RValue NewVVal; 3171 LValue VLValue = CGF.EmitLValue(V); 3172 LValue XLValue = CGF.EmitLValue(X); 3173 RValue ExprRValue = CGF.EmitAnyExpr(E); 3174 auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent 3175 : llvm::AtomicOrdering::Monotonic; 3176 QualType NewVValType; 3177 if (UE) { 3178 // 'x' is updated with some additional value. 3179 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 3180 "Update expr in 'atomic capture' must be a binary operator."); 3181 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 3182 // Update expressions are allowed to have the following forms: 3183 // x binop= expr; -> xrval + expr; 3184 // x++, ++x -> xrval + 1; 3185 // x--, --x -> xrval - 1; 3186 // x = x binop expr; -> xrval binop expr 3187 // x = expr Op x; - > expr binop xrval; 3188 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 3189 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 3190 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 3191 NewVValType = XRValExpr->getType(); 3192 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 3193 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 3194 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue { 3195 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 3196 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 3197 RValue Res = CGF.EmitAnyExpr(UE); 3198 NewVVal = IsPostfixUpdate ? XRValue : Res; 3199 return Res; 3200 }; 3201 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 3202 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 3203 if (Res.first) { 3204 // 'atomicrmw' instruction was generated. 3205 if (IsPostfixUpdate) { 3206 // Use old value from 'atomicrmw'. 3207 NewVVal = Res.second; 3208 } else { 3209 // 'atomicrmw' does not provide new value, so evaluate it using old 3210 // value of 'x'. 3211 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 3212 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 3213 NewVVal = CGF.EmitAnyExpr(UE); 3214 } 3215 } 3216 } else { 3217 // 'x' is simply rewritten with some 'expr'. 3218 NewVValType = X->getType().getNonReferenceType(); 3219 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 3220 X->getType().getNonReferenceType(), Loc); 3221 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue { 3222 NewVVal = XRValue; 3223 return ExprRValue; 3224 }; 3225 // Try to perform atomicrmw xchg, otherwise simple exchange. 3226 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 3227 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 3228 Loc, Gen); 3229 if (Res.first) { 3230 // 'atomicrmw' instruction was generated. 3231 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 3232 } 3233 } 3234 // Emit post-update store to 'v' of old/new 'x' value. 3235 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc); 3236 // OpenMP, 2.12.6, atomic Construct 3237 // Any atomic construct with a seq_cst clause forces the atomically 3238 // performed operation to include an implicit flush operation without a 3239 // list. 3240 if (IsSeqCst) 3241 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 3242 } 3243 3244 static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 3245 bool IsSeqCst, bool IsPostfixUpdate, 3246 const Expr *X, const Expr *V, const Expr *E, 3247 const Expr *UE, bool IsXLHSInRHSPart, 3248 SourceLocation Loc) { 3249 switch (Kind) { 3250 case OMPC_read: 3251 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc); 3252 break; 3253 case OMPC_write: 3254 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc); 3255 break; 3256 case OMPC_unknown: 3257 case OMPC_update: 3258 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc); 3259 break; 3260 case OMPC_capture: 3261 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE, 3262 IsXLHSInRHSPart, Loc); 3263 break; 3264 case OMPC_if: 3265 case OMPC_final: 3266 case OMPC_num_threads: 3267 case OMPC_private: 3268 case OMPC_firstprivate: 3269 case OMPC_lastprivate: 3270 case OMPC_reduction: 3271 case OMPC_safelen: 3272 case OMPC_simdlen: 3273 case OMPC_collapse: 3274 case OMPC_default: 3275 case OMPC_seq_cst: 3276 case OMPC_shared: 3277 case OMPC_linear: 3278 case OMPC_aligned: 3279 case OMPC_copyin: 3280 case OMPC_copyprivate: 3281 case OMPC_flush: 3282 case OMPC_proc_bind: 3283 case OMPC_schedule: 3284 case OMPC_ordered: 3285 case OMPC_nowait: 3286 case OMPC_untied: 3287 case OMPC_threadprivate: 3288 case OMPC_depend: 3289 case OMPC_mergeable: 3290 case OMPC_device: 3291 case OMPC_threads: 3292 case OMPC_simd: 3293 case OMPC_map: 3294 case OMPC_num_teams: 3295 case OMPC_thread_limit: 3296 case OMPC_priority: 3297 case OMPC_grainsize: 3298 case OMPC_nogroup: 3299 case OMPC_num_tasks: 3300 case OMPC_hint: 3301 case OMPC_dist_schedule: 3302 case OMPC_defaultmap: 3303 case OMPC_uniform: 3304 case OMPC_to: 3305 case OMPC_from: 3306 case OMPC_use_device_ptr: 3307 case OMPC_is_device_ptr: 3308 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 3309 } 3310 } 3311 3312 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 3313 bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>(); 3314 OpenMPClauseKind Kind = OMPC_unknown; 3315 for (auto *C : S.clauses()) { 3316 // Find first clause (skip seq_cst clause, if it is first). 3317 if (C->getClauseKind() != OMPC_seq_cst) { 3318 Kind = C->getClauseKind(); 3319 break; 3320 } 3321 } 3322 3323 const auto *CS = 3324 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true); 3325 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) { 3326 enterFullExpression(EWC); 3327 } 3328 // Processing for statements under 'atomic capture'. 3329 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) { 3330 for (const auto *C : Compound->body()) { 3331 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) { 3332 enterFullExpression(EWC); 3333 } 3334 } 3335 } 3336 3337 auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF, 3338 PrePostActionTy &) { 3339 CGF.EmitStopPoint(CS); 3340 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(), 3341 S.getV(), S.getExpr(), S.getUpdateExpr(), 3342 S.isXLHSInRHSPart(), S.getLocStart()); 3343 }; 3344 OMPLexicalScope Scope(*this, S, /*AsInlined=*/true); 3345 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen); 3346 } 3347 3348 std::pair<llvm::Function * /*OutlinedFn*/, llvm::Constant * /*OutlinedFnID*/> 3349 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction( 3350 CodeGenModule &CGM, const OMPTargetDirective &S, StringRef ParentName, 3351 bool IsOffloadEntry) { 3352 llvm::Function *OutlinedFn = nullptr; 3353 llvm::Constant *OutlinedFnID = nullptr; 3354 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3355 OMPPrivateScope PrivateScope(CGF); 3356 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 3357 CGF.EmitOMPPrivateClause(S, PrivateScope); 3358 (void)PrivateScope.Privatize(); 3359 3360 Action.Enter(CGF); 3361 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 3362 }; 3363 // Emit target region as a standalone region. 3364 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 3365 S, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen); 3366 return std::make_pair(OutlinedFn, OutlinedFnID); 3367 } 3368 3369 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) { 3370 const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt()); 3371 3372 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 3373 GenerateOpenMPCapturedVars(CS, CapturedVars); 3374 3375 llvm::Function *Fn = nullptr; 3376 llvm::Constant *FnID = nullptr; 3377 3378 // Check if we have any if clause associated with the directive. 3379 const Expr *IfCond = nullptr; 3380 3381 if (auto *C = S.getSingleClause<OMPIfClause>()) { 3382 IfCond = C->getCondition(); 3383 } 3384 3385 // Check if we have any device clause associated with the directive. 3386 const Expr *Device = nullptr; 3387 if (auto *C = S.getSingleClause<OMPDeviceClause>()) { 3388 Device = C->getDevice(); 3389 } 3390 3391 // Check if we have an if clause whose conditional always evaluates to false 3392 // or if we do not have any targets specified. If so the target region is not 3393 // an offload entry point. 3394 bool IsOffloadEntry = true; 3395 if (IfCond) { 3396 bool Val; 3397 if (ConstantFoldsToSimpleInteger(IfCond, Val) && !Val) 3398 IsOffloadEntry = false; 3399 } 3400 if (CGM.getLangOpts().OMPTargetTriples.empty()) 3401 IsOffloadEntry = false; 3402 3403 assert(CurFuncDecl && "No parent declaration for target region!"); 3404 StringRef ParentName; 3405 // In case we have Ctors/Dtors we use the complete type variant to produce 3406 // the mangling of the device outlined kernel. 3407 if (auto *D = dyn_cast<CXXConstructorDecl>(CurFuncDecl)) 3408 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete)); 3409 else if (auto *D = dyn_cast<CXXDestructorDecl>(CurFuncDecl)) 3410 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete)); 3411 else 3412 ParentName = 3413 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CurFuncDecl))); 3414 3415 std::tie(Fn, FnID) = EmitOMPTargetDirectiveOutlinedFunction( 3416 CGM, S, ParentName, IsOffloadEntry); 3417 OMPLexicalScope Scope(*this, S); 3418 CGM.getOpenMPRuntime().emitTargetCall(*this, S, Fn, FnID, IfCond, Device, 3419 CapturedVars); 3420 } 3421 3422 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, 3423 const OMPExecutableDirective &S, 3424 OpenMPDirectiveKind InnermostKind, 3425 const RegionCodeGenTy &CodeGen) { 3426 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 3427 auto OutlinedFn = CGF.CGM.getOpenMPRuntime(). 3428 emitParallelOrTeamsOutlinedFunction(S, 3429 *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 3430 3431 const OMPTeamsDirective &TD = *dyn_cast<OMPTeamsDirective>(&S); 3432 const OMPNumTeamsClause *NT = TD.getSingleClause<OMPNumTeamsClause>(); 3433 const OMPThreadLimitClause *TL = TD.getSingleClause<OMPThreadLimitClause>(); 3434 if (NT || TL) { 3435 Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr; 3436 Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr; 3437 3438 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit, 3439 S.getLocStart()); 3440 } 3441 3442 OMPLexicalScope Scope(CGF, S); 3443 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 3444 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 3445 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn, 3446 CapturedVars); 3447 } 3448 3449 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) { 3450 // Emit teams region as a standalone region. 3451 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3452 OMPPrivateScope PrivateScope(CGF); 3453 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 3454 CGF.EmitOMPPrivateClause(S, PrivateScope); 3455 (void)PrivateScope.Privatize(); 3456 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 3457 }; 3458 emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen); 3459 } 3460 3461 void CodeGenFunction::EmitOMPCancellationPointDirective( 3462 const OMPCancellationPointDirective &S) { 3463 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(), 3464 S.getCancelRegion()); 3465 } 3466 3467 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) { 3468 const Expr *IfCond = nullptr; 3469 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 3470 if (C->getNameModifier() == OMPD_unknown || 3471 C->getNameModifier() == OMPD_cancel) { 3472 IfCond = C->getCondition(); 3473 break; 3474 } 3475 } 3476 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond, 3477 S.getCancelRegion()); 3478 } 3479 3480 CodeGenFunction::JumpDest 3481 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) { 3482 if (Kind == OMPD_parallel || Kind == OMPD_task || 3483 Kind == OMPD_target_parallel) 3484 return ReturnBlock; 3485 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections || 3486 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for || 3487 Kind == OMPD_distribute_parallel_for || 3488 Kind == OMPD_target_parallel_for); 3489 return OMPCancelStack.getExitBlock(); 3490 } 3491 3492 void CodeGenFunction::EmitOMPUseDevicePtrClause( 3493 const OMPClause &NC, OMPPrivateScope &PrivateScope, 3494 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 3495 const auto &C = cast<OMPUseDevicePtrClause>(NC); 3496 auto OrigVarIt = C.varlist_begin(); 3497 auto InitIt = C.inits().begin(); 3498 for (auto PvtVarIt : C.private_copies()) { 3499 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl()); 3500 auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl()); 3501 auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl()); 3502 3503 // In order to identify the right initializer we need to match the 3504 // declaration used by the mapping logic. In some cases we may get 3505 // OMPCapturedExprDecl that refers to the original declaration. 3506 const ValueDecl *MatchingVD = OrigVD; 3507 if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 3508 // OMPCapturedExprDecl are used to privative fields of the current 3509 // structure. 3510 auto *ME = cast<MemberExpr>(OED->getInit()); 3511 assert(isa<CXXThisExpr>(ME->getBase()) && 3512 "Base should be the current struct!"); 3513 MatchingVD = ME->getMemberDecl(); 3514 } 3515 3516 // If we don't have information about the current list item, move on to 3517 // the next one. 3518 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 3519 if (InitAddrIt == CaptureDeviceAddrMap.end()) 3520 continue; 3521 3522 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address { 3523 // Initialize the temporary initialization variable with the address we 3524 // get from the runtime library. We have to cast the source address 3525 // because it is always a void *. References are materialized in the 3526 // privatization scope, so the initialization here disregards the fact 3527 // the original variable is a reference. 3528 QualType AddrQTy = 3529 getContext().getPointerType(OrigVD->getType().getNonReferenceType()); 3530 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy); 3531 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy); 3532 setAddrOfLocalVar(InitVD, InitAddr); 3533 3534 // Emit private declaration, it will be initialized by the value we 3535 // declaration we just added to the local declarations map. 3536 EmitDecl(*PvtVD); 3537 3538 // The initialization variables reached its purpose in the emission 3539 // ofthe previous declaration, so we don't need it anymore. 3540 LocalDeclMap.erase(InitVD); 3541 3542 // Return the address of the private variable. 3543 return GetAddrOfLocalVar(PvtVD); 3544 }); 3545 assert(IsRegistered && "firstprivate var already registered as private"); 3546 // Silence the warning about unused variable. 3547 (void)IsRegistered; 3548 3549 ++OrigVarIt; 3550 ++InitIt; 3551 } 3552 } 3553 3554 // Generate the instructions for '#pragma omp target data' directive. 3555 void CodeGenFunction::EmitOMPTargetDataDirective( 3556 const OMPTargetDataDirective &S) { 3557 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true); 3558 3559 // Create a pre/post action to signal the privatization of the device pointer. 3560 // This action can be replaced by the OpenMP runtime code generation to 3561 // deactivate privatization. 3562 bool PrivatizeDevicePointers = false; 3563 class DevicePointerPrivActionTy : public PrePostActionTy { 3564 bool &PrivatizeDevicePointers; 3565 3566 public: 3567 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers) 3568 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {} 3569 void Enter(CodeGenFunction &CGF) override { 3570 PrivatizeDevicePointers = true; 3571 } 3572 }; 3573 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers); 3574 3575 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers]( 3576 CodeGenFunction &CGF, PrePostActionTy &Action) { 3577 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3578 CGF.EmitStmt( 3579 cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 3580 }; 3581 3582 // Codegen that selects wheather to generate the privatization code or not. 3583 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers, 3584 &InnermostCodeGen](CodeGenFunction &CGF, 3585 PrePostActionTy &Action) { 3586 RegionCodeGenTy RCG(InnermostCodeGen); 3587 PrivatizeDevicePointers = false; 3588 3589 // Call the pre-action to change the status of PrivatizeDevicePointers if 3590 // needed. 3591 Action.Enter(CGF); 3592 3593 if (PrivatizeDevicePointers) { 3594 OMPPrivateScope PrivateScope(CGF); 3595 // Emit all instances of the use_device_ptr clause. 3596 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>()) 3597 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope, 3598 Info.CaptureDeviceAddrMap); 3599 (void)PrivateScope.Privatize(); 3600 RCG(CGF); 3601 } else 3602 RCG(CGF); 3603 }; 3604 3605 // Forward the provided action to the privatization codegen. 3606 RegionCodeGenTy PrivRCG(PrivCodeGen); 3607 PrivRCG.setAction(Action); 3608 3609 // Notwithstanding the body of the region is emitted as inlined directive, 3610 // we don't use an inline scope as changes in the references inside the 3611 // region are expected to be visible outside, so we do not privative them. 3612 OMPLexicalScope Scope(CGF, S); 3613 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, 3614 PrivRCG); 3615 }; 3616 3617 RegionCodeGenTy RCG(CodeGen); 3618 3619 // If we don't have target devices, don't bother emitting the data mapping 3620 // code. 3621 if (CGM.getLangOpts().OMPTargetTriples.empty()) { 3622 RCG(*this); 3623 return; 3624 } 3625 3626 // Check if we have any if clause associated with the directive. 3627 const Expr *IfCond = nullptr; 3628 if (auto *C = S.getSingleClause<OMPIfClause>()) 3629 IfCond = C->getCondition(); 3630 3631 // Check if we have any device clause associated with the directive. 3632 const Expr *Device = nullptr; 3633 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 3634 Device = C->getDevice(); 3635 3636 // Set the action to signal privatization of device pointers. 3637 RCG.setAction(PrivAction); 3638 3639 // Emit region code. 3640 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG, 3641 Info); 3642 } 3643 3644 void CodeGenFunction::EmitOMPTargetEnterDataDirective( 3645 const OMPTargetEnterDataDirective &S) { 3646 // If we don't have target devices, don't bother emitting the data mapping 3647 // code. 3648 if (CGM.getLangOpts().OMPTargetTriples.empty()) 3649 return; 3650 3651 // Check if we have any if clause associated with the directive. 3652 const Expr *IfCond = nullptr; 3653 if (auto *C = S.getSingleClause<OMPIfClause>()) 3654 IfCond = C->getCondition(); 3655 3656 // Check if we have any device clause associated with the directive. 3657 const Expr *Device = nullptr; 3658 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 3659 Device = C->getDevice(); 3660 3661 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 3662 } 3663 3664 void CodeGenFunction::EmitOMPTargetExitDataDirective( 3665 const OMPTargetExitDataDirective &S) { 3666 // If we don't have target devices, don't bother emitting the data mapping 3667 // code. 3668 if (CGM.getLangOpts().OMPTargetTriples.empty()) 3669 return; 3670 3671 // Check if we have any if clause associated with the directive. 3672 const Expr *IfCond = nullptr; 3673 if (auto *C = S.getSingleClause<OMPIfClause>()) 3674 IfCond = C->getCondition(); 3675 3676 // Check if we have any device clause associated with the directive. 3677 const Expr *Device = nullptr; 3678 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 3679 Device = C->getDevice(); 3680 3681 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 3682 } 3683 3684 void CodeGenFunction::EmitOMPTargetParallelDirective( 3685 const OMPTargetParallelDirective &S) { 3686 // TODO: codegen for target parallel. 3687 } 3688 3689 void CodeGenFunction::EmitOMPTargetParallelForDirective( 3690 const OMPTargetParallelForDirective &S) { 3691 // TODO: codegen for target parallel for. 3692 } 3693 3694 /// Emit a helper variable and return corresponding lvalue. 3695 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, 3696 const ImplicitParamDecl *PVD, 3697 CodeGenFunction::OMPPrivateScope &Privates) { 3698 auto *VDecl = cast<VarDecl>(Helper->getDecl()); 3699 Privates.addPrivate( 3700 VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); }); 3701 } 3702 3703 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) { 3704 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind())); 3705 // Emit outlined function for task construct. 3706 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 3707 auto CapturedStruct = GenerateCapturedStmtArgument(*CS); 3708 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 3709 const Expr *IfCond = nullptr; 3710 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 3711 if (C->getNameModifier() == OMPD_unknown || 3712 C->getNameModifier() == OMPD_taskloop) { 3713 IfCond = C->getCondition(); 3714 break; 3715 } 3716 } 3717 3718 OMPTaskDataTy Data; 3719 // Check if taskloop must be emitted without taskgroup. 3720 Data.Nogroup = S.getSingleClause<OMPNogroupClause>(); 3721 // TODO: Check if we should emit tied or untied task. 3722 Data.Tied = true; 3723 // Set scheduling for taskloop 3724 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) { 3725 // grainsize clause 3726 Data.Schedule.setInt(/*IntVal=*/false); 3727 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize())); 3728 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) { 3729 // num_tasks clause 3730 Data.Schedule.setInt(/*IntVal=*/true); 3731 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks())); 3732 } 3733 3734 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) { 3735 // if (PreCond) { 3736 // for (IV in 0..LastIteration) BODY; 3737 // <Final counter/linear vars updates>; 3738 // } 3739 // 3740 3741 // Emit: if (PreCond) - begin. 3742 // If the condition constant folds and can be elided, avoid emitting the 3743 // whole loop. 3744 bool CondConstant; 3745 llvm::BasicBlock *ContBlock = nullptr; 3746 OMPLoopScope PreInitScope(CGF, S); 3747 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 3748 if (!CondConstant) 3749 return; 3750 } else { 3751 auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then"); 3752 ContBlock = CGF.createBasicBlock("taskloop.if.end"); 3753 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 3754 CGF.getProfileCount(&S)); 3755 CGF.EmitBlock(ThenBlock); 3756 CGF.incrementProfileCounter(&S); 3757 } 3758 3759 if (isOpenMPSimdDirective(S.getDirectiveKind())) 3760 CGF.EmitOMPSimdInit(S); 3761 3762 OMPPrivateScope LoopScope(CGF); 3763 // Emit helper vars inits. 3764 enum { LowerBound = 5, UpperBound, Stride, LastIter }; 3765 auto *I = CS->getCapturedDecl()->param_begin(); 3766 auto *LBP = std::next(I, LowerBound); 3767 auto *UBP = std::next(I, UpperBound); 3768 auto *STP = std::next(I, Stride); 3769 auto *LIP = std::next(I, LastIter); 3770 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP, 3771 LoopScope); 3772 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP, 3773 LoopScope); 3774 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope); 3775 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP, 3776 LoopScope); 3777 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 3778 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 3779 (void)LoopScope.Privatize(); 3780 // Emit the loop iteration variable. 3781 const Expr *IVExpr = S.getIterationVariable(); 3782 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 3783 CGF.EmitVarDecl(*IVDecl); 3784 CGF.EmitIgnoredExpr(S.getInit()); 3785 3786 // Emit the iterations count variable. 3787 // If it is not a variable, Sema decided to calculate iterations count on 3788 // each iteration (e.g., it is foldable into a constant). 3789 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 3790 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 3791 // Emit calculation of the iterations count. 3792 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 3793 } 3794 3795 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), 3796 S.getInc(), 3797 [&S](CodeGenFunction &CGF) { 3798 CGF.EmitOMPLoopBody(S, JumpDest()); 3799 CGF.EmitStopPoint(&S); 3800 }, 3801 [](CodeGenFunction &) {}); 3802 // Emit: if (PreCond) - end. 3803 if (ContBlock) { 3804 CGF.EmitBranch(ContBlock); 3805 CGF.EmitBlock(ContBlock, true); 3806 } 3807 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3808 if (HasLastprivateClause) { 3809 CGF.EmitOMPLastprivateClauseFinal( 3810 S, isOpenMPSimdDirective(S.getDirectiveKind()), 3811 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar( 3812 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 3813 (*LIP)->getType(), S.getLocStart()))); 3814 } 3815 }; 3816 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 3817 IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn, 3818 const OMPTaskDataTy &Data) { 3819 auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) { 3820 OMPLoopScope PreInitScope(CGF, S); 3821 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S, 3822 OutlinedFn, SharedsTy, 3823 CapturedStruct, IfCond, Data); 3824 }; 3825 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop, 3826 CodeGen); 3827 }; 3828 EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data); 3829 } 3830 3831 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) { 3832 EmitOMPTaskLoopBasedDirective(S); 3833 } 3834 3835 void CodeGenFunction::EmitOMPTaskLoopSimdDirective( 3836 const OMPTaskLoopSimdDirective &S) { 3837 EmitOMPTaskLoopBasedDirective(S); 3838 } 3839 3840 // Generate the instructions for '#pragma omp target update' directive. 3841 void CodeGenFunction::EmitOMPTargetUpdateDirective( 3842 const OMPTargetUpdateDirective &S) { 3843 // If we don't have target devices, don't bother emitting the data mapping 3844 // code. 3845 if (CGM.getLangOpts().OMPTargetTriples.empty()) 3846 return; 3847 3848 // Check if we have any if clause associated with the directive. 3849 const Expr *IfCond = nullptr; 3850 if (auto *C = S.getSingleClause<OMPIfClause>()) 3851 IfCond = C->getCondition(); 3852 3853 // Check if we have any device clause associated with the directive. 3854 const Expr *Device = nullptr; 3855 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 3856 Device = C->getDevice(); 3857 3858 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 3859 } 3860