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