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