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 "CGOpenMPRuntime.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "TargetInfo.h" 18 #include "clang/AST/Stmt.h" 19 #include "clang/AST/StmtOpenMP.h" 20 using namespace clang; 21 using namespace CodeGen; 22 23 //===----------------------------------------------------------------------===// 24 // OpenMP Directive Emission 25 //===----------------------------------------------------------------------===// 26 void CodeGenFunction::EmitOMPAggregateAssign( 27 llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType, 28 const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen) { 29 // Perform element-by-element initialization. 30 QualType ElementTy; 31 auto SrcBegin = SrcAddr; 32 auto DestBegin = DestAddr; 33 auto ArrayTy = OriginalType->getAsArrayTypeUnsafe(); 34 auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestBegin); 35 // Cast from pointer to array type to pointer to single element. 36 SrcBegin = Builder.CreatePointerBitCastOrAddrSpaceCast(SrcBegin, 37 DestBegin->getType()); 38 auto DestEnd = Builder.CreateGEP(DestBegin, NumElements); 39 // The basic structure here is a while-do loop. 40 auto BodyBB = createBasicBlock("omp.arraycpy.body"); 41 auto DoneBB = createBasicBlock("omp.arraycpy.done"); 42 auto IsEmpty = 43 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty"); 44 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 45 46 // Enter the loop body, making that address the current address. 47 auto EntryBB = Builder.GetInsertBlock(); 48 EmitBlock(BodyBB); 49 auto SrcElementCurrent = 50 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 51 SrcElementCurrent->addIncoming(SrcBegin, EntryBB); 52 auto DestElementCurrent = Builder.CreatePHI(DestBegin->getType(), 2, 53 "omp.arraycpy.destElementPast"); 54 DestElementCurrent->addIncoming(DestBegin, EntryBB); 55 56 // Emit copy. 57 CopyGen(DestElementCurrent, SrcElementCurrent); 58 59 // Shift the address forward by one element. 60 auto DestElementNext = Builder.CreateConstGEP1_32( 61 DestElementCurrent, /*Idx0=*/1, "omp.arraycpy.dest.element"); 62 auto SrcElementNext = Builder.CreateConstGEP1_32( 63 SrcElementCurrent, /*Idx0=*/1, "omp.arraycpy.src.element"); 64 // Check whether we've reached the end. 65 auto Done = 66 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 67 Builder.CreateCondBr(Done, DoneBB, BodyBB); 68 DestElementCurrent->addIncoming(DestElementNext, Builder.GetInsertBlock()); 69 SrcElementCurrent->addIncoming(SrcElementNext, Builder.GetInsertBlock()); 70 71 // Done. 72 EmitBlock(DoneBB, /*IsFinished=*/true); 73 } 74 75 void CodeGenFunction::EmitOMPCopy(CodeGenFunction &CGF, 76 QualType OriginalType, llvm::Value *DestAddr, 77 llvm::Value *SrcAddr, const VarDecl *DestVD, 78 const VarDecl *SrcVD, const Expr *Copy) { 79 if (OriginalType->isArrayType()) { 80 auto *BO = dyn_cast<BinaryOperator>(Copy); 81 if (BO && BO->getOpcode() == BO_Assign) { 82 // Perform simple memcpy for simple copying. 83 CGF.EmitAggregateAssign(DestAddr, SrcAddr, OriginalType); 84 } else { 85 // For arrays with complex element types perform element by element 86 // copying. 87 CGF.EmitOMPAggregateAssign( 88 DestAddr, SrcAddr, OriginalType, 89 [&CGF, Copy, SrcVD, DestVD](llvm::Value *DestElement, 90 llvm::Value *SrcElement) { 91 // Working with the single array element, so have to remap 92 // destination and source variables to corresponding array 93 // elements. 94 CodeGenFunction::OMPPrivateScope Remap(CGF); 95 Remap.addPrivate(DestVD, [DestElement]() -> llvm::Value *{ 96 return DestElement; 97 }); 98 Remap.addPrivate( 99 SrcVD, [SrcElement]() -> llvm::Value *{ return SrcElement; }); 100 (void)Remap.Privatize(); 101 CGF.EmitIgnoredExpr(Copy); 102 }); 103 } 104 } else { 105 // Remap pseudo source variable to private copy. 106 CodeGenFunction::OMPPrivateScope Remap(CGF); 107 Remap.addPrivate(SrcVD, [SrcAddr]() -> llvm::Value *{ return SrcAddr; }); 108 Remap.addPrivate(DestVD, [DestAddr]() -> llvm::Value *{ return DestAddr; }); 109 (void)Remap.Privatize(); 110 // Emit copying of the whole variable. 111 CGF.EmitIgnoredExpr(Copy); 112 } 113 } 114 115 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 116 OMPPrivateScope &PrivateScope) { 117 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate; 118 for (auto &&I = D.getClausesOfKind(OMPC_firstprivate); I; ++I) { 119 auto *C = cast<OMPFirstprivateClause>(*I); 120 auto IRef = C->varlist_begin(); 121 auto InitsRef = C->inits().begin(); 122 for (auto IInit : C->private_copies()) { 123 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 124 if (EmittedAsFirstprivate.count(OrigVD) == 0) { 125 EmittedAsFirstprivate.insert(OrigVD); 126 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 127 auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl()); 128 bool IsRegistered; 129 DeclRefExpr DRE( 130 const_cast<VarDecl *>(OrigVD), 131 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup( 132 OrigVD) != nullptr, 133 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 134 auto *OriginalAddr = EmitLValue(&DRE).getAddress(); 135 QualType Type = OrigVD->getType(); 136 if (auto *PVD = dyn_cast<ParmVarDecl>(OrigVD)) { 137 Type = PVD->getOriginalType(); 138 } 139 if (Type->isArrayType()) { 140 // Emit VarDecl with copy init for arrays. 141 // Get the address of the original variable captured in current 142 // captured region. 143 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{ 144 auto Emission = EmitAutoVarAlloca(*VD); 145 auto *Init = VD->getInit(); 146 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) { 147 // Perform simple memcpy. 148 EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr, 149 Type); 150 } else { 151 EmitOMPAggregateAssign( 152 Emission.getAllocatedAddress(), OriginalAddr, Type, 153 [this, VDInit, Init](llvm::Value *DestElement, 154 llvm::Value *SrcElement) { 155 // Clean up any temporaries needed by the initialization. 156 RunCleanupsScope InitScope(*this); 157 // Emit initialization for single element. 158 LocalDeclMap[VDInit] = SrcElement; 159 EmitAnyExprToMem(Init, DestElement, 160 Init->getType().getQualifiers(), 161 /*IsInitializer*/ false); 162 LocalDeclMap.erase(VDInit); 163 }); 164 } 165 EmitAutoVarCleanups(Emission); 166 return Emission.getAllocatedAddress(); 167 }); 168 } else { 169 IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{ 170 // Emit private VarDecl with copy init. 171 // Remap temp VDInit variable to the address of the original 172 // variable 173 // (for proper handling of captured global variables). 174 LocalDeclMap[VDInit] = OriginalAddr; 175 EmitDecl(*VD); 176 LocalDeclMap.erase(VDInit); 177 return GetAddrOfLocalVar(VD); 178 }); 179 } 180 assert(IsRegistered && 181 "firstprivate var already registered as private"); 182 // Silence the warning about unused variable. 183 (void)IsRegistered; 184 } 185 ++IRef, ++InitsRef; 186 } 187 } 188 return !EmittedAsFirstprivate.empty(); 189 } 190 191 void CodeGenFunction::EmitOMPPrivateClause( 192 const OMPExecutableDirective &D, 193 CodeGenFunction::OMPPrivateScope &PrivateScope) { 194 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 195 for (auto &&I = D.getClausesOfKind(OMPC_private); I; ++I) { 196 auto *C = cast<OMPPrivateClause>(*I); 197 auto IRef = C->varlist_begin(); 198 for (auto IInit : C->private_copies()) { 199 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 200 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 201 auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 202 bool IsRegistered = 203 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{ 204 // Emit private VarDecl with copy init. 205 EmitDecl(*VD); 206 return GetAddrOfLocalVar(VD); 207 }); 208 assert(IsRegistered && "private var already registered as private"); 209 // Silence the warning about unused variable. 210 (void)IsRegistered; 211 } 212 ++IRef; 213 } 214 } 215 } 216 217 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) { 218 // threadprivate_var1 = master_threadprivate_var1; 219 // operator=(threadprivate_var2, master_threadprivate_var2); 220 // ... 221 // __kmpc_barrier(&loc, global_tid); 222 llvm::DenseSet<const VarDecl *> CopiedVars; 223 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr; 224 for (auto &&I = D.getClausesOfKind(OMPC_copyin); I; ++I) { 225 auto *C = cast<OMPCopyinClause>(*I); 226 auto IRef = C->varlist_begin(); 227 auto ISrcRef = C->source_exprs().begin(); 228 auto IDestRef = C->destination_exprs().begin(); 229 for (auto *AssignOp : C->assignment_ops()) { 230 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 231 QualType Type = VD->getType(); 232 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) { 233 Type = PVD->getOriginalType(); 234 } 235 if (CopiedVars.insert(VD->getCanonicalDecl()).second) { 236 // Get the address of the master variable. 237 auto *MasterAddr = VD->isStaticLocal() 238 ? CGM.getStaticLocalDeclAddress(VD) 239 : CGM.GetAddrOfGlobal(VD); 240 // Get the address of the threadprivate variable. 241 auto *PrivateAddr = EmitLValue(*IRef).getAddress(); 242 if (CopiedVars.size() == 1) { 243 // At first check if current thread is a master thread. If it is, no 244 // need to copy data. 245 CopyBegin = createBasicBlock("copyin.not.master"); 246 CopyEnd = createBasicBlock("copyin.not.master.end"); 247 Builder.CreateCondBr( 248 Builder.CreateICmpNE( 249 Builder.CreatePtrToInt(MasterAddr, CGM.IntPtrTy), 250 Builder.CreatePtrToInt(PrivateAddr, CGM.IntPtrTy)), 251 CopyBegin, CopyEnd); 252 EmitBlock(CopyBegin); 253 } 254 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 255 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 256 EmitOMPCopy(*this, Type, PrivateAddr, MasterAddr, DestVD, SrcVD, 257 AssignOp); 258 } 259 ++IRef; 260 ++ISrcRef; 261 ++IDestRef; 262 } 263 } 264 if (CopyEnd) { 265 // Exit out of copying procedure for non-master thread. 266 EmitBlock(CopyEnd, /*IsFinished=*/true); 267 return true; 268 } 269 return false; 270 } 271 272 bool CodeGenFunction::EmitOMPLastprivateClauseInit( 273 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) { 274 bool HasAtLeastOneLastprivate = false; 275 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 276 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) { 277 HasAtLeastOneLastprivate = true; 278 auto *C = cast<OMPLastprivateClause>(*I); 279 auto IRef = C->varlist_begin(); 280 auto IDestRef = C->destination_exprs().begin(); 281 for (auto *IInit : C->private_copies()) { 282 // Keep the address of the original variable for future update at the end 283 // of the loop. 284 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 285 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) { 286 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 287 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> llvm::Value *{ 288 DeclRefExpr DRE( 289 const_cast<VarDecl *>(OrigVD), 290 /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup( 291 OrigVD) != nullptr, 292 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 293 return EmitLValue(&DRE).getAddress(); 294 }); 295 // Check if the variable is also a firstprivate: in this case IInit is 296 // not generated. Initialization of this variable will happen in codegen 297 // for 'firstprivate' clause. 298 if (IInit) { 299 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 300 bool IsRegistered = 301 PrivateScope.addPrivate(OrigVD, [&]() -> llvm::Value *{ 302 // Emit private VarDecl with copy init. 303 EmitDecl(*VD); 304 return GetAddrOfLocalVar(VD); 305 }); 306 assert(IsRegistered && 307 "lastprivate var already registered as private"); 308 (void)IsRegistered; 309 } 310 } 311 ++IRef, ++IDestRef; 312 } 313 } 314 return HasAtLeastOneLastprivate; 315 } 316 317 void CodeGenFunction::EmitOMPLastprivateClauseFinal( 318 const OMPExecutableDirective &D, llvm::Value *IsLastIterCond) { 319 // Emit following code: 320 // if (<IsLastIterCond>) { 321 // orig_var1 = private_orig_var1; 322 // ... 323 // orig_varn = private_orig_varn; 324 // } 325 auto *ThenBB = createBasicBlock(".omp.lastprivate.then"); 326 auto *DoneBB = createBasicBlock(".omp.lastprivate.done"); 327 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB); 328 EmitBlock(ThenBB); 329 { 330 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 331 for (auto &&I = D.getClausesOfKind(OMPC_lastprivate); I; ++I) { 332 auto *C = cast<OMPLastprivateClause>(*I); 333 auto IRef = C->varlist_begin(); 334 auto ISrcRef = C->source_exprs().begin(); 335 auto IDestRef = C->destination_exprs().begin(); 336 for (auto *AssignOp : C->assignment_ops()) { 337 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 338 QualType Type = PrivateVD->getType(); 339 if (auto *PVD = dyn_cast<ParmVarDecl>(PrivateVD)) { 340 Type = PVD->getOriginalType(); 341 } 342 if (AlreadyEmittedVars.insert(PrivateVD->getCanonicalDecl()).second) { 343 auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 344 auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 345 // Get the address of the original variable. 346 auto *OriginalAddr = GetAddrOfLocalVar(DestVD); 347 // Get the address of the private variable. 348 auto *PrivateAddr = GetAddrOfLocalVar(PrivateVD); 349 EmitOMPCopy(*this, Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, 350 AssignOp); 351 } 352 ++IRef; 353 ++ISrcRef; 354 ++IDestRef; 355 } 356 } 357 } 358 EmitBlock(DoneBB, /*IsFinished=*/true); 359 } 360 361 void CodeGenFunction::EmitOMPReductionClauseInit( 362 const OMPExecutableDirective &D, 363 CodeGenFunction::OMPPrivateScope &PrivateScope) { 364 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) { 365 auto *C = cast<OMPReductionClause>(*I); 366 auto ILHS = C->lhs_exprs().begin(); 367 auto IRHS = C->rhs_exprs().begin(); 368 for (auto IRef : C->varlists()) { 369 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 370 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 371 auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 372 // Store the address of the original variable associated with the LHS 373 // implicit variable. 374 PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef]() -> llvm::Value *{ 375 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 376 CapturedStmtInfo->lookup(OrigVD) != nullptr, 377 IRef->getType(), VK_LValue, IRef->getExprLoc()); 378 return EmitLValue(&DRE).getAddress(); 379 }); 380 // Emit reduction copy. 381 bool IsRegistered = 382 PrivateScope.addPrivate(OrigVD, [this, PrivateVD]() -> llvm::Value *{ 383 // Emit private VarDecl with reduction init. 384 EmitDecl(*PrivateVD); 385 return GetAddrOfLocalVar(PrivateVD); 386 }); 387 assert(IsRegistered && "private var already registered as private"); 388 // Silence the warning about unused variable. 389 (void)IsRegistered; 390 ++ILHS, ++IRHS; 391 } 392 } 393 } 394 395 void CodeGenFunction::EmitOMPReductionClauseFinal( 396 const OMPExecutableDirective &D) { 397 llvm::SmallVector<const Expr *, 8> LHSExprs; 398 llvm::SmallVector<const Expr *, 8> RHSExprs; 399 llvm::SmallVector<const Expr *, 8> ReductionOps; 400 bool HasAtLeastOneReduction = false; 401 for (auto &&I = D.getClausesOfKind(OMPC_reduction); I; ++I) { 402 HasAtLeastOneReduction = true; 403 auto *C = cast<OMPReductionClause>(*I); 404 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 405 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 406 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 407 } 408 if (HasAtLeastOneReduction) { 409 // Emit nowait reduction if nowait clause is present or directive is a 410 // parallel directive (it always has implicit barrier). 411 CGM.getOpenMPRuntime().emitReduction( 412 *this, D.getLocEnd(), LHSExprs, RHSExprs, ReductionOps, 413 D.getSingleClause(OMPC_nowait) || 414 isOpenMPParallelDirective(D.getDirectiveKind())); 415 } 416 } 417 418 static void emitCommonOMPParallelDirective(CodeGenFunction &CGF, 419 const OMPExecutableDirective &S, 420 const RegionCodeGenTy &CodeGen) { 421 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 422 auto CapturedStruct = CGF.GenerateCapturedStmtArgument(*CS); 423 auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction( 424 S, *CS->getCapturedDecl()->param_begin(), CodeGen); 425 if (auto C = S.getSingleClause(OMPC_num_threads)) { 426 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 427 auto NumThreadsClause = cast<OMPNumThreadsClause>(C); 428 auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 429 /*IgnoreResultAssign*/ true); 430 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause( 431 CGF, NumThreads, NumThreadsClause->getLocStart()); 432 } 433 const Expr *IfCond = nullptr; 434 if (auto C = S.getSingleClause(OMPC_if)) { 435 IfCond = cast<OMPIfClause>(C)->getCondition(); 436 } 437 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn, 438 CapturedStruct, IfCond); 439 } 440 441 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) { 442 LexicalScope Scope(*this, S.getSourceRange()); 443 // Emit parallel region as a standalone region. 444 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 445 OMPPrivateScope PrivateScope(CGF); 446 bool Copyins = CGF.EmitOMPCopyinClause(S); 447 bool Firstprivates = CGF.EmitOMPFirstprivateClause(S, PrivateScope); 448 if (Copyins || Firstprivates) { 449 // Emit implicit barrier to synchronize threads and avoid data races on 450 // initialization of firstprivate variables or propagation master's thread 451 // values of threadprivate variables to local instances of that variables 452 // of all other implicit threads. 453 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 454 OMPD_unknown); 455 } 456 CGF.EmitOMPPrivateClause(S, PrivateScope); 457 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 458 (void)PrivateScope.Privatize(); 459 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 460 CGF.EmitOMPReductionClauseFinal(S); 461 // Emit implicit barrier at the end of the 'parallel' directive. 462 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 463 OMPD_unknown); 464 }; 465 emitCommonOMPParallelDirective(*this, S, CodeGen); 466 } 467 468 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &S, 469 bool SeparateIter) { 470 RunCleanupsScope BodyScope(*this); 471 // Update counters values on current iteration. 472 for (auto I : S.updates()) { 473 EmitIgnoredExpr(I); 474 } 475 // Update the linear variables. 476 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) { 477 auto *C = cast<OMPLinearClause>(*I); 478 for (auto U : C->updates()) { 479 EmitIgnoredExpr(U); 480 } 481 } 482 483 // On a continue in the body, jump to the end. 484 auto Continue = getJumpDestInCurrentScope("omp.body.continue"); 485 BreakContinueStack.push_back(BreakContinue(JumpDest(), Continue)); 486 // Emit loop body. 487 EmitStmt(S.getBody()); 488 // The end (updates/cleanups). 489 EmitBlock(Continue.getBlock()); 490 BreakContinueStack.pop_back(); 491 if (SeparateIter) { 492 // TODO: Update lastprivates if the SeparateIter flag is true. 493 // This will be implemented in a follow-up OMPLastprivateClause patch, but 494 // result should be still correct without it, as we do not make these 495 // variables private yet. 496 } 497 } 498 499 void CodeGenFunction::EmitOMPInnerLoop( 500 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 501 const Expr *IncExpr, 502 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen, 503 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) { 504 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end"); 505 506 // Start the loop with a block that tests the condition. 507 auto CondBlock = createBasicBlock("omp.inner.for.cond"); 508 EmitBlock(CondBlock); 509 LoopStack.push(CondBlock); 510 511 // If there are any cleanups between here and the loop-exit scope, 512 // create a block to stage a loop exit along. 513 auto ExitBlock = LoopExit.getBlock(); 514 if (RequiresCleanup) 515 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup"); 516 517 auto LoopBody = createBasicBlock("omp.inner.for.body"); 518 519 // Emit condition. 520 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S)); 521 if (ExitBlock != LoopExit.getBlock()) { 522 EmitBlock(ExitBlock); 523 EmitBranchThroughCleanup(LoopExit); 524 } 525 526 EmitBlock(LoopBody); 527 incrementProfileCounter(&S); 528 529 // Create a block for the increment. 530 auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc"); 531 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 532 533 BodyGen(*this); 534 535 // Emit "IV = IV + 1" and a back-edge to the condition block. 536 EmitBlock(Continue.getBlock()); 537 EmitIgnoredExpr(IncExpr); 538 PostIncGen(*this); 539 BreakContinueStack.pop_back(); 540 EmitBranch(CondBlock); 541 LoopStack.pop(); 542 // Emit the fall-through block. 543 EmitBlock(LoopExit.getBlock()); 544 } 545 546 void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &S) { 547 auto IC = S.counters().begin(); 548 for (auto F : S.finals()) { 549 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 550 if (LocalDeclMap.lookup(OrigVD)) { 551 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 552 CapturedStmtInfo->lookup(OrigVD) != nullptr, 553 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 554 auto *OrigAddr = EmitLValue(&DRE).getAddress(); 555 OMPPrivateScope VarScope(*this); 556 VarScope.addPrivate(OrigVD, 557 [OrigAddr]() -> llvm::Value *{ return OrigAddr; }); 558 (void)VarScope.Privatize(); 559 EmitIgnoredExpr(F); 560 } 561 ++IC; 562 } 563 // Emit the final values of the linear variables. 564 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) { 565 auto *C = cast<OMPLinearClause>(*I); 566 auto IC = C->varlist_begin(); 567 for (auto F : C->finals()) { 568 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl()); 569 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 570 CapturedStmtInfo->lookup(OrigVD) != nullptr, 571 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 572 auto *OrigAddr = EmitLValue(&DRE).getAddress(); 573 OMPPrivateScope VarScope(*this); 574 VarScope.addPrivate(OrigVD, 575 [OrigAddr]() -> llvm::Value *{ return OrigAddr; }); 576 (void)VarScope.Privatize(); 577 EmitIgnoredExpr(F); 578 ++IC; 579 } 580 } 581 } 582 583 static void EmitOMPAlignedClause(CodeGenFunction &CGF, CodeGenModule &CGM, 584 const OMPAlignedClause &Clause) { 585 unsigned ClauseAlignment = 0; 586 if (auto AlignmentExpr = Clause.getAlignment()) { 587 auto AlignmentCI = 588 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr)); 589 ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue()); 590 } 591 for (auto E : Clause.varlists()) { 592 unsigned Alignment = ClauseAlignment; 593 if (Alignment == 0) { 594 // OpenMP [2.8.1, Description] 595 // If no optional parameter is specified, implementation-defined default 596 // alignments for SIMD instructions on the target platforms are assumed. 597 Alignment = CGM.getTargetCodeGenInfo().getOpenMPSimdDefaultAlignment( 598 E->getType()); 599 } 600 assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) && 601 "alignment is not power of 2"); 602 if (Alignment != 0) { 603 llvm::Value *PtrValue = CGF.EmitScalarExpr(E); 604 CGF.EmitAlignmentAssumption(PtrValue, Alignment); 605 } 606 } 607 } 608 609 static void EmitPrivateLoopCounters(CodeGenFunction &CGF, 610 CodeGenFunction::OMPPrivateScope &LoopScope, 611 ArrayRef<Expr *> Counters) { 612 for (auto *E : Counters) { 613 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 614 (void)LoopScope.addPrivate(VD, [&]() -> llvm::Value *{ 615 // Emit var without initialization. 616 auto VarEmission = CGF.EmitAutoVarAlloca(*VD); 617 CGF.EmitAutoVarCleanups(VarEmission); 618 return VarEmission.getAllocatedAddress(); 619 }); 620 } 621 } 622 623 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, 624 const Expr *Cond, llvm::BasicBlock *TrueBlock, 625 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) { 626 CodeGenFunction::OMPPrivateScope PreCondScope(CGF); 627 EmitPrivateLoopCounters(CGF, PreCondScope, S.counters()); 628 const VarDecl *IVDecl = 629 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl()); 630 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{ 631 // Emit var without initialization. 632 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl); 633 CGF.EmitAutoVarCleanups(VarEmission); 634 return VarEmission.getAllocatedAddress(); 635 }); 636 assert(IsRegistered && "counter already registered as private"); 637 // Silence the warning about unused variable. 638 (void)IsRegistered; 639 (void)PreCondScope.Privatize(); 640 // Initialize internal counter to 0 to calculate initial values of real 641 // counters. 642 LValue IV = CGF.EmitLValue(S.getIterationVariable()); 643 CGF.EmitStoreOfScalar( 644 llvm::ConstantInt::getNullValue( 645 IV.getAddress()->getType()->getPointerElementType()), 646 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true); 647 // Get initial values of real counters. 648 for (auto I : S.updates()) { 649 CGF.EmitIgnoredExpr(I); 650 } 651 // Check that loop is executed at least one time. 652 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 653 } 654 655 static void 656 EmitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D, 657 CodeGenFunction::OMPPrivateScope &PrivateScope) { 658 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) { 659 auto *C = cast<OMPLinearClause>(*I); 660 for (auto *E : C->varlists()) { 661 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 662 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * { 663 // Emit var without initialization. 664 auto VarEmission = CGF.EmitAutoVarAlloca(*VD); 665 CGF.EmitAutoVarCleanups(VarEmission); 666 return VarEmission.getAllocatedAddress(); 667 }); 668 assert(IsRegistered && "linear var already registered as private"); 669 // Silence the warning about unused variable. 670 (void)IsRegistered; 671 } 672 } 673 } 674 675 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 676 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 677 // Pragma 'simd' code depends on presence of 'lastprivate'. 678 // If present, we have to separate last iteration of the loop: 679 // 680 // if (PreCond) { 681 // for (IV in 0..LastIteration-1) BODY; 682 // BODY with updates of lastprivate vars; 683 // <Final counter/linear vars updates>; 684 // } 685 // 686 // otherwise (when there's no lastprivate): 687 // 688 // if (PreCond) { 689 // for (IV in 0..LastIteration) BODY; 690 // <Final counter/linear vars updates>; 691 // } 692 // 693 694 // Emit: if (PreCond) - begin. 695 // If the condition constant folds and can be elided, avoid emitting the 696 // whole loop. 697 bool CondConstant; 698 llvm::BasicBlock *ContBlock = nullptr; 699 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 700 if (!CondConstant) 701 return; 702 } else { 703 auto *ThenBlock = CGF.createBasicBlock("simd.if.then"); 704 ContBlock = CGF.createBasicBlock("simd.if.end"); 705 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 706 CGF.getProfileCount(&S)); 707 CGF.EmitBlock(ThenBlock); 708 CGF.incrementProfileCounter(&S); 709 } 710 // Walk clauses and process safelen/lastprivate. 711 bool SeparateIter = false; 712 CGF.LoopStack.setParallel(); 713 CGF.LoopStack.setVectorizerEnable(true); 714 for (auto C : S.clauses()) { 715 switch (C->getClauseKind()) { 716 case OMPC_safelen: { 717 RValue Len = CGF.EmitAnyExpr(cast<OMPSafelenClause>(C)->getSafelen(), 718 AggValueSlot::ignored(), true); 719 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 720 CGF.LoopStack.setVectorizerWidth(Val->getZExtValue()); 721 // In presence of finite 'safelen', it may be unsafe to mark all 722 // the memory instructions parallel, because loop-carried 723 // dependences of 'safelen' iterations are possible. 724 CGF.LoopStack.setParallel(false); 725 break; 726 } 727 case OMPC_aligned: 728 EmitOMPAlignedClause(CGF, CGF.CGM, cast<OMPAlignedClause>(*C)); 729 break; 730 case OMPC_lastprivate: 731 SeparateIter = true; 732 break; 733 default: 734 // Not handled yet 735 ; 736 } 737 } 738 739 // Emit inits for the linear variables. 740 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) { 741 auto *C = cast<OMPLinearClause>(*I); 742 for (auto Init : C->inits()) { 743 auto *D = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl()); 744 CGF.EmitVarDecl(*D); 745 } 746 } 747 748 // Emit the loop iteration variable. 749 const Expr *IVExpr = S.getIterationVariable(); 750 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 751 CGF.EmitVarDecl(*IVDecl); 752 CGF.EmitIgnoredExpr(S.getInit()); 753 754 // Emit the iterations count variable. 755 // If it is not a variable, Sema decided to calculate iterations count on 756 // each 757 // iteration (e.g., it is foldable into a constant). 758 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 759 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 760 // Emit calculation of the iterations count. 761 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 762 } 763 764 // Emit the linear steps for the linear clauses. 765 // If a step is not constant, it is pre-calculated before the loop. 766 for (auto &&I = S.getClausesOfKind(OMPC_linear); I; ++I) { 767 auto *C = cast<OMPLinearClause>(*I); 768 if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep())) 769 if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) { 770 CGF.EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl())); 771 // Emit calculation of the linear step. 772 CGF.EmitIgnoredExpr(CS); 773 } 774 } 775 776 { 777 OMPPrivateScope LoopScope(CGF); 778 EmitPrivateLoopCounters(CGF, LoopScope, S.counters()); 779 EmitPrivateLinearVars(CGF, S, LoopScope); 780 CGF.EmitOMPPrivateClause(S, LoopScope); 781 (void)LoopScope.Privatize(); 782 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), 783 S.getCond(SeparateIter), S.getInc(), 784 [&S](CodeGenFunction &CGF) { 785 CGF.EmitOMPLoopBody(S); 786 CGF.EmitStopPoint(&S); 787 }, 788 [](CodeGenFunction &) {}); 789 if (SeparateIter) { 790 CGF.EmitOMPLoopBody(S, /*SeparateIter=*/true); 791 } 792 } 793 CGF.EmitOMPSimdFinal(S); 794 // Emit: if (PreCond) - end. 795 if (ContBlock) { 796 CGF.EmitBranch(ContBlock); 797 CGF.EmitBlock(ContBlock, true); 798 } 799 }; 800 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen); 801 } 802 803 void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind, 804 const OMPLoopDirective &S, 805 OMPPrivateScope &LoopScope, 806 llvm::Value *LB, llvm::Value *UB, 807 llvm::Value *ST, llvm::Value *IL, 808 llvm::Value *Chunk) { 809 auto &RT = CGM.getOpenMPRuntime(); 810 811 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 812 const bool Dynamic = RT.isDynamic(ScheduleKind); 813 814 assert(!RT.isStaticNonchunked(ScheduleKind, /* Chunked */ Chunk != nullptr) && 815 "static non-chunked schedule does not need outer loop"); 816 817 // Emit outer loop. 818 // 819 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 820 // When schedule(dynamic,chunk_size) is specified, the iterations are 821 // distributed to threads in the team in chunks as the threads request them. 822 // Each thread executes a chunk of iterations, then requests another chunk, 823 // until no chunks remain to be distributed. Each chunk contains chunk_size 824 // iterations, except for the last chunk to be distributed, which may have 825 // fewer iterations. When no chunk_size is specified, it defaults to 1. 826 // 827 // When schedule(guided,chunk_size) is specified, the iterations are assigned 828 // to threads in the team in chunks as the executing threads request them. 829 // Each thread executes a chunk of iterations, then requests another chunk, 830 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 831 // each chunk is proportional to the number of unassigned iterations divided 832 // by the number of threads in the team, decreasing to 1. For a chunk_size 833 // with value k (greater than 1), the size of each chunk is determined in the 834 // same way, with the restriction that the chunks do not contain fewer than k 835 // iterations (except for the last chunk to be assigned, which may have fewer 836 // than k iterations). 837 // 838 // When schedule(auto) is specified, the decision regarding scheduling is 839 // delegated to the compiler and/or runtime system. The programmer gives the 840 // implementation the freedom to choose any possible mapping of iterations to 841 // threads in the team. 842 // 843 // When schedule(runtime) is specified, the decision regarding scheduling is 844 // deferred until run time, and the schedule and chunk size are taken from the 845 // run-sched-var ICV. If the ICV is set to auto, the schedule is 846 // implementation defined 847 // 848 // while(__kmpc_dispatch_next(&LB, &UB)) { 849 // idx = LB; 850 // while (idx <= UB) { BODY; ++idx; 851 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 852 // } // inner loop 853 // } 854 // 855 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 856 // When schedule(static, chunk_size) is specified, iterations are divided into 857 // chunks of size chunk_size, and the chunks are assigned to the threads in 858 // the team in a round-robin fashion in the order of the thread number. 859 // 860 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 861 // while (idx <= UB) { BODY; ++idx; } // inner loop 862 // LB = LB + ST; 863 // UB = UB + ST; 864 // } 865 // 866 867 const Expr *IVExpr = S.getIterationVariable(); 868 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 869 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 870 871 RT.emitForInit( 872 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, IL, LB, 873 (Dynamic ? EmitAnyExpr(S.getLastIteration()).getScalarVal() : UB), ST, 874 Chunk); 875 876 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 877 878 // Start the loop with a block that tests the condition. 879 auto CondBlock = createBasicBlock("omp.dispatch.cond"); 880 EmitBlock(CondBlock); 881 LoopStack.push(CondBlock); 882 883 llvm::Value *BoolCondVal = nullptr; 884 if (!Dynamic) { 885 // UB = min(UB, GlobalUB) 886 EmitIgnoredExpr(S.getEnsureUpperBound()); 887 // IV = LB 888 EmitIgnoredExpr(S.getInit()); 889 // IV < UB 890 BoolCondVal = EvaluateExprAsBool(S.getCond(false)); 891 } else { 892 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, 893 IL, LB, UB, ST); 894 } 895 896 // If there are any cleanups between here and the loop-exit scope, 897 // create a block to stage a loop exit along. 898 auto ExitBlock = LoopExit.getBlock(); 899 if (LoopScope.requiresCleanups()) 900 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 901 902 auto LoopBody = createBasicBlock("omp.dispatch.body"); 903 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 904 if (ExitBlock != LoopExit.getBlock()) { 905 EmitBlock(ExitBlock); 906 EmitBranchThroughCleanup(LoopExit); 907 } 908 EmitBlock(LoopBody); 909 910 // Emit "IV = LB" (in case of static schedule, we have already calculated new 911 // LB for loop condition and emitted it above). 912 if (Dynamic) 913 EmitIgnoredExpr(S.getInit()); 914 915 // Create a block for the increment. 916 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 917 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 918 919 bool DynamicWithOrderedClause = 920 Dynamic && S.getSingleClause(OMPC_ordered) != nullptr; 921 SourceLocation Loc = S.getLocStart(); 922 // Generate !llvm.loop.parallel metadata for loads and stores for loops with 923 // dynamic/guided scheduling and without ordered clause. 924 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic || 925 ScheduleKind == OMPC_SCHEDULE_guided) && 926 !DynamicWithOrderedClause); 927 EmitOMPInnerLoop( 928 S, LoopScope.requiresCleanups(), S.getCond(/*SeparateIter=*/false), 929 S.getInc(), 930 [&S](CodeGenFunction &CGF) { 931 CGF.EmitOMPLoopBody(S); 932 CGF.EmitStopPoint(&S); 933 }, 934 [DynamicWithOrderedClause, IVSize, IVSigned, Loc](CodeGenFunction &CGF) { 935 if (DynamicWithOrderedClause) { 936 CGF.CGM.getOpenMPRuntime().emitForOrderedDynamicIterationEnd( 937 CGF, Loc, IVSize, IVSigned); 938 } 939 }); 940 941 EmitBlock(Continue.getBlock()); 942 BreakContinueStack.pop_back(); 943 if (!Dynamic) { 944 // Emit "LB = LB + Stride", "UB = UB + Stride". 945 EmitIgnoredExpr(S.getNextLowerBound()); 946 EmitIgnoredExpr(S.getNextUpperBound()); 947 } 948 949 EmitBranch(CondBlock); 950 LoopStack.pop(); 951 // Emit the fall-through block. 952 EmitBlock(LoopExit.getBlock()); 953 954 // Tell the runtime we are done. 955 if (!Dynamic) 956 RT.emitForStaticFinish(*this, S.getLocEnd()); 957 } 958 959 /// \brief Emit a helper variable and return corresponding lvalue. 960 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 961 const DeclRefExpr *Helper) { 962 auto VDecl = cast<VarDecl>(Helper->getDecl()); 963 CGF.EmitVarDecl(*VDecl); 964 return CGF.EmitLValue(Helper); 965 } 966 967 static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind> 968 emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S, 969 bool OuterRegion) { 970 // Detect the loop schedule kind and chunk. 971 auto ScheduleKind = OMPC_SCHEDULE_unknown; 972 llvm::Value *Chunk = nullptr; 973 if (auto *C = 974 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) { 975 ScheduleKind = C->getScheduleKind(); 976 if (const auto *Ch = C->getChunkSize()) { 977 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) { 978 if (OuterRegion) { 979 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl()); 980 CGF.EmitVarDecl(*ImpVar); 981 CGF.EmitStoreThroughLValue( 982 CGF.EmitAnyExpr(Ch), 983 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar), 984 ImpVar->getType())); 985 } else { 986 Ch = ImpRef; 987 } 988 } 989 if (!C->getHelperChunkSize() || !OuterRegion) { 990 Chunk = CGF.EmitScalarExpr(Ch); 991 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(), 992 S.getIterationVariable()->getType()); 993 } 994 } 995 } 996 return std::make_pair(Chunk, ScheduleKind); 997 } 998 999 bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) { 1000 // Emit the loop iteration variable. 1001 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 1002 auto IVDecl = cast<VarDecl>(IVExpr->getDecl()); 1003 EmitVarDecl(*IVDecl); 1004 1005 // Emit the iterations count variable. 1006 // If it is not a variable, Sema decided to calculate iterations count on each 1007 // iteration (e.g., it is foldable into a constant). 1008 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 1009 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 1010 // Emit calculation of the iterations count. 1011 EmitIgnoredExpr(S.getCalcLastIteration()); 1012 } 1013 1014 auto &RT = CGM.getOpenMPRuntime(); 1015 1016 bool HasLastprivateClause; 1017 // Check pre-condition. 1018 { 1019 // Skip the entire loop if we don't meet the precondition. 1020 // If the condition constant folds and can be elided, avoid emitting the 1021 // whole loop. 1022 bool CondConstant; 1023 llvm::BasicBlock *ContBlock = nullptr; 1024 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 1025 if (!CondConstant) 1026 return false; 1027 } else { 1028 auto *ThenBlock = createBasicBlock("omp.precond.then"); 1029 ContBlock = createBasicBlock("omp.precond.end"); 1030 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 1031 getProfileCount(&S)); 1032 EmitBlock(ThenBlock); 1033 incrementProfileCounter(&S); 1034 } 1035 // Emit 'then' code. 1036 { 1037 // Emit helper vars inits. 1038 LValue LB = 1039 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable())); 1040 LValue UB = 1041 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable())); 1042 LValue ST = 1043 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 1044 LValue IL = 1045 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 1046 1047 OMPPrivateScope LoopScope(*this); 1048 if (EmitOMPFirstprivateClause(S, LoopScope)) { 1049 // Emit implicit barrier to synchronize threads and avoid data races on 1050 // initialization of firstprivate variables. 1051 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), 1052 OMPD_unknown); 1053 } 1054 EmitOMPPrivateClause(S, LoopScope); 1055 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 1056 EmitOMPReductionClauseInit(S, LoopScope); 1057 EmitPrivateLoopCounters(*this, LoopScope, S.counters()); 1058 (void)LoopScope.Privatize(); 1059 1060 // Detect the loop schedule kind and chunk. 1061 llvm::Value *Chunk; 1062 OpenMPScheduleClauseKind ScheduleKind; 1063 auto ScheduleInfo = 1064 emitScheduleClause(*this, S, /*OuterRegion=*/false); 1065 Chunk = ScheduleInfo.first; 1066 ScheduleKind = ScheduleInfo.second; 1067 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 1068 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 1069 if (RT.isStaticNonchunked(ScheduleKind, 1070 /* Chunked */ Chunk != nullptr)) { 1071 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 1072 // When no chunk_size is specified, the iteration space is divided into 1073 // chunks that are approximately equal in size, and at most one chunk is 1074 // distributed to each thread. Note that the size of the chunks is 1075 // unspecified in this case. 1076 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, 1077 IL.getAddress(), LB.getAddress(), UB.getAddress(), 1078 ST.getAddress()); 1079 // UB = min(UB, GlobalUB); 1080 EmitIgnoredExpr(S.getEnsureUpperBound()); 1081 // IV = LB; 1082 EmitIgnoredExpr(S.getInit()); 1083 // while (idx <= UB) { BODY; ++idx; } 1084 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), 1085 S.getCond(/*SeparateIter=*/false), S.getInc(), 1086 [&S](CodeGenFunction &CGF) { 1087 CGF.EmitOMPLoopBody(S); 1088 CGF.EmitStopPoint(&S); 1089 }, 1090 [](CodeGenFunction &) {}); 1091 // Tell the runtime we are done. 1092 RT.emitForStaticFinish(*this, S.getLocStart()); 1093 } else { 1094 // Emit the outer loop, which requests its work chunk [LB..UB] from 1095 // runtime and runs the inner loop to process it. 1096 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, LB.getAddress(), 1097 UB.getAddress(), ST.getAddress(), IL.getAddress(), 1098 Chunk); 1099 } 1100 EmitOMPReductionClauseFinal(S); 1101 // Emit final copy of the lastprivate variables if IsLastIter != 0. 1102 if (HasLastprivateClause) 1103 EmitOMPLastprivateClauseFinal( 1104 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart()))); 1105 } 1106 // We're now done with the loop, so jump to the continuation block. 1107 if (ContBlock) { 1108 EmitBranch(ContBlock); 1109 EmitBlock(ContBlock, true); 1110 } 1111 } 1112 return HasLastprivateClause; 1113 } 1114 1115 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 1116 LexicalScope Scope(*this, S.getSourceRange()); 1117 bool HasLastprivates = false; 1118 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) { 1119 HasLastprivates = CGF.EmitOMPWorksharingLoop(S); 1120 }; 1121 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen); 1122 1123 // Emit an implicit barrier at the end. 1124 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) { 1125 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for); 1126 } 1127 } 1128 1129 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &) { 1130 llvm_unreachable("CodeGen for 'omp for simd' is not supported yet."); 1131 } 1132 1133 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 1134 const Twine &Name, 1135 llvm::Value *Init = nullptr) { 1136 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 1137 if (Init) 1138 CGF.EmitScalarInit(Init, LVal); 1139 return LVal; 1140 } 1141 1142 static OpenMPDirectiveKind emitSections(CodeGenFunction &CGF, 1143 const OMPExecutableDirective &S) { 1144 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt(); 1145 auto *CS = dyn_cast<CompoundStmt>(Stmt); 1146 if (CS && CS->size() > 1) { 1147 bool HasLastprivates = false; 1148 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) { 1149 auto &C = CGF.CGM.getContext(); 1150 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1151 // Emit helper vars inits. 1152 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 1153 CGF.Builder.getInt32(0)); 1154 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1); 1155 LValue UB = 1156 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 1157 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 1158 CGF.Builder.getInt32(1)); 1159 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 1160 CGF.Builder.getInt32(0)); 1161 // Loop counter. 1162 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 1163 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue); 1164 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 1165 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue); 1166 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 1167 // Generate condition for loop. 1168 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue, 1169 OK_Ordinary, S.getLocStart(), 1170 /*fpContractable=*/false); 1171 // Increment for loop counter. 1172 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, 1173 OK_Ordinary, S.getLocStart()); 1174 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) { 1175 // Iterate through all sections and emit a switch construct: 1176 // switch (IV) { 1177 // case 0: 1178 // <SectionStmt[0]>; 1179 // break; 1180 // ... 1181 // case <NumSection> - 1: 1182 // <SectionStmt[<NumSection> - 1]>; 1183 // break; 1184 // } 1185 // .omp.sections.exit: 1186 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 1187 auto *SwitchStmt = CGF.Builder.CreateSwitch( 1188 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB, 1189 CS->size()); 1190 unsigned CaseNumber = 0; 1191 for (auto C = CS->children(); C; ++C, ++CaseNumber) { 1192 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 1193 CGF.EmitBlock(CaseBB); 1194 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 1195 CGF.EmitStmt(*C); 1196 CGF.EmitBranch(ExitBB); 1197 } 1198 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 1199 }; 1200 1201 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 1202 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 1203 // Emit implicit barrier to synchronize threads and avoid data races on 1204 // initialization of firstprivate variables. 1205 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1206 OMPD_unknown); 1207 } 1208 CGF.EmitOMPPrivateClause(S, LoopScope); 1209 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 1210 CGF.EmitOMPReductionClauseInit(S, LoopScope); 1211 (void)LoopScope.Privatize(); 1212 1213 // Emit static non-chunked loop. 1214 CGF.CGM.getOpenMPRuntime().emitForInit( 1215 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32, 1216 /*IVSigned=*/true, IL.getAddress(), LB.getAddress(), UB.getAddress(), 1217 ST.getAddress()); 1218 // UB = min(UB, GlobalUB); 1219 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart()); 1220 auto *MinUBGlobalUB = CGF.Builder.CreateSelect( 1221 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 1222 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 1223 // IV = LB; 1224 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV); 1225 // while (idx <= UB) { BODY; ++idx; } 1226 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen, 1227 [](CodeGenFunction &) {}); 1228 // Tell the runtime we are done. 1229 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart()); 1230 CGF.EmitOMPReductionClauseFinal(S); 1231 1232 // Emit final copy of the lastprivate variables if IsLastIter != 0. 1233 if (HasLastprivates) 1234 CGF.EmitOMPLastprivateClauseFinal( 1235 S, CGF.Builder.CreateIsNotNull( 1236 CGF.EmitLoadOfScalar(IL, S.getLocStart()))); 1237 }; 1238 1239 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, CodeGen); 1240 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 1241 // clause. Otherwise the barrier will be generated by the codegen for the 1242 // directive. 1243 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) { 1244 // Emit implicit barrier to synchronize threads and avoid data races on 1245 // initialization of firstprivate variables. 1246 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1247 OMPD_unknown); 1248 } 1249 return OMPD_sections; 1250 } 1251 // If only one section is found - no need to generate loop, emit as a single 1252 // region. 1253 bool HasFirstprivates; 1254 // No need to generate reductions for sections with single section region, we 1255 // can use original shared variables for all operations. 1256 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty(); 1257 // No need to generate lastprivates for sections with single section region, 1258 // we can use original shared variable for all calculations with barrier at 1259 // the end of the sections. 1260 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty(); 1261 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) { 1262 CodeGenFunction::OMPPrivateScope SingleScope(CGF); 1263 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope); 1264 CGF.EmitOMPPrivateClause(S, SingleScope); 1265 (void)SingleScope.Privatize(); 1266 1267 CGF.EmitStmt(Stmt); 1268 CGF.EnsureInsertPoint(); 1269 }; 1270 CGF.CGM.getOpenMPRuntime().emitSingleRegion(CGF, CodeGen, S.getLocStart(), 1271 llvm::None, llvm::None, 1272 llvm::None, llvm::None); 1273 // Emit barrier for firstprivates, lastprivates or reductions only if 1274 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be 1275 // generated by the codegen for the directive. 1276 if ((HasFirstprivates || HasLastprivates || HasReductions) && 1277 S.getSingleClause(OMPC_nowait)) { 1278 // Emit implicit barrier to synchronize threads and avoid data races on 1279 // initialization of firstprivate variables. 1280 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1281 OMPD_unknown); 1282 } 1283 return OMPD_single; 1284 } 1285 1286 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 1287 LexicalScope Scope(*this, S.getSourceRange()); 1288 OpenMPDirectiveKind EmittedAs = emitSections(*this, S); 1289 // Emit an implicit barrier at the end. 1290 if (!S.getSingleClause(OMPC_nowait)) { 1291 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs); 1292 } 1293 } 1294 1295 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 1296 LexicalScope Scope(*this, S.getSourceRange()); 1297 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1298 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1299 CGF.EnsureInsertPoint(); 1300 }; 1301 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen); 1302 } 1303 1304 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 1305 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 1306 llvm::SmallVector<const Expr *, 8> DestExprs; 1307 llvm::SmallVector<const Expr *, 8> SrcExprs; 1308 llvm::SmallVector<const Expr *, 8> AssignmentOps; 1309 // Check if there are any 'copyprivate' clauses associated with this 1310 // 'single' 1311 // construct. 1312 // Build a list of copyprivate variables along with helper expressions 1313 // (<source>, <destination>, <destination>=<source> expressions) 1314 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) { 1315 auto *C = cast<OMPCopyprivateClause>(*I); 1316 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 1317 DestExprs.append(C->destination_exprs().begin(), 1318 C->destination_exprs().end()); 1319 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 1320 AssignmentOps.append(C->assignment_ops().begin(), 1321 C->assignment_ops().end()); 1322 } 1323 LexicalScope Scope(*this, S.getSourceRange()); 1324 // Emit code for 'single' region along with 'copyprivate' clauses 1325 bool HasFirstprivates; 1326 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) { 1327 CodeGenFunction::OMPPrivateScope SingleScope(CGF); 1328 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope); 1329 CGF.EmitOMPPrivateClause(S, SingleScope); 1330 (void)SingleScope.Privatize(); 1331 1332 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1333 CGF.EnsureInsertPoint(); 1334 }; 1335 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(), 1336 CopyprivateVars, DestExprs, SrcExprs, 1337 AssignmentOps); 1338 // Emit an implicit barrier at the end (to avoid data race on firstprivate 1339 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 1340 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) && 1341 CopyprivateVars.empty()) { 1342 CGM.getOpenMPRuntime().emitBarrierCall( 1343 *this, S.getLocStart(), 1344 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single); 1345 } 1346 } 1347 1348 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 1349 LexicalScope Scope(*this, S.getSourceRange()); 1350 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1351 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1352 CGF.EnsureInsertPoint(); 1353 }; 1354 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart()); 1355 } 1356 1357 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 1358 LexicalScope Scope(*this, S.getSourceRange()); 1359 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1360 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1361 CGF.EnsureInsertPoint(); 1362 }; 1363 CGM.getOpenMPRuntime().emitCriticalRegion( 1364 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart()); 1365 } 1366 1367 void CodeGenFunction::EmitOMPParallelForDirective( 1368 const OMPParallelForDirective &S) { 1369 // Emit directive as a combined directive that consists of two implicit 1370 // directives: 'parallel' with 'for' directive. 1371 LexicalScope Scope(*this, S.getSourceRange()); 1372 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true); 1373 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1374 CGF.EmitOMPWorksharingLoop(S); 1375 // Emit implicit barrier at the end of parallel region, but this barrier 1376 // is at the end of 'for' directive, so emit it as the implicit barrier for 1377 // this 'for' directive. 1378 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1379 OMPD_parallel); 1380 }; 1381 emitCommonOMPParallelDirective(*this, S, CodeGen); 1382 } 1383 1384 void CodeGenFunction::EmitOMPParallelForSimdDirective( 1385 const OMPParallelForSimdDirective &) { 1386 llvm_unreachable("CodeGen for 'omp parallel for simd' is not supported yet."); 1387 } 1388 1389 void CodeGenFunction::EmitOMPParallelSectionsDirective( 1390 const OMPParallelSectionsDirective &S) { 1391 // Emit directive as a combined directive that consists of two implicit 1392 // directives: 'parallel' with 'sections' directive. 1393 LexicalScope Scope(*this, S.getSourceRange()); 1394 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1395 (void)emitSections(CGF, S); 1396 // Emit implicit barrier at the end of parallel region. 1397 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1398 OMPD_parallel); 1399 }; 1400 emitCommonOMPParallelDirective(*this, S, CodeGen); 1401 } 1402 1403 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 1404 // Emit outlined function for task construct. 1405 LexicalScope Scope(*this, S.getSourceRange()); 1406 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 1407 auto CapturedStruct = GenerateCapturedStmtArgument(*CS); 1408 auto *I = CS->getCapturedDecl()->param_begin(); 1409 auto *PartId = std::next(I); 1410 // The first function argument for tasks is a thread id, the second one is a 1411 // part id (0 for tied tasks, >=0 for untied task). 1412 auto &&CodeGen = [PartId, &S](CodeGenFunction &CGF) { 1413 if (*PartId) { 1414 // TODO: emit code for untied tasks. 1415 } 1416 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1417 }; 1418 auto OutlinedFn = 1419 CGM.getOpenMPRuntime().emitTaskOutlinedFunction(S, *I, CodeGen); 1420 // Check if we should emit tied or untied task. 1421 bool Tied = !S.getSingleClause(OMPC_untied); 1422 // Check if the task is final 1423 llvm::PointerIntPair<llvm::Value *, 1, bool> Final; 1424 if (auto *Clause = S.getSingleClause(OMPC_final)) { 1425 // If the condition constant folds and can be elided, try to avoid emitting 1426 // the condition and the dead arm of the if/else. 1427 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition(); 1428 bool CondConstant; 1429 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 1430 Final.setInt(CondConstant); 1431 else 1432 Final.setPointer(EvaluateExprAsBool(Cond)); 1433 } else { 1434 // By default the task is not final. 1435 Final.setInt(/*IntVal=*/false); 1436 } 1437 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 1438 const Expr *IfCond = nullptr; 1439 if (auto C = S.getSingleClause(OMPC_if)) { 1440 IfCond = cast<OMPIfClause>(C)->getCondition(); 1441 } 1442 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 1443 // Get list of private variables. 1444 llvm::SmallVector<const Expr *, 8> Privates; 1445 llvm::SmallVector<const Expr *, 8> PrivateCopies; 1446 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) { 1447 auto *C = cast<OMPPrivateClause>(*I); 1448 auto IRef = C->varlist_begin(); 1449 for (auto *IInit : C->private_copies()) { 1450 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1451 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 1452 Privates.push_back(*IRef); 1453 PrivateCopies.push_back(IInit); 1454 } 1455 ++IRef; 1456 } 1457 } 1458 EmittedAsPrivate.clear(); 1459 // Get list of firstprivate variables. 1460 llvm::SmallVector<const Expr *, 8> FirstprivateVars; 1461 llvm::SmallVector<const Expr *, 8> FirstprivateCopies; 1462 llvm::SmallVector<const Expr *, 8> FirstprivateInits; 1463 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) { 1464 auto *C = cast<OMPFirstprivateClause>(*I); 1465 auto IRef = C->varlist_begin(); 1466 auto IElemInitRef = C->inits().begin(); 1467 for (auto *IInit : C->private_copies()) { 1468 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1469 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 1470 FirstprivateVars.push_back(*IRef); 1471 FirstprivateCopies.push_back(IInit); 1472 FirstprivateInits.push_back(*IElemInitRef); 1473 } 1474 ++IRef, ++IElemInitRef; 1475 } 1476 } 1477 CGM.getOpenMPRuntime().emitTaskCall( 1478 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy, 1479 CapturedStruct, IfCond, Privates, PrivateCopies, FirstprivateVars, 1480 FirstprivateCopies, FirstprivateInits); 1481 } 1482 1483 void CodeGenFunction::EmitOMPTaskyieldDirective( 1484 const OMPTaskyieldDirective &S) { 1485 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart()); 1486 } 1487 1488 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 1489 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier); 1490 } 1491 1492 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 1493 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart()); 1494 } 1495 1496 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 1497 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> { 1498 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) { 1499 auto FlushClause = cast<OMPFlushClause>(C); 1500 return llvm::makeArrayRef(FlushClause->varlist_begin(), 1501 FlushClause->varlist_end()); 1502 } 1503 return llvm::None; 1504 }(), S.getLocStart()); 1505 } 1506 1507 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 1508 LexicalScope Scope(*this, S.getSourceRange()); 1509 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1510 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1511 CGF.EnsureInsertPoint(); 1512 }; 1513 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart()); 1514 } 1515 1516 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 1517 QualType SrcType, QualType DestType) { 1518 assert(CGF.hasScalarEvaluationKind(DestType) && 1519 "DestType must have scalar evaluation kind."); 1520 assert(!Val.isAggregate() && "Must be a scalar or complex."); 1521 return Val.isScalar() 1522 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType) 1523 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType, 1524 DestType); 1525 } 1526 1527 static CodeGenFunction::ComplexPairTy 1528 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 1529 QualType DestType) { 1530 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 1531 "DestType must have complex evaluation kind."); 1532 CodeGenFunction::ComplexPairTy ComplexVal; 1533 if (Val.isScalar()) { 1534 // Convert the input element to the element type of the complex. 1535 auto DestElementType = DestType->castAs<ComplexType>()->getElementType(); 1536 auto ScalarVal = 1537 CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestElementType); 1538 ComplexVal = CodeGenFunction::ComplexPairTy( 1539 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 1540 } else { 1541 assert(Val.isComplex() && "Must be a scalar or complex."); 1542 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 1543 auto DestElementType = DestType->castAs<ComplexType>()->getElementType(); 1544 ComplexVal.first = CGF.EmitScalarConversion( 1545 Val.getComplexVal().first, SrcElementType, DestElementType); 1546 ComplexVal.second = CGF.EmitScalarConversion( 1547 Val.getComplexVal().second, SrcElementType, DestElementType); 1548 } 1549 return ComplexVal; 1550 } 1551 1552 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst, 1553 LValue LVal, RValue RVal) { 1554 if (LVal.isGlobalReg()) { 1555 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 1556 } else { 1557 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent 1558 : llvm::Monotonic, 1559 LVal.isVolatile(), /*IsInit=*/false); 1560 } 1561 } 1562 1563 static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal, 1564 QualType RValTy) { 1565 switch (CGF.getEvaluationKind(LVal.getType())) { 1566 case TEK_Scalar: 1567 CGF.EmitStoreThroughLValue( 1568 RValue::get(convertToScalarValue(CGF, RVal, RValTy, LVal.getType())), 1569 LVal); 1570 break; 1571 case TEK_Complex: 1572 CGF.EmitStoreOfComplex( 1573 convertToComplexValue(CGF, RVal, RValTy, LVal.getType()), LVal, 1574 /*isInit=*/false); 1575 break; 1576 case TEK_Aggregate: 1577 llvm_unreachable("Must be a scalar or complex."); 1578 } 1579 } 1580 1581 static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst, 1582 const Expr *X, const Expr *V, 1583 SourceLocation Loc) { 1584 // v = x; 1585 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 1586 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 1587 LValue XLValue = CGF.EmitLValue(X); 1588 LValue VLValue = CGF.EmitLValue(V); 1589 RValue Res = XLValue.isGlobalReg() 1590 ? CGF.EmitLoadOfLValue(XLValue, Loc) 1591 : CGF.EmitAtomicLoad(XLValue, Loc, 1592 IsSeqCst ? llvm::SequentiallyConsistent 1593 : llvm::Monotonic, 1594 XLValue.isVolatile()); 1595 // OpenMP, 2.12.6, atomic Construct 1596 // Any atomic construct with a seq_cst clause forces the atomically 1597 // performed operation to include an implicit flush operation without a 1598 // list. 1599 if (IsSeqCst) 1600 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1601 emitSimpleStore(CGF,VLValue, Res, X->getType().getNonReferenceType()); 1602 } 1603 1604 static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst, 1605 const Expr *X, const Expr *E, 1606 SourceLocation Loc) { 1607 // x = expr; 1608 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 1609 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 1610 // OpenMP, 2.12.6, atomic Construct 1611 // Any atomic construct with a seq_cst clause forces the atomically 1612 // performed operation to include an implicit flush operation without a 1613 // list. 1614 if (IsSeqCst) 1615 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1616 } 1617 1618 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 1619 RValue Update, 1620 BinaryOperatorKind BO, 1621 llvm::AtomicOrdering AO, 1622 bool IsXLHSInRHSPart) { 1623 auto &Context = CGF.CGM.getContext(); 1624 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 1625 // expression is simple and atomic is allowed for the given type for the 1626 // target platform. 1627 if (BO == BO_Comma || !Update.isScalar() || 1628 !Update.getScalarVal()->getType()->isIntegerTy() || 1629 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 1630 (Update.getScalarVal()->getType() != 1631 X.getAddress()->getType()->getPointerElementType())) || 1632 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() || 1633 !Context.getTargetInfo().hasBuiltinAtomic( 1634 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 1635 return std::make_pair(false, RValue::get(nullptr)); 1636 1637 llvm::AtomicRMWInst::BinOp RMWOp; 1638 switch (BO) { 1639 case BO_Add: 1640 RMWOp = llvm::AtomicRMWInst::Add; 1641 break; 1642 case BO_Sub: 1643 if (!IsXLHSInRHSPart) 1644 return std::make_pair(false, RValue::get(nullptr)); 1645 RMWOp = llvm::AtomicRMWInst::Sub; 1646 break; 1647 case BO_And: 1648 RMWOp = llvm::AtomicRMWInst::And; 1649 break; 1650 case BO_Or: 1651 RMWOp = llvm::AtomicRMWInst::Or; 1652 break; 1653 case BO_Xor: 1654 RMWOp = llvm::AtomicRMWInst::Xor; 1655 break; 1656 case BO_LT: 1657 RMWOp = X.getType()->hasSignedIntegerRepresentation() 1658 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 1659 : llvm::AtomicRMWInst::Max) 1660 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 1661 : llvm::AtomicRMWInst::UMax); 1662 break; 1663 case BO_GT: 1664 RMWOp = X.getType()->hasSignedIntegerRepresentation() 1665 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 1666 : llvm::AtomicRMWInst::Min) 1667 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 1668 : llvm::AtomicRMWInst::UMin); 1669 break; 1670 case BO_Assign: 1671 RMWOp = llvm::AtomicRMWInst::Xchg; 1672 break; 1673 case BO_Mul: 1674 case BO_Div: 1675 case BO_Rem: 1676 case BO_Shl: 1677 case BO_Shr: 1678 case BO_LAnd: 1679 case BO_LOr: 1680 return std::make_pair(false, RValue::get(nullptr)); 1681 case BO_PtrMemD: 1682 case BO_PtrMemI: 1683 case BO_LE: 1684 case BO_GE: 1685 case BO_EQ: 1686 case BO_NE: 1687 case BO_AddAssign: 1688 case BO_SubAssign: 1689 case BO_AndAssign: 1690 case BO_OrAssign: 1691 case BO_XorAssign: 1692 case BO_MulAssign: 1693 case BO_DivAssign: 1694 case BO_RemAssign: 1695 case BO_ShlAssign: 1696 case BO_ShrAssign: 1697 case BO_Comma: 1698 llvm_unreachable("Unsupported atomic update operation"); 1699 } 1700 auto *UpdateVal = Update.getScalarVal(); 1701 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 1702 UpdateVal = CGF.Builder.CreateIntCast( 1703 IC, X.getAddress()->getType()->getPointerElementType(), 1704 X.getType()->hasSignedIntegerRepresentation()); 1705 } 1706 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO); 1707 return std::make_pair(true, RValue::get(Res)); 1708 } 1709 1710 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 1711 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 1712 llvm::AtomicOrdering AO, SourceLocation Loc, 1713 const llvm::function_ref<RValue(RValue)> &CommonGen) { 1714 // Update expressions are allowed to have the following forms: 1715 // x binop= expr; -> xrval + expr; 1716 // x++, ++x -> xrval + 1; 1717 // x--, --x -> xrval - 1; 1718 // x = x binop expr; -> xrval binop expr 1719 // x = expr Op x; - > expr binop xrval; 1720 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 1721 if (!Res.first) { 1722 if (X.isGlobalReg()) { 1723 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 1724 // 'xrval'. 1725 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 1726 } else { 1727 // Perform compare-and-swap procedure. 1728 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 1729 } 1730 } 1731 return Res; 1732 } 1733 1734 static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst, 1735 const Expr *X, const Expr *E, 1736 const Expr *UE, bool IsXLHSInRHSPart, 1737 SourceLocation Loc) { 1738 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 1739 "Update expr in 'atomic update' must be a binary operator."); 1740 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 1741 // Update expressions are allowed to have the following forms: 1742 // x binop= expr; -> xrval + expr; 1743 // x++, ++x -> xrval + 1; 1744 // x--, --x -> xrval - 1; 1745 // x = x binop expr; -> xrval binop expr 1746 // x = expr Op x; - > expr binop xrval; 1747 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 1748 LValue XLValue = CGF.EmitLValue(X); 1749 RValue ExprRValue = CGF.EmitAnyExpr(E); 1750 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic; 1751 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 1752 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 1753 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 1754 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 1755 auto Gen = 1756 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue { 1757 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 1758 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 1759 return CGF.EmitAnyExpr(UE); 1760 }; 1761 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 1762 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 1763 // OpenMP, 2.12.6, atomic Construct 1764 // Any atomic construct with a seq_cst clause forces the atomically 1765 // performed operation to include an implicit flush operation without a 1766 // list. 1767 if (IsSeqCst) 1768 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1769 } 1770 1771 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 1772 QualType SourceType, QualType ResType) { 1773 switch (CGF.getEvaluationKind(ResType)) { 1774 case TEK_Scalar: 1775 return RValue::get(convertToScalarValue(CGF, Value, SourceType, ResType)); 1776 case TEK_Complex: { 1777 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType); 1778 return RValue::getComplex(Res.first, Res.second); 1779 } 1780 case TEK_Aggregate: 1781 break; 1782 } 1783 llvm_unreachable("Must be a scalar or complex."); 1784 } 1785 1786 static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst, 1787 bool IsPostfixUpdate, const Expr *V, 1788 const Expr *X, const Expr *E, 1789 const Expr *UE, bool IsXLHSInRHSPart, 1790 SourceLocation Loc) { 1791 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 1792 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 1793 RValue NewVVal; 1794 LValue VLValue = CGF.EmitLValue(V); 1795 LValue XLValue = CGF.EmitLValue(X); 1796 RValue ExprRValue = CGF.EmitAnyExpr(E); 1797 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic; 1798 QualType NewVValType; 1799 if (UE) { 1800 // 'x' is updated with some additional value. 1801 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 1802 "Update expr in 'atomic capture' must be a binary operator."); 1803 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 1804 // Update expressions are allowed to have the following forms: 1805 // x binop= expr; -> xrval + expr; 1806 // x++, ++x -> xrval + 1; 1807 // x--, --x -> xrval - 1; 1808 // x = x binop expr; -> xrval binop expr 1809 // x = expr Op x; - > expr binop xrval; 1810 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 1811 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 1812 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 1813 NewVValType = XRValExpr->getType(); 1814 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 1815 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 1816 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue { 1817 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 1818 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 1819 RValue Res = CGF.EmitAnyExpr(UE); 1820 NewVVal = IsPostfixUpdate ? XRValue : Res; 1821 return Res; 1822 }; 1823 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 1824 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 1825 if (Res.first) { 1826 // 'atomicrmw' instruction was generated. 1827 if (IsPostfixUpdate) { 1828 // Use old value from 'atomicrmw'. 1829 NewVVal = Res.second; 1830 } else { 1831 // 'atomicrmw' does not provide new value, so evaluate it using old 1832 // value of 'x'. 1833 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 1834 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 1835 NewVVal = CGF.EmitAnyExpr(UE); 1836 } 1837 } 1838 } else { 1839 // 'x' is simply rewritten with some 'expr'. 1840 NewVValType = X->getType().getNonReferenceType(); 1841 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 1842 X->getType().getNonReferenceType()); 1843 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue { 1844 NewVVal = XRValue; 1845 return ExprRValue; 1846 }; 1847 // Try to perform atomicrmw xchg, otherwise simple exchange. 1848 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 1849 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 1850 Loc, Gen); 1851 if (Res.first) { 1852 // 'atomicrmw' instruction was generated. 1853 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 1854 } 1855 } 1856 // Emit post-update store to 'v' of old/new 'x' value. 1857 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType); 1858 // OpenMP, 2.12.6, atomic Construct 1859 // Any atomic construct with a seq_cst clause forces the atomically 1860 // performed operation to include an implicit flush operation without a 1861 // list. 1862 if (IsSeqCst) 1863 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1864 } 1865 1866 static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 1867 bool IsSeqCst, bool IsPostfixUpdate, 1868 const Expr *X, const Expr *V, const Expr *E, 1869 const Expr *UE, bool IsXLHSInRHSPart, 1870 SourceLocation Loc) { 1871 switch (Kind) { 1872 case OMPC_read: 1873 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc); 1874 break; 1875 case OMPC_write: 1876 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc); 1877 break; 1878 case OMPC_unknown: 1879 case OMPC_update: 1880 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc); 1881 break; 1882 case OMPC_capture: 1883 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE, 1884 IsXLHSInRHSPart, Loc); 1885 break; 1886 case OMPC_if: 1887 case OMPC_final: 1888 case OMPC_num_threads: 1889 case OMPC_private: 1890 case OMPC_firstprivate: 1891 case OMPC_lastprivate: 1892 case OMPC_reduction: 1893 case OMPC_safelen: 1894 case OMPC_collapse: 1895 case OMPC_default: 1896 case OMPC_seq_cst: 1897 case OMPC_shared: 1898 case OMPC_linear: 1899 case OMPC_aligned: 1900 case OMPC_copyin: 1901 case OMPC_copyprivate: 1902 case OMPC_flush: 1903 case OMPC_proc_bind: 1904 case OMPC_schedule: 1905 case OMPC_ordered: 1906 case OMPC_nowait: 1907 case OMPC_untied: 1908 case OMPC_threadprivate: 1909 case OMPC_mergeable: 1910 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 1911 } 1912 } 1913 1914 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 1915 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst); 1916 OpenMPClauseKind Kind = OMPC_unknown; 1917 for (auto *C : S.clauses()) { 1918 // Find first clause (skip seq_cst clause, if it is first). 1919 if (C->getClauseKind() != OMPC_seq_cst) { 1920 Kind = C->getClauseKind(); 1921 break; 1922 } 1923 } 1924 1925 const auto *CS = 1926 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true); 1927 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) { 1928 enterFullExpression(EWC); 1929 } 1930 // Processing for statements under 'atomic capture'. 1931 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) { 1932 for (const auto *C : Compound->body()) { 1933 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) { 1934 enterFullExpression(EWC); 1935 } 1936 } 1937 } 1938 1939 LexicalScope Scope(*this, S.getSourceRange()); 1940 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) { 1941 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(), 1942 S.getV(), S.getExpr(), S.getUpdateExpr(), 1943 S.isXLHSInRHSPart(), S.getLocStart()); 1944 }; 1945 CGM.getOpenMPRuntime().emitInlinedDirective(*this, CodeGen); 1946 } 1947 1948 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) { 1949 llvm_unreachable("CodeGen for 'omp target' is not supported yet."); 1950 } 1951 1952 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) { 1953 llvm_unreachable("CodeGen for 'omp teams' is not supported yet."); 1954 } 1955