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 const VarDecl *IVDecl = 710 cast<VarDecl>(cast<DeclRefExpr>(S.getIterationVariable())->getDecl()); 711 bool IsRegistered = PreCondScope.addPrivate(IVDecl, [&]() -> llvm::Value *{ 712 // Emit var without initialization. 713 auto VarEmission = CGF.EmitAutoVarAlloca(*IVDecl); 714 CGF.EmitAutoVarCleanups(VarEmission); 715 return VarEmission.getAllocatedAddress(); 716 }); 717 assert(IsRegistered && "counter already registered as private"); 718 // Silence the warning about unused variable. 719 (void)IsRegistered; 720 (void)PreCondScope.Privatize(); 721 // Initialize internal counter to 0 to calculate initial values of real 722 // counters. 723 LValue IV = CGF.EmitLValue(S.getIterationVariable()); 724 CGF.EmitStoreOfScalar( 725 llvm::ConstantInt::getNullValue( 726 IV.getAddress()->getType()->getPointerElementType()), 727 CGF.EmitLValue(S.getIterationVariable()), /*isInit=*/true); 728 // Get initial values of real counters. 729 for (auto I : S.updates()) { 730 CGF.EmitIgnoredExpr(I); 731 } 732 } 733 // Check that loop is executed at least one time. 734 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 735 } 736 737 static void 738 emitPrivateLinearVars(CodeGenFunction &CGF, const OMPExecutableDirective &D, 739 CodeGenFunction::OMPPrivateScope &PrivateScope) { 740 for (auto &&I = D.getClausesOfKind(OMPC_linear); I; ++I) { 741 auto *C = cast<OMPLinearClause>(*I); 742 for (auto *E : C->varlists()) { 743 auto VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 744 bool IsRegistered = PrivateScope.addPrivate(VD, [&]()->llvm::Value * { 745 // Emit var without initialization. 746 auto VarEmission = CGF.EmitAutoVarAlloca(*VD); 747 CGF.EmitAutoVarCleanups(VarEmission); 748 return VarEmission.getAllocatedAddress(); 749 }); 750 assert(IsRegistered && "linear var already registered as private"); 751 // Silence the warning about unused variable. 752 (void)IsRegistered; 753 } 754 } 755 } 756 757 static void emitSafelenClause(CodeGenFunction &CGF, 758 const OMPExecutableDirective &D) { 759 if (auto *C = 760 cast_or_null<OMPSafelenClause>(D.getSingleClause(OMPC_safelen))) { 761 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(), 762 /*ignoreResult=*/true); 763 llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 764 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 765 // In presence of finite 'safelen', it may be unsafe to mark all 766 // the memory instructions parallel, because loop-carried 767 // dependences of 'safelen' iterations are possible. 768 CGF.LoopStack.setParallel(false); 769 } 770 } 771 772 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) { 773 // Walk clauses and process safelen/lastprivate. 774 LoopStack.setParallel(); 775 LoopStack.setVectorizeEnable(true); 776 emitSafelenClause(*this, D); 777 } 778 779 void CodeGenFunction::EmitOMPSimdFinal(const OMPLoopDirective &D) { 780 auto IC = D.counters().begin(); 781 for (auto F : D.finals()) { 782 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 783 if (LocalDeclMap.lookup(OrigVD) || CapturedStmtInfo->lookup(OrigVD)) { 784 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), 785 CapturedStmtInfo->lookup(OrigVD) != nullptr, 786 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 787 auto *OrigAddr = EmitLValue(&DRE).getAddress(); 788 OMPPrivateScope VarScope(*this); 789 VarScope.addPrivate(OrigVD, 790 [OrigAddr]() -> llvm::Value *{ return OrigAddr; }); 791 (void)VarScope.Privatize(); 792 EmitIgnoredExpr(F); 793 } 794 ++IC; 795 } 796 emitLinearClauseFinal(*this, D); 797 } 798 799 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 800 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 801 // if (PreCond) { 802 // for (IV in 0..LastIteration) BODY; 803 // <Final counter/linear vars updates>; 804 // } 805 // 806 807 // Emit: if (PreCond) - begin. 808 // If the condition constant folds and can be elided, avoid emitting the 809 // whole loop. 810 bool CondConstant; 811 llvm::BasicBlock *ContBlock = nullptr; 812 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 813 if (!CondConstant) 814 return; 815 } else { 816 auto *ThenBlock = CGF.createBasicBlock("simd.if.then"); 817 ContBlock = CGF.createBasicBlock("simd.if.end"); 818 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 819 CGF.getProfileCount(&S)); 820 CGF.EmitBlock(ThenBlock); 821 CGF.incrementProfileCounter(&S); 822 } 823 824 // Emit the loop iteration variable. 825 const Expr *IVExpr = S.getIterationVariable(); 826 const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 827 CGF.EmitVarDecl(*IVDecl); 828 CGF.EmitIgnoredExpr(S.getInit()); 829 830 // Emit the iterations count variable. 831 // If it is not a variable, Sema decided to calculate iterations count on 832 // each iteration (e.g., it is foldable into a constant). 833 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 834 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 835 // Emit calculation of the iterations count. 836 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 837 } 838 839 CGF.EmitOMPSimdInit(S); 840 841 emitAlignedClause(CGF, S); 842 CGF.EmitOMPLinearClauseInit(S); 843 bool HasLastprivateClause; 844 { 845 OMPPrivateScope LoopScope(CGF); 846 emitPrivateLoopCounters(CGF, LoopScope, S.counters(), 847 S.private_counters()); 848 emitPrivateLinearVars(CGF, S, LoopScope); 849 CGF.EmitOMPPrivateClause(S, LoopScope); 850 CGF.EmitOMPReductionClauseInit(S, LoopScope); 851 HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 852 (void)LoopScope.Privatize(); 853 CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), 854 S.getInc(), 855 [&S](CodeGenFunction &CGF) { 856 CGF.EmitOMPLoopBody(S, JumpDest()); 857 CGF.EmitStopPoint(&S); 858 }, 859 [](CodeGenFunction &) {}); 860 // Emit final copy of the lastprivate variables at the end of loops. 861 if (HasLastprivateClause) { 862 CGF.EmitOMPLastprivateClauseFinal(S); 863 } 864 CGF.EmitOMPReductionClauseFinal(S); 865 } 866 CGF.EmitOMPSimdFinal(S); 867 // Emit: if (PreCond) - end. 868 if (ContBlock) { 869 CGF.EmitBranch(ContBlock); 870 CGF.EmitBlock(ContBlock, true); 871 } 872 }; 873 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 874 } 875 876 void CodeGenFunction::EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind, 877 const OMPLoopDirective &S, 878 OMPPrivateScope &LoopScope, 879 bool Ordered, llvm::Value *LB, 880 llvm::Value *UB, llvm::Value *ST, 881 llvm::Value *IL, llvm::Value *Chunk) { 882 auto &RT = CGM.getOpenMPRuntime(); 883 884 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 885 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind); 886 887 assert((Ordered || 888 !RT.isStaticNonchunked(ScheduleKind, /*Chunked=*/Chunk != nullptr)) && 889 "static non-chunked schedule does not need outer loop"); 890 891 // Emit outer loop. 892 // 893 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 894 // When schedule(dynamic,chunk_size) is specified, the iterations are 895 // distributed to threads in the team in chunks as the threads request them. 896 // Each thread executes a chunk of iterations, then requests another chunk, 897 // until no chunks remain to be distributed. Each chunk contains chunk_size 898 // iterations, except for the last chunk to be distributed, which may have 899 // fewer iterations. When no chunk_size is specified, it defaults to 1. 900 // 901 // When schedule(guided,chunk_size) is specified, the iterations are assigned 902 // to threads in the team in chunks as the executing threads request them. 903 // Each thread executes a chunk of iterations, then requests another chunk, 904 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 905 // each chunk is proportional to the number of unassigned iterations divided 906 // by the number of threads in the team, decreasing to 1. For a chunk_size 907 // with value k (greater than 1), the size of each chunk is determined in the 908 // same way, with the restriction that the chunks do not contain fewer than k 909 // iterations (except for the last chunk to be assigned, which may have fewer 910 // than k iterations). 911 // 912 // When schedule(auto) is specified, the decision regarding scheduling is 913 // delegated to the compiler and/or runtime system. The programmer gives the 914 // implementation the freedom to choose any possible mapping of iterations to 915 // threads in the team. 916 // 917 // When schedule(runtime) is specified, the decision regarding scheduling is 918 // deferred until run time, and the schedule and chunk size are taken from the 919 // run-sched-var ICV. If the ICV is set to auto, the schedule is 920 // implementation defined 921 // 922 // while(__kmpc_dispatch_next(&LB, &UB)) { 923 // idx = LB; 924 // while (idx <= UB) { BODY; ++idx; 925 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 926 // } // inner loop 927 // } 928 // 929 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 930 // When schedule(static, chunk_size) is specified, iterations are divided into 931 // chunks of size chunk_size, and the chunks are assigned to the threads in 932 // the team in a round-robin fashion in the order of the thread number. 933 // 934 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 935 // while (idx <= UB) { BODY; ++idx; } // inner loop 936 // LB = LB + ST; 937 // UB = UB + ST; 938 // } 939 // 940 941 const Expr *IVExpr = S.getIterationVariable(); 942 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 943 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 944 945 RT.emitForInit( 946 *this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, Ordered, IL, LB, 947 (DynamicOrOrdered ? EmitAnyExpr(S.getLastIteration()).getScalarVal() 948 : UB), 949 ST, Chunk); 950 951 auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 952 953 // Start the loop with a block that tests the condition. 954 auto CondBlock = createBasicBlock("omp.dispatch.cond"); 955 EmitBlock(CondBlock); 956 LoopStack.push(CondBlock); 957 958 llvm::Value *BoolCondVal = nullptr; 959 if (!DynamicOrOrdered) { 960 // UB = min(UB, GlobalUB) 961 EmitIgnoredExpr(S.getEnsureUpperBound()); 962 // IV = LB 963 EmitIgnoredExpr(S.getInit()); 964 // IV < UB 965 BoolCondVal = EvaluateExprAsBool(S.getCond()); 966 } else { 967 BoolCondVal = RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, 968 IL, LB, UB, ST); 969 } 970 971 // If there are any cleanups between here and the loop-exit scope, 972 // create a block to stage a loop exit along. 973 auto ExitBlock = LoopExit.getBlock(); 974 if (LoopScope.requiresCleanups()) 975 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 976 977 auto LoopBody = createBasicBlock("omp.dispatch.body"); 978 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 979 if (ExitBlock != LoopExit.getBlock()) { 980 EmitBlock(ExitBlock); 981 EmitBranchThroughCleanup(LoopExit); 982 } 983 EmitBlock(LoopBody); 984 985 // Emit "IV = LB" (in case of static schedule, we have already calculated new 986 // LB for loop condition and emitted it above). 987 if (DynamicOrOrdered) 988 EmitIgnoredExpr(S.getInit()); 989 990 // Create a block for the increment. 991 auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 992 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 993 994 // Generate !llvm.loop.parallel metadata for loads and stores for loops 995 // with dynamic/guided scheduling and without ordered clause. 996 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 997 LoopStack.setParallel((ScheduleKind == OMPC_SCHEDULE_dynamic || 998 ScheduleKind == OMPC_SCHEDULE_guided) && 999 !Ordered); 1000 } else { 1001 EmitOMPSimdInit(S); 1002 } 1003 1004 SourceLocation Loc = S.getLocStart(); 1005 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 1006 [&S, LoopExit](CodeGenFunction &CGF) { 1007 CGF.EmitOMPLoopBody(S, LoopExit); 1008 CGF.EmitStopPoint(&S); 1009 }, 1010 [Ordered, IVSize, IVSigned, Loc](CodeGenFunction &CGF) { 1011 if (Ordered) { 1012 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd( 1013 CGF, Loc, IVSize, IVSigned); 1014 } 1015 }); 1016 1017 EmitBlock(Continue.getBlock()); 1018 BreakContinueStack.pop_back(); 1019 if (!DynamicOrOrdered) { 1020 // Emit "LB = LB + Stride", "UB = UB + Stride". 1021 EmitIgnoredExpr(S.getNextLowerBound()); 1022 EmitIgnoredExpr(S.getNextUpperBound()); 1023 } 1024 1025 EmitBranch(CondBlock); 1026 LoopStack.pop(); 1027 // Emit the fall-through block. 1028 EmitBlock(LoopExit.getBlock()); 1029 1030 // Tell the runtime we are done. 1031 if (!DynamicOrOrdered) 1032 RT.emitForStaticFinish(*this, S.getLocEnd()); 1033 } 1034 1035 /// \brief Emit a helper variable and return corresponding lvalue. 1036 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 1037 const DeclRefExpr *Helper) { 1038 auto VDecl = cast<VarDecl>(Helper->getDecl()); 1039 CGF.EmitVarDecl(*VDecl); 1040 return CGF.EmitLValue(Helper); 1041 } 1042 1043 static std::pair<llvm::Value * /*Chunk*/, OpenMPScheduleClauseKind> 1044 emitScheduleClause(CodeGenFunction &CGF, const OMPLoopDirective &S, 1045 bool OuterRegion) { 1046 // Detect the loop schedule kind and chunk. 1047 auto ScheduleKind = OMPC_SCHEDULE_unknown; 1048 llvm::Value *Chunk = nullptr; 1049 if (auto *C = 1050 cast_or_null<OMPScheduleClause>(S.getSingleClause(OMPC_schedule))) { 1051 ScheduleKind = C->getScheduleKind(); 1052 if (const auto *Ch = C->getChunkSize()) { 1053 if (auto *ImpRef = cast_or_null<DeclRefExpr>(C->getHelperChunkSize())) { 1054 if (OuterRegion) { 1055 const VarDecl *ImpVar = cast<VarDecl>(ImpRef->getDecl()); 1056 CGF.EmitVarDecl(*ImpVar); 1057 CGF.EmitStoreThroughLValue( 1058 CGF.EmitAnyExpr(Ch), 1059 CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(ImpVar), 1060 ImpVar->getType())); 1061 } else { 1062 Ch = ImpRef; 1063 } 1064 } 1065 if (!C->getHelperChunkSize() || !OuterRegion) { 1066 Chunk = CGF.EmitScalarExpr(Ch); 1067 Chunk = CGF.EmitScalarConversion(Chunk, Ch->getType(), 1068 S.getIterationVariable()->getType(), 1069 S.getLocStart()); 1070 } 1071 } 1072 } 1073 return std::make_pair(Chunk, ScheduleKind); 1074 } 1075 1076 bool CodeGenFunction::EmitOMPWorksharingLoop(const OMPLoopDirective &S) { 1077 // Emit the loop iteration variable. 1078 auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 1079 auto IVDecl = cast<VarDecl>(IVExpr->getDecl()); 1080 EmitVarDecl(*IVDecl); 1081 1082 // Emit the iterations count variable. 1083 // If it is not a variable, Sema decided to calculate iterations count on each 1084 // iteration (e.g., it is foldable into a constant). 1085 if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 1086 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 1087 // Emit calculation of the iterations count. 1088 EmitIgnoredExpr(S.getCalcLastIteration()); 1089 } 1090 1091 auto &RT = CGM.getOpenMPRuntime(); 1092 1093 bool HasLastprivateClause; 1094 // Check pre-condition. 1095 { 1096 // Skip the entire loop if we don't meet the precondition. 1097 // If the condition constant folds and can be elided, avoid emitting the 1098 // whole loop. 1099 bool CondConstant; 1100 llvm::BasicBlock *ContBlock = nullptr; 1101 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 1102 if (!CondConstant) 1103 return false; 1104 } else { 1105 auto *ThenBlock = createBasicBlock("omp.precond.then"); 1106 ContBlock = createBasicBlock("omp.precond.end"); 1107 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 1108 getProfileCount(&S)); 1109 EmitBlock(ThenBlock); 1110 incrementProfileCounter(&S); 1111 } 1112 1113 emitAlignedClause(*this, S); 1114 EmitOMPLinearClauseInit(S); 1115 // Emit 'then' code. 1116 { 1117 // Emit helper vars inits. 1118 LValue LB = 1119 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getLowerBoundVariable())); 1120 LValue UB = 1121 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getUpperBoundVariable())); 1122 LValue ST = 1123 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 1124 LValue IL = 1125 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 1126 1127 OMPPrivateScope LoopScope(*this); 1128 if (EmitOMPFirstprivateClause(S, LoopScope)) { 1129 // Emit implicit barrier to synchronize threads and avoid data races on 1130 // initialization of firstprivate variables. 1131 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), 1132 OMPD_unknown); 1133 } 1134 EmitOMPPrivateClause(S, LoopScope); 1135 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 1136 EmitOMPReductionClauseInit(S, LoopScope); 1137 emitPrivateLoopCounters(*this, LoopScope, S.counters(), 1138 S.private_counters()); 1139 emitPrivateLinearVars(*this, S, LoopScope); 1140 (void)LoopScope.Privatize(); 1141 1142 // Detect the loop schedule kind and chunk. 1143 llvm::Value *Chunk; 1144 OpenMPScheduleClauseKind ScheduleKind; 1145 auto ScheduleInfo = 1146 emitScheduleClause(*this, S, /*OuterRegion=*/false); 1147 Chunk = ScheduleInfo.first; 1148 ScheduleKind = ScheduleInfo.second; 1149 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 1150 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 1151 const bool Ordered = S.getSingleClause(OMPC_ordered) != nullptr; 1152 if (RT.isStaticNonchunked(ScheduleKind, 1153 /* Chunked */ Chunk != nullptr) && 1154 !Ordered) { 1155 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 1156 EmitOMPSimdInit(S); 1157 } 1158 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 1159 // When no chunk_size is specified, the iteration space is divided into 1160 // chunks that are approximately equal in size, and at most one chunk is 1161 // distributed to each thread. Note that the size of the chunks is 1162 // unspecified in this case. 1163 RT.emitForInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned, 1164 Ordered, IL.getAddress(), LB.getAddress(), 1165 UB.getAddress(), ST.getAddress()); 1166 auto LoopExit = getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 1167 // UB = min(UB, GlobalUB); 1168 EmitIgnoredExpr(S.getEnsureUpperBound()); 1169 // IV = LB; 1170 EmitIgnoredExpr(S.getInit()); 1171 // while (idx <= UB) { BODY; ++idx; } 1172 EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(), 1173 S.getInc(), 1174 [&S, LoopExit](CodeGenFunction &CGF) { 1175 CGF.EmitOMPLoopBody(S, LoopExit); 1176 CGF.EmitStopPoint(&S); 1177 }, 1178 [](CodeGenFunction &) {}); 1179 EmitBlock(LoopExit.getBlock()); 1180 // Tell the runtime we are done. 1181 RT.emitForStaticFinish(*this, S.getLocStart()); 1182 } else { 1183 // Emit the outer loop, which requests its work chunk [LB..UB] from 1184 // runtime and runs the inner loop to process it. 1185 EmitOMPForOuterLoop(ScheduleKind, S, LoopScope, Ordered, 1186 LB.getAddress(), UB.getAddress(), ST.getAddress(), 1187 IL.getAddress(), Chunk); 1188 } 1189 EmitOMPReductionClauseFinal(S); 1190 // Emit final copy of the lastprivate variables if IsLastIter != 0. 1191 if (HasLastprivateClause) 1192 EmitOMPLastprivateClauseFinal( 1193 S, Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart()))); 1194 } 1195 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 1196 EmitOMPSimdFinal(S); 1197 } 1198 // We're now done with the loop, so jump to the continuation block. 1199 if (ContBlock) { 1200 EmitBranch(ContBlock); 1201 EmitBlock(ContBlock, true); 1202 } 1203 } 1204 return HasLastprivateClause; 1205 } 1206 1207 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 1208 LexicalScope Scope(*this, S.getSourceRange()); 1209 bool HasLastprivates = false; 1210 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) { 1211 HasLastprivates = CGF.EmitOMPWorksharingLoop(S); 1212 }; 1213 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen); 1214 1215 // Emit an implicit barrier at the end. 1216 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) { 1217 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for); 1218 } 1219 } 1220 1221 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) { 1222 LexicalScope Scope(*this, S.getSourceRange()); 1223 bool HasLastprivates = false; 1224 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF) { 1225 HasLastprivates = CGF.EmitOMPWorksharingLoop(S); 1226 }; 1227 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 1228 1229 // Emit an implicit barrier at the end. 1230 if (!S.getSingleClause(OMPC_nowait) || HasLastprivates) { 1231 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for); 1232 } 1233 } 1234 1235 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 1236 const Twine &Name, 1237 llvm::Value *Init = nullptr) { 1238 auto LVal = CGF.MakeNaturalAlignAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 1239 if (Init) 1240 CGF.EmitScalarInit(Init, LVal); 1241 return LVal; 1242 } 1243 1244 OpenMPDirectiveKind 1245 CodeGenFunction::EmitSections(const OMPExecutableDirective &S) { 1246 auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt(); 1247 auto *CS = dyn_cast<CompoundStmt>(Stmt); 1248 if (CS && CS->size() > 1) { 1249 bool HasLastprivates = false; 1250 auto &&CodeGen = [&S, CS, &HasLastprivates](CodeGenFunction &CGF) { 1251 auto &C = CGF.CGM.getContext(); 1252 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1253 // Emit helper vars inits. 1254 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 1255 CGF.Builder.getInt32(0)); 1256 auto *GlobalUBVal = CGF.Builder.getInt32(CS->size() - 1); 1257 LValue UB = 1258 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 1259 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 1260 CGF.Builder.getInt32(1)); 1261 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 1262 CGF.Builder.getInt32(0)); 1263 // Loop counter. 1264 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 1265 OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue); 1266 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 1267 OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue); 1268 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 1269 // Generate condition for loop. 1270 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue, 1271 OK_Ordinary, S.getLocStart(), 1272 /*fpContractable=*/false); 1273 // Increment for loop counter. 1274 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, 1275 OK_Ordinary, S.getLocStart()); 1276 auto BodyGen = [CS, &S, &IV](CodeGenFunction &CGF) { 1277 // Iterate through all sections and emit a switch construct: 1278 // switch (IV) { 1279 // case 0: 1280 // <SectionStmt[0]>; 1281 // break; 1282 // ... 1283 // case <NumSection> - 1: 1284 // <SectionStmt[<NumSection> - 1]>; 1285 // break; 1286 // } 1287 // .omp.sections.exit: 1288 auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 1289 auto *SwitchStmt = CGF.Builder.CreateSwitch( 1290 CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB, 1291 CS->size()); 1292 unsigned CaseNumber = 0; 1293 for (auto *SubStmt : CS->children()) { 1294 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 1295 CGF.EmitBlock(CaseBB); 1296 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 1297 CGF.EmitStmt(SubStmt); 1298 CGF.EmitBranch(ExitBB); 1299 ++CaseNumber; 1300 } 1301 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 1302 }; 1303 1304 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 1305 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 1306 // Emit implicit barrier to synchronize threads and avoid data races on 1307 // initialization of firstprivate variables. 1308 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1309 OMPD_unknown); 1310 } 1311 CGF.EmitOMPPrivateClause(S, LoopScope); 1312 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 1313 CGF.EmitOMPReductionClauseInit(S, LoopScope); 1314 (void)LoopScope.Privatize(); 1315 1316 // Emit static non-chunked loop. 1317 CGF.CGM.getOpenMPRuntime().emitForInit( 1318 CGF, S.getLocStart(), OMPC_SCHEDULE_static, /*IVSize=*/32, 1319 /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), 1320 LB.getAddress(), UB.getAddress(), ST.getAddress()); 1321 // UB = min(UB, GlobalUB); 1322 auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart()); 1323 auto *MinUBGlobalUB = CGF.Builder.CreateSelect( 1324 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 1325 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 1326 // IV = LB; 1327 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV); 1328 // while (idx <= UB) { BODY; ++idx; } 1329 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen, 1330 [](CodeGenFunction &) {}); 1331 // Tell the runtime we are done. 1332 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocStart()); 1333 CGF.EmitOMPReductionClauseFinal(S); 1334 1335 // Emit final copy of the lastprivate variables if IsLastIter != 0. 1336 if (HasLastprivates) 1337 CGF.EmitOMPLastprivateClauseFinal( 1338 S, CGF.Builder.CreateIsNotNull( 1339 CGF.EmitLoadOfScalar(IL, S.getLocStart()))); 1340 }; 1341 1342 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen); 1343 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 1344 // clause. Otherwise the barrier will be generated by the codegen for the 1345 // directive. 1346 if (HasLastprivates && S.getSingleClause(OMPC_nowait)) { 1347 // Emit implicit barrier to synchronize threads and avoid data races on 1348 // initialization of firstprivate variables. 1349 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), 1350 OMPD_unknown); 1351 } 1352 return OMPD_sections; 1353 } 1354 // If only one section is found - no need to generate loop, emit as a single 1355 // region. 1356 bool HasFirstprivates; 1357 // No need to generate reductions for sections with single section region, we 1358 // can use original shared variables for all operations. 1359 bool HasReductions = !S.getClausesOfKind(OMPC_reduction).empty(); 1360 // No need to generate lastprivates for sections with single section region, 1361 // we can use original shared variable for all calculations with barrier at 1362 // the end of the sections. 1363 bool HasLastprivates = !S.getClausesOfKind(OMPC_lastprivate).empty(); 1364 auto &&CodeGen = [Stmt, &S, &HasFirstprivates](CodeGenFunction &CGF) { 1365 CodeGenFunction::OMPPrivateScope SingleScope(CGF); 1366 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope); 1367 CGF.EmitOMPPrivateClause(S, SingleScope); 1368 (void)SingleScope.Privatize(); 1369 1370 CGF.EmitStmt(Stmt); 1371 }; 1372 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(), 1373 llvm::None, llvm::None, llvm::None, 1374 llvm::None); 1375 // Emit barrier for firstprivates, lastprivates or reductions only if 1376 // 'sections' directive has 'nowait' clause. Otherwise the barrier will be 1377 // generated by the codegen for the directive. 1378 if ((HasFirstprivates || HasLastprivates || HasReductions) && 1379 S.getSingleClause(OMPC_nowait)) { 1380 // Emit implicit barrier to synchronize threads and avoid data races on 1381 // initialization of firstprivate variables. 1382 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_unknown); 1383 } 1384 return OMPD_single; 1385 } 1386 1387 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 1388 LexicalScope Scope(*this, S.getSourceRange()); 1389 OpenMPDirectiveKind EmittedAs = EmitSections(S); 1390 // Emit an implicit barrier at the end. 1391 if (!S.getSingleClause(OMPC_nowait)) { 1392 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), EmittedAs); 1393 } 1394 } 1395 1396 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 1397 LexicalScope Scope(*this, S.getSourceRange()); 1398 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1399 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1400 CGF.EnsureInsertPoint(); 1401 }; 1402 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen); 1403 } 1404 1405 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 1406 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 1407 llvm::SmallVector<const Expr *, 8> DestExprs; 1408 llvm::SmallVector<const Expr *, 8> SrcExprs; 1409 llvm::SmallVector<const Expr *, 8> AssignmentOps; 1410 // Check if there are any 'copyprivate' clauses associated with this 1411 // 'single' 1412 // construct. 1413 // Build a list of copyprivate variables along with helper expressions 1414 // (<source>, <destination>, <destination>=<source> expressions) 1415 for (auto &&I = S.getClausesOfKind(OMPC_copyprivate); I; ++I) { 1416 auto *C = cast<OMPCopyprivateClause>(*I); 1417 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 1418 DestExprs.append(C->destination_exprs().begin(), 1419 C->destination_exprs().end()); 1420 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 1421 AssignmentOps.append(C->assignment_ops().begin(), 1422 C->assignment_ops().end()); 1423 } 1424 LexicalScope Scope(*this, S.getSourceRange()); 1425 // Emit code for 'single' region along with 'copyprivate' clauses 1426 bool HasFirstprivates; 1427 auto &&CodeGen = [&S, &HasFirstprivates](CodeGenFunction &CGF) { 1428 CodeGenFunction::OMPPrivateScope SingleScope(CGF); 1429 HasFirstprivates = CGF.EmitOMPFirstprivateClause(S, SingleScope); 1430 CGF.EmitOMPPrivateClause(S, SingleScope); 1431 (void)SingleScope.Privatize(); 1432 1433 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1434 CGF.EnsureInsertPoint(); 1435 }; 1436 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(), 1437 CopyprivateVars, DestExprs, SrcExprs, 1438 AssignmentOps); 1439 // Emit an implicit barrier at the end (to avoid data race on firstprivate 1440 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 1441 if ((!S.getSingleClause(OMPC_nowait) || HasFirstprivates) && 1442 CopyprivateVars.empty()) { 1443 CGM.getOpenMPRuntime().emitBarrierCall( 1444 *this, S.getLocStart(), 1445 S.getSingleClause(OMPC_nowait) ? OMPD_unknown : OMPD_single); 1446 } 1447 } 1448 1449 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 1450 LexicalScope Scope(*this, S.getSourceRange()); 1451 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1452 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1453 CGF.EnsureInsertPoint(); 1454 }; 1455 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart()); 1456 } 1457 1458 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 1459 LexicalScope Scope(*this, S.getSourceRange()); 1460 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1461 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1462 CGF.EnsureInsertPoint(); 1463 }; 1464 CGM.getOpenMPRuntime().emitCriticalRegion( 1465 *this, S.getDirectiveName().getAsString(), CodeGen, S.getLocStart()); 1466 } 1467 1468 void CodeGenFunction::EmitOMPParallelForDirective( 1469 const OMPParallelForDirective &S) { 1470 // Emit directive as a combined directive that consists of two implicit 1471 // directives: 'parallel' with 'for' directive. 1472 LexicalScope Scope(*this, S.getSourceRange()); 1473 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true); 1474 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1475 CGF.EmitOMPWorksharingLoop(S); 1476 // Emit implicit barrier at the end of parallel region, but this barrier 1477 // is at the end of 'for' directive, so emit it as the implicit barrier for 1478 // this 'for' directive. 1479 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1480 OMPD_parallel); 1481 }; 1482 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen); 1483 } 1484 1485 void CodeGenFunction::EmitOMPParallelForSimdDirective( 1486 const OMPParallelForSimdDirective &S) { 1487 // Emit directive as a combined directive that consists of two implicit 1488 // directives: 'parallel' with 'for' directive. 1489 LexicalScope Scope(*this, S.getSourceRange()); 1490 (void)emitScheduleClause(*this, S, /*OuterRegion=*/true); 1491 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1492 CGF.EmitOMPWorksharingLoop(S); 1493 // Emit implicit barrier at the end of parallel region, but this barrier 1494 // is at the end of 'for' directive, so emit it as the implicit barrier for 1495 // this 'for' directive. 1496 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1497 OMPD_parallel); 1498 }; 1499 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen); 1500 } 1501 1502 void CodeGenFunction::EmitOMPParallelSectionsDirective( 1503 const OMPParallelSectionsDirective &S) { 1504 // Emit directive as a combined directive that consists of two implicit 1505 // directives: 'parallel' with 'sections' directive. 1506 LexicalScope Scope(*this, S.getSourceRange()); 1507 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1508 (void)CGF.EmitSections(S); 1509 // Emit implicit barrier at the end of parallel region. 1510 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getLocStart(), 1511 OMPD_parallel); 1512 }; 1513 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen); 1514 } 1515 1516 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 1517 // Emit outlined function for task construct. 1518 LexicalScope Scope(*this, S.getSourceRange()); 1519 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 1520 auto CapturedStruct = GenerateCapturedStmtArgument(*CS); 1521 auto *I = CS->getCapturedDecl()->param_begin(); 1522 auto *PartId = std::next(I); 1523 // The first function argument for tasks is a thread id, the second one is a 1524 // part id (0 for tied tasks, >=0 for untied task). 1525 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 1526 // Get list of private variables. 1527 llvm::SmallVector<const Expr *, 8> PrivateVars; 1528 llvm::SmallVector<const Expr *, 8> PrivateCopies; 1529 for (auto &&I = S.getClausesOfKind(OMPC_private); I; ++I) { 1530 auto *C = cast<OMPPrivateClause>(*I); 1531 auto IRef = C->varlist_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 PrivateVars.push_back(*IRef); 1536 PrivateCopies.push_back(IInit); 1537 } 1538 ++IRef; 1539 } 1540 } 1541 EmittedAsPrivate.clear(); 1542 // Get list of firstprivate variables. 1543 llvm::SmallVector<const Expr *, 8> FirstprivateVars; 1544 llvm::SmallVector<const Expr *, 8> FirstprivateCopies; 1545 llvm::SmallVector<const Expr *, 8> FirstprivateInits; 1546 for (auto &&I = S.getClausesOfKind(OMPC_firstprivate); I; ++I) { 1547 auto *C = cast<OMPFirstprivateClause>(*I); 1548 auto IRef = C->varlist_begin(); 1549 auto IElemInitRef = C->inits().begin(); 1550 for (auto *IInit : C->private_copies()) { 1551 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1552 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 1553 FirstprivateVars.push_back(*IRef); 1554 FirstprivateCopies.push_back(IInit); 1555 FirstprivateInits.push_back(*IElemInitRef); 1556 } 1557 ++IRef, ++IElemInitRef; 1558 } 1559 } 1560 // Build list of dependences. 1561 llvm::SmallVector<std::pair<OpenMPDependClauseKind, const Expr *>, 8> 1562 Dependences; 1563 for (auto &&I = S.getClausesOfKind(OMPC_depend); I; ++I) { 1564 auto *C = cast<OMPDependClause>(*I); 1565 for (auto *IRef : C->varlists()) { 1566 Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef)); 1567 } 1568 } 1569 auto &&CodeGen = [PartId, &S, &PrivateVars, &FirstprivateVars]( 1570 CodeGenFunction &CGF) { 1571 // Set proper addresses for generated private copies. 1572 auto *CS = cast<CapturedStmt>(S.getAssociatedStmt()); 1573 OMPPrivateScope Scope(CGF); 1574 if (!PrivateVars.empty() || !FirstprivateVars.empty()) { 1575 auto *CopyFn = CGF.Builder.CreateAlignedLoad( 1576 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)), 1577 CGF.PointerAlignInBytes); 1578 auto *PrivatesPtr = CGF.Builder.CreateAlignedLoad( 1579 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)), 1580 CGF.PointerAlignInBytes); 1581 // Map privates. 1582 llvm::SmallVector<std::pair<const VarDecl *, llvm::Value *>, 16> 1583 PrivatePtrs; 1584 llvm::SmallVector<llvm::Value *, 16> CallArgs; 1585 CallArgs.push_back(PrivatesPtr); 1586 for (auto *E : PrivateVars) { 1587 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1588 auto *PrivatePtr = 1589 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType())); 1590 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr)); 1591 CallArgs.push_back(PrivatePtr); 1592 } 1593 for (auto *E : FirstprivateVars) { 1594 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1595 auto *PrivatePtr = 1596 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType())); 1597 PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr)); 1598 CallArgs.push_back(PrivatePtr); 1599 } 1600 CGF.EmitRuntimeCall(CopyFn, CallArgs); 1601 for (auto &&Pair : PrivatePtrs) { 1602 auto *Replacement = 1603 CGF.Builder.CreateAlignedLoad(Pair.second, CGF.PointerAlignInBytes); 1604 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 1605 } 1606 } 1607 (void)Scope.Privatize(); 1608 if (*PartId) { 1609 // TODO: emit code for untied tasks. 1610 } 1611 CGF.EmitStmt(CS->getCapturedStmt()); 1612 }; 1613 auto OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 1614 S, *I, OMPD_task, CodeGen); 1615 // Check if we should emit tied or untied task. 1616 bool Tied = !S.getSingleClause(OMPC_untied); 1617 // Check if the task is final 1618 llvm::PointerIntPair<llvm::Value *, 1, bool> Final; 1619 if (auto *Clause = S.getSingleClause(OMPC_final)) { 1620 // If the condition constant folds and can be elided, try to avoid emitting 1621 // the condition and the dead arm of the if/else. 1622 auto *Cond = cast<OMPFinalClause>(Clause)->getCondition(); 1623 bool CondConstant; 1624 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 1625 Final.setInt(CondConstant); 1626 else 1627 Final.setPointer(EvaluateExprAsBool(Cond)); 1628 } else { 1629 // By default the task is not final. 1630 Final.setInt(/*IntVal=*/false); 1631 } 1632 auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 1633 const Expr *IfCond = nullptr; 1634 if (auto C = S.getSingleClause(OMPC_if)) { 1635 IfCond = cast<OMPIfClause>(C)->getCondition(); 1636 } 1637 CGM.getOpenMPRuntime().emitTaskCall( 1638 *this, S.getLocStart(), S, Tied, Final, OutlinedFn, SharedsTy, 1639 CapturedStruct, IfCond, PrivateVars, PrivateCopies, FirstprivateVars, 1640 FirstprivateCopies, FirstprivateInits, Dependences); 1641 } 1642 1643 void CodeGenFunction::EmitOMPTaskyieldDirective( 1644 const OMPTaskyieldDirective &S) { 1645 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart()); 1646 } 1647 1648 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 1649 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier); 1650 } 1651 1652 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 1653 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart()); 1654 } 1655 1656 void CodeGenFunction::EmitOMPTaskgroupDirective( 1657 const OMPTaskgroupDirective &S) { 1658 LexicalScope Scope(*this, S.getSourceRange()); 1659 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1660 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1661 CGF.EnsureInsertPoint(); 1662 }; 1663 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart()); 1664 } 1665 1666 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 1667 CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> { 1668 if (auto C = S.getSingleClause(/*K*/ OMPC_flush)) { 1669 auto FlushClause = cast<OMPFlushClause>(C); 1670 return llvm::makeArrayRef(FlushClause->varlist_begin(), 1671 FlushClause->varlist_end()); 1672 } 1673 return llvm::None; 1674 }(), S.getLocStart()); 1675 } 1676 1677 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 1678 LexicalScope Scope(*this, S.getSourceRange()); 1679 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 1680 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 1681 CGF.EnsureInsertPoint(); 1682 }; 1683 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart()); 1684 } 1685 1686 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 1687 QualType SrcType, QualType DestType, 1688 SourceLocation Loc) { 1689 assert(CGF.hasScalarEvaluationKind(DestType) && 1690 "DestType must have scalar evaluation kind."); 1691 assert(!Val.isAggregate() && "Must be a scalar or complex."); 1692 return Val.isScalar() 1693 ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType, 1694 Loc) 1695 : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType, 1696 DestType, Loc); 1697 } 1698 1699 static CodeGenFunction::ComplexPairTy 1700 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 1701 QualType DestType, SourceLocation Loc) { 1702 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 1703 "DestType must have complex evaluation kind."); 1704 CodeGenFunction::ComplexPairTy ComplexVal; 1705 if (Val.isScalar()) { 1706 // Convert the input element to the element type of the complex. 1707 auto DestElementType = DestType->castAs<ComplexType>()->getElementType(); 1708 auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, 1709 DestElementType, Loc); 1710 ComplexVal = CodeGenFunction::ComplexPairTy( 1711 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 1712 } else { 1713 assert(Val.isComplex() && "Must be a scalar or complex."); 1714 auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 1715 auto DestElementType = DestType->castAs<ComplexType>()->getElementType(); 1716 ComplexVal.first = CGF.EmitScalarConversion( 1717 Val.getComplexVal().first, SrcElementType, DestElementType, Loc); 1718 ComplexVal.second = CGF.EmitScalarConversion( 1719 Val.getComplexVal().second, SrcElementType, DestElementType, Loc); 1720 } 1721 return ComplexVal; 1722 } 1723 1724 static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst, 1725 LValue LVal, RValue RVal) { 1726 if (LVal.isGlobalReg()) { 1727 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 1728 } else { 1729 CGF.EmitAtomicStore(RVal, LVal, IsSeqCst ? llvm::SequentiallyConsistent 1730 : llvm::Monotonic, 1731 LVal.isVolatile(), /*IsInit=*/false); 1732 } 1733 } 1734 1735 static void emitSimpleStore(CodeGenFunction &CGF, LValue LVal, RValue RVal, 1736 QualType RValTy, SourceLocation Loc) { 1737 switch (CGF.getEvaluationKind(LVal.getType())) { 1738 case TEK_Scalar: 1739 CGF.EmitStoreThroughLValue(RValue::get(convertToScalarValue( 1740 CGF, RVal, RValTy, LVal.getType(), Loc)), 1741 LVal); 1742 break; 1743 case TEK_Complex: 1744 CGF.EmitStoreOfComplex( 1745 convertToComplexValue(CGF, RVal, RValTy, LVal.getType(), Loc), LVal, 1746 /*isInit=*/false); 1747 break; 1748 case TEK_Aggregate: 1749 llvm_unreachable("Must be a scalar or complex."); 1750 } 1751 } 1752 1753 static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst, 1754 const Expr *X, const Expr *V, 1755 SourceLocation Loc) { 1756 // v = x; 1757 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 1758 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 1759 LValue XLValue = CGF.EmitLValue(X); 1760 LValue VLValue = CGF.EmitLValue(V); 1761 RValue Res = XLValue.isGlobalReg() 1762 ? CGF.EmitLoadOfLValue(XLValue, Loc) 1763 : CGF.EmitAtomicLoad(XLValue, Loc, 1764 IsSeqCst ? llvm::SequentiallyConsistent 1765 : llvm::Monotonic, 1766 XLValue.isVolatile()); 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 emitSimpleStore(CGF, VLValue, Res, X->getType().getNonReferenceType(), Loc); 1774 } 1775 1776 static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst, 1777 const Expr *X, const Expr *E, 1778 SourceLocation Loc) { 1779 // x = expr; 1780 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 1781 emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 1782 // OpenMP, 2.12.6, atomic Construct 1783 // Any atomic construct with a seq_cst clause forces the atomically 1784 // performed operation to include an implicit flush operation without a 1785 // list. 1786 if (IsSeqCst) 1787 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1788 } 1789 1790 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 1791 RValue Update, 1792 BinaryOperatorKind BO, 1793 llvm::AtomicOrdering AO, 1794 bool IsXLHSInRHSPart) { 1795 auto &Context = CGF.CGM.getContext(); 1796 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 1797 // expression is simple and atomic is allowed for the given type for the 1798 // target platform. 1799 if (BO == BO_Comma || !Update.isScalar() || 1800 !Update.getScalarVal()->getType()->isIntegerTy() || 1801 !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 1802 (Update.getScalarVal()->getType() != 1803 X.getAddress()->getType()->getPointerElementType())) || 1804 !X.getAddress()->getType()->getPointerElementType()->isIntegerTy() || 1805 !Context.getTargetInfo().hasBuiltinAtomic( 1806 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 1807 return std::make_pair(false, RValue::get(nullptr)); 1808 1809 llvm::AtomicRMWInst::BinOp RMWOp; 1810 switch (BO) { 1811 case BO_Add: 1812 RMWOp = llvm::AtomicRMWInst::Add; 1813 break; 1814 case BO_Sub: 1815 if (!IsXLHSInRHSPart) 1816 return std::make_pair(false, RValue::get(nullptr)); 1817 RMWOp = llvm::AtomicRMWInst::Sub; 1818 break; 1819 case BO_And: 1820 RMWOp = llvm::AtomicRMWInst::And; 1821 break; 1822 case BO_Or: 1823 RMWOp = llvm::AtomicRMWInst::Or; 1824 break; 1825 case BO_Xor: 1826 RMWOp = llvm::AtomicRMWInst::Xor; 1827 break; 1828 case BO_LT: 1829 RMWOp = X.getType()->hasSignedIntegerRepresentation() 1830 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 1831 : llvm::AtomicRMWInst::Max) 1832 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 1833 : llvm::AtomicRMWInst::UMax); 1834 break; 1835 case BO_GT: 1836 RMWOp = X.getType()->hasSignedIntegerRepresentation() 1837 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 1838 : llvm::AtomicRMWInst::Min) 1839 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 1840 : llvm::AtomicRMWInst::UMin); 1841 break; 1842 case BO_Assign: 1843 RMWOp = llvm::AtomicRMWInst::Xchg; 1844 break; 1845 case BO_Mul: 1846 case BO_Div: 1847 case BO_Rem: 1848 case BO_Shl: 1849 case BO_Shr: 1850 case BO_LAnd: 1851 case BO_LOr: 1852 return std::make_pair(false, RValue::get(nullptr)); 1853 case BO_PtrMemD: 1854 case BO_PtrMemI: 1855 case BO_LE: 1856 case BO_GE: 1857 case BO_EQ: 1858 case BO_NE: 1859 case BO_AddAssign: 1860 case BO_SubAssign: 1861 case BO_AndAssign: 1862 case BO_OrAssign: 1863 case BO_XorAssign: 1864 case BO_MulAssign: 1865 case BO_DivAssign: 1866 case BO_RemAssign: 1867 case BO_ShlAssign: 1868 case BO_ShrAssign: 1869 case BO_Comma: 1870 llvm_unreachable("Unsupported atomic update operation"); 1871 } 1872 auto *UpdateVal = Update.getScalarVal(); 1873 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 1874 UpdateVal = CGF.Builder.CreateIntCast( 1875 IC, X.getAddress()->getType()->getPointerElementType(), 1876 X.getType()->hasSignedIntegerRepresentation()); 1877 } 1878 auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getAddress(), UpdateVal, AO); 1879 return std::make_pair(true, RValue::get(Res)); 1880 } 1881 1882 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 1883 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 1884 llvm::AtomicOrdering AO, SourceLocation Loc, 1885 const llvm::function_ref<RValue(RValue)> &CommonGen) { 1886 // Update expressions are allowed to have the following forms: 1887 // x binop= expr; -> xrval + expr; 1888 // x++, ++x -> xrval + 1; 1889 // x--, --x -> xrval - 1; 1890 // x = x binop expr; -> xrval binop expr 1891 // x = expr Op x; - > expr binop xrval; 1892 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 1893 if (!Res.first) { 1894 if (X.isGlobalReg()) { 1895 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 1896 // 'xrval'. 1897 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 1898 } else { 1899 // Perform compare-and-swap procedure. 1900 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 1901 } 1902 } 1903 return Res; 1904 } 1905 1906 static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst, 1907 const Expr *X, const Expr *E, 1908 const Expr *UE, bool IsXLHSInRHSPart, 1909 SourceLocation Loc) { 1910 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 1911 "Update expr in 'atomic update' must be a binary operator."); 1912 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 1913 // Update expressions are allowed to have the following forms: 1914 // x binop= expr; -> xrval + expr; 1915 // x++, ++x -> xrval + 1; 1916 // x--, --x -> xrval - 1; 1917 // x = x binop expr; -> xrval binop expr 1918 // x = expr Op x; - > expr binop xrval; 1919 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 1920 LValue XLValue = CGF.EmitLValue(X); 1921 RValue ExprRValue = CGF.EmitAnyExpr(E); 1922 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic; 1923 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 1924 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 1925 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 1926 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 1927 auto Gen = 1928 [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue { 1929 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 1930 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 1931 return CGF.EmitAnyExpr(UE); 1932 }; 1933 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 1934 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 1935 // OpenMP, 2.12.6, atomic Construct 1936 // Any atomic construct with a seq_cst clause forces the atomically 1937 // performed operation to include an implicit flush operation without a 1938 // list. 1939 if (IsSeqCst) 1940 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 1941 } 1942 1943 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 1944 QualType SourceType, QualType ResType, 1945 SourceLocation Loc) { 1946 switch (CGF.getEvaluationKind(ResType)) { 1947 case TEK_Scalar: 1948 return RValue::get( 1949 convertToScalarValue(CGF, Value, SourceType, ResType, Loc)); 1950 case TEK_Complex: { 1951 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc); 1952 return RValue::getComplex(Res.first, Res.second); 1953 } 1954 case TEK_Aggregate: 1955 break; 1956 } 1957 llvm_unreachable("Must be a scalar or complex."); 1958 } 1959 1960 static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst, 1961 bool IsPostfixUpdate, const Expr *V, 1962 const Expr *X, const Expr *E, 1963 const Expr *UE, bool IsXLHSInRHSPart, 1964 SourceLocation Loc) { 1965 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 1966 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 1967 RValue NewVVal; 1968 LValue VLValue = CGF.EmitLValue(V); 1969 LValue XLValue = CGF.EmitLValue(X); 1970 RValue ExprRValue = CGF.EmitAnyExpr(E); 1971 auto AO = IsSeqCst ? llvm::SequentiallyConsistent : llvm::Monotonic; 1972 QualType NewVValType; 1973 if (UE) { 1974 // 'x' is updated with some additional value. 1975 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 1976 "Update expr in 'atomic capture' must be a binary operator."); 1977 auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 1978 // Update expressions are allowed to have the following forms: 1979 // x binop= expr; -> xrval + expr; 1980 // x++, ++x -> xrval + 1; 1981 // x--, --x -> xrval - 1; 1982 // x = x binop expr; -> xrval binop expr 1983 // x = expr Op x; - > expr binop xrval; 1984 auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 1985 auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 1986 auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 1987 NewVValType = XRValExpr->getType(); 1988 auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 1989 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 1990 IsSeqCst, IsPostfixUpdate](RValue XRValue) -> RValue { 1991 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 1992 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 1993 RValue Res = CGF.EmitAnyExpr(UE); 1994 NewVVal = IsPostfixUpdate ? XRValue : Res; 1995 return Res; 1996 }; 1997 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 1998 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 1999 if (Res.first) { 2000 // 'atomicrmw' instruction was generated. 2001 if (IsPostfixUpdate) { 2002 // Use old value from 'atomicrmw'. 2003 NewVVal = Res.second; 2004 } else { 2005 // 'atomicrmw' does not provide new value, so evaluate it using old 2006 // value of 'x'. 2007 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 2008 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 2009 NewVVal = CGF.EmitAnyExpr(UE); 2010 } 2011 } 2012 } else { 2013 // 'x' is simply rewritten with some 'expr'. 2014 NewVValType = X->getType().getNonReferenceType(); 2015 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 2016 X->getType().getNonReferenceType(), Loc); 2017 auto &&Gen = [&CGF, &NewVVal, ExprRValue](RValue XRValue) -> RValue { 2018 NewVVal = XRValue; 2019 return ExprRValue; 2020 }; 2021 // Try to perform atomicrmw xchg, otherwise simple exchange. 2022 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 2023 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 2024 Loc, Gen); 2025 if (Res.first) { 2026 // 'atomicrmw' instruction was generated. 2027 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 2028 } 2029 } 2030 // Emit post-update store to 'v' of old/new 'x' value. 2031 emitSimpleStore(CGF, VLValue, NewVVal, NewVValType, Loc); 2032 // OpenMP, 2.12.6, atomic Construct 2033 // Any atomic construct with a seq_cst clause forces the atomically 2034 // performed operation to include an implicit flush operation without a 2035 // list. 2036 if (IsSeqCst) 2037 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc); 2038 } 2039 2040 static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 2041 bool IsSeqCst, bool IsPostfixUpdate, 2042 const Expr *X, const Expr *V, const Expr *E, 2043 const Expr *UE, bool IsXLHSInRHSPart, 2044 SourceLocation Loc) { 2045 switch (Kind) { 2046 case OMPC_read: 2047 EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc); 2048 break; 2049 case OMPC_write: 2050 EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc); 2051 break; 2052 case OMPC_unknown: 2053 case OMPC_update: 2054 EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc); 2055 break; 2056 case OMPC_capture: 2057 EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE, 2058 IsXLHSInRHSPart, Loc); 2059 break; 2060 case OMPC_if: 2061 case OMPC_final: 2062 case OMPC_num_threads: 2063 case OMPC_private: 2064 case OMPC_firstprivate: 2065 case OMPC_lastprivate: 2066 case OMPC_reduction: 2067 case OMPC_safelen: 2068 case OMPC_collapse: 2069 case OMPC_default: 2070 case OMPC_seq_cst: 2071 case OMPC_shared: 2072 case OMPC_linear: 2073 case OMPC_aligned: 2074 case OMPC_copyin: 2075 case OMPC_copyprivate: 2076 case OMPC_flush: 2077 case OMPC_proc_bind: 2078 case OMPC_schedule: 2079 case OMPC_ordered: 2080 case OMPC_nowait: 2081 case OMPC_untied: 2082 case OMPC_threadprivate: 2083 case OMPC_depend: 2084 case OMPC_mergeable: 2085 case OMPC_device: 2086 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 2087 } 2088 } 2089 2090 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 2091 bool IsSeqCst = S.getSingleClause(/*K=*/OMPC_seq_cst); 2092 OpenMPClauseKind Kind = OMPC_unknown; 2093 for (auto *C : S.clauses()) { 2094 // Find first clause (skip seq_cst clause, if it is first). 2095 if (C->getClauseKind() != OMPC_seq_cst) { 2096 Kind = C->getClauseKind(); 2097 break; 2098 } 2099 } 2100 2101 const auto *CS = 2102 S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true); 2103 if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) { 2104 enterFullExpression(EWC); 2105 } 2106 // Processing for statements under 'atomic capture'. 2107 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) { 2108 for (const auto *C : Compound->body()) { 2109 if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) { 2110 enterFullExpression(EWC); 2111 } 2112 } 2113 } 2114 2115 LexicalScope Scope(*this, S.getSourceRange()); 2116 auto &&CodeGen = [&S, Kind, IsSeqCst](CodeGenFunction &CGF) { 2117 EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(), 2118 S.getV(), S.getExpr(), S.getUpdateExpr(), 2119 S.isXLHSInRHSPart(), S.getLocStart()); 2120 }; 2121 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen); 2122 } 2123 2124 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &) { 2125 llvm_unreachable("CodeGen for 'omp target' is not supported yet."); 2126 } 2127 2128 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &) { 2129 llvm_unreachable("CodeGen for 'omp teams' is not supported yet."); 2130 } 2131 2132 void CodeGenFunction::EmitOMPCancellationPointDirective( 2133 const OMPCancellationPointDirective &S) { 2134 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(), 2135 S.getCancelRegion()); 2136 } 2137 2138 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) { 2139 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), 2140 S.getCancelRegion()); 2141 } 2142 2143 CodeGenFunction::JumpDest 2144 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) { 2145 if (Kind == OMPD_parallel || Kind == OMPD_task) 2146 return ReturnBlock; 2147 else if (Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections) 2148 return BreakContinueStack.empty() ? JumpDest() 2149 : BreakContinueStack.back().BreakBlock; 2150 return JumpDest(); 2151 } 2152 2153 // Generate the instructions for '#pragma omp target data' directive. 2154 void CodeGenFunction::EmitOMPTargetDataDirective( 2155 const OMPTargetDataDirective &S) { 2156 2157 // emit the code inside the construct for now 2158 auto CS = cast<CapturedStmt>(S.getAssociatedStmt()); 2159 CGM.getOpenMPRuntime().emitInlinedDirective( 2160 *this, OMPD_target_data, 2161 [&CS](CodeGenFunction &CGF) { CGF.EmitStmt(CS->getCapturedStmt()); }); 2162 } 2163