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