CGOpenMPRuntime.cpp 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843
  1. //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
  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 provides a class for OpenMP runtime code generation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGOpenMPRuntime.h"
  14. #include "CodeGenFunction.h"
  15. #include "CGCleanup.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/StmtOpenMP.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/IR/CallSite.h"
  20. #include "llvm/IR/DerivedTypes.h"
  21. #include "llvm/IR/GlobalValue.h"
  22. #include "llvm/IR/Value.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include <cassert>
  25. using namespace clang;
  26. using namespace CodeGen;
  27. // HLSL Change Starts
  28. // No OpenMP codegen support, so simply skip all of this compilation.
  29. // Here are enough stubs to link the current targets.
  30. #if 0
  31. // HLSL Change Ends
  32. namespace {
  33. /// \brief Base class for handling code generation inside OpenMP regions.
  34. class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
  35. public:
  36. /// \brief Kinds of OpenMP regions used in codegen.
  37. enum CGOpenMPRegionKind {
  38. /// \brief Region with outlined function for standalone 'parallel'
  39. /// directive.
  40. ParallelOutlinedRegion,
  41. /// \brief Region with outlined function for standalone 'task' directive.
  42. TaskOutlinedRegion,
  43. /// \brief Region for constructs that do not require function outlining,
  44. /// like 'for', 'sections', 'atomic' etc. directives.
  45. InlinedRegion,
  46. };
  47. CGOpenMPRegionInfo(const CapturedStmt &CS,
  48. const CGOpenMPRegionKind RegionKind,
  49. const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind)
  50. : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
  51. CodeGen(CodeGen), Kind(Kind) {}
  52. CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
  53. const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind)
  54. : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
  55. Kind(Kind) {}
  56. /// \brief Get a variable or parameter for storing global thread id
  57. /// inside OpenMP construct.
  58. virtual const VarDecl *getThreadIDVariable() const = 0;
  59. /// \brief Emit the captured statement body.
  60. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
  61. /// \brief Get an LValue for the current ThreadID variable.
  62. /// \return LValue for thread id variable. This LValue always has type int32*.
  63. virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
  64. CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
  65. OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
  66. static bool classof(const CGCapturedStmtInfo *Info) {
  67. return Info->getKind() == CR_OpenMP;
  68. }
  69. protected:
  70. CGOpenMPRegionKind RegionKind;
  71. const RegionCodeGenTy &CodeGen;
  72. OpenMPDirectiveKind Kind;
  73. };
  74. /// \brief API for captured statement code generation in OpenMP constructs.
  75. class CGOpenMPOutlinedRegionInfo : public CGOpenMPRegionInfo {
  76. public:
  77. CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
  78. const RegionCodeGenTy &CodeGen,
  79. OpenMPDirectiveKind Kind)
  80. : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind),
  81. ThreadIDVar(ThreadIDVar) {
  82. assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
  83. }
  84. /// \brief Get a variable or parameter for storing global thread id
  85. /// inside OpenMP construct.
  86. const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
  87. /// \brief Get the name of the capture helper.
  88. StringRef getHelperName() const override { return ".omp_outlined."; }
  89. static bool classof(const CGCapturedStmtInfo *Info) {
  90. return CGOpenMPRegionInfo::classof(Info) &&
  91. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
  92. ParallelOutlinedRegion;
  93. }
  94. private:
  95. /// \brief A variable or parameter storing global thread id for OpenMP
  96. /// constructs.
  97. const VarDecl *ThreadIDVar;
  98. };
  99. /// \brief API for captured statement code generation in OpenMP constructs.
  100. class CGOpenMPTaskOutlinedRegionInfo : public CGOpenMPRegionInfo {
  101. public:
  102. CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
  103. const VarDecl *ThreadIDVar,
  104. const RegionCodeGenTy &CodeGen,
  105. OpenMPDirectiveKind Kind)
  106. : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind),
  107. ThreadIDVar(ThreadIDVar) {
  108. assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
  109. }
  110. /// \brief Get a variable or parameter for storing global thread id
  111. /// inside OpenMP construct.
  112. const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
  113. /// \brief Get an LValue for the current ThreadID variable.
  114. LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
  115. /// \brief Get the name of the capture helper.
  116. StringRef getHelperName() const override { return ".omp_outlined."; }
  117. static bool classof(const CGCapturedStmtInfo *Info) {
  118. return CGOpenMPRegionInfo::classof(Info) &&
  119. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
  120. TaskOutlinedRegion;
  121. }
  122. private:
  123. /// \brief A variable or parameter storing global thread id for OpenMP
  124. /// constructs.
  125. const VarDecl *ThreadIDVar;
  126. };
  127. /// \brief API for inlined captured statement code generation in OpenMP
  128. /// constructs.
  129. class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
  130. public:
  131. CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
  132. const RegionCodeGenTy &CodeGen,
  133. OpenMPDirectiveKind Kind)
  134. : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind), OldCSI(OldCSI),
  135. OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
  136. // \brief Retrieve the value of the context parameter.
  137. llvm::Value *getContextValue() const override {
  138. if (OuterRegionInfo)
  139. return OuterRegionInfo->getContextValue();
  140. llvm_unreachable("No context value for inlined OpenMP region");
  141. }
  142. virtual void setContextValue(llvm::Value *V) override {
  143. if (OuterRegionInfo) {
  144. OuterRegionInfo->setContextValue(V);
  145. return;
  146. }
  147. llvm_unreachable("No context value for inlined OpenMP region");
  148. }
  149. /// \brief Lookup the captured field decl for a variable.
  150. const FieldDecl *lookup(const VarDecl *VD) const override {
  151. if (OuterRegionInfo)
  152. return OuterRegionInfo->lookup(VD);
  153. // If there is no outer outlined region,no need to lookup in a list of
  154. // captured variables, we can use the original one.
  155. return nullptr;
  156. }
  157. FieldDecl *getThisFieldDecl() const override {
  158. if (OuterRegionInfo)
  159. return OuterRegionInfo->getThisFieldDecl();
  160. return nullptr;
  161. }
  162. /// \brief Get a variable or parameter for storing global thread id
  163. /// inside OpenMP construct.
  164. const VarDecl *getThreadIDVariable() const override {
  165. if (OuterRegionInfo)
  166. return OuterRegionInfo->getThreadIDVariable();
  167. return nullptr;
  168. }
  169. /// \brief Get the name of the capture helper.
  170. StringRef getHelperName() const override {
  171. if (auto *OuterRegionInfo = getOldCSI())
  172. return OuterRegionInfo->getHelperName();
  173. llvm_unreachable("No helper name for inlined OpenMP construct");
  174. }
  175. CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
  176. static bool classof(const CGCapturedStmtInfo *Info) {
  177. return CGOpenMPRegionInfo::classof(Info) &&
  178. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
  179. }
  180. private:
  181. /// \brief CodeGen info about outer OpenMP region.
  182. CodeGenFunction::CGCapturedStmtInfo *OldCSI;
  183. CGOpenMPRegionInfo *OuterRegionInfo;
  184. };
  185. /// \brief RAII for emitting code of OpenMP constructs.
  186. class InlinedOpenMPRegionRAII {
  187. CodeGenFunction &CGF;
  188. public:
  189. /// \brief Constructs region for combined constructs.
  190. /// \param CodeGen Code generation sequence for combined directives. Includes
  191. /// a list of functions used for code generation of implicitly inlined
  192. /// regions.
  193. InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
  194. OpenMPDirectiveKind Kind)
  195. : CGF(CGF) {
  196. // Start emission for the construct.
  197. CGF.CapturedStmtInfo =
  198. new CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, CodeGen, Kind);
  199. }
  200. ~InlinedOpenMPRegionRAII() {
  201. // Restore original CapturedStmtInfo only if we're done with code emission.
  202. auto *OldCSI =
  203. cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
  204. delete CGF.CapturedStmtInfo;
  205. CGF.CapturedStmtInfo = OldCSI;
  206. }
  207. };
  208. } // namespace
  209. LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
  210. return CGF.MakeNaturalAlignAddrLValue(
  211. CGF.Builder.CreateAlignedLoad(
  212. CGF.GetAddrOfLocalVar(getThreadIDVariable()),
  213. CGF.PointerAlignInBytes),
  214. getThreadIDVariable()
  215. ->getType()
  216. ->castAs<PointerType>()
  217. ->getPointeeType());
  218. }
  219. void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
  220. // 1.2.2 OpenMP Language Terminology
  221. // Structured block - An executable statement with a single entry at the
  222. // top and a single exit at the bottom.
  223. // The point of exit cannot be a branch out of the structured block.
  224. // longjmp() and throw() must not violate the entry/exit criteria.
  225. CGF.EHStack.pushTerminate();
  226. {
  227. CodeGenFunction::RunCleanupsScope Scope(CGF);
  228. CodeGen(CGF);
  229. }
  230. CGF.EHStack.popTerminate();
  231. }
  232. LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
  233. CodeGenFunction &CGF) {
  234. return CGF.MakeNaturalAlignAddrLValue(
  235. CGF.GetAddrOfLocalVar(getThreadIDVariable()),
  236. getThreadIDVariable()->getType());
  237. }
  238. CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
  239. : CGM(CGM), DefaultOpenMPPSource(nullptr), KmpRoutineEntryPtrTy(nullptr) {
  240. IdentTy = llvm::StructType::create(
  241. "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
  242. CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
  243. CGM.Int8PtrTy /* psource */, nullptr);
  244. // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
  245. llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
  246. llvm::PointerType::getUnqual(CGM.Int32Ty)};
  247. Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
  248. KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
  249. }
  250. void CGOpenMPRuntime::clear() {
  251. InternalVars.clear();
  252. }
  253. llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
  254. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  255. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  256. assert(ThreadIDVar->getType()->isPointerType() &&
  257. "thread id variable must be of type kmp_int32 *");
  258. const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
  259. CodeGenFunction CGF(CGM, true);
  260. CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind);
  261. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  262. return CGF.GenerateCapturedStmtFunction(*CS);
  263. }
  264. llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
  265. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  266. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  267. assert(!ThreadIDVar->getType()->isPointerType() &&
  268. "thread id variable must be of type kmp_int32 for tasks");
  269. auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
  270. CodeGenFunction CGF(CGM, true);
  271. CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
  272. InnermostKind);
  273. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  274. return CGF.GenerateCapturedStmtFunction(*CS);
  275. }
  276. llvm::Value *
  277. CGOpenMPRuntime::getOrCreateDefaultLocation(OpenMPLocationFlags Flags) {
  278. llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
  279. if (!Entry) {
  280. if (!DefaultOpenMPPSource) {
  281. // Initialize default location for psource field of ident_t structure of
  282. // all ident_t objects. Format is ";file;function;line;column;;".
  283. // Taken from
  284. // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
  285. DefaultOpenMPPSource =
  286. CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;");
  287. DefaultOpenMPPSource =
  288. llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
  289. }
  290. auto DefaultOpenMPLocation = new llvm::GlobalVariable(
  291. CGM.getModule(), IdentTy, /*isConstant*/ true,
  292. llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
  293. DefaultOpenMPLocation->setUnnamedAddr(true);
  294. llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
  295. llvm::Constant *Values[] = {Zero,
  296. llvm::ConstantInt::get(CGM.Int32Ty, Flags),
  297. Zero, Zero, DefaultOpenMPPSource};
  298. llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
  299. DefaultOpenMPLocation->setInitializer(Init);
  300. OpenMPDefaultLocMap[Flags] = DefaultOpenMPLocation;
  301. return DefaultOpenMPLocation;
  302. }
  303. return Entry;
  304. }
  305. llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
  306. SourceLocation Loc,
  307. OpenMPLocationFlags Flags) {
  308. // If no debug info is generated - return global default location.
  309. if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::NoDebugInfo ||
  310. Loc.isInvalid())
  311. return getOrCreateDefaultLocation(Flags);
  312. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  313. llvm::Value *LocValue = nullptr;
  314. auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
  315. if (I != OpenMPLocThreadIDMap.end())
  316. LocValue = I->second.DebugLoc;
  317. // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
  318. // GetOpenMPThreadID was called before this routine.
  319. if (LocValue == nullptr) {
  320. // Generate "ident_t .kmpc_loc.addr;"
  321. llvm::AllocaInst *AI = CGF.CreateTempAlloca(IdentTy, ".kmpc_loc.addr");
  322. AI->setAlignment(CGM.getDataLayout().getPrefTypeAlignment(IdentTy));
  323. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  324. Elem.second.DebugLoc = AI;
  325. LocValue = AI;
  326. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  327. CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
  328. CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
  329. llvm::ConstantExpr::getSizeOf(IdentTy),
  330. CGM.PointerAlignInBytes);
  331. }
  332. // char **psource = &.kmpc_loc_<flags>.addr.psource;
  333. auto *PSource = CGF.Builder.CreateConstInBoundsGEP2_32(IdentTy, LocValue, 0,
  334. IdentField_PSource);
  335. auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
  336. if (OMPDebugLoc == nullptr) {
  337. SmallString<128> Buffer2;
  338. llvm::raw_svector_ostream OS2(Buffer2);
  339. // Build debug location
  340. PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
  341. OS2 << ";" << PLoc.getFilename() << ";";
  342. if (const FunctionDecl *FD =
  343. dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
  344. OS2 << FD->getQualifiedNameAsString();
  345. }
  346. OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
  347. OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
  348. OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
  349. }
  350. // *psource = ";<File>;<Function>;<Line>;<Column>;;";
  351. CGF.Builder.CreateStore(OMPDebugLoc, PSource);
  352. return LocValue;
  353. }
  354. llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
  355. SourceLocation Loc) {
  356. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  357. llvm::Value *ThreadID = nullptr;
  358. // Check whether we've already cached a load of the thread id in this
  359. // function.
  360. auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
  361. if (I != OpenMPLocThreadIDMap.end()) {
  362. ThreadID = I->second.ThreadID;
  363. if (ThreadID != nullptr)
  364. return ThreadID;
  365. }
  366. if (auto OMPRegionInfo =
  367. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  368. if (OMPRegionInfo->getThreadIDVariable()) {
  369. // Check if this an outlined function with thread id passed as argument.
  370. auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
  371. ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
  372. // If value loaded in entry block, cache it and use it everywhere in
  373. // function.
  374. if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
  375. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  376. Elem.second.ThreadID = ThreadID;
  377. }
  378. return ThreadID;
  379. }
  380. }
  381. // This is not an outlined function region - need to call __kmpc_int32
  382. // kmpc_global_thread_num(ident_t *loc).
  383. // Generate thread id value and cache this value for use across the
  384. // function.
  385. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  386. CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
  387. ThreadID =
  388. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
  389. emitUpdateLocation(CGF, Loc));
  390. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  391. Elem.second.ThreadID = ThreadID;
  392. return ThreadID;
  393. }
  394. void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
  395. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  396. if (OpenMPLocThreadIDMap.count(CGF.CurFn))
  397. OpenMPLocThreadIDMap.erase(CGF.CurFn);
  398. }
  399. llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
  400. return llvm::PointerType::getUnqual(IdentTy);
  401. }
  402. llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
  403. return llvm::PointerType::getUnqual(Kmpc_MicroTy);
  404. }
  405. llvm::Constant *
  406. CGOpenMPRuntime::createRuntimeFunction(OpenMPRTLFunction Function) {
  407. llvm::Constant *RTLFn = nullptr;
  408. switch (Function) {
  409. case OMPRTL__kmpc_fork_call: {
  410. // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
  411. // microtask, ...);
  412. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  413. getKmpc_MicroPointerTy()};
  414. llvm::FunctionType *FnTy =
  415. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
  416. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
  417. break;
  418. }
  419. case OMPRTL__kmpc_global_thread_num: {
  420. // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
  421. llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
  422. llvm::FunctionType *FnTy =
  423. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  424. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
  425. break;
  426. }
  427. case OMPRTL__kmpc_threadprivate_cached: {
  428. // Build void *__kmpc_threadprivate_cached(ident_t *loc,
  429. // kmp_int32 global_tid, void *data, size_t size, void ***cache);
  430. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  431. CGM.VoidPtrTy, CGM.SizeTy,
  432. CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
  433. llvm::FunctionType *FnTy =
  434. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
  435. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
  436. break;
  437. }
  438. case OMPRTL__kmpc_critical: {
  439. // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
  440. // kmp_critical_name *crit);
  441. llvm::Type *TypeParams[] = {
  442. getIdentTyPointerTy(), CGM.Int32Ty,
  443. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  444. llvm::FunctionType *FnTy =
  445. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  446. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
  447. break;
  448. }
  449. case OMPRTL__kmpc_threadprivate_register: {
  450. // Build void __kmpc_threadprivate_register(ident_t *, void *data,
  451. // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
  452. // typedef void *(*kmpc_ctor)(void *);
  453. auto KmpcCtorTy =
  454. llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
  455. /*isVarArg*/ false)->getPointerTo();
  456. // typedef void *(*kmpc_cctor)(void *, void *);
  457. llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  458. auto KmpcCopyCtorTy =
  459. llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
  460. /*isVarArg*/ false)->getPointerTo();
  461. // typedef void (*kmpc_dtor)(void *);
  462. auto KmpcDtorTy =
  463. llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
  464. ->getPointerTo();
  465. llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
  466. KmpcCopyCtorTy, KmpcDtorTy};
  467. auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
  468. /*isVarArg*/ false);
  469. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
  470. break;
  471. }
  472. case OMPRTL__kmpc_end_critical: {
  473. // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
  474. // kmp_critical_name *crit);
  475. llvm::Type *TypeParams[] = {
  476. getIdentTyPointerTy(), CGM.Int32Ty,
  477. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  478. llvm::FunctionType *FnTy =
  479. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  480. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
  481. break;
  482. }
  483. case OMPRTL__kmpc_cancel_barrier: {
  484. // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
  485. // global_tid);
  486. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  487. llvm::FunctionType *FnTy =
  488. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  489. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
  490. break;
  491. }
  492. case OMPRTL__kmpc_barrier: {
  493. // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
  494. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  495. llvm::FunctionType *FnTy =
  496. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  497. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
  498. break;
  499. }
  500. case OMPRTL__kmpc_for_static_fini: {
  501. // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
  502. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  503. llvm::FunctionType *FnTy =
  504. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  505. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
  506. break;
  507. }
  508. case OMPRTL__kmpc_push_num_threads: {
  509. // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
  510. // kmp_int32 num_threads)
  511. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  512. CGM.Int32Ty};
  513. llvm::FunctionType *FnTy =
  514. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  515. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
  516. break;
  517. }
  518. case OMPRTL__kmpc_serialized_parallel: {
  519. // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
  520. // global_tid);
  521. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  522. llvm::FunctionType *FnTy =
  523. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  524. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
  525. break;
  526. }
  527. case OMPRTL__kmpc_end_serialized_parallel: {
  528. // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
  529. // global_tid);
  530. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  531. llvm::FunctionType *FnTy =
  532. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  533. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
  534. break;
  535. }
  536. case OMPRTL__kmpc_flush: {
  537. // Build void __kmpc_flush(ident_t *loc);
  538. llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
  539. llvm::FunctionType *FnTy =
  540. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  541. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
  542. break;
  543. }
  544. case OMPRTL__kmpc_master: {
  545. // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
  546. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  547. llvm::FunctionType *FnTy =
  548. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  549. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
  550. break;
  551. }
  552. case OMPRTL__kmpc_end_master: {
  553. // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
  554. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  555. llvm::FunctionType *FnTy =
  556. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  557. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
  558. break;
  559. }
  560. case OMPRTL__kmpc_omp_taskyield: {
  561. // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
  562. // int end_part);
  563. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  564. llvm::FunctionType *FnTy =
  565. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  566. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
  567. break;
  568. }
  569. case OMPRTL__kmpc_single: {
  570. // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
  571. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  572. llvm::FunctionType *FnTy =
  573. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  574. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
  575. break;
  576. }
  577. case OMPRTL__kmpc_end_single: {
  578. // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
  579. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  580. llvm::FunctionType *FnTy =
  581. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  582. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
  583. break;
  584. }
  585. case OMPRTL__kmpc_omp_task_alloc: {
  586. // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  587. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  588. // kmp_routine_entry_t *task_entry);
  589. assert(KmpRoutineEntryPtrTy != nullptr &&
  590. "Type kmp_routine_entry_t must be created.");
  591. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  592. CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
  593. // Return void * and then cast to particular kmp_task_t type.
  594. llvm::FunctionType *FnTy =
  595. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  596. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
  597. break;
  598. }
  599. case OMPRTL__kmpc_omp_task: {
  600. // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  601. // *new_task);
  602. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  603. CGM.VoidPtrTy};
  604. llvm::FunctionType *FnTy =
  605. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  606. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
  607. break;
  608. }
  609. case OMPRTL__kmpc_copyprivate: {
  610. // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
  611. // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
  612. // kmp_int32 didit);
  613. llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  614. auto *CpyFnTy =
  615. llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
  616. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
  617. CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
  618. CGM.Int32Ty};
  619. llvm::FunctionType *FnTy =
  620. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  621. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
  622. break;
  623. }
  624. case OMPRTL__kmpc_reduce: {
  625. // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
  626. // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
  627. // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
  628. llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  629. auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
  630. /*isVarArg=*/false);
  631. llvm::Type *TypeParams[] = {
  632. getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
  633. CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
  634. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  635. llvm::FunctionType *FnTy =
  636. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  637. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
  638. break;
  639. }
  640. case OMPRTL__kmpc_reduce_nowait: {
  641. // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
  642. // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
  643. // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
  644. // *lck);
  645. llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  646. auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
  647. /*isVarArg=*/false);
  648. llvm::Type *TypeParams[] = {
  649. getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
  650. CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
  651. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  652. llvm::FunctionType *FnTy =
  653. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  654. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
  655. break;
  656. }
  657. case OMPRTL__kmpc_end_reduce: {
  658. // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
  659. // kmp_critical_name *lck);
  660. llvm::Type *TypeParams[] = {
  661. getIdentTyPointerTy(), CGM.Int32Ty,
  662. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  663. llvm::FunctionType *FnTy =
  664. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  665. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
  666. break;
  667. }
  668. case OMPRTL__kmpc_end_reduce_nowait: {
  669. // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
  670. // kmp_critical_name *lck);
  671. llvm::Type *TypeParams[] = {
  672. getIdentTyPointerTy(), CGM.Int32Ty,
  673. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  674. llvm::FunctionType *FnTy =
  675. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  676. RTLFn =
  677. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
  678. break;
  679. }
  680. case OMPRTL__kmpc_omp_task_begin_if0: {
  681. // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  682. // *new_task);
  683. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  684. CGM.VoidPtrTy};
  685. llvm::FunctionType *FnTy =
  686. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  687. RTLFn =
  688. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
  689. break;
  690. }
  691. case OMPRTL__kmpc_omp_task_complete_if0: {
  692. // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  693. // *new_task);
  694. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  695. CGM.VoidPtrTy};
  696. llvm::FunctionType *FnTy =
  697. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  698. RTLFn = CGM.CreateRuntimeFunction(FnTy,
  699. /*Name=*/"__kmpc_omp_task_complete_if0");
  700. break;
  701. }
  702. case OMPRTL__kmpc_ordered: {
  703. // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
  704. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  705. llvm::FunctionType *FnTy =
  706. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  707. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
  708. break;
  709. }
  710. case OMPRTL__kmpc_end_ordered: {
  711. // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
  712. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  713. llvm::FunctionType *FnTy =
  714. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  715. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
  716. break;
  717. }
  718. case OMPRTL__kmpc_omp_taskwait: {
  719. // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
  720. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  721. llvm::FunctionType *FnTy =
  722. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  723. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
  724. break;
  725. }
  726. case OMPRTL__kmpc_taskgroup: {
  727. // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
  728. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  729. llvm::FunctionType *FnTy =
  730. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  731. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
  732. break;
  733. }
  734. case OMPRTL__kmpc_end_taskgroup: {
  735. // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
  736. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  737. llvm::FunctionType *FnTy =
  738. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  739. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
  740. break;
  741. }
  742. case OMPRTL__kmpc_push_proc_bind: {
  743. // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
  744. // int proc_bind)
  745. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  746. llvm::FunctionType *FnTy =
  747. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  748. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
  749. break;
  750. }
  751. case OMPRTL__kmpc_omp_task_with_deps: {
  752. // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
  753. // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
  754. // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
  755. llvm::Type *TypeParams[] = {
  756. getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
  757. CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
  758. llvm::FunctionType *FnTy =
  759. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  760. RTLFn =
  761. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
  762. break;
  763. }
  764. case OMPRTL__kmpc_omp_wait_deps: {
  765. // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
  766. // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
  767. // kmp_depend_info_t *noalias_dep_list);
  768. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  769. CGM.Int32Ty, CGM.VoidPtrTy,
  770. CGM.Int32Ty, CGM.VoidPtrTy};
  771. llvm::FunctionType *FnTy =
  772. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  773. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
  774. break;
  775. }
  776. case OMPRTL__kmpc_cancellationpoint: {
  777. // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  778. // global_tid, kmp_int32 cncl_kind)
  779. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  780. llvm::FunctionType *FnTy =
  781. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  782. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
  783. break;
  784. }
  785. case OMPRTL__kmpc_cancel: {
  786. // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  787. // kmp_int32 cncl_kind)
  788. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  789. llvm::FunctionType *FnTy =
  790. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  791. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
  792. break;
  793. }
  794. }
  795. return RTLFn;
  796. }
  797. llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
  798. bool IVSigned) {
  799. assert((IVSize == 32 || IVSize == 64) &&
  800. "IV size is not compatible with the omp runtime");
  801. auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
  802. : "__kmpc_for_static_init_4u")
  803. : (IVSigned ? "__kmpc_for_static_init_8"
  804. : "__kmpc_for_static_init_8u");
  805. auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  806. auto PtrTy = llvm::PointerType::getUnqual(ITy);
  807. llvm::Type *TypeParams[] = {
  808. getIdentTyPointerTy(), // loc
  809. CGM.Int32Ty, // tid
  810. CGM.Int32Ty, // schedtype
  811. llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
  812. PtrTy, // p_lower
  813. PtrTy, // p_upper
  814. PtrTy, // p_stride
  815. ITy, // incr
  816. ITy // chunk
  817. };
  818. llvm::FunctionType *FnTy =
  819. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  820. return CGM.CreateRuntimeFunction(FnTy, Name);
  821. }
  822. llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
  823. bool IVSigned) {
  824. assert((IVSize == 32 || IVSize == 64) &&
  825. "IV size is not compatible with the omp runtime");
  826. auto Name =
  827. IVSize == 32
  828. ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
  829. : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
  830. auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  831. llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
  832. CGM.Int32Ty, // tid
  833. CGM.Int32Ty, // schedtype
  834. ITy, // lower
  835. ITy, // upper
  836. ITy, // stride
  837. ITy // chunk
  838. };
  839. llvm::FunctionType *FnTy =
  840. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  841. return CGM.CreateRuntimeFunction(FnTy, Name);
  842. }
  843. llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
  844. bool IVSigned) {
  845. assert((IVSize == 32 || IVSize == 64) &&
  846. "IV size is not compatible with the omp runtime");
  847. auto Name =
  848. IVSize == 32
  849. ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
  850. : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
  851. llvm::Type *TypeParams[] = {
  852. getIdentTyPointerTy(), // loc
  853. CGM.Int32Ty, // tid
  854. };
  855. llvm::FunctionType *FnTy =
  856. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  857. return CGM.CreateRuntimeFunction(FnTy, Name);
  858. }
  859. llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
  860. bool IVSigned) {
  861. assert((IVSize == 32 || IVSize == 64) &&
  862. "IV size is not compatible with the omp runtime");
  863. auto Name =
  864. IVSize == 32
  865. ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
  866. : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
  867. auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  868. auto PtrTy = llvm::PointerType::getUnqual(ITy);
  869. llvm::Type *TypeParams[] = {
  870. getIdentTyPointerTy(), // loc
  871. CGM.Int32Ty, // tid
  872. llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
  873. PtrTy, // p_lower
  874. PtrTy, // p_upper
  875. PtrTy // p_stride
  876. };
  877. llvm::FunctionType *FnTy =
  878. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  879. return CGM.CreateRuntimeFunction(FnTy, Name);
  880. }
  881. llvm::Constant *
  882. CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
  883. assert(!CGM.getLangOpts().OpenMPUseTLS ||
  884. !CGM.getContext().getTargetInfo().isTLSSupported());
  885. // Lookup the entry, lazily creating it if necessary.
  886. return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
  887. Twine(CGM.getMangledName(VD)) + ".cache.");
  888. }
  889. llvm::Value *CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
  890. const VarDecl *VD,
  891. llvm::Value *VDAddr,
  892. SourceLocation Loc) {
  893. if (CGM.getLangOpts().OpenMPUseTLS &&
  894. CGM.getContext().getTargetInfo().isTLSSupported())
  895. return VDAddr;
  896. auto VarTy = VDAddr->getType()->getPointerElementType();
  897. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  898. CGF.Builder.CreatePointerCast(VDAddr, CGM.Int8PtrTy),
  899. CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
  900. getOrCreateThreadPrivateCache(VD)};
  901. return CGF.EmitRuntimeCall(
  902. createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args);
  903. }
  904. void CGOpenMPRuntime::emitThreadPrivateVarInit(
  905. CodeGenFunction &CGF, llvm::Value *VDAddr, llvm::Value *Ctor,
  906. llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
  907. // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
  908. // library.
  909. auto OMPLoc = emitUpdateLocation(CGF, Loc);
  910. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
  911. OMPLoc);
  912. // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
  913. // to register constructor/destructor for variable.
  914. llvm::Value *Args[] = {OMPLoc,
  915. CGF.Builder.CreatePointerCast(VDAddr, CGM.VoidPtrTy),
  916. Ctor, CopyCtor, Dtor};
  917. CGF.EmitRuntimeCall(
  918. createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
  919. }
  920. llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
  921. const VarDecl *VD, llvm::Value *VDAddr, SourceLocation Loc,
  922. bool PerformInit, CodeGenFunction *CGF) {
  923. if (CGM.getLangOpts().OpenMPUseTLS &&
  924. CGM.getContext().getTargetInfo().isTLSSupported())
  925. return nullptr;
  926. VD = VD->getDefinition(CGM.getContext());
  927. if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
  928. ThreadPrivateWithDefinition.insert(VD);
  929. QualType ASTTy = VD->getType();
  930. llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
  931. auto Init = VD->getAnyInitializer();
  932. if (CGM.getLangOpts().CPlusPlus && PerformInit) {
  933. // Generate function that re-emits the declaration's initializer into the
  934. // threadprivate copy of the variable VD
  935. CodeGenFunction CtorCGF(CGM);
  936. FunctionArgList Args;
  937. ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
  938. /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
  939. Args.push_back(&Dst);
  940. auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
  941. CGM.getContext().VoidPtrTy, Args, FunctionType::ExtInfo(),
  942. /*isVariadic=*/false);
  943. auto FTy = CGM.getTypes().GetFunctionType(FI);
  944. auto Fn = CGM.CreateGlobalInitOrDestructFunction(
  945. FTy, ".__kmpc_global_ctor_.", Loc);
  946. CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
  947. Args, SourceLocation());
  948. auto ArgVal = CtorCGF.EmitLoadOfScalar(
  949. CtorCGF.GetAddrOfLocalVar(&Dst),
  950. /*Volatile=*/false, CGM.PointerAlignInBytes,
  951. CGM.getContext().VoidPtrTy, Dst.getLocation());
  952. auto Arg = CtorCGF.Builder.CreatePointerCast(
  953. ArgVal,
  954. CtorCGF.ConvertTypeForMem(CGM.getContext().getPointerType(ASTTy)));
  955. CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
  956. /*IsInitializer=*/true);
  957. ArgVal = CtorCGF.EmitLoadOfScalar(
  958. CtorCGF.GetAddrOfLocalVar(&Dst),
  959. /*Volatile=*/false, CGM.PointerAlignInBytes,
  960. CGM.getContext().VoidPtrTy, Dst.getLocation());
  961. CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
  962. CtorCGF.FinishFunction();
  963. Ctor = Fn;
  964. }
  965. if (VD->getType().isDestructedType() != QualType::DK_none) {
  966. // Generate function that emits destructor call for the threadprivate copy
  967. // of the variable VD
  968. CodeGenFunction DtorCGF(CGM);
  969. FunctionArgList Args;
  970. ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
  971. /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
  972. Args.push_back(&Dst);
  973. auto &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
  974. CGM.getContext().VoidTy, Args, FunctionType::ExtInfo(),
  975. /*isVariadic=*/false);
  976. auto FTy = CGM.getTypes().GetFunctionType(FI);
  977. auto Fn = CGM.CreateGlobalInitOrDestructFunction(
  978. FTy, ".__kmpc_global_dtor_.", Loc);
  979. DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
  980. SourceLocation());
  981. auto ArgVal = DtorCGF.EmitLoadOfScalar(
  982. DtorCGF.GetAddrOfLocalVar(&Dst),
  983. /*Volatile=*/false, CGM.PointerAlignInBytes,
  984. CGM.getContext().VoidPtrTy, Dst.getLocation());
  985. DtorCGF.emitDestroy(ArgVal, ASTTy,
  986. DtorCGF.getDestroyer(ASTTy.isDestructedType()),
  987. DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
  988. DtorCGF.FinishFunction();
  989. Dtor = Fn;
  990. }
  991. // Do not emit init function if it is not required.
  992. if (!Ctor && !Dtor)
  993. return nullptr;
  994. llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  995. auto CopyCtorTy =
  996. llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
  997. /*isVarArg=*/false)->getPointerTo();
  998. // Copying constructor for the threadprivate variable.
  999. // Must be NULL - reserved by runtime, but currently it requires that this
  1000. // parameter is always NULL. Otherwise it fires assertion.
  1001. CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
  1002. if (Ctor == nullptr) {
  1003. auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
  1004. /*isVarArg=*/false)->getPointerTo();
  1005. Ctor = llvm::Constant::getNullValue(CtorTy);
  1006. }
  1007. if (Dtor == nullptr) {
  1008. auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
  1009. /*isVarArg=*/false)->getPointerTo();
  1010. Dtor = llvm::Constant::getNullValue(DtorTy);
  1011. }
  1012. if (!CGF) {
  1013. auto InitFunctionTy =
  1014. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
  1015. auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
  1016. InitFunctionTy, ".__omp_threadprivate_init_.");
  1017. CodeGenFunction InitCGF(CGM);
  1018. FunctionArgList ArgList;
  1019. InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
  1020. CGM.getTypes().arrangeNullaryFunction(), ArgList,
  1021. Loc);
  1022. emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
  1023. InitCGF.FinishFunction();
  1024. return InitFunction;
  1025. }
  1026. emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
  1027. }
  1028. return nullptr;
  1029. }
  1030. /// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
  1031. /// function. Here is the logic:
  1032. /// if (Cond) {
  1033. /// ThenGen();
  1034. /// } else {
  1035. /// ElseGen();
  1036. /// }
  1037. static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
  1038. const RegionCodeGenTy &ThenGen,
  1039. const RegionCodeGenTy &ElseGen) {
  1040. CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
  1041. // If the condition constant folds and can be elided, try to avoid emitting
  1042. // the condition and the dead arm of the if/else.
  1043. bool CondConstant;
  1044. if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
  1045. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1046. if (CondConstant) {
  1047. ThenGen(CGF);
  1048. } else {
  1049. ElseGen(CGF);
  1050. }
  1051. return;
  1052. }
  1053. // Otherwise, the condition did not fold, or we couldn't elide it. Just
  1054. // emit the conditional branch.
  1055. auto ThenBlock = CGF.createBasicBlock("omp_if.then");
  1056. auto ElseBlock = CGF.createBasicBlock("omp_if.else");
  1057. auto ContBlock = CGF.createBasicBlock("omp_if.end");
  1058. CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
  1059. // Emit the 'then' code.
  1060. CGF.EmitBlock(ThenBlock);
  1061. {
  1062. CodeGenFunction::RunCleanupsScope ThenScope(CGF);
  1063. ThenGen(CGF);
  1064. }
  1065. CGF.EmitBranch(ContBlock);
  1066. // Emit the 'else' code if present.
  1067. {
  1068. // There is no need to emit line number for unconditional branch.
  1069. auto NL = ApplyDebugLocation::CreateEmpty(CGF);
  1070. CGF.EmitBlock(ElseBlock);
  1071. }
  1072. {
  1073. CodeGenFunction::RunCleanupsScope ThenScope(CGF);
  1074. ElseGen(CGF);
  1075. }
  1076. {
  1077. // There is no need to emit line number for unconditional branch.
  1078. auto NL = ApplyDebugLocation::CreateEmpty(CGF);
  1079. CGF.EmitBranch(ContBlock);
  1080. }
  1081. // Emit the continuation block for code after the if.
  1082. CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
  1083. }
  1084. void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  1085. llvm::Value *OutlinedFn,
  1086. llvm::Value *CapturedStruct,
  1087. const Expr *IfCond) {
  1088. auto *RTLoc = emitUpdateLocation(CGF, Loc);
  1089. auto &&ThenGen =
  1090. [this, OutlinedFn, CapturedStruct, RTLoc](CodeGenFunction &CGF) {
  1091. // Build call __kmpc_fork_call(loc, 1, microtask,
  1092. // captured_struct/*context*/)
  1093. llvm::Value *Args[] = {
  1094. RTLoc,
  1095. CGF.Builder.getInt32(
  1096. 1), // Number of arguments after 'microtask' argument
  1097. // (there is only one additional argument - 'context')
  1098. CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy()),
  1099. CGF.EmitCastToVoidPtr(CapturedStruct)};
  1100. auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_call);
  1101. CGF.EmitRuntimeCall(RTLFn, Args);
  1102. };
  1103. auto &&ElseGen = [this, OutlinedFn, CapturedStruct, RTLoc, Loc](
  1104. CodeGenFunction &CGF) {
  1105. auto ThreadID = getThreadID(CGF, Loc);
  1106. // Build calls:
  1107. // __kmpc_serialized_parallel(&Loc, GTid);
  1108. llvm::Value *Args[] = {RTLoc, ThreadID};
  1109. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_serialized_parallel),
  1110. Args);
  1111. // OutlinedFn(&GTid, &zero, CapturedStruct);
  1112. auto ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
  1113. auto Int32Ty = CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32,
  1114. /*Signed*/ true);
  1115. auto ZeroAddr = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".zero.addr");
  1116. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  1117. llvm::Value *OutlinedFnArgs[] = {ThreadIDAddr, ZeroAddr, CapturedStruct};
  1118. CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
  1119. // __kmpc_end_serialized_parallel(&Loc, GTid);
  1120. llvm::Value *EndArgs[] = {emitUpdateLocation(CGF, Loc), ThreadID};
  1121. CGF.EmitRuntimeCall(
  1122. createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), EndArgs);
  1123. };
  1124. if (IfCond) {
  1125. emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
  1126. } else {
  1127. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1128. ThenGen(CGF);
  1129. }
  1130. }
  1131. // If we're inside an (outlined) parallel region, use the region info's
  1132. // thread-ID variable (it is passed in a first argument of the outlined function
  1133. // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
  1134. // regular serial code region, get thread ID by calling kmp_int32
  1135. // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
  1136. // return the address of that temp.
  1137. llvm::Value *CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
  1138. SourceLocation Loc) {
  1139. if (auto OMPRegionInfo =
  1140. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  1141. if (OMPRegionInfo->getThreadIDVariable())
  1142. return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
  1143. auto ThreadID = getThreadID(CGF, Loc);
  1144. auto Int32Ty =
  1145. CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
  1146. auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
  1147. CGF.EmitStoreOfScalar(ThreadID,
  1148. CGF.MakeNaturalAlignAddrLValue(ThreadIDTemp, Int32Ty));
  1149. return ThreadIDTemp;
  1150. }
  1151. llvm::Constant *
  1152. CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
  1153. const llvm::Twine &Name) {
  1154. SmallString<256> Buffer;
  1155. llvm::raw_svector_ostream Out(Buffer);
  1156. Out << Name;
  1157. auto RuntimeName = Out.str();
  1158. auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
  1159. if (Elem.second) {
  1160. assert(Elem.second->getType()->getPointerElementType() == Ty &&
  1161. "OMP internal variable has different type than requested");
  1162. return &*Elem.second;
  1163. }
  1164. return Elem.second = new llvm::GlobalVariable(
  1165. CGM.getModule(), Ty, /*IsConstant*/ false,
  1166. llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
  1167. Elem.first());
  1168. }
  1169. llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
  1170. llvm::Twine Name(".gomp_critical_user_", CriticalName);
  1171. return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
  1172. }
  1173. namespace {
  1174. template <size_t N> class CallEndCleanup : public EHScopeStack::Cleanup {
  1175. llvm::Value *Callee;
  1176. llvm::Value *Args[N];
  1177. public:
  1178. CallEndCleanup(llvm::Value *Callee, ArrayRef<llvm::Value *> CleanupArgs)
  1179. : Callee(Callee) {
  1180. assert(CleanupArgs.size() == N);
  1181. std::copy(CleanupArgs.begin(), CleanupArgs.end(), std::begin(Args));
  1182. }
  1183. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  1184. CGF.EmitRuntimeCall(Callee, Args);
  1185. }
  1186. };
  1187. } // namespace
  1188. void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
  1189. StringRef CriticalName,
  1190. const RegionCodeGenTy &CriticalOpGen,
  1191. SourceLocation Loc) {
  1192. // __kmpc_critical(ident_t *, gtid, Lock);
  1193. // CriticalOpGen();
  1194. // __kmpc_end_critical(ident_t *, gtid, Lock);
  1195. // Prepare arguments and build a call to __kmpc_critical
  1196. {
  1197. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1198. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  1199. getCriticalRegionLock(CriticalName)};
  1200. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_critical), Args);
  1201. // Build a call to __kmpc_end_critical
  1202. CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
  1203. NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_critical),
  1204. llvm::makeArrayRef(Args));
  1205. emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
  1206. }
  1207. }
  1208. static void emitIfStmt(CodeGenFunction &CGF, llvm::Value *IfCond,
  1209. OpenMPDirectiveKind Kind,
  1210. const RegionCodeGenTy &BodyOpGen) {
  1211. llvm::Value *CallBool = CGF.EmitScalarConversion(
  1212. IfCond,
  1213. CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true),
  1214. CGF.getContext().BoolTy);
  1215. auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
  1216. auto *ContBlock = CGF.createBasicBlock("omp_if.end");
  1217. // Generate the branch (If-stmt)
  1218. CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
  1219. CGF.EmitBlock(ThenBlock);
  1220. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, Kind, BodyOpGen);
  1221. // Emit the rest of bblocks/branches
  1222. CGF.EmitBranch(ContBlock);
  1223. CGF.EmitBlock(ContBlock, true);
  1224. }
  1225. void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
  1226. const RegionCodeGenTy &MasterOpGen,
  1227. SourceLocation Loc) {
  1228. // if(__kmpc_master(ident_t *, gtid)) {
  1229. // MasterOpGen();
  1230. // __kmpc_end_master(ident_t *, gtid);
  1231. // }
  1232. // Prepare arguments and build a call to __kmpc_master
  1233. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  1234. auto *IsMaster =
  1235. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_master), Args);
  1236. typedef CallEndCleanup<std::extent<decltype(Args)>::value>
  1237. MasterCallEndCleanup;
  1238. emitIfStmt(CGF, IsMaster, OMPD_master, [&](CodeGenFunction &CGF) -> void {
  1239. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1240. CGF.EHStack.pushCleanup<MasterCallEndCleanup>(
  1241. NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_master),
  1242. llvm::makeArrayRef(Args));
  1243. MasterOpGen(CGF);
  1244. });
  1245. }
  1246. void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
  1247. SourceLocation Loc) {
  1248. // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
  1249. llvm::Value *Args[] = {
  1250. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  1251. llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
  1252. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
  1253. }
  1254. void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
  1255. const RegionCodeGenTy &TaskgroupOpGen,
  1256. SourceLocation Loc) {
  1257. // __kmpc_taskgroup(ident_t *, gtid);
  1258. // TaskgroupOpGen();
  1259. // __kmpc_end_taskgroup(ident_t *, gtid);
  1260. // Prepare arguments and build a call to __kmpc_taskgroup
  1261. {
  1262. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1263. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  1264. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args);
  1265. // Build a call to __kmpc_end_taskgroup
  1266. CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
  1267. NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
  1268. llvm::makeArrayRef(Args));
  1269. emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
  1270. }
  1271. }
  1272. static llvm::Value *emitCopyprivateCopyFunction(
  1273. CodeGenModule &CGM, llvm::Type *ArgsType,
  1274. ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
  1275. ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
  1276. auto &C = CGM.getContext();
  1277. // void copy_func(void *LHSArg, void *RHSArg);
  1278. FunctionArgList Args;
  1279. ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
  1280. C.VoidPtrTy);
  1281. ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
  1282. C.VoidPtrTy);
  1283. Args.push_back(&LHSArg);
  1284. Args.push_back(&RHSArg);
  1285. FunctionType::ExtInfo EI;
  1286. auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
  1287. C.VoidTy, Args, EI, /*isVariadic=*/false);
  1288. auto *Fn = llvm::Function::Create(
  1289. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  1290. ".omp.copyprivate.copy_func", &CGM.getModule());
  1291. CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
  1292. CodeGenFunction CGF(CGM);
  1293. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
  1294. // Dest = (void*[n])(LHSArg);
  1295. // Src = (void*[n])(RHSArg);
  1296. auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1297. CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
  1298. CGF.PointerAlignInBytes),
  1299. ArgsType);
  1300. auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1301. CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
  1302. CGF.PointerAlignInBytes),
  1303. ArgsType);
  1304. // *(Type0*)Dst[0] = *(Type0*)Src[0];
  1305. // *(Type1*)Dst[1] = *(Type1*)Src[1];
  1306. // ...
  1307. // *(Typen*)Dst[n] = *(Typen*)Src[n];
  1308. for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
  1309. auto *DestAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1310. CGF.Builder.CreateAlignedLoad(
  1311. CGF.Builder.CreateStructGEP(nullptr, LHS, I),
  1312. CGM.PointerAlignInBytes),
  1313. CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
  1314. auto *SrcAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1315. CGF.Builder.CreateAlignedLoad(
  1316. CGF.Builder.CreateStructGEP(nullptr, RHS, I),
  1317. CGM.PointerAlignInBytes),
  1318. CGF.ConvertTypeForMem(C.getPointerType(SrcExprs[I]->getType())));
  1319. auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
  1320. QualType Type = VD->getType();
  1321. CGF.EmitOMPCopy(CGF, Type, DestAddr, SrcAddr,
  1322. cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()),
  1323. cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()),
  1324. AssignmentOps[I]);
  1325. }
  1326. CGF.FinishFunction();
  1327. return Fn;
  1328. }
  1329. void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
  1330. const RegionCodeGenTy &SingleOpGen,
  1331. SourceLocation Loc,
  1332. ArrayRef<const Expr *> CopyprivateVars,
  1333. ArrayRef<const Expr *> SrcExprs,
  1334. ArrayRef<const Expr *> DstExprs,
  1335. ArrayRef<const Expr *> AssignmentOps) {
  1336. assert(CopyprivateVars.size() == SrcExprs.size() &&
  1337. CopyprivateVars.size() == DstExprs.size() &&
  1338. CopyprivateVars.size() == AssignmentOps.size());
  1339. auto &C = CGM.getContext();
  1340. // int32 did_it = 0;
  1341. // if(__kmpc_single(ident_t *, gtid)) {
  1342. // SingleOpGen();
  1343. // __kmpc_end_single(ident_t *, gtid);
  1344. // did_it = 1;
  1345. // }
  1346. // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
  1347. // <copy_func>, did_it);
  1348. llvm::AllocaInst *DidIt = nullptr;
  1349. if (!CopyprivateVars.empty()) {
  1350. // int32 did_it = 0;
  1351. auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  1352. DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
  1353. CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(0), DidIt,
  1354. DidIt->getAlignment());
  1355. }
  1356. // Prepare arguments and build a call to __kmpc_single
  1357. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  1358. auto *IsSingle =
  1359. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_single), Args);
  1360. typedef CallEndCleanup<std::extent<decltype(Args)>::value>
  1361. SingleCallEndCleanup;
  1362. emitIfStmt(CGF, IsSingle, OMPD_single, [&](CodeGenFunction &CGF) -> void {
  1363. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1364. CGF.EHStack.pushCleanup<SingleCallEndCleanup>(
  1365. NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_single),
  1366. llvm::makeArrayRef(Args));
  1367. SingleOpGen(CGF);
  1368. if (DidIt) {
  1369. // did_it = 1;
  1370. CGF.Builder.CreateAlignedStore(CGF.Builder.getInt32(1), DidIt,
  1371. DidIt->getAlignment());
  1372. }
  1373. });
  1374. // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
  1375. // <copy_func>, did_it);
  1376. if (DidIt) {
  1377. llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
  1378. auto CopyprivateArrayTy =
  1379. C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
  1380. /*IndexTypeQuals=*/0);
  1381. // Create a list of all private variables for copyprivate.
  1382. auto *CopyprivateList =
  1383. CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
  1384. for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
  1385. auto *Elem = CGF.Builder.CreateStructGEP(
  1386. CopyprivateList->getAllocatedType(), CopyprivateList, I);
  1387. CGF.Builder.CreateAlignedStore(
  1388. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1389. CGF.EmitLValue(CopyprivateVars[I]).getAddress(), CGF.VoidPtrTy),
  1390. Elem, CGM.PointerAlignInBytes);
  1391. }
  1392. // Build function that copies private values from single region to all other
  1393. // threads in the corresponding parallel region.
  1394. auto *CpyFn = emitCopyprivateCopyFunction(
  1395. CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
  1396. CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
  1397. auto *BufSize = llvm::ConstantInt::get(
  1398. CGM.SizeTy, C.getTypeSizeInChars(CopyprivateArrayTy).getQuantity());
  1399. auto *CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
  1400. CGF.VoidPtrTy);
  1401. auto *DidItVal =
  1402. CGF.Builder.CreateAlignedLoad(DidIt, CGF.PointerAlignInBytes);
  1403. llvm::Value *Args[] = {
  1404. emitUpdateLocation(CGF, Loc), // ident_t *<loc>
  1405. getThreadID(CGF, Loc), // i32 <gtid>
  1406. BufSize, // size_t <buf_size>
  1407. CL, // void *<copyprivate list>
  1408. CpyFn, // void (*) (void *, void *) <copy_func>
  1409. DidItVal // i32 did_it
  1410. };
  1411. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
  1412. }
  1413. }
  1414. void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
  1415. const RegionCodeGenTy &OrderedOpGen,
  1416. SourceLocation Loc) {
  1417. // __kmpc_ordered(ident_t *, gtid);
  1418. // OrderedOpGen();
  1419. // __kmpc_end_ordered(ident_t *, gtid);
  1420. // Prepare arguments and build a call to __kmpc_ordered
  1421. {
  1422. CodeGenFunction::RunCleanupsScope Scope(CGF);
  1423. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  1424. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_ordered), Args);
  1425. // Build a call to __kmpc_end_ordered
  1426. CGF.EHStack.pushCleanup<CallEndCleanup<std::extent<decltype(Args)>::value>>(
  1427. NormalAndEHCleanup, createRuntimeFunction(OMPRTL__kmpc_end_ordered),
  1428. llvm::makeArrayRef(Args));
  1429. emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
  1430. }
  1431. }
  1432. void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
  1433. OpenMPDirectiveKind Kind,
  1434. bool CheckForCancel) {
  1435. // Build call __kmpc_cancel_barrier(loc, thread_id);
  1436. // Build call __kmpc_barrier(loc, thread_id);
  1437. OpenMPLocationFlags Flags = OMP_IDENT_KMPC;
  1438. if (Kind == OMPD_for) {
  1439. Flags =
  1440. static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_FOR);
  1441. } else if (Kind == OMPD_sections) {
  1442. Flags = static_cast<OpenMPLocationFlags>(Flags |
  1443. OMP_IDENT_BARRIER_IMPL_SECTIONS);
  1444. } else if (Kind == OMPD_single) {
  1445. Flags =
  1446. static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL_SINGLE);
  1447. } else if (Kind == OMPD_barrier) {
  1448. Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_EXPL);
  1449. } else {
  1450. Flags = static_cast<OpenMPLocationFlags>(Flags | OMP_IDENT_BARRIER_IMPL);
  1451. }
  1452. // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
  1453. // thread_id);
  1454. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
  1455. getThreadID(CGF, Loc)};
  1456. if (auto *OMPRegionInfo =
  1457. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  1458. auto CancelDestination =
  1459. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  1460. if (CancelDestination.isValid()) {
  1461. auto *Result = CGF.EmitRuntimeCall(
  1462. createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
  1463. if (CheckForCancel) {
  1464. // if (__kmpc_cancel_barrier()) {
  1465. // exit from construct;
  1466. // }
  1467. auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
  1468. auto *ContBB = CGF.createBasicBlock(".cancel.continue");
  1469. auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
  1470. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  1471. CGF.EmitBlock(ExitBB);
  1472. // exit from construct;
  1473. CGF.EmitBranchThroughCleanup(CancelDestination);
  1474. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  1475. }
  1476. return;
  1477. }
  1478. }
  1479. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
  1480. }
  1481. /// \brief Schedule types for 'omp for' loops (these enumerators are taken from
  1482. /// the enum sched_type in kmp.h).
  1483. enum OpenMPSchedType {
  1484. /// \brief Lower bound for default (unordered) versions.
  1485. OMP_sch_lower = 32,
  1486. OMP_sch_static_chunked = 33,
  1487. OMP_sch_static = 34,
  1488. OMP_sch_dynamic_chunked = 35,
  1489. OMP_sch_guided_chunked = 36,
  1490. OMP_sch_runtime = 37,
  1491. OMP_sch_auto = 38,
  1492. /// \brief Lower bound for 'ordered' versions.
  1493. OMP_ord_lower = 64,
  1494. OMP_ord_static_chunked = 65,
  1495. OMP_ord_static = 66,
  1496. OMP_ord_dynamic_chunked = 67,
  1497. OMP_ord_guided_chunked = 68,
  1498. OMP_ord_runtime = 69,
  1499. OMP_ord_auto = 70,
  1500. OMP_sch_default = OMP_sch_static,
  1501. };
  1502. /// \brief Map the OpenMP loop schedule to the runtime enumeration.
  1503. static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
  1504. bool Chunked, bool Ordered) {
  1505. switch (ScheduleKind) {
  1506. case OMPC_SCHEDULE_static:
  1507. return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
  1508. : (Ordered ? OMP_ord_static : OMP_sch_static);
  1509. case OMPC_SCHEDULE_dynamic:
  1510. return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
  1511. case OMPC_SCHEDULE_guided:
  1512. return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
  1513. case OMPC_SCHEDULE_runtime:
  1514. return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
  1515. case OMPC_SCHEDULE_auto:
  1516. return Ordered ? OMP_ord_auto : OMP_sch_auto;
  1517. case OMPC_SCHEDULE_unknown:
  1518. assert(!Chunked && "chunk was specified but schedule kind not known");
  1519. return Ordered ? OMP_ord_static : OMP_sch_static;
  1520. }
  1521. llvm_unreachable("Unexpected runtime schedule");
  1522. }
  1523. bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
  1524. bool Chunked) const {
  1525. auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
  1526. return Schedule == OMP_sch_static;
  1527. }
  1528. bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
  1529. auto Schedule =
  1530. getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
  1531. assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
  1532. return Schedule != OMP_sch_static;
  1533. }
  1534. void CGOpenMPRuntime::emitForInit(CodeGenFunction &CGF, SourceLocation Loc,
  1535. OpenMPScheduleClauseKind ScheduleKind,
  1536. unsigned IVSize, bool IVSigned, bool Ordered,
  1537. llvm::Value *IL, llvm::Value *LB,
  1538. llvm::Value *UB, llvm::Value *ST,
  1539. llvm::Value *Chunk) {
  1540. OpenMPSchedType Schedule =
  1541. getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
  1542. if (Ordered ||
  1543. (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
  1544. Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked)) {
  1545. // Call __kmpc_dispatch_init(
  1546. // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
  1547. // kmp_int[32|64] lower, kmp_int[32|64] upper,
  1548. // kmp_int[32|64] stride, kmp_int[32|64] chunk);
  1549. // If the Chunk was not specified in the clause - use default value 1.
  1550. if (Chunk == nullptr)
  1551. Chunk = CGF.Builder.getIntN(IVSize, 1);
  1552. llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
  1553. getThreadID(CGF, Loc),
  1554. CGF.Builder.getInt32(Schedule), // Schedule type
  1555. CGF.Builder.getIntN(IVSize, 0), // Lower
  1556. UB, // Upper
  1557. CGF.Builder.getIntN(IVSize, 1), // Stride
  1558. Chunk // Chunk
  1559. };
  1560. CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
  1561. } else {
  1562. // Call __kmpc_for_static_init(
  1563. // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
  1564. // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
  1565. // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
  1566. // kmp_int[32|64] incr, kmp_int[32|64] chunk);
  1567. if (Chunk == nullptr) {
  1568. assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static) &&
  1569. "expected static non-chunked schedule");
  1570. // If the Chunk was not specified in the clause - use default value 1.
  1571. Chunk = CGF.Builder.getIntN(IVSize, 1);
  1572. } else
  1573. assert((Schedule == OMP_sch_static_chunked ||
  1574. Schedule == OMP_ord_static_chunked) &&
  1575. "expected static chunked schedule");
  1576. llvm::Value *Args[] = { emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
  1577. getThreadID(CGF, Loc),
  1578. CGF.Builder.getInt32(Schedule), // Schedule type
  1579. IL, // &isLastIter
  1580. LB, // &LB
  1581. UB, // &UB
  1582. ST, // &Stride
  1583. CGF.Builder.getIntN(IVSize, 1), // Incr
  1584. Chunk // Chunk
  1585. };
  1586. CGF.EmitRuntimeCall(createForStaticInitFunction(IVSize, IVSigned), Args);
  1587. }
  1588. }
  1589. void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
  1590. SourceLocation Loc) {
  1591. // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
  1592. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
  1593. getThreadID(CGF, Loc)};
  1594. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
  1595. Args);
  1596. }
  1597. void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
  1598. SourceLocation Loc,
  1599. unsigned IVSize,
  1600. bool IVSigned) {
  1601. // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
  1602. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC),
  1603. getThreadID(CGF, Loc)};
  1604. CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
  1605. }
  1606. llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
  1607. SourceLocation Loc, unsigned IVSize,
  1608. bool IVSigned, llvm::Value *IL,
  1609. llvm::Value *LB, llvm::Value *UB,
  1610. llvm::Value *ST) {
  1611. // Call __kmpc_dispatch_next(
  1612. // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
  1613. // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
  1614. // kmp_int[32|64] *p_stride);
  1615. llvm::Value *Args[] = {
  1616. emitUpdateLocation(CGF, Loc, OMP_IDENT_KMPC), getThreadID(CGF, Loc),
  1617. IL, // &isLastIter
  1618. LB, // &Lower
  1619. UB, // &Upper
  1620. ST // &Stride
  1621. };
  1622. llvm::Value *Call =
  1623. CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
  1624. return CGF.EmitScalarConversion(
  1625. Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
  1626. CGF.getContext().BoolTy);
  1627. }
  1628. void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
  1629. llvm::Value *NumThreads,
  1630. SourceLocation Loc) {
  1631. // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
  1632. llvm::Value *Args[] = {
  1633. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  1634. CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
  1635. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
  1636. Args);
  1637. }
  1638. void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
  1639. OpenMPProcBindClauseKind ProcBind,
  1640. SourceLocation Loc) {
  1641. // Constants for proc bind value accepted by the runtime.
  1642. enum ProcBindTy {
  1643. ProcBindFalse = 0,
  1644. ProcBindTrue,
  1645. ProcBindMaster,
  1646. ProcBindClose,
  1647. ProcBindSpread,
  1648. ProcBindIntel,
  1649. ProcBindDefault
  1650. } RuntimeProcBind;
  1651. switch (ProcBind) {
  1652. case OMPC_PROC_BIND_master:
  1653. RuntimeProcBind = ProcBindMaster;
  1654. break;
  1655. case OMPC_PROC_BIND_close:
  1656. RuntimeProcBind = ProcBindClose;
  1657. break;
  1658. case OMPC_PROC_BIND_spread:
  1659. RuntimeProcBind = ProcBindSpread;
  1660. break;
  1661. case OMPC_PROC_BIND_unknown:
  1662. llvm_unreachable("Unsupported proc_bind value.");
  1663. }
  1664. // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
  1665. llvm::Value *Args[] = {
  1666. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  1667. llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
  1668. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
  1669. }
  1670. void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
  1671. SourceLocation Loc) {
  1672. // Build call void __kmpc_flush(ident_t *loc)
  1673. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
  1674. emitUpdateLocation(CGF, Loc));
  1675. }
  1676. namespace {
  1677. /// \brief Indexes of fields for type kmp_task_t.
  1678. enum KmpTaskTFields {
  1679. /// \brief List of shared variables.
  1680. KmpTaskTShareds,
  1681. /// \brief Task routine.
  1682. KmpTaskTRoutine,
  1683. /// \brief Partition id for the untied tasks.
  1684. KmpTaskTPartId,
  1685. /// \brief Function with call of destructors for private variables.
  1686. KmpTaskTDestructors,
  1687. };
  1688. } // namespace
  1689. void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
  1690. if (!KmpRoutineEntryPtrTy) {
  1691. // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
  1692. auto &C = CGM.getContext();
  1693. QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
  1694. FunctionProtoType::ExtProtoInfo EPI;
  1695. KmpRoutineEntryPtrQTy = C.getPointerType(
  1696. C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
  1697. KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
  1698. }
  1699. }
  1700. static void addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
  1701. QualType FieldTy) {
  1702. auto *Field = FieldDecl::Create(
  1703. C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
  1704. C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
  1705. /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
  1706. Field->setAccess(AS_public);
  1707. DC->addDecl(Field);
  1708. }
  1709. namespace {
  1710. struct PrivateHelpersTy {
  1711. PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
  1712. const VarDecl *PrivateElemInit)
  1713. : Original(Original), PrivateCopy(PrivateCopy),
  1714. PrivateElemInit(PrivateElemInit) {}
  1715. const VarDecl *Original;
  1716. const VarDecl *PrivateCopy;
  1717. const VarDecl *PrivateElemInit;
  1718. };
  1719. typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
  1720. } // namespace
  1721. static RecordDecl *
  1722. createPrivatesRecordDecl(CodeGenModule &CGM,
  1723. const ArrayRef<PrivateDataTy> Privates) {
  1724. if (!Privates.empty()) {
  1725. auto &C = CGM.getContext();
  1726. // Build struct .kmp_privates_t. {
  1727. // /* private vars */
  1728. // };
  1729. auto *RD = C.buildImplicitRecord(".kmp_privates.t");
  1730. RD->startDefinition();
  1731. for (auto &&Pair : Privates) {
  1732. auto Type = Pair.second.Original->getType();
  1733. Type = Type.getNonReferenceType();
  1734. addFieldToRecordDecl(C, RD, Type);
  1735. }
  1736. RD->completeDefinition();
  1737. return RD;
  1738. }
  1739. return nullptr;
  1740. }
  1741. static RecordDecl *
  1742. createKmpTaskTRecordDecl(CodeGenModule &CGM, QualType KmpInt32Ty,
  1743. QualType KmpRoutineEntryPointerQTy) {
  1744. auto &C = CGM.getContext();
  1745. // Build struct kmp_task_t {
  1746. // void * shareds;
  1747. // kmp_routine_entry_t routine;
  1748. // kmp_int32 part_id;
  1749. // kmp_routine_entry_t destructors;
  1750. // };
  1751. auto *RD = C.buildImplicitRecord("kmp_task_t");
  1752. RD->startDefinition();
  1753. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  1754. addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
  1755. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1756. addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
  1757. RD->completeDefinition();
  1758. return RD;
  1759. }
  1760. static RecordDecl *
  1761. createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
  1762. const ArrayRef<PrivateDataTy> Privates) {
  1763. auto &C = CGM.getContext();
  1764. // Build struct kmp_task_t_with_privates {
  1765. // kmp_task_t task_data;
  1766. // .kmp_privates_t. privates;
  1767. // };
  1768. auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
  1769. RD->startDefinition();
  1770. addFieldToRecordDecl(C, RD, KmpTaskTQTy);
  1771. if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
  1772. addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
  1773. }
  1774. RD->completeDefinition();
  1775. return RD;
  1776. }
  1777. /// \brief Emit a proxy function which accepts kmp_task_t as the second
  1778. /// argument.
  1779. /// \code
  1780. /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
  1781. /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map,
  1782. /// tt->shareds);
  1783. /// return 0;
  1784. /// }
  1785. /// \endcode
  1786. static llvm::Value *
  1787. emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
  1788. QualType KmpInt32Ty, QualType KmpTaskTWithPrivatesPtrQTy,
  1789. QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
  1790. QualType SharedsPtrTy, llvm::Value *TaskFunction,
  1791. llvm::Value *TaskPrivatesMap) {
  1792. auto &C = CGM.getContext();
  1793. FunctionArgList Args;
  1794. ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
  1795. ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
  1796. /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
  1797. Args.push_back(&GtidArg);
  1798. Args.push_back(&TaskTypeArg);
  1799. FunctionType::ExtInfo Info;
  1800. auto &TaskEntryFnInfo =
  1801. CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
  1802. /*isVariadic=*/false);
  1803. auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
  1804. auto *TaskEntry =
  1805. llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
  1806. ".omp_task_entry.", &CGM.getModule());
  1807. CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskEntryFnInfo, TaskEntry);
  1808. CodeGenFunction CGF(CGM);
  1809. CGF.disableDebugInfo();
  1810. CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
  1811. // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
  1812. // tt->task_data.shareds);
  1813. auto *GtidParam = CGF.EmitLoadOfScalar(
  1814. CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false,
  1815. C.getTypeAlignInChars(KmpInt32Ty).getQuantity(), KmpInt32Ty, Loc);
  1816. auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
  1817. CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
  1818. LValue TDBase =
  1819. CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
  1820. auto *KmpTaskTWithPrivatesQTyRD =
  1821. cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
  1822. LValue Base =
  1823. CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  1824. auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
  1825. auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
  1826. auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
  1827. auto *PartidParam = CGF.EmitLoadOfLValue(PartIdLVal, Loc).getScalarVal();
  1828. auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
  1829. auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
  1830. auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1831. CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
  1832. CGF.ConvertTypeForMem(SharedsPtrTy));
  1833. auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
  1834. llvm::Value *PrivatesParam;
  1835. if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
  1836. auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
  1837. PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1838. PrivatesLVal.getAddress(), CGF.VoidPtrTy);
  1839. } else {
  1840. PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  1841. }
  1842. llvm::Value *CallArgs[] = {GtidParam, PartidParam, PrivatesParam,
  1843. TaskPrivatesMap, SharedsParam};
  1844. CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
  1845. CGF.EmitStoreThroughLValue(
  1846. RValue::get(CGF.Builder.getInt32(/*C=*/0)),
  1847. CGF.MakeNaturalAlignAddrLValue(CGF.ReturnValue, KmpInt32Ty));
  1848. CGF.FinishFunction();
  1849. return TaskEntry;
  1850. }
  1851. static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
  1852. SourceLocation Loc,
  1853. QualType KmpInt32Ty,
  1854. QualType KmpTaskTWithPrivatesPtrQTy,
  1855. QualType KmpTaskTWithPrivatesQTy) {
  1856. auto &C = CGM.getContext();
  1857. FunctionArgList Args;
  1858. ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
  1859. ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
  1860. /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
  1861. Args.push_back(&GtidArg);
  1862. Args.push_back(&TaskTypeArg);
  1863. FunctionType::ExtInfo Info;
  1864. auto &DestructorFnInfo =
  1865. CGM.getTypes().arrangeFreeFunctionDeclaration(KmpInt32Ty, Args, Info,
  1866. /*isVariadic=*/false);
  1867. auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
  1868. auto *DestructorFn =
  1869. llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
  1870. ".omp_task_destructor.", &CGM.getModule());
  1871. CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, DestructorFnInfo, DestructorFn);
  1872. CodeGenFunction CGF(CGM);
  1873. CGF.disableDebugInfo();
  1874. CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
  1875. Args);
  1876. auto *TaskTypeArgAddr = CGF.Builder.CreateAlignedLoad(
  1877. CGF.GetAddrOfLocalVar(&TaskTypeArg), CGM.PointerAlignInBytes);
  1878. LValue Base =
  1879. CGF.MakeNaturalAlignAddrLValue(TaskTypeArgAddr, KmpTaskTWithPrivatesQTy);
  1880. auto *KmpTaskTWithPrivatesQTyRD =
  1881. cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
  1882. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  1883. Base = CGF.EmitLValueForField(Base, *FI);
  1884. for (auto *Field :
  1885. cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
  1886. if (auto DtorKind = Field->getType().isDestructedType()) {
  1887. auto FieldLValue = CGF.EmitLValueForField(Base, Field);
  1888. CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
  1889. }
  1890. }
  1891. CGF.FinishFunction();
  1892. return DestructorFn;
  1893. }
  1894. /// \brief Emit a privates mapping function for correct handling of private and
  1895. /// firstprivate variables.
  1896. /// \code
  1897. /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
  1898. /// **noalias priv1,..., <tyn> **noalias privn) {
  1899. /// *priv1 = &.privates.priv1;
  1900. /// ...;
  1901. /// *privn = &.privates.privn;
  1902. /// }
  1903. /// \endcode
  1904. static llvm::Value *
  1905. emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
  1906. const ArrayRef<const Expr *> PrivateVars,
  1907. const ArrayRef<const Expr *> FirstprivateVars,
  1908. QualType PrivatesQTy,
  1909. const ArrayRef<PrivateDataTy> Privates) {
  1910. auto &C = CGM.getContext();
  1911. FunctionArgList Args;
  1912. ImplicitParamDecl TaskPrivatesArg(
  1913. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  1914. C.getPointerType(PrivatesQTy).withConst().withRestrict());
  1915. Args.push_back(&TaskPrivatesArg);
  1916. llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
  1917. unsigned Counter = 1;
  1918. for (auto *E: PrivateVars) {
  1919. Args.push_back(ImplicitParamDecl::Create(
  1920. C, /*DC=*/nullptr, Loc,
  1921. /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
  1922. .withConst()
  1923. .withRestrict()));
  1924. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  1925. PrivateVarsPos[VD] = Counter;
  1926. ++Counter;
  1927. }
  1928. for (auto *E : FirstprivateVars) {
  1929. Args.push_back(ImplicitParamDecl::Create(
  1930. C, /*DC=*/nullptr, Loc,
  1931. /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
  1932. .withConst()
  1933. .withRestrict()));
  1934. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  1935. PrivateVarsPos[VD] = Counter;
  1936. ++Counter;
  1937. }
  1938. FunctionType::ExtInfo Info;
  1939. auto &TaskPrivatesMapFnInfo =
  1940. CGM.getTypes().arrangeFreeFunctionDeclaration(C.VoidTy, Args, Info,
  1941. /*isVariadic=*/false);
  1942. auto *TaskPrivatesMapTy =
  1943. CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
  1944. auto *TaskPrivatesMap = llvm::Function::Create(
  1945. TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
  1946. ".omp_task_privates_map.", &CGM.getModule());
  1947. CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, TaskPrivatesMapFnInfo,
  1948. TaskPrivatesMap);
  1949. TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
  1950. CodeGenFunction CGF(CGM);
  1951. CGF.disableDebugInfo();
  1952. CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
  1953. TaskPrivatesMapFnInfo, Args);
  1954. // *privi = &.privates.privi;
  1955. auto *TaskPrivatesArgAddr = CGF.Builder.CreateAlignedLoad(
  1956. CGF.GetAddrOfLocalVar(&TaskPrivatesArg), CGM.PointerAlignInBytes);
  1957. LValue Base =
  1958. CGF.MakeNaturalAlignAddrLValue(TaskPrivatesArgAddr, PrivatesQTy);
  1959. auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
  1960. Counter = 0;
  1961. for (auto *Field : PrivatesQTyRD->fields()) {
  1962. auto FieldLVal = CGF.EmitLValueForField(Base, Field);
  1963. auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
  1964. auto RefLVal = CGF.MakeNaturalAlignAddrLValue(CGF.GetAddrOfLocalVar(VD),
  1965. VD->getType());
  1966. auto RefLoadRVal = CGF.EmitLoadOfLValue(RefLVal, Loc);
  1967. CGF.EmitStoreOfScalar(
  1968. FieldLVal.getAddress(),
  1969. CGF.MakeNaturalAlignAddrLValue(RefLoadRVal.getScalarVal(),
  1970. RefLVal.getType()->getPointeeType()));
  1971. ++Counter;
  1972. }
  1973. CGF.FinishFunction();
  1974. return TaskPrivatesMap;
  1975. }
  1976. static int __cdecl array_pod_sort_comparator(const PrivateDataTy *P1, // HLSL Change - __cdecl
  1977. const PrivateDataTy *P2) {
  1978. return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
  1979. }
  1980. void CGOpenMPRuntime::emitTaskCall(
  1981. CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
  1982. bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
  1983. llvm::Value *TaskFunction, QualType SharedsTy, llvm::Value *Shareds,
  1984. const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
  1985. ArrayRef<const Expr *> PrivateCopies,
  1986. ArrayRef<const Expr *> FirstprivateVars,
  1987. ArrayRef<const Expr *> FirstprivateCopies,
  1988. ArrayRef<const Expr *> FirstprivateInits,
  1989. ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
  1990. auto &C = CGM.getContext();
  1991. llvm::SmallVector<PrivateDataTy, 8> Privates;
  1992. // Aggregate privates and sort them by the alignment.
  1993. auto I = PrivateCopies.begin();
  1994. for (auto *E : PrivateVars) {
  1995. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  1996. Privates.push_back(std::make_pair(
  1997. C.getTypeAlignInChars(VD->getType()),
  1998. PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  1999. /*PrivateElemInit=*/nullptr)));
  2000. ++I;
  2001. }
  2002. I = FirstprivateCopies.begin();
  2003. auto IElemInitRef = FirstprivateInits.begin();
  2004. for (auto *E : FirstprivateVars) {
  2005. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2006. Privates.push_back(std::make_pair(
  2007. C.getTypeAlignInChars(VD->getType()),
  2008. PrivateHelpersTy(
  2009. VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  2010. cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
  2011. ++I, ++IElemInitRef;
  2012. }
  2013. llvm::array_pod_sort(Privates.begin(), Privates.end(),
  2014. array_pod_sort_comparator);
  2015. auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  2016. // Build type kmp_routine_entry_t (if not built yet).
  2017. emitKmpRoutineEntryT(KmpInt32Ty);
  2018. // Build type kmp_task_t (if not built yet).
  2019. if (KmpTaskTQTy.isNull()) {
  2020. KmpTaskTQTy = C.getRecordType(
  2021. createKmpTaskTRecordDecl(CGM, KmpInt32Ty, KmpRoutineEntryPtrQTy));
  2022. }
  2023. auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
  2024. // Build particular struct kmp_task_t for the given task.
  2025. auto *KmpTaskTWithPrivatesQTyRD =
  2026. createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
  2027. auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
  2028. QualType KmpTaskTWithPrivatesPtrQTy =
  2029. C.getPointerType(KmpTaskTWithPrivatesQTy);
  2030. auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
  2031. auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
  2032. auto KmpTaskTWithPrivatesTySize =
  2033. CGM.getSize(C.getTypeSizeInChars(KmpTaskTWithPrivatesQTy));
  2034. QualType SharedsPtrTy = C.getPointerType(SharedsTy);
  2035. // Emit initial values for private copies (if any).
  2036. llvm::Value *TaskPrivatesMap = nullptr;
  2037. auto *TaskPrivatesMapTy =
  2038. std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
  2039. 3)
  2040. ->getType();
  2041. if (!Privates.empty()) {
  2042. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  2043. TaskPrivatesMap = emitTaskPrivateMappingFunction(
  2044. CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
  2045. TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2046. TaskPrivatesMap, TaskPrivatesMapTy);
  2047. } else {
  2048. TaskPrivatesMap = llvm::ConstantPointerNull::get(
  2049. cast<llvm::PointerType>(TaskPrivatesMapTy));
  2050. }
  2051. // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
  2052. // kmp_task_t *tt);
  2053. auto *TaskEntry = emitProxyTaskFunction(
  2054. CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTy,
  2055. KmpTaskTQTy, SharedsPtrTy, TaskFunction, TaskPrivatesMap);
  2056. // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  2057. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  2058. // kmp_routine_entry_t *task_entry);
  2059. // Task flags. Format is taken from
  2060. // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
  2061. // description of kmp_tasking_flags struct.
  2062. const unsigned TiedFlag = 0x1;
  2063. const unsigned FinalFlag = 0x2;
  2064. unsigned Flags = Tied ? TiedFlag : 0;
  2065. auto *TaskFlags =
  2066. Final.getPointer()
  2067. ? CGF.Builder.CreateSelect(Final.getPointer(),
  2068. CGF.Builder.getInt32(FinalFlag),
  2069. CGF.Builder.getInt32(/*C=*/0))
  2070. : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
  2071. TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
  2072. auto SharedsSize = C.getTypeSizeInChars(SharedsTy);
  2073. llvm::Value *AllocArgs[] = {
  2074. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), TaskFlags,
  2075. KmpTaskTWithPrivatesTySize, CGM.getSize(SharedsSize),
  2076. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskEntry,
  2077. KmpRoutineEntryPtrTy)};
  2078. auto *NewTask = CGF.EmitRuntimeCall(
  2079. createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
  2080. auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2081. NewTask, KmpTaskTWithPrivatesPtrTy);
  2082. LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
  2083. KmpTaskTWithPrivatesQTy);
  2084. LValue TDBase =
  2085. CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
  2086. // Fill the data in the resulting kmp_task_t record.
  2087. // Copy shareds if there are any.
  2088. llvm::Value *KmpTaskSharedsPtr = nullptr;
  2089. if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
  2090. KmpTaskSharedsPtr = CGF.EmitLoadOfScalar(
  2091. CGF.EmitLValueForField(
  2092. TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds)),
  2093. Loc);
  2094. CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
  2095. }
  2096. // Emit initial values for private copies (if any).
  2097. bool NeedsCleanup = false;
  2098. if (!Privates.empty()) {
  2099. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  2100. auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
  2101. FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
  2102. LValue SharedsBase;
  2103. if (!FirstprivateVars.empty()) {
  2104. SharedsBase = CGF.MakeNaturalAlignAddrLValue(
  2105. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2106. KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
  2107. SharedsTy);
  2108. }
  2109. CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
  2110. cast<CapturedStmt>(*D.getAssociatedStmt()));
  2111. for (auto &&Pair : Privates) {
  2112. auto *VD = Pair.second.PrivateCopy;
  2113. auto *Init = VD->getAnyInitializer();
  2114. LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
  2115. if (Init) {
  2116. if (auto *Elem = Pair.second.PrivateElemInit) {
  2117. auto *OriginalVD = Pair.second.Original;
  2118. auto *SharedField = CapturesInfo.lookup(OriginalVD);
  2119. auto SharedRefLValue =
  2120. CGF.EmitLValueForField(SharedsBase, SharedField);
  2121. QualType Type = OriginalVD->getType();
  2122. if (Type->isArrayType()) {
  2123. // Initialize firstprivate array.
  2124. if (!isa<CXXConstructExpr>(Init) ||
  2125. CGF.isTrivialInitializer(Init)) {
  2126. // Perform simple memcpy.
  2127. CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
  2128. SharedRefLValue.getAddress(), Type);
  2129. } else {
  2130. // Initialize firstprivate array using element-by-element
  2131. // intialization.
  2132. CGF.EmitOMPAggregateAssign(
  2133. PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
  2134. Type, [&CGF, Elem, Init, &CapturesInfo](
  2135. llvm::Value *DestElement, llvm::Value *SrcElement) {
  2136. // Clean up any temporaries needed by the initialization.
  2137. CodeGenFunction::OMPPrivateScope InitScope(CGF);
  2138. InitScope.addPrivate(Elem, [SrcElement]() -> llvm::Value *{
  2139. return SrcElement;
  2140. });
  2141. (void)InitScope.Privatize();
  2142. // Emit initialization for single element.
  2143. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
  2144. CGF, &CapturesInfo);
  2145. CGF.EmitAnyExprToMem(Init, DestElement,
  2146. Init->getType().getQualifiers(),
  2147. /*IsInitializer=*/false);
  2148. });
  2149. }
  2150. } else {
  2151. CodeGenFunction::OMPPrivateScope InitScope(CGF);
  2152. InitScope.addPrivate(Elem, [SharedRefLValue]() -> llvm::Value *{
  2153. return SharedRefLValue.getAddress();
  2154. });
  2155. (void)InitScope.Privatize();
  2156. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
  2157. CGF.EmitExprAsInit(Init, VD, PrivateLValue,
  2158. /*capturedByInit=*/false);
  2159. }
  2160. } else {
  2161. CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
  2162. }
  2163. }
  2164. NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
  2165. ++FI;
  2166. }
  2167. }
  2168. // Provide pointer to function with destructors for privates.
  2169. llvm::Value *DestructorFn =
  2170. NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
  2171. KmpTaskTWithPrivatesPtrQTy,
  2172. KmpTaskTWithPrivatesQTy)
  2173. : llvm::ConstantPointerNull::get(
  2174. cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
  2175. LValue Destructor = CGF.EmitLValueForField(
  2176. TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
  2177. CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2178. DestructorFn, KmpRoutineEntryPtrTy),
  2179. Destructor);
  2180. // Process list of dependences.
  2181. llvm::Value *DependInfo = nullptr;
  2182. unsigned DependencesNumber = Dependences.size();
  2183. if (!Dependences.empty()) {
  2184. // Dependence kind for RTL.
  2185. enum RTLDependenceKindTy { DepIn = 1, DepOut = 2, DepInOut = 3 };
  2186. enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
  2187. RecordDecl *KmpDependInfoRD;
  2188. QualType FlagsTy = C.getIntTypeForBitwidth(
  2189. C.toBits(C.getTypeSizeInChars(C.BoolTy)), /*Signed=*/false);
  2190. llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
  2191. if (KmpDependInfoTy.isNull()) {
  2192. KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
  2193. KmpDependInfoRD->startDefinition();
  2194. addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
  2195. addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
  2196. addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
  2197. KmpDependInfoRD->completeDefinition();
  2198. KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
  2199. } else {
  2200. KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
  2201. }
  2202. // Define type kmp_depend_info[<Dependences.size()>];
  2203. QualType KmpDependInfoArrayTy = C.getConstantArrayType(
  2204. KmpDependInfoTy, llvm::APInt(/*numBits=*/64, Dependences.size()),
  2205. ArrayType::Normal, /*IndexTypeQuals=*/0);
  2206. // kmp_depend_info[<Dependences.size()>] deps;
  2207. DependInfo = CGF.CreateMemTemp(KmpDependInfoArrayTy);
  2208. for (unsigned i = 0; i < DependencesNumber; ++i) {
  2209. auto Addr = CGF.EmitLValue(Dependences[i].second);
  2210. auto *Size = llvm::ConstantInt::get(
  2211. CGF.SizeTy,
  2212. C.getTypeSizeInChars(Dependences[i].second->getType()).getQuantity());
  2213. auto Base = CGF.MakeNaturalAlignAddrLValue(
  2214. CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, DependInfo, i),
  2215. KmpDependInfoTy);
  2216. // deps[i].base_addr = &<Dependences[i].second>;
  2217. auto BaseAddrLVal = CGF.EmitLValueForField(
  2218. Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
  2219. CGF.EmitStoreOfScalar(
  2220. CGF.Builder.CreatePtrToInt(Addr.getAddress(), CGF.IntPtrTy),
  2221. BaseAddrLVal);
  2222. // deps[i].len = sizeof(<Dependences[i].second>);
  2223. auto LenLVal = CGF.EmitLValueForField(
  2224. Base, *std::next(KmpDependInfoRD->field_begin(), Len));
  2225. CGF.EmitStoreOfScalar(Size, LenLVal);
  2226. // deps[i].flags = <Dependences[i].first>;
  2227. RTLDependenceKindTy DepKind;
  2228. switch (Dependences[i].first) {
  2229. case OMPC_DEPEND_in:
  2230. DepKind = DepIn;
  2231. break;
  2232. case OMPC_DEPEND_out:
  2233. DepKind = DepOut;
  2234. break;
  2235. case OMPC_DEPEND_inout:
  2236. DepKind = DepInOut;
  2237. break;
  2238. case OMPC_DEPEND_unknown:
  2239. llvm_unreachable("Unknown task dependence type");
  2240. }
  2241. auto FlagsLVal = CGF.EmitLValueForField(
  2242. Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
  2243. CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
  2244. FlagsLVal);
  2245. }
  2246. DependInfo = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2247. CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, DependInfo, 0),
  2248. CGF.VoidPtrTy);
  2249. }
  2250. // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
  2251. // libcall.
  2252. // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  2253. // *new_task);
  2254. // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
  2255. // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
  2256. // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
  2257. // list is not empty
  2258. auto *ThreadID = getThreadID(CGF, Loc);
  2259. auto *UpLoc = emitUpdateLocation(CGF, Loc);
  2260. llvm::Value *TaskArgs[] = {UpLoc, ThreadID, NewTask};
  2261. llvm::Value *DepTaskArgs[] = {
  2262. UpLoc,
  2263. ThreadID,
  2264. NewTask,
  2265. DependInfo ? CGF.Builder.getInt32(DependencesNumber) : nullptr,
  2266. DependInfo,
  2267. DependInfo ? CGF.Builder.getInt32(0) : nullptr,
  2268. DependInfo ? llvm::ConstantPointerNull::get(CGF.VoidPtrTy) : nullptr};
  2269. auto &&ThenCodeGen = [this, DependInfo, &TaskArgs,
  2270. &DepTaskArgs](CodeGenFunction &CGF) {
  2271. // TODO: add check for untied tasks.
  2272. CGF.EmitRuntimeCall(
  2273. createRuntimeFunction(DependInfo ? OMPRTL__kmpc_omp_task_with_deps
  2274. : OMPRTL__kmpc_omp_task),
  2275. DependInfo ? makeArrayRef(DepTaskArgs) : makeArrayRef(TaskArgs));
  2276. };
  2277. typedef CallEndCleanup<std::extent<decltype(TaskArgs)>::value>
  2278. IfCallEndCleanup;
  2279. llvm::Value *DepWaitTaskArgs[] = {
  2280. UpLoc,
  2281. ThreadID,
  2282. DependInfo ? CGF.Builder.getInt32(DependencesNumber) : nullptr,
  2283. DependInfo,
  2284. DependInfo ? CGF.Builder.getInt32(0) : nullptr,
  2285. DependInfo ? llvm::ConstantPointerNull::get(CGF.VoidPtrTy) : nullptr};
  2286. auto &&ElseCodeGen = [this, &TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
  2287. DependInfo, &DepWaitTaskArgs](CodeGenFunction &CGF) {
  2288. CodeGenFunction::RunCleanupsScope LocalScope(CGF);
  2289. // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
  2290. // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
  2291. // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
  2292. // is specified.
  2293. if (DependInfo)
  2294. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
  2295. DepWaitTaskArgs);
  2296. // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
  2297. // kmp_task_t *new_task);
  2298. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0),
  2299. TaskArgs);
  2300. // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
  2301. // kmp_task_t *new_task);
  2302. CGF.EHStack.pushCleanup<IfCallEndCleanup>(
  2303. NormalAndEHCleanup,
  2304. createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0),
  2305. llvm::makeArrayRef(TaskArgs));
  2306. // Call proxy_task_entry(gtid, new_task);
  2307. llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
  2308. CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
  2309. };
  2310. if (IfCond) {
  2311. emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
  2312. } else {
  2313. CodeGenFunction::RunCleanupsScope Scope(CGF);
  2314. ThenCodeGen(CGF);
  2315. }
  2316. }
  2317. static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
  2318. llvm::Type *ArgsType,
  2319. ArrayRef<const Expr *> LHSExprs,
  2320. ArrayRef<const Expr *> RHSExprs,
  2321. ArrayRef<const Expr *> ReductionOps) {
  2322. auto &C = CGM.getContext();
  2323. // void reduction_func(void *LHSArg, void *RHSArg);
  2324. FunctionArgList Args;
  2325. ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
  2326. C.VoidPtrTy);
  2327. ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
  2328. C.VoidPtrTy);
  2329. Args.push_back(&LHSArg);
  2330. Args.push_back(&RHSArg);
  2331. FunctionType::ExtInfo EI;
  2332. auto &CGFI = CGM.getTypes().arrangeFreeFunctionDeclaration(
  2333. C.VoidTy, Args, EI, /*isVariadic=*/false);
  2334. auto *Fn = llvm::Function::Create(
  2335. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  2336. ".omp.reduction.reduction_func", &CGM.getModule());
  2337. CGM.SetLLVMFunctionAttributes(/*D=*/nullptr, CGFI, Fn);
  2338. CodeGenFunction CGF(CGM);
  2339. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
  2340. // Dst = (void*[n])(LHSArg);
  2341. // Src = (void*[n])(RHSArg);
  2342. auto *LHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2343. CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&LHSArg),
  2344. CGF.PointerAlignInBytes),
  2345. ArgsType);
  2346. auto *RHS = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2347. CGF.Builder.CreateAlignedLoad(CGF.GetAddrOfLocalVar(&RHSArg),
  2348. CGF.PointerAlignInBytes),
  2349. ArgsType);
  2350. // ...
  2351. // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
  2352. // ...
  2353. CodeGenFunction::OMPPrivateScope Scope(CGF);
  2354. for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I) {
  2355. Scope.addPrivate(
  2356. cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()),
  2357. [&]() -> llvm::Value *{
  2358. return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2359. CGF.Builder.CreateAlignedLoad(
  2360. CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, RHS, I),
  2361. CGM.PointerAlignInBytes),
  2362. CGF.ConvertTypeForMem(C.getPointerType(RHSExprs[I]->getType())));
  2363. });
  2364. Scope.addPrivate(
  2365. cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()),
  2366. [&]() -> llvm::Value *{
  2367. return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2368. CGF.Builder.CreateAlignedLoad(
  2369. CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, LHS, I),
  2370. CGM.PointerAlignInBytes),
  2371. CGF.ConvertTypeForMem(C.getPointerType(LHSExprs[I]->getType())));
  2372. });
  2373. }
  2374. Scope.Privatize();
  2375. for (auto *E : ReductionOps) {
  2376. CGF.EmitIgnoredExpr(E);
  2377. }
  2378. Scope.ForceCleanup();
  2379. CGF.FinishFunction();
  2380. return Fn;
  2381. }
  2382. void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
  2383. ArrayRef<const Expr *> LHSExprs,
  2384. ArrayRef<const Expr *> RHSExprs,
  2385. ArrayRef<const Expr *> ReductionOps,
  2386. bool WithNowait, bool SimpleReduction) {
  2387. // Next code should be emitted for reduction:
  2388. //
  2389. // static kmp_critical_name lock = { 0 };
  2390. //
  2391. // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
  2392. // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
  2393. // ...
  2394. // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
  2395. // *(Type<n>-1*)rhs[<n>-1]);
  2396. // }
  2397. //
  2398. // ...
  2399. // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
  2400. // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
  2401. // RedList, reduce_func, &<lock>)) {
  2402. // case 1:
  2403. // ...
  2404. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  2405. // ...
  2406. // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  2407. // break;
  2408. // case 2:
  2409. // ...
  2410. // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
  2411. // ...
  2412. // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
  2413. // break;
  2414. // default:;
  2415. // }
  2416. //
  2417. // if SimpleReduction is true, only the next code is generated:
  2418. // ...
  2419. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  2420. // ...
  2421. auto &C = CGM.getContext();
  2422. if (SimpleReduction) {
  2423. CodeGenFunction::RunCleanupsScope Scope(CGF);
  2424. for (auto *E : ReductionOps) {
  2425. CGF.EmitIgnoredExpr(E);
  2426. }
  2427. return;
  2428. }
  2429. // 1. Build a list of reduction variables.
  2430. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  2431. llvm::APInt ArraySize(/*unsigned int numBits=*/32, RHSExprs.size());
  2432. QualType ReductionArrayTy =
  2433. C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
  2434. /*IndexTypeQuals=*/0);
  2435. auto *ReductionList =
  2436. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  2437. for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I) {
  2438. auto *Elem = CGF.Builder.CreateStructGEP(/*Ty=*/nullptr, ReductionList, I);
  2439. CGF.Builder.CreateAlignedStore(
  2440. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2441. CGF.EmitLValue(RHSExprs[I]).getAddress(), CGF.VoidPtrTy),
  2442. Elem, CGM.PointerAlignInBytes);
  2443. }
  2444. // 2. Emit reduce_func().
  2445. auto *ReductionFn = emitReductionFunction(
  2446. CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), LHSExprs,
  2447. RHSExprs, ReductionOps);
  2448. // 3. Create static kmp_critical_name lock = { 0 };
  2449. auto *Lock = getCriticalRegionLock(".reduction");
  2450. // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
  2451. // RedList, reduce_func, &<lock>);
  2452. auto *IdentTLoc = emitUpdateLocation(
  2453. CGF, Loc,
  2454. static_cast<OpenMPLocationFlags>(OMP_IDENT_KMPC | OMP_ATOMIC_REDUCE));
  2455. auto *ThreadId = getThreadID(CGF, Loc);
  2456. auto *ReductionArrayTySize = llvm::ConstantInt::get(
  2457. CGM.SizeTy, C.getTypeSizeInChars(ReductionArrayTy).getQuantity());
  2458. auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList,
  2459. CGF.VoidPtrTy);
  2460. llvm::Value *Args[] = {
  2461. IdentTLoc, // ident_t *<loc>
  2462. ThreadId, // i32 <gtid>
  2463. CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
  2464. ReductionArrayTySize, // size_type sizeof(RedList)
  2465. RL, // void *RedList
  2466. ReductionFn, // void (*) (void *, void *) <reduce_func>
  2467. Lock // kmp_critical_name *&<lock>
  2468. };
  2469. auto Res = CGF.EmitRuntimeCall(
  2470. createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
  2471. : OMPRTL__kmpc_reduce),
  2472. Args);
  2473. // 5. Build switch(res)
  2474. auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
  2475. auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
  2476. // 6. Build case 1:
  2477. // ...
  2478. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  2479. // ...
  2480. // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  2481. // break;
  2482. auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
  2483. SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
  2484. CGF.EmitBlock(Case1BB);
  2485. {
  2486. CodeGenFunction::RunCleanupsScope Scope(CGF);
  2487. // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  2488. llvm::Value *EndArgs[] = {
  2489. IdentTLoc, // ident_t *<loc>
  2490. ThreadId, // i32 <gtid>
  2491. Lock // kmp_critical_name *&<lock>
  2492. };
  2493. CGF.EHStack
  2494. .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
  2495. NormalAndEHCleanup,
  2496. createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
  2497. : OMPRTL__kmpc_end_reduce),
  2498. llvm::makeArrayRef(EndArgs));
  2499. for (auto *E : ReductionOps) {
  2500. CGF.EmitIgnoredExpr(E);
  2501. }
  2502. }
  2503. CGF.EmitBranch(DefaultBB);
  2504. // 7. Build case 2:
  2505. // ...
  2506. // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
  2507. // ...
  2508. // break;
  2509. auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
  2510. SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
  2511. CGF.EmitBlock(Case2BB);
  2512. {
  2513. CodeGenFunction::RunCleanupsScope Scope(CGF);
  2514. if (!WithNowait) {
  2515. // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
  2516. llvm::Value *EndArgs[] = {
  2517. IdentTLoc, // ident_t *<loc>
  2518. ThreadId, // i32 <gtid>
  2519. Lock // kmp_critical_name *&<lock>
  2520. };
  2521. CGF.EHStack
  2522. .pushCleanup<CallEndCleanup<std::extent<decltype(EndArgs)>::value>>(
  2523. NormalAndEHCleanup,
  2524. createRuntimeFunction(OMPRTL__kmpc_end_reduce),
  2525. llvm::makeArrayRef(EndArgs));
  2526. }
  2527. auto I = LHSExprs.begin();
  2528. for (auto *E : ReductionOps) {
  2529. const Expr *XExpr = nullptr;
  2530. const Expr *EExpr = nullptr;
  2531. const Expr *UpExpr = nullptr;
  2532. BinaryOperatorKind BO = BO_Comma;
  2533. if (auto *BO = dyn_cast<BinaryOperator>(E)) {
  2534. if (BO->getOpcode() == BO_Assign) {
  2535. XExpr = BO->getLHS();
  2536. UpExpr = BO->getRHS();
  2537. }
  2538. }
  2539. // Try to emit update expression as a simple atomic.
  2540. auto *RHSExpr = UpExpr;
  2541. if (RHSExpr) {
  2542. // Analyze RHS part of the whole expression.
  2543. if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
  2544. RHSExpr->IgnoreParenImpCasts())) {
  2545. // If this is a conditional operator, analyze its condition for
  2546. // min/max reduction operator.
  2547. RHSExpr = ACO->getCond();
  2548. }
  2549. if (auto *BORHS =
  2550. dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
  2551. EExpr = BORHS->getRHS();
  2552. BO = BORHS->getOpcode();
  2553. }
  2554. }
  2555. if (XExpr) {
  2556. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
  2557. LValue X = CGF.EmitLValue(XExpr);
  2558. RValue E;
  2559. if (EExpr)
  2560. E = CGF.EmitAnyExpr(EExpr);
  2561. CGF.EmitOMPAtomicSimpleUpdateExpr(
  2562. X, E, BO, /*IsXLHSInRHSPart=*/true, llvm::Monotonic, Loc,
  2563. [&CGF, UpExpr, VD](RValue XRValue) {
  2564. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  2565. PrivateScope.addPrivate(
  2566. VD, [&CGF, VD, XRValue]() -> llvm::Value *{
  2567. auto *LHSTemp = CGF.CreateMemTemp(VD->getType());
  2568. CGF.EmitStoreThroughLValue(
  2569. XRValue,
  2570. CGF.MakeNaturalAlignAddrLValue(LHSTemp, VD->getType()));
  2571. return LHSTemp;
  2572. });
  2573. (void)PrivateScope.Privatize();
  2574. return CGF.EmitAnyExpr(UpExpr);
  2575. });
  2576. } else {
  2577. // Emit as a critical region.
  2578. emitCriticalRegion(CGF, ".atomic_reduction", [E](CodeGenFunction &CGF) {
  2579. CGF.EmitIgnoredExpr(E);
  2580. }, Loc);
  2581. }
  2582. ++I;
  2583. }
  2584. }
  2585. CGF.EmitBranch(DefaultBB);
  2586. CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
  2587. }
  2588. void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
  2589. SourceLocation Loc) {
  2590. // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
  2591. // global_tid);
  2592. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  2593. // Ignore return result until untied tasks are supported.
  2594. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
  2595. }
  2596. void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
  2597. OpenMPDirectiveKind InnerKind,
  2598. const RegionCodeGenTy &CodeGen) {
  2599. InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind);
  2600. CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
  2601. }
  2602. namespace {
  2603. enum RTCancelKind {
  2604. CancelNoreq = 0,
  2605. CancelParallel = 1,
  2606. CancelLoop = 2,
  2607. CancelSections = 3,
  2608. CancelTaskgroup = 4
  2609. };
  2610. }
  2611. static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
  2612. RTCancelKind CancelKind = CancelNoreq;
  2613. if (CancelRegion == OMPD_parallel)
  2614. CancelKind = CancelParallel;
  2615. else if (CancelRegion == OMPD_for)
  2616. CancelKind = CancelLoop;
  2617. else if (CancelRegion == OMPD_sections)
  2618. CancelKind = CancelSections;
  2619. else {
  2620. assert(CancelRegion == OMPD_taskgroup);
  2621. CancelKind = CancelTaskgroup;
  2622. }
  2623. return CancelKind;
  2624. }
  2625. void CGOpenMPRuntime::emitCancellationPointCall(
  2626. CodeGenFunction &CGF, SourceLocation Loc,
  2627. OpenMPDirectiveKind CancelRegion) {
  2628. // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  2629. // global_tid, kmp_int32 cncl_kind);
  2630. if (auto *OMPRegionInfo =
  2631. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  2632. auto CancelDest =
  2633. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  2634. if (CancelDest.isValid()) {
  2635. llvm::Value *Args[] = {
  2636. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2637. CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
  2638. // Ignore return result until untied tasks are supported.
  2639. auto *Result = CGF.EmitRuntimeCall(
  2640. createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
  2641. // if (__kmpc_cancellationpoint()) {
  2642. // __kmpc_cancel_barrier();
  2643. // exit from construct;
  2644. // }
  2645. auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
  2646. auto *ContBB = CGF.createBasicBlock(".cancel.continue");
  2647. auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
  2648. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  2649. CGF.EmitBlock(ExitBB);
  2650. // __kmpc_cancel_barrier();
  2651. emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
  2652. // exit from construct;
  2653. CGF.EmitBranchThroughCleanup(CancelDest);
  2654. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  2655. }
  2656. }
  2657. }
  2658. void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
  2659. OpenMPDirectiveKind CancelRegion) {
  2660. // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  2661. // kmp_int32 cncl_kind);
  2662. if (auto *OMPRegionInfo =
  2663. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  2664. auto CancelDest =
  2665. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  2666. if (CancelDest.isValid()) {
  2667. llvm::Value *Args[] = {
  2668. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2669. CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
  2670. // Ignore return result until untied tasks are supported.
  2671. auto *Result =
  2672. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
  2673. // if (__kmpc_cancel()) {
  2674. // __kmpc_cancel_barrier();
  2675. // exit from construct;
  2676. // }
  2677. auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
  2678. auto *ContBB = CGF.createBasicBlock(".cancel.continue");
  2679. auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
  2680. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  2681. CGF.EmitBlock(ExitBB);
  2682. // __kmpc_cancel_barrier();
  2683. emitBarrierCall(CGF, Loc, OMPD_unknown, /*CheckForCancel=*/false);
  2684. // exit from construct;
  2685. CGF.EmitBranchThroughCleanup(CancelDest);
  2686. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  2687. }
  2688. }
  2689. }
  2690. #endif // HLSL Change