CGStmtOpenMP.cpp 88 KB

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