CGStmtOpenMP.cpp 178 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294
  1. //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit OpenMP nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGCleanup.h"
  14. #include "CGOpenMPRuntime.h"
  15. #include "CodeGenFunction.h"
  16. #include "CodeGenModule.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/Stmt.h"
  19. #include "clang/AST/StmtOpenMP.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "llvm/IR/CallSite.h"
  22. using namespace clang;
  23. using namespace CodeGen;
  24. namespace {
  25. /// Lexical scope for OpenMP executable constructs, that handles correct codegen
  26. /// for captured expressions.
  27. class OMPLexicalScope : public CodeGenFunction::LexicalScope {
  28. void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
  29. for (const auto *C : S.clauses()) {
  30. if (auto *CPI = OMPClauseWithPreInit::get(C)) {
  31. if (auto *PreInit = cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
  32. for (const auto *I : PreInit->decls()) {
  33. if (!I->hasAttr<OMPCaptureNoInitAttr>())
  34. CGF.EmitVarDecl(cast<VarDecl>(*I));
  35. else {
  36. CodeGenFunction::AutoVarEmission Emission =
  37. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  38. CGF.EmitAutoVarCleanups(Emission);
  39. }
  40. }
  41. }
  42. }
  43. }
  44. }
  45. CodeGenFunction::OMPPrivateScope InlinedShareds;
  46. static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
  47. return CGF.LambdaCaptureFields.lookup(VD) ||
  48. (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
  49. (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
  50. }
  51. public:
  52. OMPLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S,
  53. bool AsInlined = false, bool EmitPreInitStmt = true)
  54. : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
  55. InlinedShareds(CGF) {
  56. if (EmitPreInitStmt)
  57. emitPreInitStmt(CGF, S);
  58. if (AsInlined) {
  59. if (S.hasAssociatedStmt()) {
  60. auto *CS = cast<CapturedStmt>(S.getAssociatedStmt());
  61. for (auto &C : CS->captures()) {
  62. if (C.capturesVariable() || C.capturesVariableByCopy()) {
  63. auto *VD = C.getCapturedVar();
  64. DeclRefExpr DRE(const_cast<VarDecl *>(VD),
  65. isCapturedVar(CGF, VD) ||
  66. (CGF.CapturedStmtInfo &&
  67. InlinedShareds.isGlobalVarCaptured(VD)),
  68. VD->getType().getNonReferenceType(), VK_LValue,
  69. SourceLocation());
  70. InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
  71. return CGF.EmitLValue(&DRE).getAddress();
  72. });
  73. }
  74. }
  75. (void)InlinedShareds.Privatize();
  76. }
  77. }
  78. }
  79. };
  80. /// Lexical scope for OpenMP parallel construct, that handles correct codegen
  81. /// for captured expressions.
  82. class OMPParallelScope final : public OMPLexicalScope {
  83. bool EmitPreInitStmt(const OMPExecutableDirective &S) {
  84. OpenMPDirectiveKind Kind = S.getDirectiveKind();
  85. return !(isOpenMPTargetExecutionDirective(Kind) ||
  86. isOpenMPLoopBoundSharingDirective(Kind)) &&
  87. isOpenMPParallelDirective(Kind);
  88. }
  89. public:
  90. OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
  91. : OMPLexicalScope(CGF, S,
  92. /*AsInlined=*/false,
  93. /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
  94. };
  95. /// Lexical scope for OpenMP teams construct, that handles correct codegen
  96. /// for captured expressions.
  97. class OMPTeamsScope final : public OMPLexicalScope {
  98. bool EmitPreInitStmt(const OMPExecutableDirective &S) {
  99. OpenMPDirectiveKind Kind = S.getDirectiveKind();
  100. return !isOpenMPTargetExecutionDirective(Kind) &&
  101. isOpenMPTeamsDirective(Kind);
  102. }
  103. public:
  104. OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
  105. : OMPLexicalScope(CGF, S,
  106. /*AsInlined=*/false,
  107. /*EmitPreInitStmt=*/EmitPreInitStmt(S)) {}
  108. };
  109. /// Private scope for OpenMP loop-based directives, that supports capturing
  110. /// of used expression from loop statement.
  111. class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
  112. void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
  113. if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) {
  114. if (auto *PreInits = cast_or_null<DeclStmt>(LD->getPreInits())) {
  115. for (const auto *I : PreInits->decls())
  116. CGF.EmitVarDecl(cast<VarDecl>(*I));
  117. }
  118. }
  119. }
  120. public:
  121. OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
  122. : CodeGenFunction::RunCleanupsScope(CGF) {
  123. emitPreInitStmt(CGF, S);
  124. }
  125. };
  126. } // namespace
  127. llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
  128. auto &C = getContext();
  129. llvm::Value *Size = nullptr;
  130. auto SizeInChars = C.getTypeSizeInChars(Ty);
  131. if (SizeInChars.isZero()) {
  132. // getTypeSizeInChars() returns 0 for a VLA.
  133. while (auto *VAT = C.getAsVariableArrayType(Ty)) {
  134. llvm::Value *ArraySize;
  135. std::tie(ArraySize, Ty) = getVLASize(VAT);
  136. Size = Size ? Builder.CreateNUWMul(Size, ArraySize) : ArraySize;
  137. }
  138. SizeInChars = C.getTypeSizeInChars(Ty);
  139. if (SizeInChars.isZero())
  140. return llvm::ConstantInt::get(SizeTy, /*V=*/0);
  141. Size = Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
  142. } else
  143. Size = CGM.getSize(SizeInChars);
  144. return Size;
  145. }
  146. void CodeGenFunction::GenerateOpenMPCapturedVars(
  147. const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
  148. const RecordDecl *RD = S.getCapturedRecordDecl();
  149. auto CurField = RD->field_begin();
  150. auto CurCap = S.captures().begin();
  151. for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
  152. E = S.capture_init_end();
  153. I != E; ++I, ++CurField, ++CurCap) {
  154. if (CurField->hasCapturedVLAType()) {
  155. auto VAT = CurField->getCapturedVLAType();
  156. auto *Val = VLASizeMap[VAT->getSizeExpr()];
  157. CapturedVars.push_back(Val);
  158. } else if (CurCap->capturesThis())
  159. CapturedVars.push_back(CXXThisValue);
  160. else if (CurCap->capturesVariableByCopy()) {
  161. llvm::Value *CV =
  162. EmitLoadOfLValue(EmitLValue(*I), SourceLocation()).getScalarVal();
  163. // If the field is not a pointer, we need to save the actual value
  164. // and load it as a void pointer.
  165. if (!CurField->getType()->isAnyPointerType()) {
  166. auto &Ctx = getContext();
  167. auto DstAddr = CreateMemTemp(
  168. Ctx.getUIntPtrType(),
  169. Twine(CurCap->getCapturedVar()->getName()) + ".casted");
  170. LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
  171. auto *SrcAddrVal = EmitScalarConversion(
  172. DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
  173. Ctx.getPointerType(CurField->getType()), SourceLocation());
  174. LValue SrcLV =
  175. MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
  176. // Store the value using the source type pointer.
  177. EmitStoreThroughLValue(RValue::get(CV), SrcLV);
  178. // Load the value using the destination type pointer.
  179. CV = EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal();
  180. }
  181. CapturedVars.push_back(CV);
  182. } else {
  183. assert(CurCap->capturesVariable() && "Expected capture by reference.");
  184. CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
  185. }
  186. }
  187. }
  188. static Address castValueFromUintptr(CodeGenFunction &CGF, QualType DstType,
  189. StringRef Name, LValue AddrLV,
  190. bool isReferenceType = false) {
  191. ASTContext &Ctx = CGF.getContext();
  192. auto *CastedPtr = CGF.EmitScalarConversion(
  193. AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
  194. Ctx.getPointerType(DstType), SourceLocation());
  195. auto TmpAddr =
  196. CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
  197. .getAddress();
  198. // If we are dealing with references we need to return the address of the
  199. // reference instead of the reference of the value.
  200. if (isReferenceType) {
  201. QualType RefType = Ctx.getLValueReferenceType(DstType);
  202. auto *RefVal = TmpAddr.getPointer();
  203. TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name) + ".ref");
  204. auto TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
  205. CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit*/ true);
  206. }
  207. return TmpAddr;
  208. }
  209. static QualType getCanonicalParamType(ASTContext &C, QualType T) {
  210. if (T->isLValueReferenceType()) {
  211. return C.getLValueReferenceType(
  212. getCanonicalParamType(C, T.getNonReferenceType()),
  213. /*SpelledAsLValue=*/false);
  214. }
  215. if (T->isPointerType())
  216. return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
  217. return C.getCanonicalParamType(T);
  218. }
  219. llvm::Function *
  220. CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
  221. assert(
  222. CapturedStmtInfo &&
  223. "CapturedStmtInfo should be set when generating the captured function");
  224. const CapturedDecl *CD = S.getCapturedDecl();
  225. const RecordDecl *RD = S.getCapturedRecordDecl();
  226. assert(CD->hasBody() && "missing CapturedDecl body");
  227. // Build the argument list.
  228. ASTContext &Ctx = CGM.getContext();
  229. FunctionArgList Args;
  230. Args.append(CD->param_begin(),
  231. std::next(CD->param_begin(), CD->getContextParamPosition()));
  232. auto I = S.captures().begin();
  233. for (auto *FD : RD->fields()) {
  234. QualType ArgType = FD->getType();
  235. IdentifierInfo *II = nullptr;
  236. VarDecl *CapVar = nullptr;
  237. // If this is a capture by copy and the type is not a pointer, the outlined
  238. // function argument type should be uintptr and the value properly casted to
  239. // uintptr. This is necessary given that the runtime library is only able to
  240. // deal with pointers. We can pass in the same way the VLA type sizes to the
  241. // outlined function.
  242. if ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
  243. I->capturesVariableArrayType())
  244. ArgType = Ctx.getUIntPtrType();
  245. if (I->capturesVariable() || I->capturesVariableByCopy()) {
  246. CapVar = I->getCapturedVar();
  247. II = CapVar->getIdentifier();
  248. } else if (I->capturesThis())
  249. II = &getContext().Idents.get("this");
  250. else {
  251. assert(I->capturesVariableArrayType());
  252. II = &getContext().Idents.get("vla");
  253. }
  254. if (ArgType->isVariablyModifiedType()) {
  255. ArgType =
  256. getCanonicalParamType(getContext(), ArgType.getNonReferenceType());
  257. }
  258. Args.push_back(ImplicitParamDecl::Create(getContext(), /*DC=*/nullptr,
  259. FD->getLocation(), II, ArgType,
  260. ImplicitParamDecl::Other));
  261. ++I;
  262. }
  263. Args.append(
  264. std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
  265. CD->param_end());
  266. // Create the function declaration.
  267. FunctionType::ExtInfo ExtInfo;
  268. const CGFunctionInfo &FuncInfo =
  269. CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
  270. llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
  271. llvm::Function *F = llvm::Function::Create(
  272. FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
  273. CapturedStmtInfo->getHelperName(), &CGM.getModule());
  274. CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
  275. if (CD->isNothrow())
  276. F->addFnAttr(llvm::Attribute::NoUnwind);
  277. // Generate the function.
  278. StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(),
  279. CD->getBody()->getLocStart());
  280. unsigned Cnt = CD->getContextParamPosition();
  281. I = S.captures().begin();
  282. for (auto *FD : RD->fields()) {
  283. // If we are capturing a pointer by copy we don't need to do anything, just
  284. // use the value that we get from the arguments.
  285. if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
  286. const VarDecl *CurVD = I->getCapturedVar();
  287. Address LocalAddr = GetAddrOfLocalVar(Args[Cnt]);
  288. // If the variable is a reference we need to materialize it here.
  289. if (CurVD->getType()->isReferenceType()) {
  290. Address RefAddr = CreateMemTemp(CurVD->getType(), getPointerAlign(),
  291. ".materialized_ref");
  292. EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr, /*Volatile=*/false,
  293. CurVD->getType());
  294. LocalAddr = RefAddr;
  295. }
  296. setAddrOfLocalVar(CurVD, LocalAddr);
  297. ++Cnt;
  298. ++I;
  299. continue;
  300. }
  301. LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
  302. LValue ArgLVal =
  303. MakeAddrLValue(GetAddrOfLocalVar(Args[Cnt]), Args[Cnt]->getType(),
  304. BaseInfo);
  305. if (FD->hasCapturedVLAType()) {
  306. LValue CastedArgLVal =
  307. MakeAddrLValue(castValueFromUintptr(*this, FD->getType(),
  308. Args[Cnt]->getName(), ArgLVal),
  309. FD->getType(), BaseInfo);
  310. auto *ExprArg =
  311. EmitLoadOfLValue(CastedArgLVal, SourceLocation()).getScalarVal();
  312. auto VAT = FD->getCapturedVLAType();
  313. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  314. } else if (I->capturesVariable()) {
  315. auto *Var = I->getCapturedVar();
  316. QualType VarTy = Var->getType();
  317. Address ArgAddr = ArgLVal.getAddress();
  318. if (!VarTy->isReferenceType()) {
  319. if (ArgLVal.getType()->isLValueReferenceType()) {
  320. ArgAddr = EmitLoadOfReference(
  321. ArgAddr, ArgLVal.getType()->castAs<ReferenceType>());
  322. } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) {
  323. assert(ArgLVal.getType()->isPointerType());
  324. ArgAddr = EmitLoadOfPointer(
  325. ArgAddr, ArgLVal.getType()->castAs<PointerType>());
  326. }
  327. }
  328. setAddrOfLocalVar(
  329. Var, Address(ArgAddr.getPointer(), getContext().getDeclAlign(Var)));
  330. } else if (I->capturesVariableByCopy()) {
  331. assert(!FD->getType()->isAnyPointerType() &&
  332. "Not expecting a captured pointer.");
  333. auto *Var = I->getCapturedVar();
  334. QualType VarTy = Var->getType();
  335. setAddrOfLocalVar(Var, castValueFromUintptr(*this, FD->getType(),
  336. Args[Cnt]->getName(), ArgLVal,
  337. VarTy->isReferenceType()));
  338. } else {
  339. // If 'this' is captured, load it into CXXThisValue.
  340. assert(I->capturesThis());
  341. CXXThisValue =
  342. EmitLoadOfLValue(ArgLVal, Args[Cnt]->getLocation()).getScalarVal();
  343. }
  344. ++Cnt;
  345. ++I;
  346. }
  347. PGO.assignRegionCounters(GlobalDecl(CD), F);
  348. CapturedStmtInfo->EmitBody(*this, CD->getBody());
  349. FinishFunction(CD->getBodyRBrace());
  350. return F;
  351. }
  352. //===----------------------------------------------------------------------===//
  353. // OpenMP Directive Emission
  354. //===----------------------------------------------------------------------===//
  355. void CodeGenFunction::EmitOMPAggregateAssign(
  356. Address DestAddr, Address SrcAddr, QualType OriginalType,
  357. const llvm::function_ref<void(Address, Address)> &CopyGen) {
  358. // Perform element-by-element initialization.
  359. QualType ElementTy;
  360. // Drill down to the base element type on both arrays.
  361. auto ArrayTy = OriginalType->getAsArrayTypeUnsafe();
  362. auto NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
  363. SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
  364. auto SrcBegin = SrcAddr.getPointer();
  365. auto DestBegin = DestAddr.getPointer();
  366. // Cast from pointer to array type to pointer to single element.
  367. auto DestEnd = Builder.CreateGEP(DestBegin, NumElements);
  368. // The basic structure here is a while-do loop.
  369. auto BodyBB = createBasicBlock("omp.arraycpy.body");
  370. auto DoneBB = createBasicBlock("omp.arraycpy.done");
  371. auto IsEmpty =
  372. Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
  373. Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  374. // Enter the loop body, making that address the current address.
  375. auto EntryBB = Builder.GetInsertBlock();
  376. EmitBlock(BodyBB);
  377. CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
  378. llvm::PHINode *SrcElementPHI =
  379. Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
  380. SrcElementPHI->addIncoming(SrcBegin, EntryBB);
  381. Address SrcElementCurrent =
  382. Address(SrcElementPHI,
  383. SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  384. llvm::PHINode *DestElementPHI =
  385. Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
  386. DestElementPHI->addIncoming(DestBegin, EntryBB);
  387. Address DestElementCurrent =
  388. Address(DestElementPHI,
  389. DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  390. // Emit copy.
  391. CopyGen(DestElementCurrent, SrcElementCurrent);
  392. // Shift the address forward by one element.
  393. auto DestElementNext = Builder.CreateConstGEP1_32(
  394. DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  395. auto SrcElementNext = Builder.CreateConstGEP1_32(
  396. SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
  397. // Check whether we've reached the end.
  398. auto Done =
  399. Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
  400. Builder.CreateCondBr(Done, DoneBB, BodyBB);
  401. DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
  402. SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
  403. // Done.
  404. EmitBlock(DoneBB, /*IsFinished=*/true);
  405. }
  406. /// Check if the combiner is a call to UDR combiner and if it is so return the
  407. /// UDR decl used for reduction.
  408. static const OMPDeclareReductionDecl *
  409. getReductionInit(const Expr *ReductionOp) {
  410. if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
  411. if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
  412. if (auto *DRE =
  413. dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
  414. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
  415. return DRD;
  416. return nullptr;
  417. }
  418. static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
  419. const OMPDeclareReductionDecl *DRD,
  420. const Expr *InitOp,
  421. Address Private, Address Original,
  422. QualType Ty) {
  423. if (DRD->getInitializer()) {
  424. std::pair<llvm::Function *, llvm::Function *> Reduction =
  425. CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
  426. auto *CE = cast<CallExpr>(InitOp);
  427. auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
  428. const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  429. const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  430. auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
  431. auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
  432. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  433. PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
  434. [=]() -> Address { return Private; });
  435. PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
  436. [=]() -> Address { return Original; });
  437. (void)PrivateScope.Privatize();
  438. RValue Func = RValue::get(Reduction.second);
  439. CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
  440. CGF.EmitIgnoredExpr(InitOp);
  441. } else {
  442. llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
  443. auto *GV = new llvm::GlobalVariable(
  444. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  445. llvm::GlobalValue::PrivateLinkage, Init, ".init");
  446. LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
  447. RValue InitRVal;
  448. switch (CGF.getEvaluationKind(Ty)) {
  449. case TEK_Scalar:
  450. InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
  451. break;
  452. case TEK_Complex:
  453. InitRVal =
  454. RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
  455. break;
  456. case TEK_Aggregate:
  457. InitRVal = RValue::getAggregate(LV.getAddress());
  458. break;
  459. }
  460. OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
  461. CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
  462. CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
  463. /*IsInitializer=*/false);
  464. }
  465. }
  466. /// \brief Emit initialization of arrays of complex types.
  467. /// \param DestAddr Address of the array.
  468. /// \param Type Type of array.
  469. /// \param Init Initial expression of array.
  470. /// \param SrcAddr Address of the original array.
  471. static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
  472. QualType Type, const Expr *Init,
  473. Address SrcAddr = Address::invalid()) {
  474. auto *DRD = getReductionInit(Init);
  475. // Perform element-by-element initialization.
  476. QualType ElementTy;
  477. // Drill down to the base element type on both arrays.
  478. auto ArrayTy = Type->getAsArrayTypeUnsafe();
  479. auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
  480. DestAddr =
  481. CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
  482. if (DRD)
  483. SrcAddr =
  484. CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
  485. llvm::Value *SrcBegin = nullptr;
  486. if (DRD)
  487. SrcBegin = SrcAddr.getPointer();
  488. auto DestBegin = DestAddr.getPointer();
  489. // Cast from pointer to array type to pointer to single element.
  490. auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
  491. // The basic structure here is a while-do loop.
  492. auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
  493. auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
  494. auto IsEmpty =
  495. CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
  496. CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  497. // Enter the loop body, making that address the current address.
  498. auto EntryBB = CGF.Builder.GetInsertBlock();
  499. CGF.EmitBlock(BodyBB);
  500. CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
  501. llvm::PHINode *SrcElementPHI = nullptr;
  502. Address SrcElementCurrent = Address::invalid();
  503. if (DRD) {
  504. SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
  505. "omp.arraycpy.srcElementPast");
  506. SrcElementPHI->addIncoming(SrcBegin, EntryBB);
  507. SrcElementCurrent =
  508. Address(SrcElementPHI,
  509. SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  510. }
  511. llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
  512. DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
  513. DestElementPHI->addIncoming(DestBegin, EntryBB);
  514. Address DestElementCurrent =
  515. Address(DestElementPHI,
  516. DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  517. // Emit copy.
  518. {
  519. CodeGenFunction::RunCleanupsScope InitScope(CGF);
  520. if (DRD && (DRD->getInitializer() || !Init)) {
  521. emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
  522. SrcElementCurrent, ElementTy);
  523. } else
  524. CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
  525. /*IsInitializer=*/false);
  526. }
  527. if (DRD) {
  528. // Shift the address forward by one element.
  529. auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
  530. SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  531. SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
  532. }
  533. // Shift the address forward by one element.
  534. auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
  535. DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  536. // Check whether we've reached the end.
  537. auto Done =
  538. CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
  539. CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
  540. DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
  541. // Done.
  542. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  543. }
  544. void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
  545. Address SrcAddr, const VarDecl *DestVD,
  546. const VarDecl *SrcVD, const Expr *Copy) {
  547. if (OriginalType->isArrayType()) {
  548. auto *BO = dyn_cast<BinaryOperator>(Copy);
  549. if (BO && BO->getOpcode() == BO_Assign) {
  550. // Perform simple memcpy for simple copying.
  551. EmitAggregateAssign(DestAddr, SrcAddr, OriginalType);
  552. } else {
  553. // For arrays with complex element types perform element by element
  554. // copying.
  555. EmitOMPAggregateAssign(
  556. DestAddr, SrcAddr, OriginalType,
  557. [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
  558. // Working with the single array element, so have to remap
  559. // destination and source variables to corresponding array
  560. // elements.
  561. CodeGenFunction::OMPPrivateScope Remap(*this);
  562. Remap.addPrivate(DestVD, [DestElement]() -> Address {
  563. return DestElement;
  564. });
  565. Remap.addPrivate(
  566. SrcVD, [SrcElement]() -> Address { return SrcElement; });
  567. (void)Remap.Privatize();
  568. EmitIgnoredExpr(Copy);
  569. });
  570. }
  571. } else {
  572. // Remap pseudo source variable to private copy.
  573. CodeGenFunction::OMPPrivateScope Remap(*this);
  574. Remap.addPrivate(SrcVD, [SrcAddr]() -> Address { return SrcAddr; });
  575. Remap.addPrivate(DestVD, [DestAddr]() -> Address { return DestAddr; });
  576. (void)Remap.Privatize();
  577. // Emit copying of the whole variable.
  578. EmitIgnoredExpr(Copy);
  579. }
  580. }
  581. bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  582. OMPPrivateScope &PrivateScope) {
  583. if (!HaveInsertPoint())
  584. return false;
  585. bool FirstprivateIsLastprivate = false;
  586. llvm::DenseSet<const VarDecl *> Lastprivates;
  587. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  588. for (const auto *D : C->varlists())
  589. Lastprivates.insert(
  590. cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
  591. }
  592. llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
  593. CGCapturedStmtInfo CapturesInfo(cast<CapturedStmt>(*D.getAssociatedStmt()));
  594. for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
  595. auto IRef = C->varlist_begin();
  596. auto InitsRef = C->inits().begin();
  597. for (auto IInit : C->private_copies()) {
  598. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  599. bool ThisFirstprivateIsLastprivate =
  600. Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
  601. auto *CapFD = CapturesInfo.lookup(OrigVD);
  602. auto *FD = CapturedStmtInfo->lookup(OrigVD);
  603. if (!ThisFirstprivateIsLastprivate && FD && (FD == CapFD) &&
  604. !FD->getType()->isReferenceType()) {
  605. EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
  606. ++IRef;
  607. ++InitsRef;
  608. continue;
  609. }
  610. FirstprivateIsLastprivate =
  611. FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
  612. if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
  613. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  614. auto *VDInit = cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
  615. bool IsRegistered;
  616. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
  617. /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
  618. (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
  619. Address OriginalAddr = EmitLValue(&DRE).getAddress();
  620. QualType Type = VD->getType();
  621. if (Type->isArrayType()) {
  622. // Emit VarDecl with copy init for arrays.
  623. // Get the address of the original variable captured in current
  624. // captured region.
  625. IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
  626. auto Emission = EmitAutoVarAlloca(*VD);
  627. auto *Init = VD->getInit();
  628. if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) {
  629. // Perform simple memcpy.
  630. EmitAggregateAssign(Emission.getAllocatedAddress(), OriginalAddr,
  631. Type);
  632. } else {
  633. EmitOMPAggregateAssign(
  634. Emission.getAllocatedAddress(), OriginalAddr, Type,
  635. [this, VDInit, Init](Address DestElement,
  636. Address SrcElement) {
  637. // Clean up any temporaries needed by the initialization.
  638. RunCleanupsScope InitScope(*this);
  639. // Emit initialization for single element.
  640. setAddrOfLocalVar(VDInit, SrcElement);
  641. EmitAnyExprToMem(Init, DestElement,
  642. Init->getType().getQualifiers(),
  643. /*IsInitializer*/ false);
  644. LocalDeclMap.erase(VDInit);
  645. });
  646. }
  647. EmitAutoVarCleanups(Emission);
  648. return Emission.getAllocatedAddress();
  649. });
  650. } else {
  651. IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
  652. // Emit private VarDecl with copy init.
  653. // Remap temp VDInit variable to the address of the original
  654. // variable
  655. // (for proper handling of captured global variables).
  656. setAddrOfLocalVar(VDInit, OriginalAddr);
  657. EmitDecl(*VD);
  658. LocalDeclMap.erase(VDInit);
  659. return GetAddrOfLocalVar(VD);
  660. });
  661. }
  662. assert(IsRegistered &&
  663. "firstprivate var already registered as private");
  664. // Silence the warning about unused variable.
  665. (void)IsRegistered;
  666. }
  667. ++IRef;
  668. ++InitsRef;
  669. }
  670. }
  671. return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
  672. }
  673. void CodeGenFunction::EmitOMPPrivateClause(
  674. const OMPExecutableDirective &D,
  675. CodeGenFunction::OMPPrivateScope &PrivateScope) {
  676. if (!HaveInsertPoint())
  677. return;
  678. llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
  679. for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
  680. auto IRef = C->varlist_begin();
  681. for (auto IInit : C->private_copies()) {
  682. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  683. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  684. auto VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  685. bool IsRegistered =
  686. PrivateScope.addPrivate(OrigVD, [&]() -> Address {
  687. // Emit private VarDecl with copy init.
  688. EmitDecl(*VD);
  689. return GetAddrOfLocalVar(VD);
  690. });
  691. assert(IsRegistered && "private var already registered as private");
  692. // Silence the warning about unused variable.
  693. (void)IsRegistered;
  694. }
  695. ++IRef;
  696. }
  697. }
  698. }
  699. bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
  700. if (!HaveInsertPoint())
  701. return false;
  702. // threadprivate_var1 = master_threadprivate_var1;
  703. // operator=(threadprivate_var2, master_threadprivate_var2);
  704. // ...
  705. // __kmpc_barrier(&loc, global_tid);
  706. llvm::DenseSet<const VarDecl *> CopiedVars;
  707. llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
  708. for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
  709. auto IRef = C->varlist_begin();
  710. auto ISrcRef = C->source_exprs().begin();
  711. auto IDestRef = C->destination_exprs().begin();
  712. for (auto *AssignOp : C->assignment_ops()) {
  713. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  714. QualType Type = VD->getType();
  715. if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
  716. // Get the address of the master variable. If we are emitting code with
  717. // TLS support, the address is passed from the master as field in the
  718. // captured declaration.
  719. Address MasterAddr = Address::invalid();
  720. if (getLangOpts().OpenMPUseTLS &&
  721. getContext().getTargetInfo().isTLSSupported()) {
  722. assert(CapturedStmtInfo->lookup(VD) &&
  723. "Copyin threadprivates should have been captured!");
  724. DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
  725. VK_LValue, (*IRef)->getExprLoc());
  726. MasterAddr = EmitLValue(&DRE).getAddress();
  727. LocalDeclMap.erase(VD);
  728. } else {
  729. MasterAddr =
  730. Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
  731. : CGM.GetAddrOfGlobal(VD),
  732. getContext().getDeclAlign(VD));
  733. }
  734. // Get the address of the threadprivate variable.
  735. Address PrivateAddr = EmitLValue(*IRef).getAddress();
  736. if (CopiedVars.size() == 1) {
  737. // At first check if current thread is a master thread. If it is, no
  738. // need to copy data.
  739. CopyBegin = createBasicBlock("copyin.not.master");
  740. CopyEnd = createBasicBlock("copyin.not.master.end");
  741. Builder.CreateCondBr(
  742. Builder.CreateICmpNE(
  743. Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
  744. Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy)),
  745. CopyBegin, CopyEnd);
  746. EmitBlock(CopyBegin);
  747. }
  748. auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
  749. auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  750. EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
  751. }
  752. ++IRef;
  753. ++ISrcRef;
  754. ++IDestRef;
  755. }
  756. }
  757. if (CopyEnd) {
  758. // Exit out of copying procedure for non-master thread.
  759. EmitBlock(CopyEnd, /*IsFinished=*/true);
  760. return true;
  761. }
  762. return false;
  763. }
  764. bool CodeGenFunction::EmitOMPLastprivateClauseInit(
  765. const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
  766. if (!HaveInsertPoint())
  767. return false;
  768. bool HasAtLeastOneLastprivate = false;
  769. llvm::DenseSet<const VarDecl *> SIMDLCVs;
  770. if (isOpenMPSimdDirective(D.getDirectiveKind())) {
  771. auto *LoopDirective = cast<OMPLoopDirective>(&D);
  772. for (auto *C : LoopDirective->counters()) {
  773. SIMDLCVs.insert(
  774. cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
  775. }
  776. }
  777. llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
  778. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  779. HasAtLeastOneLastprivate = true;
  780. if (isOpenMPTaskLoopDirective(D.getDirectiveKind()))
  781. break;
  782. auto IRef = C->varlist_begin();
  783. auto IDestRef = C->destination_exprs().begin();
  784. for (auto *IInit : C->private_copies()) {
  785. // Keep the address of the original variable for future update at the end
  786. // of the loop.
  787. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  788. // Taskloops do not require additional initialization, it is done in
  789. // runtime support library.
  790. if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
  791. auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  792. PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() -> Address {
  793. DeclRefExpr DRE(
  794. const_cast<VarDecl *>(OrigVD),
  795. /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
  796. OrigVD) != nullptr,
  797. (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
  798. return EmitLValue(&DRE).getAddress();
  799. });
  800. // Check if the variable is also a firstprivate: in this case IInit is
  801. // not generated. Initialization of this variable will happen in codegen
  802. // for 'firstprivate' clause.
  803. if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
  804. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  805. bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
  806. // Emit private VarDecl with copy init.
  807. EmitDecl(*VD);
  808. return GetAddrOfLocalVar(VD);
  809. });
  810. assert(IsRegistered &&
  811. "lastprivate var already registered as private");
  812. (void)IsRegistered;
  813. }
  814. }
  815. ++IRef;
  816. ++IDestRef;
  817. }
  818. }
  819. return HasAtLeastOneLastprivate;
  820. }
  821. void CodeGenFunction::EmitOMPLastprivateClauseFinal(
  822. const OMPExecutableDirective &D, bool NoFinals,
  823. llvm::Value *IsLastIterCond) {
  824. if (!HaveInsertPoint())
  825. return;
  826. // Emit following code:
  827. // if (<IsLastIterCond>) {
  828. // orig_var1 = private_orig_var1;
  829. // ...
  830. // orig_varn = private_orig_varn;
  831. // }
  832. llvm::BasicBlock *ThenBB = nullptr;
  833. llvm::BasicBlock *DoneBB = nullptr;
  834. if (IsLastIterCond) {
  835. ThenBB = createBasicBlock(".omp.lastprivate.then");
  836. DoneBB = createBasicBlock(".omp.lastprivate.done");
  837. Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
  838. EmitBlock(ThenBB);
  839. }
  840. llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
  841. llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
  842. if (auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
  843. auto IC = LoopDirective->counters().begin();
  844. for (auto F : LoopDirective->finals()) {
  845. auto *D =
  846. cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
  847. if (NoFinals)
  848. AlreadyEmittedVars.insert(D);
  849. else
  850. LoopCountersAndUpdates[D] = F;
  851. ++IC;
  852. }
  853. }
  854. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  855. auto IRef = C->varlist_begin();
  856. auto ISrcRef = C->source_exprs().begin();
  857. auto IDestRef = C->destination_exprs().begin();
  858. for (auto *AssignOp : C->assignment_ops()) {
  859. auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  860. QualType Type = PrivateVD->getType();
  861. auto *CanonicalVD = PrivateVD->getCanonicalDecl();
  862. if (AlreadyEmittedVars.insert(CanonicalVD).second) {
  863. // If lastprivate variable is a loop control variable for loop-based
  864. // directive, update its value before copyin back to original
  865. // variable.
  866. if (auto *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
  867. EmitIgnoredExpr(FinalExpr);
  868. auto *SrcVD = cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
  869. auto *DestVD = cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  870. // Get the address of the original variable.
  871. Address OriginalAddr = GetAddrOfLocalVar(DestVD);
  872. // Get the address of the private variable.
  873. Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
  874. if (auto RefTy = PrivateVD->getType()->getAs<ReferenceType>())
  875. PrivateAddr =
  876. Address(Builder.CreateLoad(PrivateAddr),
  877. getNaturalTypeAlignment(RefTy->getPointeeType()));
  878. EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
  879. }
  880. ++IRef;
  881. ++ISrcRef;
  882. ++IDestRef;
  883. }
  884. if (auto *PostUpdate = C->getPostUpdateExpr())
  885. EmitIgnoredExpr(PostUpdate);
  886. }
  887. if (IsLastIterCond)
  888. EmitBlock(DoneBB, /*IsFinished=*/true);
  889. }
  890. static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
  891. LValue BaseLV, llvm::Value *Addr) {
  892. Address Tmp = Address::invalid();
  893. Address TopTmp = Address::invalid();
  894. Address MostTopTmp = Address::invalid();
  895. BaseTy = BaseTy.getNonReferenceType();
  896. while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
  897. !CGF.getContext().hasSameType(BaseTy, ElTy)) {
  898. Tmp = CGF.CreateMemTemp(BaseTy);
  899. if (TopTmp.isValid())
  900. CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
  901. else
  902. MostTopTmp = Tmp;
  903. TopTmp = Tmp;
  904. BaseTy = BaseTy->getPointeeType();
  905. }
  906. llvm::Type *Ty = BaseLV.getPointer()->getType();
  907. if (Tmp.isValid())
  908. Ty = Tmp.getElementType();
  909. Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
  910. if (Tmp.isValid()) {
  911. CGF.Builder.CreateStore(Addr, Tmp);
  912. return MostTopTmp;
  913. }
  914. return Address(Addr, BaseLV.getAlignment());
  915. }
  916. static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
  917. LValue BaseLV) {
  918. BaseTy = BaseTy.getNonReferenceType();
  919. while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
  920. !CGF.getContext().hasSameType(BaseTy, ElTy)) {
  921. if (auto *PtrTy = BaseTy->getAs<PointerType>())
  922. BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
  923. else {
  924. BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
  925. BaseTy->castAs<ReferenceType>());
  926. }
  927. BaseTy = BaseTy->getPointeeType();
  928. }
  929. return CGF.MakeAddrLValue(
  930. Address(
  931. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  932. BaseLV.getPointer(), CGF.ConvertTypeForMem(ElTy)->getPointerTo()),
  933. BaseLV.getAlignment()),
  934. BaseLV.getType(), BaseLV.getBaseInfo());
  935. }
  936. void CodeGenFunction::EmitOMPReductionClauseInit(
  937. const OMPExecutableDirective &D,
  938. CodeGenFunction::OMPPrivateScope &PrivateScope) {
  939. if (!HaveInsertPoint())
  940. return;
  941. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  942. auto ILHS = C->lhs_exprs().begin();
  943. auto IRHS = C->rhs_exprs().begin();
  944. auto IPriv = C->privates().begin();
  945. auto IRed = C->reduction_ops().begin();
  946. for (auto IRef : C->varlists()) {
  947. auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  948. auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  949. auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
  950. auto *DRD = getReductionInit(*IRed);
  951. if (auto *OASE = dyn_cast<OMPArraySectionExpr>(IRef)) {
  952. auto *Base = OASE->getBase()->IgnoreParenImpCasts();
  953. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  954. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  955. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  956. Base = TempASE->getBase()->IgnoreParenImpCasts();
  957. auto *DE = cast<DeclRefExpr>(Base);
  958. auto *OrigVD = cast<VarDecl>(DE->getDecl());
  959. auto OASELValueLB = EmitOMPArraySectionExpr(OASE);
  960. auto OASELValueUB =
  961. EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
  962. auto OriginalBaseLValue = EmitLValue(DE);
  963. LValue BaseLValue =
  964. loadToBegin(*this, OrigVD->getType(), OASELValueLB.getType(),
  965. OriginalBaseLValue);
  966. // Store the address of the original variable associated with the LHS
  967. // implicit variable.
  968. PrivateScope.addPrivate(LHSVD, [OASELValueLB]() -> Address {
  969. return OASELValueLB.getAddress();
  970. });
  971. // Emit reduction copy.
  972. bool IsRegistered = PrivateScope.addPrivate(
  973. OrigVD, [this, OrigVD, PrivateVD, BaseLValue, OASELValueLB,
  974. OASELValueUB, OriginalBaseLValue, DRD, IRed]() -> Address {
  975. // Emit VarDecl with copy init for arrays.
  976. // Get the address of the original variable captured in current
  977. // captured region.
  978. auto *Size = Builder.CreatePtrDiff(OASELValueUB.getPointer(),
  979. OASELValueLB.getPointer());
  980. Size = Builder.CreateNUWAdd(
  981. Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
  982. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  983. *this, cast<OpaqueValueExpr>(
  984. getContext()
  985. .getAsVariableArrayType(PrivateVD->getType())
  986. ->getSizeExpr()),
  987. RValue::get(Size));
  988. EmitVariablyModifiedType(PrivateVD->getType());
  989. auto Emission = EmitAutoVarAlloca(*PrivateVD);
  990. auto Addr = Emission.getAllocatedAddress();
  991. auto *Init = PrivateVD->getInit();
  992. EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
  993. DRD ? *IRed : Init,
  994. OASELValueLB.getAddress());
  995. EmitAutoVarCleanups(Emission);
  996. // Emit private VarDecl with reduction init.
  997. auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
  998. OASELValueLB.getPointer());
  999. auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
  1000. return castToBase(*this, OrigVD->getType(),
  1001. OASELValueLB.getType(), OriginalBaseLValue,
  1002. Ptr);
  1003. });
  1004. assert(IsRegistered && "private var already registered as private");
  1005. // Silence the warning about unused variable.
  1006. (void)IsRegistered;
  1007. PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
  1008. return GetAddrOfLocalVar(PrivateVD);
  1009. });
  1010. } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(IRef)) {
  1011. auto *Base = ASE->getBase()->IgnoreParenImpCasts();
  1012. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  1013. Base = TempASE->getBase()->IgnoreParenImpCasts();
  1014. auto *DE = cast<DeclRefExpr>(Base);
  1015. auto *OrigVD = cast<VarDecl>(DE->getDecl());
  1016. auto ASELValue = EmitLValue(ASE);
  1017. auto OriginalBaseLValue = EmitLValue(DE);
  1018. LValue BaseLValue = loadToBegin(
  1019. *this, OrigVD->getType(), ASELValue.getType(), OriginalBaseLValue);
  1020. // Store the address of the original variable associated with the LHS
  1021. // implicit variable.
  1022. PrivateScope.addPrivate(
  1023. LHSVD, [ASELValue]() -> Address { return ASELValue.getAddress(); });
  1024. // Emit reduction copy.
  1025. bool IsRegistered = PrivateScope.addPrivate(
  1026. OrigVD, [this, OrigVD, PrivateVD, BaseLValue, ASELValue,
  1027. OriginalBaseLValue, DRD, IRed]() -> Address {
  1028. // Emit private VarDecl with reduction init.
  1029. AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
  1030. auto Addr = Emission.getAllocatedAddress();
  1031. if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
  1032. emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
  1033. ASELValue.getAddress(),
  1034. ASELValue.getType());
  1035. } else
  1036. EmitAutoVarInit(Emission);
  1037. EmitAutoVarCleanups(Emission);
  1038. auto *Offset = Builder.CreatePtrDiff(BaseLValue.getPointer(),
  1039. ASELValue.getPointer());
  1040. auto *Ptr = Builder.CreateGEP(Addr.getPointer(), Offset);
  1041. return castToBase(*this, OrigVD->getType(), ASELValue.getType(),
  1042. OriginalBaseLValue, Ptr);
  1043. });
  1044. assert(IsRegistered && "private var already registered as private");
  1045. // Silence the warning about unused variable.
  1046. (void)IsRegistered;
  1047. PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
  1048. return Builder.CreateElementBitCast(
  1049. GetAddrOfLocalVar(PrivateVD), ConvertTypeForMem(RHSVD->getType()),
  1050. "rhs.begin");
  1051. });
  1052. } else {
  1053. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl());
  1054. QualType Type = PrivateVD->getType();
  1055. if (getContext().getAsArrayType(Type)) {
  1056. // Store the address of the original variable associated with the LHS
  1057. // implicit variable.
  1058. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
  1059. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  1060. IRef->getType(), VK_LValue, IRef->getExprLoc());
  1061. Address OriginalAddr = EmitLValue(&DRE).getAddress();
  1062. PrivateScope.addPrivate(LHSVD, [this, &OriginalAddr,
  1063. LHSVD]() -> Address {
  1064. OriginalAddr = Builder.CreateElementBitCast(
  1065. OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
  1066. return OriginalAddr;
  1067. });
  1068. bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
  1069. if (Type->isVariablyModifiedType()) {
  1070. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  1071. *this, cast<OpaqueValueExpr>(
  1072. getContext()
  1073. .getAsVariableArrayType(PrivateVD->getType())
  1074. ->getSizeExpr()),
  1075. RValue::get(
  1076. getTypeSize(OrigVD->getType().getNonReferenceType())));
  1077. EmitVariablyModifiedType(Type);
  1078. }
  1079. auto Emission = EmitAutoVarAlloca(*PrivateVD);
  1080. auto Addr = Emission.getAllocatedAddress();
  1081. auto *Init = PrivateVD->getInit();
  1082. EmitOMPAggregateInit(*this, Addr, PrivateVD->getType(),
  1083. DRD ? *IRed : Init, OriginalAddr);
  1084. EmitAutoVarCleanups(Emission);
  1085. return Emission.getAllocatedAddress();
  1086. });
  1087. assert(IsRegistered && "private var already registered as private");
  1088. // Silence the warning about unused variable.
  1089. (void)IsRegistered;
  1090. PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() -> Address {
  1091. return Builder.CreateElementBitCast(
  1092. GetAddrOfLocalVar(PrivateVD),
  1093. ConvertTypeForMem(RHSVD->getType()), "rhs.begin");
  1094. });
  1095. } else {
  1096. // Store the address of the original variable associated with the LHS
  1097. // implicit variable.
  1098. Address OriginalAddr = Address::invalid();
  1099. PrivateScope.addPrivate(LHSVD, [this, OrigVD, IRef,
  1100. &OriginalAddr]() -> Address {
  1101. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
  1102. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  1103. IRef->getType(), VK_LValue, IRef->getExprLoc());
  1104. OriginalAddr = EmitLValue(&DRE).getAddress();
  1105. return OriginalAddr;
  1106. });
  1107. // Emit reduction copy.
  1108. bool IsRegistered = PrivateScope.addPrivate(
  1109. OrigVD, [this, PrivateVD, OriginalAddr, DRD, IRed]() -> Address {
  1110. // Emit private VarDecl with reduction init.
  1111. AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
  1112. auto Addr = Emission.getAllocatedAddress();
  1113. if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
  1114. emitInitWithReductionInitializer(*this, DRD, *IRed, Addr,
  1115. OriginalAddr,
  1116. PrivateVD->getType());
  1117. } else
  1118. EmitAutoVarInit(Emission);
  1119. EmitAutoVarCleanups(Emission);
  1120. return Addr;
  1121. });
  1122. assert(IsRegistered && "private var already registered as private");
  1123. // Silence the warning about unused variable.
  1124. (void)IsRegistered;
  1125. PrivateScope.addPrivate(RHSVD, [this, PrivateVD]() -> Address {
  1126. return GetAddrOfLocalVar(PrivateVD);
  1127. });
  1128. }
  1129. }
  1130. ++ILHS;
  1131. ++IRHS;
  1132. ++IPriv;
  1133. ++IRed;
  1134. }
  1135. }
  1136. }
  1137. void CodeGenFunction::EmitOMPReductionClauseFinal(
  1138. const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
  1139. if (!HaveInsertPoint())
  1140. return;
  1141. llvm::SmallVector<const Expr *, 8> Privates;
  1142. llvm::SmallVector<const Expr *, 8> LHSExprs;
  1143. llvm::SmallVector<const Expr *, 8> RHSExprs;
  1144. llvm::SmallVector<const Expr *, 8> ReductionOps;
  1145. bool HasAtLeastOneReduction = false;
  1146. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1147. HasAtLeastOneReduction = true;
  1148. Privates.append(C->privates().begin(), C->privates().end());
  1149. LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  1150. RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  1151. ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
  1152. }
  1153. if (HasAtLeastOneReduction) {
  1154. bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
  1155. isOpenMPParallelDirective(D.getDirectiveKind()) ||
  1156. D.getDirectiveKind() == OMPD_simd;
  1157. bool SimpleReduction = D.getDirectiveKind() == OMPD_simd;
  1158. // Emit nowait reduction if nowait clause is present or directive is a
  1159. // parallel directive (it always has implicit barrier).
  1160. CGM.getOpenMPRuntime().emitReduction(
  1161. *this, D.getLocEnd(), Privates, LHSExprs, RHSExprs, ReductionOps,
  1162. {WithNowait, SimpleReduction, ReductionKind});
  1163. }
  1164. }
  1165. static void emitPostUpdateForReductionClause(
  1166. CodeGenFunction &CGF, const OMPExecutableDirective &D,
  1167. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
  1168. if (!CGF.HaveInsertPoint())
  1169. return;
  1170. llvm::BasicBlock *DoneBB = nullptr;
  1171. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1172. if (auto *PostUpdate = C->getPostUpdateExpr()) {
  1173. if (!DoneBB) {
  1174. if (auto *Cond = CondGen(CGF)) {
  1175. // If the first post-update expression is found, emit conditional
  1176. // block if it was requested.
  1177. auto *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
  1178. DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
  1179. CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  1180. CGF.EmitBlock(ThenBB);
  1181. }
  1182. }
  1183. CGF.EmitIgnoredExpr(PostUpdate);
  1184. }
  1185. }
  1186. if (DoneBB)
  1187. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  1188. }
  1189. namespace {
  1190. /// Codegen lambda for appending distribute lower and upper bounds to outlined
  1191. /// parallel function. This is necessary for combined constructs such as
  1192. /// 'distribute parallel for'
  1193. typedef llvm::function_ref<void(CodeGenFunction &,
  1194. const OMPExecutableDirective &,
  1195. llvm::SmallVectorImpl<llvm::Value *> &)>
  1196. CodeGenBoundParametersTy;
  1197. } // anonymous namespace
  1198. static void emitCommonOMPParallelDirective(
  1199. CodeGenFunction &CGF, const OMPExecutableDirective &S,
  1200. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  1201. const CodeGenBoundParametersTy &CodeGenBoundParameters) {
  1202. const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
  1203. auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
  1204. S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
  1205. if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
  1206. CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
  1207. auto NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
  1208. /*IgnoreResultAssign*/ true);
  1209. CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
  1210. CGF, NumThreads, NumThreadsClause->getLocStart());
  1211. }
  1212. if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
  1213. CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
  1214. CGF.CGM.getOpenMPRuntime().emitProcBindClause(
  1215. CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getLocStart());
  1216. }
  1217. const Expr *IfCond = nullptr;
  1218. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  1219. if (C->getNameModifier() == OMPD_unknown ||
  1220. C->getNameModifier() == OMPD_parallel) {
  1221. IfCond = C->getCondition();
  1222. break;
  1223. }
  1224. }
  1225. OMPParallelScope Scope(CGF, S);
  1226. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  1227. // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
  1228. // lower and upper bounds with the pragma 'for' chunking mechanism.
  1229. // The following lambda takes care of appending the lower and upper bound
  1230. // parameters when necessary
  1231. CodeGenBoundParameters(CGF, S, CapturedVars);
  1232. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  1233. CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getLocStart(), OutlinedFn,
  1234. CapturedVars, IfCond);
  1235. }
  1236. static void emitEmptyBoundParameters(CodeGenFunction &,
  1237. const OMPExecutableDirective &,
  1238. llvm::SmallVectorImpl<llvm::Value *> &) {}
  1239. void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
  1240. // Emit parallel region as a standalone region.
  1241. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  1242. OMPPrivateScope PrivateScope(CGF);
  1243. bool Copyins = CGF.EmitOMPCopyinClause(S);
  1244. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  1245. if (Copyins) {
  1246. // Emit implicit barrier to synchronize threads and avoid data races on
  1247. // propagation master's thread values of threadprivate variables to local
  1248. // instances of that variables of all other implicit threads.
  1249. CGF.CGM.getOpenMPRuntime().emitBarrierCall(
  1250. CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
  1251. /*ForceSimpleCall=*/true);
  1252. }
  1253. CGF.EmitOMPPrivateClause(S, PrivateScope);
  1254. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  1255. (void)PrivateScope.Privatize();
  1256. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  1257. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  1258. };
  1259. emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
  1260. emitEmptyBoundParameters);
  1261. emitPostUpdateForReductionClause(
  1262. *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
  1263. }
  1264. void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
  1265. JumpDest LoopExit) {
  1266. RunCleanupsScope BodyScope(*this);
  1267. // Update counters values on current iteration.
  1268. for (auto I : D.updates()) {
  1269. EmitIgnoredExpr(I);
  1270. }
  1271. // Update the linear variables.
  1272. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1273. for (auto *U : C->updates())
  1274. EmitIgnoredExpr(U);
  1275. }
  1276. // On a continue in the body, jump to the end.
  1277. auto Continue = getJumpDestInCurrentScope("omp.body.continue");
  1278. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  1279. // Emit loop body.
  1280. EmitStmt(D.getBody());
  1281. // The end (updates/cleanups).
  1282. EmitBlock(Continue.getBlock());
  1283. BreakContinueStack.pop_back();
  1284. }
  1285. void CodeGenFunction::EmitOMPInnerLoop(
  1286. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  1287. const Expr *IncExpr,
  1288. const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
  1289. const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen) {
  1290. auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
  1291. // Start the loop with a block that tests the condition.
  1292. auto CondBlock = createBasicBlock("omp.inner.for.cond");
  1293. EmitBlock(CondBlock);
  1294. const SourceRange &R = S.getSourceRange();
  1295. LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
  1296. SourceLocToDebugLoc(R.getEnd()));
  1297. // If there are any cleanups between here and the loop-exit scope,
  1298. // create a block to stage a loop exit along.
  1299. auto ExitBlock = LoopExit.getBlock();
  1300. if (RequiresCleanup)
  1301. ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
  1302. auto LoopBody = createBasicBlock("omp.inner.for.body");
  1303. // Emit condition.
  1304. EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
  1305. if (ExitBlock != LoopExit.getBlock()) {
  1306. EmitBlock(ExitBlock);
  1307. EmitBranchThroughCleanup(LoopExit);
  1308. }
  1309. EmitBlock(LoopBody);
  1310. incrementProfileCounter(&S);
  1311. // Create a block for the increment.
  1312. auto Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
  1313. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  1314. BodyGen(*this);
  1315. // Emit "IV = IV + 1" and a back-edge to the condition block.
  1316. EmitBlock(Continue.getBlock());
  1317. EmitIgnoredExpr(IncExpr);
  1318. PostIncGen(*this);
  1319. BreakContinueStack.pop_back();
  1320. EmitBranch(CondBlock);
  1321. LoopStack.pop();
  1322. // Emit the fall-through block.
  1323. EmitBlock(LoopExit.getBlock());
  1324. }
  1325. void CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
  1326. if (!HaveInsertPoint())
  1327. return;
  1328. // Emit inits for the linear variables.
  1329. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1330. for (auto *Init : C->inits()) {
  1331. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
  1332. if (auto *Ref = dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
  1333. AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
  1334. auto *OrigVD = cast<VarDecl>(Ref->getDecl());
  1335. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
  1336. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  1337. VD->getInit()->getType(), VK_LValue,
  1338. VD->getInit()->getExprLoc());
  1339. EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
  1340. VD->getType()),
  1341. /*capturedByInit=*/false);
  1342. EmitAutoVarCleanups(Emission);
  1343. } else
  1344. EmitVarDecl(*VD);
  1345. }
  1346. // Emit the linear steps for the linear clauses.
  1347. // If a step is not constant, it is pre-calculated before the loop.
  1348. if (auto CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
  1349. if (auto SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
  1350. EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
  1351. // Emit calculation of the linear step.
  1352. EmitIgnoredExpr(CS);
  1353. }
  1354. }
  1355. }
  1356. void CodeGenFunction::EmitOMPLinearClauseFinal(
  1357. const OMPLoopDirective &D,
  1358. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
  1359. if (!HaveInsertPoint())
  1360. return;
  1361. llvm::BasicBlock *DoneBB = nullptr;
  1362. // Emit the final values of the linear variables.
  1363. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1364. auto IC = C->varlist_begin();
  1365. for (auto *F : C->finals()) {
  1366. if (!DoneBB) {
  1367. if (auto *Cond = CondGen(*this)) {
  1368. // If the first post-update expression is found, emit conditional
  1369. // block if it was requested.
  1370. auto *ThenBB = createBasicBlock(".omp.linear.pu");
  1371. DoneBB = createBasicBlock(".omp.linear.pu.done");
  1372. Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  1373. EmitBlock(ThenBB);
  1374. }
  1375. }
  1376. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
  1377. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
  1378. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  1379. (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
  1380. Address OrigAddr = EmitLValue(&DRE).getAddress();
  1381. CodeGenFunction::OMPPrivateScope VarScope(*this);
  1382. VarScope.addPrivate(OrigVD, [OrigAddr]() -> Address { return OrigAddr; });
  1383. (void)VarScope.Privatize();
  1384. EmitIgnoredExpr(F);
  1385. ++IC;
  1386. }
  1387. if (auto *PostUpdate = C->getPostUpdateExpr())
  1388. EmitIgnoredExpr(PostUpdate);
  1389. }
  1390. if (DoneBB)
  1391. EmitBlock(DoneBB, /*IsFinished=*/true);
  1392. }
  1393. static void emitAlignedClause(CodeGenFunction &CGF,
  1394. const OMPExecutableDirective &D) {
  1395. if (!CGF.HaveInsertPoint())
  1396. return;
  1397. for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
  1398. unsigned ClauseAlignment = 0;
  1399. if (auto AlignmentExpr = Clause->getAlignment()) {
  1400. auto AlignmentCI =
  1401. cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
  1402. ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
  1403. }
  1404. for (auto E : Clause->varlists()) {
  1405. unsigned Alignment = ClauseAlignment;
  1406. if (Alignment == 0) {
  1407. // OpenMP [2.8.1, Description]
  1408. // If no optional parameter is specified, implementation-defined default
  1409. // alignments for SIMD instructions on the target platforms are assumed.
  1410. Alignment =
  1411. CGF.getContext()
  1412. .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
  1413. E->getType()->getPointeeType()))
  1414. .getQuantity();
  1415. }
  1416. assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
  1417. "alignment is not power of 2");
  1418. if (Alignment != 0) {
  1419. llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
  1420. CGF.EmitAlignmentAssumption(PtrValue, Alignment);
  1421. }
  1422. }
  1423. }
  1424. }
  1425. void CodeGenFunction::EmitOMPPrivateLoopCounters(
  1426. const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
  1427. if (!HaveInsertPoint())
  1428. return;
  1429. auto I = S.private_counters().begin();
  1430. for (auto *E : S.counters()) {
  1431. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  1432. auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
  1433. (void)LoopScope.addPrivate(VD, [&]() -> Address {
  1434. // Emit var without initialization.
  1435. if (!LocalDeclMap.count(PrivateVD)) {
  1436. auto VarEmission = EmitAutoVarAlloca(*PrivateVD);
  1437. EmitAutoVarCleanups(VarEmission);
  1438. }
  1439. DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
  1440. /*RefersToEnclosingVariableOrCapture=*/false,
  1441. (*I)->getType(), VK_LValue, (*I)->getExprLoc());
  1442. return EmitLValue(&DRE).getAddress();
  1443. });
  1444. if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
  1445. VD->hasGlobalStorage()) {
  1446. (void)LoopScope.addPrivate(PrivateVD, [&]() -> Address {
  1447. DeclRefExpr DRE(const_cast<VarDecl *>(VD),
  1448. LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
  1449. E->getType(), VK_LValue, E->getExprLoc());
  1450. return EmitLValue(&DRE).getAddress();
  1451. });
  1452. }
  1453. ++I;
  1454. }
  1455. }
  1456. static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
  1457. const Expr *Cond, llvm::BasicBlock *TrueBlock,
  1458. llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
  1459. if (!CGF.HaveInsertPoint())
  1460. return;
  1461. {
  1462. CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
  1463. CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
  1464. (void)PreCondScope.Privatize();
  1465. // Get initial values of real counters.
  1466. for (auto I : S.inits()) {
  1467. CGF.EmitIgnoredExpr(I);
  1468. }
  1469. }
  1470. // Check that loop is executed at least one time.
  1471. CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
  1472. }
  1473. void CodeGenFunction::EmitOMPLinearClause(
  1474. const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
  1475. if (!HaveInsertPoint())
  1476. return;
  1477. llvm::DenseSet<const VarDecl *> SIMDLCVs;
  1478. if (isOpenMPSimdDirective(D.getDirectiveKind())) {
  1479. auto *LoopDirective = cast<OMPLoopDirective>(&D);
  1480. for (auto *C : LoopDirective->counters()) {
  1481. SIMDLCVs.insert(
  1482. cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
  1483. }
  1484. }
  1485. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1486. auto CurPrivate = C->privates().begin();
  1487. for (auto *E : C->varlists()) {
  1488. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  1489. auto *PrivateVD =
  1490. cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
  1491. if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
  1492. bool IsRegistered = PrivateScope.addPrivate(VD, [&]() -> Address {
  1493. // Emit private VarDecl with copy init.
  1494. EmitVarDecl(*PrivateVD);
  1495. return GetAddrOfLocalVar(PrivateVD);
  1496. });
  1497. assert(IsRegistered && "linear var already registered as private");
  1498. // Silence the warning about unused variable.
  1499. (void)IsRegistered;
  1500. } else
  1501. EmitVarDecl(*PrivateVD);
  1502. ++CurPrivate;
  1503. }
  1504. }
  1505. }
  1506. static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
  1507. const OMPExecutableDirective &D,
  1508. bool IsMonotonic) {
  1509. if (!CGF.HaveInsertPoint())
  1510. return;
  1511. if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
  1512. RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
  1513. /*ignoreResult=*/true);
  1514. llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
  1515. CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
  1516. // In presence of finite 'safelen', it may be unsafe to mark all
  1517. // the memory instructions parallel, because loop-carried
  1518. // dependences of 'safelen' iterations are possible.
  1519. if (!IsMonotonic)
  1520. CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
  1521. } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
  1522. RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
  1523. /*ignoreResult=*/true);
  1524. llvm::ConstantInt *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
  1525. CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
  1526. // In presence of finite 'safelen', it may be unsafe to mark all
  1527. // the memory instructions parallel, because loop-carried
  1528. // dependences of 'safelen' iterations are possible.
  1529. CGF.LoopStack.setParallel(false);
  1530. }
  1531. }
  1532. void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
  1533. bool IsMonotonic) {
  1534. // Walk clauses and process safelen/lastprivate.
  1535. LoopStack.setParallel(!IsMonotonic);
  1536. LoopStack.setVectorizeEnable(true);
  1537. emitSimdlenSafelenClause(*this, D, IsMonotonic);
  1538. }
  1539. void CodeGenFunction::EmitOMPSimdFinal(
  1540. const OMPLoopDirective &D,
  1541. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen) {
  1542. if (!HaveInsertPoint())
  1543. return;
  1544. llvm::BasicBlock *DoneBB = nullptr;
  1545. auto IC = D.counters().begin();
  1546. auto IPC = D.private_counters().begin();
  1547. for (auto F : D.finals()) {
  1548. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
  1549. auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
  1550. auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
  1551. if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
  1552. OrigVD->hasGlobalStorage() || CED) {
  1553. if (!DoneBB) {
  1554. if (auto *Cond = CondGen(*this)) {
  1555. // If the first post-update expression is found, emit conditional
  1556. // block if it was requested.
  1557. auto *ThenBB = createBasicBlock(".omp.final.then");
  1558. DoneBB = createBasicBlock(".omp.final.done");
  1559. Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  1560. EmitBlock(ThenBB);
  1561. }
  1562. }
  1563. Address OrigAddr = Address::invalid();
  1564. if (CED)
  1565. OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
  1566. else {
  1567. DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
  1568. /*RefersToEnclosingVariableOrCapture=*/false,
  1569. (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
  1570. OrigAddr = EmitLValue(&DRE).getAddress();
  1571. }
  1572. OMPPrivateScope VarScope(*this);
  1573. VarScope.addPrivate(OrigVD,
  1574. [OrigAddr]() -> Address { return OrigAddr; });
  1575. (void)VarScope.Privatize();
  1576. EmitIgnoredExpr(F);
  1577. }
  1578. ++IC;
  1579. ++IPC;
  1580. }
  1581. if (DoneBB)
  1582. EmitBlock(DoneBB, /*IsFinished=*/true);
  1583. }
  1584. static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
  1585. const OMPLoopDirective &S,
  1586. CodeGenFunction::JumpDest LoopExit) {
  1587. CGF.EmitOMPLoopBody(S, LoopExit);
  1588. CGF.EmitStopPoint(&S);
  1589. }
  1590. void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
  1591. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  1592. OMPLoopScope PreInitScope(CGF, S);
  1593. // if (PreCond) {
  1594. // for (IV in 0..LastIteration) BODY;
  1595. // <Final counter/linear vars updates>;
  1596. // }
  1597. //
  1598. // Emit: if (PreCond) - begin.
  1599. // If the condition constant folds and can be elided, avoid emitting the
  1600. // whole loop.
  1601. bool CondConstant;
  1602. llvm::BasicBlock *ContBlock = nullptr;
  1603. if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  1604. if (!CondConstant)
  1605. return;
  1606. } else {
  1607. auto *ThenBlock = CGF.createBasicBlock("simd.if.then");
  1608. ContBlock = CGF.createBasicBlock("simd.if.end");
  1609. emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
  1610. CGF.getProfileCount(&S));
  1611. CGF.EmitBlock(ThenBlock);
  1612. CGF.incrementProfileCounter(&S);
  1613. }
  1614. // Emit the loop iteration variable.
  1615. const Expr *IVExpr = S.getIterationVariable();
  1616. const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
  1617. CGF.EmitVarDecl(*IVDecl);
  1618. CGF.EmitIgnoredExpr(S.getInit());
  1619. // Emit the iterations count variable.
  1620. // If it is not a variable, Sema decided to calculate iterations count on
  1621. // each iteration (e.g., it is foldable into a constant).
  1622. if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  1623. CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  1624. // Emit calculation of the iterations count.
  1625. CGF.EmitIgnoredExpr(S.getCalcLastIteration());
  1626. }
  1627. CGF.EmitOMPSimdInit(S);
  1628. emitAlignedClause(CGF, S);
  1629. CGF.EmitOMPLinearClauseInit(S);
  1630. {
  1631. OMPPrivateScope LoopScope(CGF);
  1632. CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
  1633. CGF.EmitOMPLinearClause(S, LoopScope);
  1634. CGF.EmitOMPPrivateClause(S, LoopScope);
  1635. CGF.EmitOMPReductionClauseInit(S, LoopScope);
  1636. bool HasLastprivateClause =
  1637. CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  1638. (void)LoopScope.Privatize();
  1639. CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
  1640. S.getInc(),
  1641. [&S](CodeGenFunction &CGF) {
  1642. CGF.EmitOMPLoopBody(S, JumpDest());
  1643. CGF.EmitStopPoint(&S);
  1644. },
  1645. [](CodeGenFunction &) {});
  1646. CGF.EmitOMPSimdFinal(
  1647. S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
  1648. // Emit final copy of the lastprivate variables at the end of loops.
  1649. if (HasLastprivateClause)
  1650. CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
  1651. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
  1652. emitPostUpdateForReductionClause(
  1653. CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
  1654. }
  1655. CGF.EmitOMPLinearClauseFinal(
  1656. S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
  1657. // Emit: if (PreCond) - end.
  1658. if (ContBlock) {
  1659. CGF.EmitBranch(ContBlock);
  1660. CGF.EmitBlock(ContBlock, true);
  1661. }
  1662. };
  1663. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  1664. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
  1665. }
  1666. void CodeGenFunction::EmitOMPOuterLoop(
  1667. bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
  1668. CodeGenFunction::OMPPrivateScope &LoopScope,
  1669. const CodeGenFunction::OMPLoopArguments &LoopArgs,
  1670. const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
  1671. const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
  1672. auto &RT = CGM.getOpenMPRuntime();
  1673. const Expr *IVExpr = S.getIterationVariable();
  1674. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  1675. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  1676. auto LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
  1677. // Start the loop with a block that tests the condition.
  1678. auto CondBlock = createBasicBlock("omp.dispatch.cond");
  1679. EmitBlock(CondBlock);
  1680. const SourceRange &R = S.getSourceRange();
  1681. LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
  1682. SourceLocToDebugLoc(R.getEnd()));
  1683. llvm::Value *BoolCondVal = nullptr;
  1684. if (!DynamicOrOrdered) {
  1685. // UB = min(UB, GlobalUB) or
  1686. // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
  1687. // 'distribute parallel for')
  1688. EmitIgnoredExpr(LoopArgs.EUB);
  1689. // IV = LB
  1690. EmitIgnoredExpr(LoopArgs.Init);
  1691. // IV < UB
  1692. BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
  1693. } else {
  1694. BoolCondVal =
  1695. RT.emitForNext(*this, S.getLocStart(), IVSize, IVSigned, LoopArgs.IL,
  1696. LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
  1697. }
  1698. // If there are any cleanups between here and the loop-exit scope,
  1699. // create a block to stage a loop exit along.
  1700. auto ExitBlock = LoopExit.getBlock();
  1701. if (LoopScope.requiresCleanups())
  1702. ExitBlock = createBasicBlock("omp.dispatch.cleanup");
  1703. auto LoopBody = createBasicBlock("omp.dispatch.body");
  1704. Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
  1705. if (ExitBlock != LoopExit.getBlock()) {
  1706. EmitBlock(ExitBlock);
  1707. EmitBranchThroughCleanup(LoopExit);
  1708. }
  1709. EmitBlock(LoopBody);
  1710. // Emit "IV = LB" (in case of static schedule, we have already calculated new
  1711. // LB for loop condition and emitted it above).
  1712. if (DynamicOrOrdered)
  1713. EmitIgnoredExpr(LoopArgs.Init);
  1714. // Create a block for the increment.
  1715. auto Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
  1716. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  1717. // Generate !llvm.loop.parallel metadata for loads and stores for loops
  1718. // with dynamic/guided scheduling and without ordered clause.
  1719. if (!isOpenMPSimdDirective(S.getDirectiveKind()))
  1720. LoopStack.setParallel(!IsMonotonic);
  1721. else
  1722. EmitOMPSimdInit(S, IsMonotonic);
  1723. SourceLocation Loc = S.getLocStart();
  1724. // when 'distribute' is not combined with a 'for':
  1725. // while (idx <= UB) { BODY; ++idx; }
  1726. // when 'distribute' is combined with a 'for'
  1727. // (e.g. 'distribute parallel for')
  1728. // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
  1729. EmitOMPInnerLoop(
  1730. S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
  1731. [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
  1732. CodeGenLoop(CGF, S, LoopExit);
  1733. },
  1734. [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
  1735. CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
  1736. });
  1737. EmitBlock(Continue.getBlock());
  1738. BreakContinueStack.pop_back();
  1739. if (!DynamicOrOrdered) {
  1740. // Emit "LB = LB + Stride", "UB = UB + Stride".
  1741. EmitIgnoredExpr(LoopArgs.NextLB);
  1742. EmitIgnoredExpr(LoopArgs.NextUB);
  1743. }
  1744. EmitBranch(CondBlock);
  1745. LoopStack.pop();
  1746. // Emit the fall-through block.
  1747. EmitBlock(LoopExit.getBlock());
  1748. // Tell the runtime we are done.
  1749. auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
  1750. if (!DynamicOrOrdered)
  1751. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
  1752. };
  1753. OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
  1754. }
  1755. void CodeGenFunction::EmitOMPForOuterLoop(
  1756. const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
  1757. const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
  1758. const OMPLoopArguments &LoopArgs,
  1759. const CodeGenDispatchBoundsTy &CGDispatchBounds) {
  1760. auto &RT = CGM.getOpenMPRuntime();
  1761. // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
  1762. const bool DynamicOrOrdered =
  1763. Ordered || RT.isDynamic(ScheduleKind.Schedule);
  1764. assert((Ordered ||
  1765. !RT.isStaticNonchunked(ScheduleKind.Schedule,
  1766. LoopArgs.Chunk != nullptr)) &&
  1767. "static non-chunked schedule does not need outer loop");
  1768. // Emit outer loop.
  1769. //
  1770. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  1771. // When schedule(dynamic,chunk_size) is specified, the iterations are
  1772. // distributed to threads in the team in chunks as the threads request them.
  1773. // Each thread executes a chunk of iterations, then requests another chunk,
  1774. // until no chunks remain to be distributed. Each chunk contains chunk_size
  1775. // iterations, except for the last chunk to be distributed, which may have
  1776. // fewer iterations. When no chunk_size is specified, it defaults to 1.
  1777. //
  1778. // When schedule(guided,chunk_size) is specified, the iterations are assigned
  1779. // to threads in the team in chunks as the executing threads request them.
  1780. // Each thread executes a chunk of iterations, then requests another chunk,
  1781. // until no chunks remain to be assigned. For a chunk_size of 1, the size of
  1782. // each chunk is proportional to the number of unassigned iterations divided
  1783. // by the number of threads in the team, decreasing to 1. For a chunk_size
  1784. // with value k (greater than 1), the size of each chunk is determined in the
  1785. // same way, with the restriction that the chunks do not contain fewer than k
  1786. // iterations (except for the last chunk to be assigned, which may have fewer
  1787. // than k iterations).
  1788. //
  1789. // When schedule(auto) is specified, the decision regarding scheduling is
  1790. // delegated to the compiler and/or runtime system. The programmer gives the
  1791. // implementation the freedom to choose any possible mapping of iterations to
  1792. // threads in the team.
  1793. //
  1794. // When schedule(runtime) is specified, the decision regarding scheduling is
  1795. // deferred until run time, and the schedule and chunk size are taken from the
  1796. // run-sched-var ICV. If the ICV is set to auto, the schedule is
  1797. // implementation defined
  1798. //
  1799. // while(__kmpc_dispatch_next(&LB, &UB)) {
  1800. // idx = LB;
  1801. // while (idx <= UB) { BODY; ++idx;
  1802. // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
  1803. // } // inner loop
  1804. // }
  1805. //
  1806. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  1807. // When schedule(static, chunk_size) is specified, iterations are divided into
  1808. // chunks of size chunk_size, and the chunks are assigned to the threads in
  1809. // the team in a round-robin fashion in the order of the thread number.
  1810. //
  1811. // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
  1812. // while (idx <= UB) { BODY; ++idx; } // inner loop
  1813. // LB = LB + ST;
  1814. // UB = UB + ST;
  1815. // }
  1816. //
  1817. const Expr *IVExpr = S.getIterationVariable();
  1818. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  1819. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  1820. if (DynamicOrOrdered) {
  1821. auto DispatchBounds = CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
  1822. llvm::Value *LBVal = DispatchBounds.first;
  1823. llvm::Value *UBVal = DispatchBounds.second;
  1824. CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
  1825. LoopArgs.Chunk};
  1826. RT.emitForDispatchInit(*this, S.getLocStart(), ScheduleKind, IVSize,
  1827. IVSigned, Ordered, DipatchRTInputValues);
  1828. } else {
  1829. RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize, IVSigned,
  1830. Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
  1831. LoopArgs.ST, LoopArgs.Chunk);
  1832. }
  1833. auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
  1834. const unsigned IVSize,
  1835. const bool IVSigned) {
  1836. if (Ordered) {
  1837. CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
  1838. IVSigned);
  1839. }
  1840. };
  1841. OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
  1842. LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
  1843. OuterLoopArgs.IncExpr = S.getInc();
  1844. OuterLoopArgs.Init = S.getInit();
  1845. OuterLoopArgs.Cond = S.getCond();
  1846. OuterLoopArgs.NextLB = S.getNextLowerBound();
  1847. OuterLoopArgs.NextUB = S.getNextUpperBound();
  1848. EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
  1849. emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
  1850. }
  1851. static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
  1852. const unsigned IVSize, const bool IVSigned) {}
  1853. void CodeGenFunction::EmitOMPDistributeOuterLoop(
  1854. OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
  1855. OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
  1856. const CodeGenLoopTy &CodeGenLoopContent) {
  1857. auto &RT = CGM.getOpenMPRuntime();
  1858. // Emit outer loop.
  1859. // Same behavior as a OMPForOuterLoop, except that schedule cannot be
  1860. // dynamic
  1861. //
  1862. const Expr *IVExpr = S.getIterationVariable();
  1863. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  1864. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  1865. RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind, IVSize,
  1866. IVSigned, /* Ordered = */ false, LoopArgs.IL,
  1867. LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
  1868. LoopArgs.Chunk);
  1869. // for combined 'distribute' and 'for' the increment expression of distribute
  1870. // is store in DistInc. For 'distribute' alone, it is in Inc.
  1871. Expr *IncExpr;
  1872. if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
  1873. IncExpr = S.getDistInc();
  1874. else
  1875. IncExpr = S.getInc();
  1876. // this routine is shared by 'omp distribute parallel for' and
  1877. // 'omp distribute': select the right EUB expression depending on the
  1878. // directive
  1879. OMPLoopArguments OuterLoopArgs;
  1880. OuterLoopArgs.LB = LoopArgs.LB;
  1881. OuterLoopArgs.UB = LoopArgs.UB;
  1882. OuterLoopArgs.ST = LoopArgs.ST;
  1883. OuterLoopArgs.IL = LoopArgs.IL;
  1884. OuterLoopArgs.Chunk = LoopArgs.Chunk;
  1885. OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1886. ? S.getCombinedEnsureUpperBound()
  1887. : S.getEnsureUpperBound();
  1888. OuterLoopArgs.IncExpr = IncExpr;
  1889. OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1890. ? S.getCombinedInit()
  1891. : S.getInit();
  1892. OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1893. ? S.getCombinedCond()
  1894. : S.getCond();
  1895. OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1896. ? S.getCombinedNextLowerBound()
  1897. : S.getNextLowerBound();
  1898. OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1899. ? S.getCombinedNextUpperBound()
  1900. : S.getNextUpperBound();
  1901. EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
  1902. LoopScope, OuterLoopArgs, CodeGenLoopContent,
  1903. emitEmptyOrdered);
  1904. }
  1905. /// Emit a helper variable and return corresponding lvalue.
  1906. static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
  1907. const DeclRefExpr *Helper) {
  1908. auto VDecl = cast<VarDecl>(Helper->getDecl());
  1909. CGF.EmitVarDecl(*VDecl);
  1910. return CGF.EmitLValue(Helper);
  1911. }
  1912. static std::pair<LValue, LValue>
  1913. emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
  1914. const OMPExecutableDirective &S) {
  1915. const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
  1916. LValue LB =
  1917. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
  1918. LValue UB =
  1919. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
  1920. // When composing 'distribute' with 'for' (e.g. as in 'distribute
  1921. // parallel for') we need to use the 'distribute'
  1922. // chunk lower and upper bounds rather than the whole loop iteration
  1923. // space. These are parameters to the outlined function for 'parallel'
  1924. // and we copy the bounds of the previous schedule into the
  1925. // the current ones.
  1926. LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
  1927. LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
  1928. llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(PrevLB, SourceLocation());
  1929. PrevLBVal = CGF.EmitScalarConversion(
  1930. PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
  1931. LS.getIterationVariable()->getType(), SourceLocation());
  1932. llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(PrevUB, SourceLocation());
  1933. PrevUBVal = CGF.EmitScalarConversion(
  1934. PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
  1935. LS.getIterationVariable()->getType(), SourceLocation());
  1936. CGF.EmitStoreOfScalar(PrevLBVal, LB);
  1937. CGF.EmitStoreOfScalar(PrevUBVal, UB);
  1938. return {LB, UB};
  1939. }
  1940. /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
  1941. /// we need to use the LB and UB expressions generated by the worksharing
  1942. /// code generation support, whereas in non combined situations we would
  1943. /// just emit 0 and the LastIteration expression
  1944. /// This function is necessary due to the difference of the LB and UB
  1945. /// types for the RT emission routines for 'for_static_init' and
  1946. /// 'for_dispatch_init'
  1947. static std::pair<llvm::Value *, llvm::Value *>
  1948. emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
  1949. const OMPExecutableDirective &S,
  1950. Address LB, Address UB) {
  1951. const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
  1952. const Expr *IVExpr = LS.getIterationVariable();
  1953. // when implementing a dynamic schedule for a 'for' combined with a
  1954. // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
  1955. // is not normalized as each team only executes its own assigned
  1956. // distribute chunk
  1957. QualType IteratorTy = IVExpr->getType();
  1958. llvm::Value *LBVal = CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy,
  1959. SourceLocation());
  1960. llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy,
  1961. SourceLocation());
  1962. return {LBVal, UBVal};
  1963. }
  1964. static void emitDistributeParallelForDistributeInnerBoundParams(
  1965. CodeGenFunction &CGF, const OMPExecutableDirective &S,
  1966. llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
  1967. const auto &Dir = cast<OMPLoopDirective>(S);
  1968. LValue LB =
  1969. CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
  1970. auto LBCast = CGF.Builder.CreateIntCast(
  1971. CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
  1972. CapturedVars.push_back(LBCast);
  1973. LValue UB =
  1974. CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
  1975. auto UBCast = CGF.Builder.CreateIntCast(
  1976. CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
  1977. CapturedVars.push_back(UBCast);
  1978. }
  1979. static void
  1980. emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
  1981. const OMPLoopDirective &S,
  1982. CodeGenFunction::JumpDest LoopExit) {
  1983. auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
  1984. PrePostActionTy &) {
  1985. CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
  1986. emitDistributeParallelForInnerBounds,
  1987. emitDistributeParallelForDispatchBounds);
  1988. };
  1989. emitCommonOMPParallelDirective(
  1990. CGF, S, OMPD_for, CGInlinedWorksharingLoop,
  1991. emitDistributeParallelForDistributeInnerBoundParams);
  1992. }
  1993. void CodeGenFunction::EmitOMPDistributeParallelForDirective(
  1994. const OMPDistributeParallelForDirective &S) {
  1995. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  1996. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  1997. S.getDistInc());
  1998. };
  1999. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2000. OMPCancelStackRAII CancelRegion(*this, OMPD_distribute_parallel_for,
  2001. /*HasCancel=*/false);
  2002. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
  2003. /*HasCancel=*/false);
  2004. }
  2005. void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
  2006. const OMPDistributeParallelForSimdDirective &S) {
  2007. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2008. CGM.getOpenMPRuntime().emitInlinedDirective(
  2009. *this, OMPD_distribute_parallel_for_simd,
  2010. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2011. OMPLoopScope PreInitScope(CGF, S);
  2012. CGF.EmitStmt(
  2013. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2014. });
  2015. }
  2016. void CodeGenFunction::EmitOMPDistributeSimdDirective(
  2017. const OMPDistributeSimdDirective &S) {
  2018. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2019. CGM.getOpenMPRuntime().emitInlinedDirective(
  2020. *this, OMPD_distribute_simd,
  2021. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2022. OMPLoopScope PreInitScope(CGF, S);
  2023. CGF.EmitStmt(
  2024. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2025. });
  2026. }
  2027. void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
  2028. const OMPTargetParallelForSimdDirective &S) {
  2029. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2030. CGM.getOpenMPRuntime().emitInlinedDirective(
  2031. *this, OMPD_target_parallel_for_simd,
  2032. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2033. OMPLoopScope PreInitScope(CGF, S);
  2034. CGF.EmitStmt(
  2035. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2036. });
  2037. }
  2038. void CodeGenFunction::EmitOMPTargetSimdDirective(
  2039. const OMPTargetSimdDirective &S) {
  2040. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2041. CGM.getOpenMPRuntime().emitInlinedDirective(
  2042. *this, OMPD_target_simd, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2043. OMPLoopScope PreInitScope(CGF, S);
  2044. CGF.EmitStmt(
  2045. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2046. });
  2047. }
  2048. void CodeGenFunction::EmitOMPTeamsDistributeDirective(
  2049. const OMPTeamsDistributeDirective &S) {
  2050. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2051. CGM.getOpenMPRuntime().emitInlinedDirective(
  2052. *this, OMPD_teams_distribute,
  2053. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2054. OMPLoopScope PreInitScope(CGF, S);
  2055. CGF.EmitStmt(
  2056. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2057. });
  2058. }
  2059. void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
  2060. const OMPTeamsDistributeSimdDirective &S) {
  2061. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2062. CGM.getOpenMPRuntime().emitInlinedDirective(
  2063. *this, OMPD_teams_distribute_simd,
  2064. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2065. OMPLoopScope PreInitScope(CGF, S);
  2066. CGF.EmitStmt(
  2067. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2068. });
  2069. }
  2070. void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
  2071. const OMPTeamsDistributeParallelForSimdDirective &S) {
  2072. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2073. CGM.getOpenMPRuntime().emitInlinedDirective(
  2074. *this, OMPD_teams_distribute_parallel_for_simd,
  2075. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2076. OMPLoopScope PreInitScope(CGF, S);
  2077. CGF.EmitStmt(
  2078. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2079. });
  2080. }
  2081. void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
  2082. const OMPTeamsDistributeParallelForDirective &S) {
  2083. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2084. CGM.getOpenMPRuntime().emitInlinedDirective(
  2085. *this, OMPD_teams_distribute_parallel_for,
  2086. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2087. OMPLoopScope PreInitScope(CGF, S);
  2088. CGF.EmitStmt(
  2089. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2090. });
  2091. }
  2092. void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
  2093. const OMPTargetTeamsDistributeDirective &S) {
  2094. CGM.getOpenMPRuntime().emitInlinedDirective(
  2095. *this, OMPD_target_teams_distribute,
  2096. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2097. CGF.EmitStmt(
  2098. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2099. });
  2100. }
  2101. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
  2102. const OMPTargetTeamsDistributeParallelForDirective &S) {
  2103. CGM.getOpenMPRuntime().emitInlinedDirective(
  2104. *this, OMPD_target_teams_distribute_parallel_for,
  2105. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2106. CGF.EmitStmt(
  2107. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2108. });
  2109. }
  2110. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
  2111. const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
  2112. CGM.getOpenMPRuntime().emitInlinedDirective(
  2113. *this, OMPD_target_teams_distribute_parallel_for_simd,
  2114. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2115. CGF.EmitStmt(
  2116. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2117. });
  2118. }
  2119. void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
  2120. const OMPTargetTeamsDistributeSimdDirective &S) {
  2121. CGM.getOpenMPRuntime().emitInlinedDirective(
  2122. *this, OMPD_target_teams_distribute_simd,
  2123. [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2124. CGF.EmitStmt(
  2125. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2126. });
  2127. }
  2128. namespace {
  2129. struct ScheduleKindModifiersTy {
  2130. OpenMPScheduleClauseKind Kind;
  2131. OpenMPScheduleClauseModifier M1;
  2132. OpenMPScheduleClauseModifier M2;
  2133. ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
  2134. OpenMPScheduleClauseModifier M1,
  2135. OpenMPScheduleClauseModifier M2)
  2136. : Kind(Kind), M1(M1), M2(M2) {}
  2137. };
  2138. } // namespace
  2139. bool CodeGenFunction::EmitOMPWorksharingLoop(
  2140. const OMPLoopDirective &S, Expr *EUB,
  2141. const CodeGenLoopBoundsTy &CodeGenLoopBounds,
  2142. const CodeGenDispatchBoundsTy &CGDispatchBounds) {
  2143. // Emit the loop iteration variable.
  2144. auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
  2145. auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
  2146. EmitVarDecl(*IVDecl);
  2147. // Emit the iterations count variable.
  2148. // If it is not a variable, Sema decided to calculate iterations count on each
  2149. // iteration (e.g., it is foldable into a constant).
  2150. if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  2151. EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  2152. // Emit calculation of the iterations count.
  2153. EmitIgnoredExpr(S.getCalcLastIteration());
  2154. }
  2155. auto &RT = CGM.getOpenMPRuntime();
  2156. bool HasLastprivateClause;
  2157. // Check pre-condition.
  2158. {
  2159. OMPLoopScope PreInitScope(*this, S);
  2160. // Skip the entire loop if we don't meet the precondition.
  2161. // If the condition constant folds and can be elided, avoid emitting the
  2162. // whole loop.
  2163. bool CondConstant;
  2164. llvm::BasicBlock *ContBlock = nullptr;
  2165. if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  2166. if (!CondConstant)
  2167. return false;
  2168. } else {
  2169. auto *ThenBlock = createBasicBlock("omp.precond.then");
  2170. ContBlock = createBasicBlock("omp.precond.end");
  2171. emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
  2172. getProfileCount(&S));
  2173. EmitBlock(ThenBlock);
  2174. incrementProfileCounter(&S);
  2175. }
  2176. bool Ordered = false;
  2177. if (auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
  2178. if (OrderedClause->getNumForLoops())
  2179. RT.emitDoacrossInit(*this, S);
  2180. else
  2181. Ordered = true;
  2182. }
  2183. llvm::DenseSet<const Expr *> EmittedFinals;
  2184. emitAlignedClause(*this, S);
  2185. EmitOMPLinearClauseInit(S);
  2186. // Emit helper vars inits.
  2187. std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
  2188. LValue LB = Bounds.first;
  2189. LValue UB = Bounds.second;
  2190. LValue ST =
  2191. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
  2192. LValue IL =
  2193. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
  2194. // Emit 'then' code.
  2195. {
  2196. OMPPrivateScope LoopScope(*this);
  2197. if (EmitOMPFirstprivateClause(S, LoopScope)) {
  2198. // Emit implicit barrier to synchronize threads and avoid data races on
  2199. // initialization of firstprivate variables and post-update of
  2200. // lastprivate variables.
  2201. CGM.getOpenMPRuntime().emitBarrierCall(
  2202. *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
  2203. /*ForceSimpleCall=*/true);
  2204. }
  2205. EmitOMPPrivateClause(S, LoopScope);
  2206. HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
  2207. EmitOMPReductionClauseInit(S, LoopScope);
  2208. EmitOMPPrivateLoopCounters(S, LoopScope);
  2209. EmitOMPLinearClause(S, LoopScope);
  2210. (void)LoopScope.Privatize();
  2211. // Detect the loop schedule kind and chunk.
  2212. llvm::Value *Chunk = nullptr;
  2213. OpenMPScheduleTy ScheduleKind;
  2214. if (auto *C = S.getSingleClause<OMPScheduleClause>()) {
  2215. ScheduleKind.Schedule = C->getScheduleKind();
  2216. ScheduleKind.M1 = C->getFirstScheduleModifier();
  2217. ScheduleKind.M2 = C->getSecondScheduleModifier();
  2218. if (const auto *Ch = C->getChunkSize()) {
  2219. Chunk = EmitScalarExpr(Ch);
  2220. Chunk = EmitScalarConversion(Chunk, Ch->getType(),
  2221. S.getIterationVariable()->getType(),
  2222. S.getLocStart());
  2223. }
  2224. }
  2225. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  2226. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  2227. // OpenMP 4.5, 2.7.1 Loop Construct, Description.
  2228. // If the static schedule kind is specified or if the ordered clause is
  2229. // specified, and if no monotonic modifier is specified, the effect will
  2230. // be as if the monotonic modifier was specified.
  2231. if (RT.isStaticNonchunked(ScheduleKind.Schedule,
  2232. /* Chunked */ Chunk != nullptr) &&
  2233. !Ordered) {
  2234. if (isOpenMPSimdDirective(S.getDirectiveKind()))
  2235. EmitOMPSimdInit(S, /*IsMonotonic=*/true);
  2236. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  2237. // When no chunk_size is specified, the iteration space is divided into
  2238. // chunks that are approximately equal in size, and at most one chunk is
  2239. // distributed to each thread. Note that the size of the chunks is
  2240. // unspecified in this case.
  2241. RT.emitForStaticInit(*this, S.getLocStart(), ScheduleKind,
  2242. IVSize, IVSigned, Ordered,
  2243. IL.getAddress(), LB.getAddress(),
  2244. UB.getAddress(), ST.getAddress());
  2245. auto LoopExit =
  2246. getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
  2247. // UB = min(UB, GlobalUB);
  2248. EmitIgnoredExpr(S.getEnsureUpperBound());
  2249. // IV = LB;
  2250. EmitIgnoredExpr(S.getInit());
  2251. // while (idx <= UB) { BODY; ++idx; }
  2252. EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
  2253. S.getInc(),
  2254. [&S, LoopExit](CodeGenFunction &CGF) {
  2255. CGF.EmitOMPLoopBody(S, LoopExit);
  2256. CGF.EmitStopPoint(&S);
  2257. },
  2258. [](CodeGenFunction &) {});
  2259. EmitBlock(LoopExit.getBlock());
  2260. // Tell the runtime we are done.
  2261. auto &&CodeGen = [&S](CodeGenFunction &CGF) {
  2262. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
  2263. };
  2264. OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
  2265. } else {
  2266. const bool IsMonotonic =
  2267. Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
  2268. ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
  2269. ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
  2270. ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
  2271. // Emit the outer loop, which requests its work chunk [LB..UB] from
  2272. // runtime and runs the inner loop to process it.
  2273. const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
  2274. ST.getAddress(), IL.getAddress(),
  2275. Chunk, EUB);
  2276. EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
  2277. LoopArguments, CGDispatchBounds);
  2278. }
  2279. if (isOpenMPSimdDirective(S.getDirectiveKind())) {
  2280. EmitOMPSimdFinal(S,
  2281. [&](CodeGenFunction &CGF) -> llvm::Value * {
  2282. return CGF.Builder.CreateIsNotNull(
  2283. CGF.EmitLoadOfScalar(IL, S.getLocStart()));
  2284. });
  2285. }
  2286. EmitOMPReductionClauseFinal(
  2287. S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
  2288. ? /*Parallel and Simd*/ OMPD_parallel_for_simd
  2289. : /*Parallel only*/ OMPD_parallel);
  2290. // Emit post-update of the reduction variables if IsLastIter != 0.
  2291. emitPostUpdateForReductionClause(
  2292. *this, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
  2293. return CGF.Builder.CreateIsNotNull(
  2294. CGF.EmitLoadOfScalar(IL, S.getLocStart()));
  2295. });
  2296. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  2297. if (HasLastprivateClause)
  2298. EmitOMPLastprivateClauseFinal(
  2299. S, isOpenMPSimdDirective(S.getDirectiveKind()),
  2300. Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getLocStart())));
  2301. }
  2302. EmitOMPLinearClauseFinal(S, [&](CodeGenFunction &CGF) -> llvm::Value * {
  2303. return CGF.Builder.CreateIsNotNull(
  2304. CGF.EmitLoadOfScalar(IL, S.getLocStart()));
  2305. });
  2306. // We're now done with the loop, so jump to the continuation block.
  2307. if (ContBlock) {
  2308. EmitBranch(ContBlock);
  2309. EmitBlock(ContBlock, true);
  2310. }
  2311. }
  2312. return HasLastprivateClause;
  2313. }
  2314. /// The following two functions generate expressions for the loop lower
  2315. /// and upper bounds in case of static and dynamic (dispatch) schedule
  2316. /// of the associated 'for' or 'distribute' loop.
  2317. static std::pair<LValue, LValue>
  2318. emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
  2319. const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
  2320. LValue LB =
  2321. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
  2322. LValue UB =
  2323. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
  2324. return {LB, UB};
  2325. }
  2326. /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
  2327. /// consider the lower and upper bound expressions generated by the
  2328. /// worksharing loop support, but we use 0 and the iteration space size as
  2329. /// constants
  2330. static std::pair<llvm::Value *, llvm::Value *>
  2331. emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
  2332. Address LB, Address UB) {
  2333. const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
  2334. const Expr *IVExpr = LS.getIterationVariable();
  2335. const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
  2336. llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
  2337. llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
  2338. return {LBVal, UBVal};
  2339. }
  2340. void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
  2341. bool HasLastprivates = false;
  2342. auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
  2343. PrePostActionTy &) {
  2344. OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
  2345. HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
  2346. emitForLoopBounds,
  2347. emitDispatchForLoopBounds);
  2348. };
  2349. {
  2350. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2351. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
  2352. S.hasCancel());
  2353. }
  2354. // Emit an implicit barrier at the end.
  2355. if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
  2356. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
  2357. }
  2358. }
  2359. void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
  2360. bool HasLastprivates = false;
  2361. auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
  2362. PrePostActionTy &) {
  2363. HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
  2364. emitForLoopBounds,
  2365. emitDispatchForLoopBounds);
  2366. };
  2367. {
  2368. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2369. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
  2370. }
  2371. // Emit an implicit barrier at the end.
  2372. if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) {
  2373. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_for);
  2374. }
  2375. }
  2376. static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
  2377. const Twine &Name,
  2378. llvm::Value *Init = nullptr) {
  2379. auto LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
  2380. if (Init)
  2381. CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
  2382. return LVal;
  2383. }
  2384. void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
  2385. auto *Stmt = cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt();
  2386. auto *CS = dyn_cast<CompoundStmt>(Stmt);
  2387. bool HasLastprivates = false;
  2388. auto &&CodeGen = [&S, Stmt, CS, &HasLastprivates](CodeGenFunction &CGF,
  2389. PrePostActionTy &) {
  2390. auto &C = CGF.CGM.getContext();
  2391. auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  2392. // Emit helper vars inits.
  2393. LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
  2394. CGF.Builder.getInt32(0));
  2395. auto *GlobalUBVal = CS != nullptr ? CGF.Builder.getInt32(CS->size() - 1)
  2396. : CGF.Builder.getInt32(0);
  2397. LValue UB =
  2398. createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
  2399. LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
  2400. CGF.Builder.getInt32(1));
  2401. LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
  2402. CGF.Builder.getInt32(0));
  2403. // Loop counter.
  2404. LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
  2405. OpaqueValueExpr IVRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
  2406. CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
  2407. OpaqueValueExpr UBRefExpr(S.getLocStart(), KmpInt32Ty, VK_LValue);
  2408. CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
  2409. // Generate condition for loop.
  2410. BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
  2411. OK_Ordinary, S.getLocStart(), FPOptions());
  2412. // Increment for loop counter.
  2413. UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
  2414. S.getLocStart());
  2415. auto BodyGen = [Stmt, CS, &S, &IV](CodeGenFunction &CGF) {
  2416. // Iterate through all sections and emit a switch construct:
  2417. // switch (IV) {
  2418. // case 0:
  2419. // <SectionStmt[0]>;
  2420. // break;
  2421. // ...
  2422. // case <NumSection> - 1:
  2423. // <SectionStmt[<NumSection> - 1]>;
  2424. // break;
  2425. // }
  2426. // .omp.sections.exit:
  2427. auto *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
  2428. auto *SwitchStmt = CGF.Builder.CreateSwitch(
  2429. CGF.EmitLoadOfLValue(IV, S.getLocStart()).getScalarVal(), ExitBB,
  2430. CS == nullptr ? 1 : CS->size());
  2431. if (CS) {
  2432. unsigned CaseNumber = 0;
  2433. for (auto *SubStmt : CS->children()) {
  2434. auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
  2435. CGF.EmitBlock(CaseBB);
  2436. SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
  2437. CGF.EmitStmt(SubStmt);
  2438. CGF.EmitBranch(ExitBB);
  2439. ++CaseNumber;
  2440. }
  2441. } else {
  2442. auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
  2443. CGF.EmitBlock(CaseBB);
  2444. SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
  2445. CGF.EmitStmt(Stmt);
  2446. CGF.EmitBranch(ExitBB);
  2447. }
  2448. CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
  2449. };
  2450. CodeGenFunction::OMPPrivateScope LoopScope(CGF);
  2451. if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
  2452. // Emit implicit barrier to synchronize threads and avoid data races on
  2453. // initialization of firstprivate variables and post-update of lastprivate
  2454. // variables.
  2455. CGF.CGM.getOpenMPRuntime().emitBarrierCall(
  2456. CGF, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
  2457. /*ForceSimpleCall=*/true);
  2458. }
  2459. CGF.EmitOMPPrivateClause(S, LoopScope);
  2460. HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  2461. CGF.EmitOMPReductionClauseInit(S, LoopScope);
  2462. (void)LoopScope.Privatize();
  2463. // Emit static non-chunked loop.
  2464. OpenMPScheduleTy ScheduleKind;
  2465. ScheduleKind.Schedule = OMPC_SCHEDULE_static;
  2466. CGF.CGM.getOpenMPRuntime().emitForStaticInit(
  2467. CGF, S.getLocStart(), ScheduleKind, /*IVSize=*/32,
  2468. /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(), LB.getAddress(),
  2469. UB.getAddress(), ST.getAddress());
  2470. // UB = min(UB, GlobalUB);
  2471. auto *UBVal = CGF.EmitLoadOfScalar(UB, S.getLocStart());
  2472. auto *MinUBGlobalUB = CGF.Builder.CreateSelect(
  2473. CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
  2474. CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
  2475. // IV = LB;
  2476. CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getLocStart()), IV);
  2477. // while (idx <= UB) { BODY; ++idx; }
  2478. CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
  2479. [](CodeGenFunction &) {});
  2480. // Tell the runtime we are done.
  2481. auto &&CodeGen = [&S](CodeGenFunction &CGF) {
  2482. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getLocEnd());
  2483. };
  2484. CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
  2485. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  2486. // Emit post-update of the reduction variables if IsLastIter != 0.
  2487. emitPostUpdateForReductionClause(
  2488. CGF, S, [&](CodeGenFunction &CGF) -> llvm::Value * {
  2489. return CGF.Builder.CreateIsNotNull(
  2490. CGF.EmitLoadOfScalar(IL, S.getLocStart()));
  2491. });
  2492. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  2493. if (HasLastprivates)
  2494. CGF.EmitOMPLastprivateClauseFinal(
  2495. S, /*NoFinals=*/false,
  2496. CGF.Builder.CreateIsNotNull(
  2497. CGF.EmitLoadOfScalar(IL, S.getLocStart())));
  2498. };
  2499. bool HasCancel = false;
  2500. if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
  2501. HasCancel = OSD->hasCancel();
  2502. else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
  2503. HasCancel = OPSD->hasCancel();
  2504. OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
  2505. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
  2506. HasCancel);
  2507. // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
  2508. // clause. Otherwise the barrier will be generated by the codegen for the
  2509. // directive.
  2510. if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
  2511. // Emit implicit barrier to synchronize threads and avoid data races on
  2512. // initialization of firstprivate variables.
  2513. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
  2514. OMPD_unknown);
  2515. }
  2516. }
  2517. void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
  2518. {
  2519. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2520. EmitSections(S);
  2521. }
  2522. // Emit an implicit barrier at the end.
  2523. if (!S.getSingleClause<OMPNowaitClause>()) {
  2524. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(),
  2525. OMPD_sections);
  2526. }
  2527. }
  2528. void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
  2529. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2530. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2531. };
  2532. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2533. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
  2534. S.hasCancel());
  2535. }
  2536. void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
  2537. llvm::SmallVector<const Expr *, 8> CopyprivateVars;
  2538. llvm::SmallVector<const Expr *, 8> DestExprs;
  2539. llvm::SmallVector<const Expr *, 8> SrcExprs;
  2540. llvm::SmallVector<const Expr *, 8> AssignmentOps;
  2541. // Check if there are any 'copyprivate' clauses associated with this
  2542. // 'single' construct.
  2543. // Build a list of copyprivate variables along with helper expressions
  2544. // (<source>, <destination>, <destination>=<source> expressions)
  2545. for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
  2546. CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
  2547. DestExprs.append(C->destination_exprs().begin(),
  2548. C->destination_exprs().end());
  2549. SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
  2550. AssignmentOps.append(C->assignment_ops().begin(),
  2551. C->assignment_ops().end());
  2552. }
  2553. // Emit code for 'single' region along with 'copyprivate' clauses
  2554. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2555. Action.Enter(CGF);
  2556. OMPPrivateScope SingleScope(CGF);
  2557. (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
  2558. CGF.EmitOMPPrivateClause(S, SingleScope);
  2559. (void)SingleScope.Privatize();
  2560. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2561. };
  2562. {
  2563. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2564. CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getLocStart(),
  2565. CopyprivateVars, DestExprs,
  2566. SrcExprs, AssignmentOps);
  2567. }
  2568. // Emit an implicit barrier at the end (to avoid data race on firstprivate
  2569. // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
  2570. if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
  2571. CGM.getOpenMPRuntime().emitBarrierCall(
  2572. *this, S.getLocStart(),
  2573. S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
  2574. }
  2575. }
  2576. void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
  2577. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2578. Action.Enter(CGF);
  2579. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2580. };
  2581. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2582. CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getLocStart());
  2583. }
  2584. void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
  2585. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2586. Action.Enter(CGF);
  2587. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2588. };
  2589. Expr *Hint = nullptr;
  2590. if (auto *HintClause = S.getSingleClause<OMPHintClause>())
  2591. Hint = HintClause->getHint();
  2592. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2593. CGM.getOpenMPRuntime().emitCriticalRegion(*this,
  2594. S.getDirectiveName().getAsString(),
  2595. CodeGen, S.getLocStart(), Hint);
  2596. }
  2597. void CodeGenFunction::EmitOMPParallelForDirective(
  2598. const OMPParallelForDirective &S) {
  2599. // Emit directive as a combined directive that consists of two implicit
  2600. // directives: 'parallel' with 'for' directive.
  2601. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2602. OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
  2603. CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
  2604. emitDispatchForLoopBounds);
  2605. };
  2606. emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
  2607. emitEmptyBoundParameters);
  2608. }
  2609. void CodeGenFunction::EmitOMPParallelForSimdDirective(
  2610. const OMPParallelForSimdDirective &S) {
  2611. // Emit directive as a combined directive that consists of two implicit
  2612. // directives: 'parallel' with 'for' directive.
  2613. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2614. CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
  2615. emitDispatchForLoopBounds);
  2616. };
  2617. emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
  2618. emitEmptyBoundParameters);
  2619. }
  2620. void CodeGenFunction::EmitOMPParallelSectionsDirective(
  2621. const OMPParallelSectionsDirective &S) {
  2622. // Emit directive as a combined directive that consists of two implicit
  2623. // directives: 'parallel' with 'sections' directive.
  2624. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2625. CGF.EmitSections(S);
  2626. };
  2627. emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
  2628. emitEmptyBoundParameters);
  2629. }
  2630. void CodeGenFunction::EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
  2631. const RegionCodeGenTy &BodyGen,
  2632. const TaskGenTy &TaskGen,
  2633. OMPTaskDataTy &Data) {
  2634. // Emit outlined function for task construct.
  2635. auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
  2636. auto *I = CS->getCapturedDecl()->param_begin();
  2637. auto *PartId = std::next(I);
  2638. auto *TaskT = std::next(I, 4);
  2639. // Check if the task is final
  2640. if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
  2641. // If the condition constant folds and can be elided, try to avoid emitting
  2642. // the condition and the dead arm of the if/else.
  2643. auto *Cond = Clause->getCondition();
  2644. bool CondConstant;
  2645. if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
  2646. Data.Final.setInt(CondConstant);
  2647. else
  2648. Data.Final.setPointer(EvaluateExprAsBool(Cond));
  2649. } else {
  2650. // By default the task is not final.
  2651. Data.Final.setInt(/*IntVal=*/false);
  2652. }
  2653. // Check if the task has 'priority' clause.
  2654. if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
  2655. auto *Prio = Clause->getPriority();
  2656. Data.Priority.setInt(/*IntVal=*/true);
  2657. Data.Priority.setPointer(EmitScalarConversion(
  2658. EmitScalarExpr(Prio), Prio->getType(),
  2659. getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
  2660. Prio->getExprLoc()));
  2661. }
  2662. // The first function argument for tasks is a thread id, the second one is a
  2663. // part id (0 for tied tasks, >=0 for untied task).
  2664. llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
  2665. // Get list of private variables.
  2666. for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
  2667. auto IRef = C->varlist_begin();
  2668. for (auto *IInit : C->private_copies()) {
  2669. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  2670. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  2671. Data.PrivateVars.push_back(*IRef);
  2672. Data.PrivateCopies.push_back(IInit);
  2673. }
  2674. ++IRef;
  2675. }
  2676. }
  2677. EmittedAsPrivate.clear();
  2678. // Get list of firstprivate variables.
  2679. for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
  2680. auto IRef = C->varlist_begin();
  2681. auto IElemInitRef = C->inits().begin();
  2682. for (auto *IInit : C->private_copies()) {
  2683. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  2684. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  2685. Data.FirstprivateVars.push_back(*IRef);
  2686. Data.FirstprivateCopies.push_back(IInit);
  2687. Data.FirstprivateInits.push_back(*IElemInitRef);
  2688. }
  2689. ++IRef;
  2690. ++IElemInitRef;
  2691. }
  2692. }
  2693. // Get list of lastprivate variables (for taskloops).
  2694. llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
  2695. for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
  2696. auto IRef = C->varlist_begin();
  2697. auto ID = C->destination_exprs().begin();
  2698. for (auto *IInit : C->private_copies()) {
  2699. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  2700. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  2701. Data.LastprivateVars.push_back(*IRef);
  2702. Data.LastprivateCopies.push_back(IInit);
  2703. }
  2704. LastprivateDstsOrigs.insert(
  2705. {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
  2706. cast<DeclRefExpr>(*IRef)});
  2707. ++IRef;
  2708. ++ID;
  2709. }
  2710. }
  2711. // Build list of dependences.
  2712. for (const auto *C : S.getClausesOfKind<OMPDependClause>())
  2713. for (auto *IRef : C->varlists())
  2714. Data.Dependences.push_back(std::make_pair(C->getDependencyKind(), IRef));
  2715. auto &&CodeGen = [&Data, CS, &BodyGen, &LastprivateDstsOrigs](
  2716. CodeGenFunction &CGF, PrePostActionTy &Action) {
  2717. // Set proper addresses for generated private copies.
  2718. OMPPrivateScope Scope(CGF);
  2719. if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
  2720. !Data.LastprivateVars.empty()) {
  2721. auto *CopyFn = CGF.Builder.CreateLoad(
  2722. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(3)));
  2723. auto *PrivatesPtr = CGF.Builder.CreateLoad(
  2724. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(2)));
  2725. // Map privates.
  2726. llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
  2727. llvm::SmallVector<llvm::Value *, 16> CallArgs;
  2728. CallArgs.push_back(PrivatesPtr);
  2729. for (auto *E : Data.PrivateVars) {
  2730. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2731. Address PrivatePtr = CGF.CreateMemTemp(
  2732. CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
  2733. PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
  2734. CallArgs.push_back(PrivatePtr.getPointer());
  2735. }
  2736. for (auto *E : Data.FirstprivateVars) {
  2737. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2738. Address PrivatePtr =
  2739. CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
  2740. ".firstpriv.ptr.addr");
  2741. PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
  2742. CallArgs.push_back(PrivatePtr.getPointer());
  2743. }
  2744. for (auto *E : Data.LastprivateVars) {
  2745. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2746. Address PrivatePtr =
  2747. CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
  2748. ".lastpriv.ptr.addr");
  2749. PrivatePtrs.push_back(std::make_pair(VD, PrivatePtr));
  2750. CallArgs.push_back(PrivatePtr.getPointer());
  2751. }
  2752. CGF.EmitRuntimeCall(CopyFn, CallArgs);
  2753. for (auto &&Pair : LastprivateDstsOrigs) {
  2754. auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
  2755. DeclRefExpr DRE(
  2756. const_cast<VarDecl *>(OrigVD),
  2757. /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
  2758. OrigVD) != nullptr,
  2759. Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
  2760. Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
  2761. return CGF.EmitLValue(&DRE).getAddress();
  2762. });
  2763. }
  2764. for (auto &&Pair : PrivatePtrs) {
  2765. Address Replacement(CGF.Builder.CreateLoad(Pair.second),
  2766. CGF.getContext().getDeclAlign(Pair.first));
  2767. Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
  2768. }
  2769. }
  2770. (void)Scope.Privatize();
  2771. Action.Enter(CGF);
  2772. BodyGen(CGF);
  2773. };
  2774. auto *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
  2775. S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
  2776. Data.NumberOfParts);
  2777. OMPLexicalScope Scope(*this, S);
  2778. TaskGen(*this, OutlinedFn, Data);
  2779. }
  2780. void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
  2781. // Emit outlined function for task construct.
  2782. auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
  2783. auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
  2784. auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  2785. const Expr *IfCond = nullptr;
  2786. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  2787. if (C->getNameModifier() == OMPD_unknown ||
  2788. C->getNameModifier() == OMPD_task) {
  2789. IfCond = C->getCondition();
  2790. break;
  2791. }
  2792. }
  2793. OMPTaskDataTy Data;
  2794. // Check if we should emit tied or untied task.
  2795. Data.Tied = !S.getSingleClause<OMPUntiedClause>();
  2796. auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
  2797. CGF.EmitStmt(CS->getCapturedStmt());
  2798. };
  2799. auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
  2800. IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
  2801. const OMPTaskDataTy &Data) {
  2802. CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getLocStart(), S, OutlinedFn,
  2803. SharedsTy, CapturedStruct, IfCond,
  2804. Data);
  2805. };
  2806. EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
  2807. }
  2808. void CodeGenFunction::EmitOMPTaskyieldDirective(
  2809. const OMPTaskyieldDirective &S) {
  2810. CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getLocStart());
  2811. }
  2812. void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
  2813. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getLocStart(), OMPD_barrier);
  2814. }
  2815. void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
  2816. CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getLocStart());
  2817. }
  2818. void CodeGenFunction::EmitOMPTaskgroupDirective(
  2819. const OMPTaskgroupDirective &S) {
  2820. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2821. Action.Enter(CGF);
  2822. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  2823. };
  2824. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2825. CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getLocStart());
  2826. }
  2827. void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
  2828. CGM.getOpenMPRuntime().emitFlush(*this, [&]() -> ArrayRef<const Expr *> {
  2829. if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) {
  2830. return llvm::makeArrayRef(FlushClause->varlist_begin(),
  2831. FlushClause->varlist_end());
  2832. }
  2833. return llvm::None;
  2834. }(), S.getLocStart());
  2835. }
  2836. void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
  2837. const CodeGenLoopTy &CodeGenLoop,
  2838. Expr *IncExpr) {
  2839. // Emit the loop iteration variable.
  2840. auto IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
  2841. auto IVDecl = cast<VarDecl>(IVExpr->getDecl());
  2842. EmitVarDecl(*IVDecl);
  2843. // Emit the iterations count variable.
  2844. // If it is not a variable, Sema decided to calculate iterations count on each
  2845. // iteration (e.g., it is foldable into a constant).
  2846. if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  2847. EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  2848. // Emit calculation of the iterations count.
  2849. EmitIgnoredExpr(S.getCalcLastIteration());
  2850. }
  2851. auto &RT = CGM.getOpenMPRuntime();
  2852. bool HasLastprivateClause = false;
  2853. // Check pre-condition.
  2854. {
  2855. OMPLoopScope PreInitScope(*this, S);
  2856. // Skip the entire loop if we don't meet the precondition.
  2857. // If the condition constant folds and can be elided, avoid emitting the
  2858. // whole loop.
  2859. bool CondConstant;
  2860. llvm::BasicBlock *ContBlock = nullptr;
  2861. if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  2862. if (!CondConstant)
  2863. return;
  2864. } else {
  2865. auto *ThenBlock = createBasicBlock("omp.precond.then");
  2866. ContBlock = createBasicBlock("omp.precond.end");
  2867. emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
  2868. getProfileCount(&S));
  2869. EmitBlock(ThenBlock);
  2870. incrementProfileCounter(&S);
  2871. }
  2872. // Emit 'then' code.
  2873. {
  2874. // Emit helper vars inits.
  2875. LValue LB = EmitOMPHelperVar(
  2876. *this, cast<DeclRefExpr>(
  2877. (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2878. ? S.getCombinedLowerBoundVariable()
  2879. : S.getLowerBoundVariable())));
  2880. LValue UB = EmitOMPHelperVar(
  2881. *this, cast<DeclRefExpr>(
  2882. (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2883. ? S.getCombinedUpperBoundVariable()
  2884. : S.getUpperBoundVariable())));
  2885. LValue ST =
  2886. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
  2887. LValue IL =
  2888. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
  2889. OMPPrivateScope LoopScope(*this);
  2890. if (EmitOMPFirstprivateClause(S, LoopScope)) {
  2891. // Emit implicit barrier to synchronize threads and avoid data races on
  2892. // initialization of firstprivate variables and post-update of
  2893. // lastprivate variables.
  2894. CGM.getOpenMPRuntime().emitBarrierCall(
  2895. *this, S.getLocStart(), OMPD_unknown, /*EmitChecks=*/false,
  2896. /*ForceSimpleCall=*/true);
  2897. }
  2898. EmitOMPPrivateClause(S, LoopScope);
  2899. HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
  2900. EmitOMPPrivateLoopCounters(S, LoopScope);
  2901. (void)LoopScope.Privatize();
  2902. // Detect the distribute schedule kind and chunk.
  2903. llvm::Value *Chunk = nullptr;
  2904. OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
  2905. if (auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
  2906. ScheduleKind = C->getDistScheduleKind();
  2907. if (const auto *Ch = C->getChunkSize()) {
  2908. Chunk = EmitScalarExpr(Ch);
  2909. Chunk = EmitScalarConversion(Chunk, Ch->getType(),
  2910. S.getIterationVariable()->getType(),
  2911. S.getLocStart());
  2912. }
  2913. }
  2914. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  2915. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  2916. // OpenMP [2.10.8, distribute Construct, Description]
  2917. // If dist_schedule is specified, kind must be static. If specified,
  2918. // iterations are divided into chunks of size chunk_size, chunks are
  2919. // assigned to the teams of the league in a round-robin fashion in the
  2920. // order of the team number. When no chunk_size is specified, the
  2921. // iteration space is divided into chunks that are approximately equal
  2922. // in size, and at most one chunk is distributed to each team of the
  2923. // league. The size of the chunks is unspecified in this case.
  2924. if (RT.isStaticNonchunked(ScheduleKind,
  2925. /* Chunked */ Chunk != nullptr)) {
  2926. RT.emitDistributeStaticInit(*this, S.getLocStart(), ScheduleKind,
  2927. IVSize, IVSigned, /* Ordered = */ false,
  2928. IL.getAddress(), LB.getAddress(),
  2929. UB.getAddress(), ST.getAddress());
  2930. auto LoopExit =
  2931. getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
  2932. // UB = min(UB, GlobalUB);
  2933. EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2934. ? S.getCombinedEnsureUpperBound()
  2935. : S.getEnsureUpperBound());
  2936. // IV = LB;
  2937. EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2938. ? S.getCombinedInit()
  2939. : S.getInit());
  2940. Expr *Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  2941. ? S.getCombinedCond()
  2942. : S.getCond();
  2943. // for distribute alone, codegen
  2944. // while (idx <= UB) { BODY; ++idx; }
  2945. // when combined with 'for' (e.g. as in 'distribute parallel for')
  2946. // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
  2947. EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
  2948. [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
  2949. CodeGenLoop(CGF, S, LoopExit);
  2950. },
  2951. [](CodeGenFunction &) {});
  2952. EmitBlock(LoopExit.getBlock());
  2953. // Tell the runtime we are done.
  2954. RT.emitForStaticFinish(*this, S.getLocStart());
  2955. } else {
  2956. // Emit the outer loop, which requests its work chunk [LB..UB] from
  2957. // runtime and runs the inner loop to process it.
  2958. const OMPLoopArguments LoopArguments = {
  2959. LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
  2960. Chunk};
  2961. EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
  2962. CodeGenLoop);
  2963. }
  2964. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  2965. if (HasLastprivateClause)
  2966. EmitOMPLastprivateClauseFinal(
  2967. S, /*NoFinals=*/false,
  2968. Builder.CreateIsNotNull(
  2969. EmitLoadOfScalar(IL, S.getLocStart())));
  2970. }
  2971. // We're now done with the loop, so jump to the continuation block.
  2972. if (ContBlock) {
  2973. EmitBranch(ContBlock);
  2974. EmitBlock(ContBlock, true);
  2975. }
  2976. }
  2977. }
  2978. void CodeGenFunction::EmitOMPDistributeDirective(
  2979. const OMPDistributeDirective &S) {
  2980. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2981. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  2982. };
  2983. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  2984. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen,
  2985. false);
  2986. }
  2987. static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
  2988. const CapturedStmt *S) {
  2989. CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
  2990. CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
  2991. CGF.CapturedStmtInfo = &CapStmtInfo;
  2992. auto *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
  2993. Fn->addFnAttr(llvm::Attribute::NoInline);
  2994. return Fn;
  2995. }
  2996. void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
  2997. if (!S.getAssociatedStmt()) {
  2998. for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
  2999. CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
  3000. return;
  3001. }
  3002. auto *C = S.getSingleClause<OMPSIMDClause>();
  3003. auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
  3004. PrePostActionTy &Action) {
  3005. if (C) {
  3006. auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
  3007. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  3008. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  3009. auto *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
  3010. CGF.EmitNounwindRuntimeCall(OutlinedFn, CapturedVars);
  3011. } else {
  3012. Action.Enter(CGF);
  3013. CGF.EmitStmt(
  3014. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  3015. }
  3016. };
  3017. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  3018. CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getLocStart(), !C);
  3019. }
  3020. static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
  3021. QualType SrcType, QualType DestType,
  3022. SourceLocation Loc) {
  3023. assert(CGF.hasScalarEvaluationKind(DestType) &&
  3024. "DestType must have scalar evaluation kind.");
  3025. assert(!Val.isAggregate() && "Must be a scalar or complex.");
  3026. return Val.isScalar()
  3027. ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, DestType,
  3028. Loc)
  3029. : CGF.EmitComplexToScalarConversion(Val.getComplexVal(), SrcType,
  3030. DestType, Loc);
  3031. }
  3032. static CodeGenFunction::ComplexPairTy
  3033. convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
  3034. QualType DestType, SourceLocation Loc) {
  3035. assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
  3036. "DestType must have complex evaluation kind.");
  3037. CodeGenFunction::ComplexPairTy ComplexVal;
  3038. if (Val.isScalar()) {
  3039. // Convert the input element to the element type of the complex.
  3040. auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
  3041. auto ScalarVal = CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
  3042. DestElementType, Loc);
  3043. ComplexVal = CodeGenFunction::ComplexPairTy(
  3044. ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
  3045. } else {
  3046. assert(Val.isComplex() && "Must be a scalar or complex.");
  3047. auto SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
  3048. auto DestElementType = DestType->castAs<ComplexType>()->getElementType();
  3049. ComplexVal.first = CGF.EmitScalarConversion(
  3050. Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
  3051. ComplexVal.second = CGF.EmitScalarConversion(
  3052. Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
  3053. }
  3054. return ComplexVal;
  3055. }
  3056. static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
  3057. LValue LVal, RValue RVal) {
  3058. if (LVal.isGlobalReg()) {
  3059. CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
  3060. } else {
  3061. CGF.EmitAtomicStore(RVal, LVal,
  3062. IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
  3063. : llvm::AtomicOrdering::Monotonic,
  3064. LVal.isVolatile(), /*IsInit=*/false);
  3065. }
  3066. }
  3067. void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
  3068. QualType RValTy, SourceLocation Loc) {
  3069. switch (getEvaluationKind(LVal.getType())) {
  3070. case TEK_Scalar:
  3071. EmitStoreThroughLValue(RValue::get(convertToScalarValue(
  3072. *this, RVal, RValTy, LVal.getType(), Loc)),
  3073. LVal);
  3074. break;
  3075. case TEK_Complex:
  3076. EmitStoreOfComplex(
  3077. convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
  3078. /*isInit=*/false);
  3079. break;
  3080. case TEK_Aggregate:
  3081. llvm_unreachable("Must be a scalar or complex.");
  3082. }
  3083. }
  3084. static void EmitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
  3085. const Expr *X, const Expr *V,
  3086. SourceLocation Loc) {
  3087. // v = x;
  3088. assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
  3089. assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
  3090. LValue XLValue = CGF.EmitLValue(X);
  3091. LValue VLValue = CGF.EmitLValue(V);
  3092. RValue Res = XLValue.isGlobalReg()
  3093. ? CGF.EmitLoadOfLValue(XLValue, Loc)
  3094. : CGF.EmitAtomicLoad(
  3095. XLValue, Loc,
  3096. IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
  3097. : llvm::AtomicOrdering::Monotonic,
  3098. XLValue.isVolatile());
  3099. // OpenMP, 2.12.6, atomic Construct
  3100. // Any atomic construct with a seq_cst clause forces the atomically
  3101. // performed operation to include an implicit flush operation without a
  3102. // list.
  3103. if (IsSeqCst)
  3104. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
  3105. CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
  3106. }
  3107. static void EmitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
  3108. const Expr *X, const Expr *E,
  3109. SourceLocation Loc) {
  3110. // x = expr;
  3111. assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
  3112. emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
  3113. // OpenMP, 2.12.6, atomic Construct
  3114. // Any atomic construct with a seq_cst clause forces the atomically
  3115. // performed operation to include an implicit flush operation without a
  3116. // list.
  3117. if (IsSeqCst)
  3118. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
  3119. }
  3120. static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
  3121. RValue Update,
  3122. BinaryOperatorKind BO,
  3123. llvm::AtomicOrdering AO,
  3124. bool IsXLHSInRHSPart) {
  3125. auto &Context = CGF.CGM.getContext();
  3126. // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
  3127. // expression is simple and atomic is allowed for the given type for the
  3128. // target platform.
  3129. if (BO == BO_Comma || !Update.isScalar() ||
  3130. !Update.getScalarVal()->getType()->isIntegerTy() ||
  3131. !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
  3132. (Update.getScalarVal()->getType() !=
  3133. X.getAddress().getElementType())) ||
  3134. !X.getAddress().getElementType()->isIntegerTy() ||
  3135. !Context.getTargetInfo().hasBuiltinAtomic(
  3136. Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
  3137. return std::make_pair(false, RValue::get(nullptr));
  3138. llvm::AtomicRMWInst::BinOp RMWOp;
  3139. switch (BO) {
  3140. case BO_Add:
  3141. RMWOp = llvm::AtomicRMWInst::Add;
  3142. break;
  3143. case BO_Sub:
  3144. if (!IsXLHSInRHSPart)
  3145. return std::make_pair(false, RValue::get(nullptr));
  3146. RMWOp = llvm::AtomicRMWInst::Sub;
  3147. break;
  3148. case BO_And:
  3149. RMWOp = llvm::AtomicRMWInst::And;
  3150. break;
  3151. case BO_Or:
  3152. RMWOp = llvm::AtomicRMWInst::Or;
  3153. break;
  3154. case BO_Xor:
  3155. RMWOp = llvm::AtomicRMWInst::Xor;
  3156. break;
  3157. case BO_LT:
  3158. RMWOp = X.getType()->hasSignedIntegerRepresentation()
  3159. ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
  3160. : llvm::AtomicRMWInst::Max)
  3161. : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
  3162. : llvm::AtomicRMWInst::UMax);
  3163. break;
  3164. case BO_GT:
  3165. RMWOp = X.getType()->hasSignedIntegerRepresentation()
  3166. ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
  3167. : llvm::AtomicRMWInst::Min)
  3168. : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
  3169. : llvm::AtomicRMWInst::UMin);
  3170. break;
  3171. case BO_Assign:
  3172. RMWOp = llvm::AtomicRMWInst::Xchg;
  3173. break;
  3174. case BO_Mul:
  3175. case BO_Div:
  3176. case BO_Rem:
  3177. case BO_Shl:
  3178. case BO_Shr:
  3179. case BO_LAnd:
  3180. case BO_LOr:
  3181. return std::make_pair(false, RValue::get(nullptr));
  3182. case BO_PtrMemD:
  3183. case BO_PtrMemI:
  3184. case BO_LE:
  3185. case BO_GE:
  3186. case BO_EQ:
  3187. case BO_NE:
  3188. case BO_AddAssign:
  3189. case BO_SubAssign:
  3190. case BO_AndAssign:
  3191. case BO_OrAssign:
  3192. case BO_XorAssign:
  3193. case BO_MulAssign:
  3194. case BO_DivAssign:
  3195. case BO_RemAssign:
  3196. case BO_ShlAssign:
  3197. case BO_ShrAssign:
  3198. case BO_Comma:
  3199. llvm_unreachable("Unsupported atomic update operation");
  3200. }
  3201. auto *UpdateVal = Update.getScalarVal();
  3202. if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
  3203. UpdateVal = CGF.Builder.CreateIntCast(
  3204. IC, X.getAddress().getElementType(),
  3205. X.getType()->hasSignedIntegerRepresentation());
  3206. }
  3207. auto *Res = CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
  3208. return std::make_pair(true, RValue::get(Res));
  3209. }
  3210. std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
  3211. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  3212. llvm::AtomicOrdering AO, SourceLocation Loc,
  3213. const llvm::function_ref<RValue(RValue)> &CommonGen) {
  3214. // Update expressions are allowed to have the following forms:
  3215. // x binop= expr; -> xrval + expr;
  3216. // x++, ++x -> xrval + 1;
  3217. // x--, --x -> xrval - 1;
  3218. // x = x binop expr; -> xrval binop expr
  3219. // x = expr Op x; - > expr binop xrval;
  3220. auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
  3221. if (!Res.first) {
  3222. if (X.isGlobalReg()) {
  3223. // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
  3224. // 'xrval'.
  3225. EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
  3226. } else {
  3227. // Perform compare-and-swap procedure.
  3228. EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
  3229. }
  3230. }
  3231. return Res;
  3232. }
  3233. static void EmitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
  3234. const Expr *X, const Expr *E,
  3235. const Expr *UE, bool IsXLHSInRHSPart,
  3236. SourceLocation Loc) {
  3237. assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
  3238. "Update expr in 'atomic update' must be a binary operator.");
  3239. auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
  3240. // Update expressions are allowed to have the following forms:
  3241. // x binop= expr; -> xrval + expr;
  3242. // x++, ++x -> xrval + 1;
  3243. // x--, --x -> xrval - 1;
  3244. // x = x binop expr; -> xrval binop expr
  3245. // x = expr Op x; - > expr binop xrval;
  3246. assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
  3247. LValue XLValue = CGF.EmitLValue(X);
  3248. RValue ExprRValue = CGF.EmitAnyExpr(E);
  3249. auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
  3250. : llvm::AtomicOrdering::Monotonic;
  3251. auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
  3252. auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
  3253. auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
  3254. auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
  3255. auto Gen =
  3256. [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) -> RValue {
  3257. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  3258. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
  3259. return CGF.EmitAnyExpr(UE);
  3260. };
  3261. (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
  3262. XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
  3263. // OpenMP, 2.12.6, atomic Construct
  3264. // Any atomic construct with a seq_cst clause forces the atomically
  3265. // performed operation to include an implicit flush operation without a
  3266. // list.
  3267. if (IsSeqCst)
  3268. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
  3269. }
  3270. static RValue convertToType(CodeGenFunction &CGF, RValue Value,
  3271. QualType SourceType, QualType ResType,
  3272. SourceLocation Loc) {
  3273. switch (CGF.getEvaluationKind(ResType)) {
  3274. case TEK_Scalar:
  3275. return RValue::get(
  3276. convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
  3277. case TEK_Complex: {
  3278. auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
  3279. return RValue::getComplex(Res.first, Res.second);
  3280. }
  3281. case TEK_Aggregate:
  3282. break;
  3283. }
  3284. llvm_unreachable("Must be a scalar or complex.");
  3285. }
  3286. static void EmitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
  3287. bool IsPostfixUpdate, const Expr *V,
  3288. const Expr *X, const Expr *E,
  3289. const Expr *UE, bool IsXLHSInRHSPart,
  3290. SourceLocation Loc) {
  3291. assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
  3292. assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
  3293. RValue NewVVal;
  3294. LValue VLValue = CGF.EmitLValue(V);
  3295. LValue XLValue = CGF.EmitLValue(X);
  3296. RValue ExprRValue = CGF.EmitAnyExpr(E);
  3297. auto AO = IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
  3298. : llvm::AtomicOrdering::Monotonic;
  3299. QualType NewVValType;
  3300. if (UE) {
  3301. // 'x' is updated with some additional value.
  3302. assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
  3303. "Update expr in 'atomic capture' must be a binary operator.");
  3304. auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
  3305. // Update expressions are allowed to have the following forms:
  3306. // x binop= expr; -> xrval + expr;
  3307. // x++, ++x -> xrval + 1;
  3308. // x--, --x -> xrval - 1;
  3309. // x = x binop expr; -> xrval binop expr
  3310. // x = expr Op x; - > expr binop xrval;
  3311. auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
  3312. auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
  3313. auto *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
  3314. NewVValType = XRValExpr->getType();
  3315. auto *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
  3316. auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
  3317. IsPostfixUpdate](RValue XRValue) -> RValue {
  3318. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  3319. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
  3320. RValue Res = CGF.EmitAnyExpr(UE);
  3321. NewVVal = IsPostfixUpdate ? XRValue : Res;
  3322. return Res;
  3323. };
  3324. auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
  3325. XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
  3326. if (Res.first) {
  3327. // 'atomicrmw' instruction was generated.
  3328. if (IsPostfixUpdate) {
  3329. // Use old value from 'atomicrmw'.
  3330. NewVVal = Res.second;
  3331. } else {
  3332. // 'atomicrmw' does not provide new value, so evaluate it using old
  3333. // value of 'x'.
  3334. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  3335. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
  3336. NewVVal = CGF.EmitAnyExpr(UE);
  3337. }
  3338. }
  3339. } else {
  3340. // 'x' is simply rewritten with some 'expr'.
  3341. NewVValType = X->getType().getNonReferenceType();
  3342. ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
  3343. X->getType().getNonReferenceType(), Loc);
  3344. auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) -> RValue {
  3345. NewVVal = XRValue;
  3346. return ExprRValue;
  3347. };
  3348. // Try to perform atomicrmw xchg, otherwise simple exchange.
  3349. auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
  3350. XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
  3351. Loc, Gen);
  3352. if (Res.first) {
  3353. // 'atomicrmw' instruction was generated.
  3354. NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
  3355. }
  3356. }
  3357. // Emit post-update store to 'v' of old/new 'x' value.
  3358. CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
  3359. // OpenMP, 2.12.6, atomic Construct
  3360. // Any atomic construct with a seq_cst clause forces the atomically
  3361. // performed operation to include an implicit flush operation without a
  3362. // list.
  3363. if (IsSeqCst)
  3364. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
  3365. }
  3366. static void EmitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
  3367. bool IsSeqCst, bool IsPostfixUpdate,
  3368. const Expr *X, const Expr *V, const Expr *E,
  3369. const Expr *UE, bool IsXLHSInRHSPart,
  3370. SourceLocation Loc) {
  3371. switch (Kind) {
  3372. case OMPC_read:
  3373. EmitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
  3374. break;
  3375. case OMPC_write:
  3376. EmitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
  3377. break;
  3378. case OMPC_unknown:
  3379. case OMPC_update:
  3380. EmitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
  3381. break;
  3382. case OMPC_capture:
  3383. EmitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
  3384. IsXLHSInRHSPart, Loc);
  3385. break;
  3386. case OMPC_if:
  3387. case OMPC_final:
  3388. case OMPC_num_threads:
  3389. case OMPC_private:
  3390. case OMPC_firstprivate:
  3391. case OMPC_lastprivate:
  3392. case OMPC_reduction:
  3393. case OMPC_safelen:
  3394. case OMPC_simdlen:
  3395. case OMPC_collapse:
  3396. case OMPC_default:
  3397. case OMPC_seq_cst:
  3398. case OMPC_shared:
  3399. case OMPC_linear:
  3400. case OMPC_aligned:
  3401. case OMPC_copyin:
  3402. case OMPC_copyprivate:
  3403. case OMPC_flush:
  3404. case OMPC_proc_bind:
  3405. case OMPC_schedule:
  3406. case OMPC_ordered:
  3407. case OMPC_nowait:
  3408. case OMPC_untied:
  3409. case OMPC_threadprivate:
  3410. case OMPC_depend:
  3411. case OMPC_mergeable:
  3412. case OMPC_device:
  3413. case OMPC_threads:
  3414. case OMPC_simd:
  3415. case OMPC_map:
  3416. case OMPC_num_teams:
  3417. case OMPC_thread_limit:
  3418. case OMPC_priority:
  3419. case OMPC_grainsize:
  3420. case OMPC_nogroup:
  3421. case OMPC_num_tasks:
  3422. case OMPC_hint:
  3423. case OMPC_dist_schedule:
  3424. case OMPC_defaultmap:
  3425. case OMPC_uniform:
  3426. case OMPC_to:
  3427. case OMPC_from:
  3428. case OMPC_use_device_ptr:
  3429. case OMPC_is_device_ptr:
  3430. llvm_unreachable("Clause is not allowed in 'omp atomic'.");
  3431. }
  3432. }
  3433. void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
  3434. bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
  3435. OpenMPClauseKind Kind = OMPC_unknown;
  3436. for (auto *C : S.clauses()) {
  3437. // Find first clause (skip seq_cst clause, if it is first).
  3438. if (C->getClauseKind() != OMPC_seq_cst) {
  3439. Kind = C->getClauseKind();
  3440. break;
  3441. }
  3442. }
  3443. const auto *CS =
  3444. S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  3445. if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
  3446. enterFullExpression(EWC);
  3447. }
  3448. // Processing for statements under 'atomic capture'.
  3449. if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
  3450. for (const auto *C : Compound->body()) {
  3451. if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
  3452. enterFullExpression(EWC);
  3453. }
  3454. }
  3455. }
  3456. auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
  3457. PrePostActionTy &) {
  3458. CGF.EmitStopPoint(CS);
  3459. EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
  3460. S.getV(), S.getExpr(), S.getUpdateExpr(),
  3461. S.isXLHSInRHSPart(), S.getLocStart());
  3462. };
  3463. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  3464. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
  3465. }
  3466. static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
  3467. const OMPExecutableDirective &S,
  3468. const RegionCodeGenTy &CodeGen) {
  3469. assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
  3470. CodeGenModule &CGM = CGF.CGM;
  3471. const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
  3472. llvm::Function *Fn = nullptr;
  3473. llvm::Constant *FnID = nullptr;
  3474. const Expr *IfCond = nullptr;
  3475. // Check for the at most one if clause associated with the target region.
  3476. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  3477. if (C->getNameModifier() == OMPD_unknown ||
  3478. C->getNameModifier() == OMPD_target) {
  3479. IfCond = C->getCondition();
  3480. break;
  3481. }
  3482. }
  3483. // Check if we have any device clause associated with the directive.
  3484. const Expr *Device = nullptr;
  3485. if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
  3486. Device = C->getDevice();
  3487. }
  3488. // Check if we have an if clause whose conditional always evaluates to false
  3489. // or if we do not have any targets specified. If so the target region is not
  3490. // an offload entry point.
  3491. bool IsOffloadEntry = true;
  3492. if (IfCond) {
  3493. bool Val;
  3494. if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
  3495. IsOffloadEntry = false;
  3496. }
  3497. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3498. IsOffloadEntry = false;
  3499. assert(CGF.CurFuncDecl && "No parent declaration for target region!");
  3500. StringRef ParentName;
  3501. // In case we have Ctors/Dtors we use the complete type variant to produce
  3502. // the mangling of the device outlined kernel.
  3503. if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
  3504. ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
  3505. else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
  3506. ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
  3507. else
  3508. ParentName =
  3509. CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
  3510. // Emit target region as a standalone region.
  3511. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
  3512. IsOffloadEntry, CodeGen);
  3513. OMPLexicalScope Scope(CGF, S);
  3514. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  3515. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  3516. CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
  3517. CapturedVars);
  3518. }
  3519. static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
  3520. PrePostActionTy &Action) {
  3521. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  3522. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3523. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3524. (void)PrivateScope.Privatize();
  3525. Action.Enter(CGF);
  3526. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  3527. }
  3528. void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
  3529. StringRef ParentName,
  3530. const OMPTargetDirective &S) {
  3531. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3532. emitTargetRegion(CGF, S, Action);
  3533. };
  3534. llvm::Function *Fn;
  3535. llvm::Constant *Addr;
  3536. // Emit target region as a standalone region.
  3537. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3538. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3539. assert(Fn && Addr && "Target device function emission failed.");
  3540. }
  3541. void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
  3542. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3543. emitTargetRegion(CGF, S, Action);
  3544. };
  3545. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3546. }
  3547. static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
  3548. const OMPExecutableDirective &S,
  3549. OpenMPDirectiveKind InnermostKind,
  3550. const RegionCodeGenTy &CodeGen) {
  3551. const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
  3552. auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
  3553. S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
  3554. const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
  3555. const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
  3556. if (NT || TL) {
  3557. Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
  3558. Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
  3559. CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
  3560. S.getLocStart());
  3561. }
  3562. OMPTeamsScope Scope(CGF, S);
  3563. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  3564. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  3565. CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
  3566. CapturedVars);
  3567. }
  3568. void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
  3569. // Emit teams region as a standalone region.
  3570. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3571. OMPPrivateScope PrivateScope(CGF);
  3572. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3573. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3574. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3575. (void)PrivateScope.Privatize();
  3576. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  3577. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  3578. };
  3579. emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
  3580. emitPostUpdateForReductionClause(
  3581. *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
  3582. }
  3583. static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
  3584. const OMPTargetTeamsDirective &S) {
  3585. auto *CS = S.getCapturedStmt(OMPD_teams);
  3586. Action.Enter(CGF);
  3587. auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
  3588. // TODO: Add support for clauses.
  3589. CGF.EmitStmt(CS->getCapturedStmt());
  3590. };
  3591. emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
  3592. }
  3593. void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
  3594. CodeGenModule &CGM, StringRef ParentName,
  3595. const OMPTargetTeamsDirective &S) {
  3596. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3597. emitTargetTeamsRegion(CGF, Action, S);
  3598. };
  3599. llvm::Function *Fn;
  3600. llvm::Constant *Addr;
  3601. // Emit target region as a standalone region.
  3602. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3603. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3604. assert(Fn && Addr && "Target device function emission failed.");
  3605. }
  3606. void CodeGenFunction::EmitOMPTargetTeamsDirective(
  3607. const OMPTargetTeamsDirective &S) {
  3608. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3609. emitTargetTeamsRegion(CGF, Action, S);
  3610. };
  3611. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3612. }
  3613. void CodeGenFunction::EmitOMPCancellationPointDirective(
  3614. const OMPCancellationPointDirective &S) {
  3615. CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
  3616. S.getCancelRegion());
  3617. }
  3618. void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
  3619. const Expr *IfCond = nullptr;
  3620. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  3621. if (C->getNameModifier() == OMPD_unknown ||
  3622. C->getNameModifier() == OMPD_cancel) {
  3623. IfCond = C->getCondition();
  3624. break;
  3625. }
  3626. }
  3627. CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
  3628. S.getCancelRegion());
  3629. }
  3630. CodeGenFunction::JumpDest
  3631. CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
  3632. if (Kind == OMPD_parallel || Kind == OMPD_task ||
  3633. Kind == OMPD_target_parallel)
  3634. return ReturnBlock;
  3635. assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
  3636. Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
  3637. Kind == OMPD_distribute_parallel_for ||
  3638. Kind == OMPD_target_parallel_for);
  3639. return OMPCancelStack.getExitBlock();
  3640. }
  3641. void CodeGenFunction::EmitOMPUseDevicePtrClause(
  3642. const OMPClause &NC, OMPPrivateScope &PrivateScope,
  3643. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
  3644. const auto &C = cast<OMPUseDevicePtrClause>(NC);
  3645. auto OrigVarIt = C.varlist_begin();
  3646. auto InitIt = C.inits().begin();
  3647. for (auto PvtVarIt : C.private_copies()) {
  3648. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
  3649. auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
  3650. auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
  3651. // In order to identify the right initializer we need to match the
  3652. // declaration used by the mapping logic. In some cases we may get
  3653. // OMPCapturedExprDecl that refers to the original declaration.
  3654. const ValueDecl *MatchingVD = OrigVD;
  3655. if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
  3656. // OMPCapturedExprDecl are used to privative fields of the current
  3657. // structure.
  3658. auto *ME = cast<MemberExpr>(OED->getInit());
  3659. assert(isa<CXXThisExpr>(ME->getBase()) &&
  3660. "Base should be the current struct!");
  3661. MatchingVD = ME->getMemberDecl();
  3662. }
  3663. // If we don't have information about the current list item, move on to
  3664. // the next one.
  3665. auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
  3666. if (InitAddrIt == CaptureDeviceAddrMap.end())
  3667. continue;
  3668. bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
  3669. // Initialize the temporary initialization variable with the address we
  3670. // get from the runtime library. We have to cast the source address
  3671. // because it is always a void *. References are materialized in the
  3672. // privatization scope, so the initialization here disregards the fact
  3673. // the original variable is a reference.
  3674. QualType AddrQTy =
  3675. getContext().getPointerType(OrigVD->getType().getNonReferenceType());
  3676. llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
  3677. Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
  3678. setAddrOfLocalVar(InitVD, InitAddr);
  3679. // Emit private declaration, it will be initialized by the value we
  3680. // declaration we just added to the local declarations map.
  3681. EmitDecl(*PvtVD);
  3682. // The initialization variables reached its purpose in the emission
  3683. // ofthe previous declaration, so we don't need it anymore.
  3684. LocalDeclMap.erase(InitVD);
  3685. // Return the address of the private variable.
  3686. return GetAddrOfLocalVar(PvtVD);
  3687. });
  3688. assert(IsRegistered && "firstprivate var already registered as private");
  3689. // Silence the warning about unused variable.
  3690. (void)IsRegistered;
  3691. ++OrigVarIt;
  3692. ++InitIt;
  3693. }
  3694. }
  3695. // Generate the instructions for '#pragma omp target data' directive.
  3696. void CodeGenFunction::EmitOMPTargetDataDirective(
  3697. const OMPTargetDataDirective &S) {
  3698. CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
  3699. // Create a pre/post action to signal the privatization of the device pointer.
  3700. // This action can be replaced by the OpenMP runtime code generation to
  3701. // deactivate privatization.
  3702. bool PrivatizeDevicePointers = false;
  3703. class DevicePointerPrivActionTy : public PrePostActionTy {
  3704. bool &PrivatizeDevicePointers;
  3705. public:
  3706. explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
  3707. : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
  3708. void Enter(CodeGenFunction &CGF) override {
  3709. PrivatizeDevicePointers = true;
  3710. }
  3711. };
  3712. DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
  3713. auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
  3714. CodeGenFunction &CGF, PrePostActionTy &Action) {
  3715. auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3716. CGF.EmitStmt(
  3717. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  3718. };
  3719. // Codegen that selects wheather to generate the privatization code or not.
  3720. auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
  3721. &InnermostCodeGen](CodeGenFunction &CGF,
  3722. PrePostActionTy &Action) {
  3723. RegionCodeGenTy RCG(InnermostCodeGen);
  3724. PrivatizeDevicePointers = false;
  3725. // Call the pre-action to change the status of PrivatizeDevicePointers if
  3726. // needed.
  3727. Action.Enter(CGF);
  3728. if (PrivatizeDevicePointers) {
  3729. OMPPrivateScope PrivateScope(CGF);
  3730. // Emit all instances of the use_device_ptr clause.
  3731. for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
  3732. CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
  3733. Info.CaptureDeviceAddrMap);
  3734. (void)PrivateScope.Privatize();
  3735. RCG(CGF);
  3736. } else
  3737. RCG(CGF);
  3738. };
  3739. // Forward the provided action to the privatization codegen.
  3740. RegionCodeGenTy PrivRCG(PrivCodeGen);
  3741. PrivRCG.setAction(Action);
  3742. // Notwithstanding the body of the region is emitted as inlined directive,
  3743. // we don't use an inline scope as changes in the references inside the
  3744. // region are expected to be visible outside, so we do not privative them.
  3745. OMPLexicalScope Scope(CGF, S);
  3746. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
  3747. PrivRCG);
  3748. };
  3749. RegionCodeGenTy RCG(CodeGen);
  3750. // If we don't have target devices, don't bother emitting the data mapping
  3751. // code.
  3752. if (CGM.getLangOpts().OMPTargetTriples.empty()) {
  3753. RCG(*this);
  3754. return;
  3755. }
  3756. // Check if we have any if clause associated with the directive.
  3757. const Expr *IfCond = nullptr;
  3758. if (auto *C = S.getSingleClause<OMPIfClause>())
  3759. IfCond = C->getCondition();
  3760. // Check if we have any device clause associated with the directive.
  3761. const Expr *Device = nullptr;
  3762. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3763. Device = C->getDevice();
  3764. // Set the action to signal privatization of device pointers.
  3765. RCG.setAction(PrivAction);
  3766. // Emit region code.
  3767. CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
  3768. Info);
  3769. }
  3770. void CodeGenFunction::EmitOMPTargetEnterDataDirective(
  3771. const OMPTargetEnterDataDirective &S) {
  3772. // If we don't have target devices, don't bother emitting the data mapping
  3773. // code.
  3774. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3775. return;
  3776. // Check if we have any if clause associated with the directive.
  3777. const Expr *IfCond = nullptr;
  3778. if (auto *C = S.getSingleClause<OMPIfClause>())
  3779. IfCond = C->getCondition();
  3780. // Check if we have any device clause associated with the directive.
  3781. const Expr *Device = nullptr;
  3782. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3783. Device = C->getDevice();
  3784. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  3785. }
  3786. void CodeGenFunction::EmitOMPTargetExitDataDirective(
  3787. const OMPTargetExitDataDirective &S) {
  3788. // If we don't have target devices, don't bother emitting the data mapping
  3789. // code.
  3790. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3791. return;
  3792. // Check if we have any if clause associated with the directive.
  3793. const Expr *IfCond = nullptr;
  3794. if (auto *C = S.getSingleClause<OMPIfClause>())
  3795. IfCond = C->getCondition();
  3796. // Check if we have any device clause associated with the directive.
  3797. const Expr *Device = nullptr;
  3798. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3799. Device = C->getDevice();
  3800. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  3801. }
  3802. static void emitTargetParallelRegion(CodeGenFunction &CGF,
  3803. const OMPTargetParallelDirective &S,
  3804. PrePostActionTy &Action) {
  3805. // Get the captured statement associated with the 'parallel' region.
  3806. auto *CS = S.getCapturedStmt(OMPD_parallel);
  3807. Action.Enter(CGF);
  3808. auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
  3809. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  3810. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3811. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3812. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3813. (void)PrivateScope.Privatize();
  3814. // TODO: Add support for clauses.
  3815. CGF.EmitStmt(CS->getCapturedStmt());
  3816. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  3817. };
  3818. emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
  3819. emitEmptyBoundParameters);
  3820. emitPostUpdateForReductionClause(
  3821. CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
  3822. }
  3823. void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
  3824. CodeGenModule &CGM, StringRef ParentName,
  3825. const OMPTargetParallelDirective &S) {
  3826. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3827. emitTargetParallelRegion(CGF, S, Action);
  3828. };
  3829. llvm::Function *Fn;
  3830. llvm::Constant *Addr;
  3831. // Emit target region as a standalone region.
  3832. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3833. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3834. assert(Fn && Addr && "Target device function emission failed.");
  3835. }
  3836. void CodeGenFunction::EmitOMPTargetParallelDirective(
  3837. const OMPTargetParallelDirective &S) {
  3838. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3839. emitTargetParallelRegion(CGF, S, Action);
  3840. };
  3841. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3842. }
  3843. void CodeGenFunction::EmitOMPTargetParallelForDirective(
  3844. const OMPTargetParallelForDirective &S) {
  3845. // TODO: codegen for target parallel for.
  3846. }
  3847. /// Emit a helper variable and return corresponding lvalue.
  3848. static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
  3849. const ImplicitParamDecl *PVD,
  3850. CodeGenFunction::OMPPrivateScope &Privates) {
  3851. auto *VDecl = cast<VarDecl>(Helper->getDecl());
  3852. Privates.addPrivate(
  3853. VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
  3854. }
  3855. void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
  3856. assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
  3857. // Emit outlined function for task construct.
  3858. auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
  3859. auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
  3860. auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  3861. const Expr *IfCond = nullptr;
  3862. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  3863. if (C->getNameModifier() == OMPD_unknown ||
  3864. C->getNameModifier() == OMPD_taskloop) {
  3865. IfCond = C->getCondition();
  3866. break;
  3867. }
  3868. }
  3869. OMPTaskDataTy Data;
  3870. // Check if taskloop must be emitted without taskgroup.
  3871. Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
  3872. // TODO: Check if we should emit tied or untied task.
  3873. Data.Tied = true;
  3874. // Set scheduling for taskloop
  3875. if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
  3876. // grainsize clause
  3877. Data.Schedule.setInt(/*IntVal=*/false);
  3878. Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
  3879. } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
  3880. // num_tasks clause
  3881. Data.Schedule.setInt(/*IntVal=*/true);
  3882. Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
  3883. }
  3884. auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
  3885. // if (PreCond) {
  3886. // for (IV in 0..LastIteration) BODY;
  3887. // <Final counter/linear vars updates>;
  3888. // }
  3889. //
  3890. // Emit: if (PreCond) - begin.
  3891. // If the condition constant folds and can be elided, avoid emitting the
  3892. // whole loop.
  3893. bool CondConstant;
  3894. llvm::BasicBlock *ContBlock = nullptr;
  3895. OMPLoopScope PreInitScope(CGF, S);
  3896. if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  3897. if (!CondConstant)
  3898. return;
  3899. } else {
  3900. auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
  3901. ContBlock = CGF.createBasicBlock("taskloop.if.end");
  3902. emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
  3903. CGF.getProfileCount(&S));
  3904. CGF.EmitBlock(ThenBlock);
  3905. CGF.incrementProfileCounter(&S);
  3906. }
  3907. if (isOpenMPSimdDirective(S.getDirectiveKind()))
  3908. CGF.EmitOMPSimdInit(S);
  3909. OMPPrivateScope LoopScope(CGF);
  3910. // Emit helper vars inits.
  3911. enum { LowerBound = 5, UpperBound, Stride, LastIter };
  3912. auto *I = CS->getCapturedDecl()->param_begin();
  3913. auto *LBP = std::next(I, LowerBound);
  3914. auto *UBP = std::next(I, UpperBound);
  3915. auto *STP = std::next(I, Stride);
  3916. auto *LIP = std::next(I, LastIter);
  3917. mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
  3918. LoopScope);
  3919. mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
  3920. LoopScope);
  3921. mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
  3922. mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
  3923. LoopScope);
  3924. CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
  3925. bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  3926. (void)LoopScope.Privatize();
  3927. // Emit the loop iteration variable.
  3928. const Expr *IVExpr = S.getIterationVariable();
  3929. const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
  3930. CGF.EmitVarDecl(*IVDecl);
  3931. CGF.EmitIgnoredExpr(S.getInit());
  3932. // Emit the iterations count variable.
  3933. // If it is not a variable, Sema decided to calculate iterations count on
  3934. // each iteration (e.g., it is foldable into a constant).
  3935. if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  3936. CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  3937. // Emit calculation of the iterations count.
  3938. CGF.EmitIgnoredExpr(S.getCalcLastIteration());
  3939. }
  3940. CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
  3941. S.getInc(),
  3942. [&S](CodeGenFunction &CGF) {
  3943. CGF.EmitOMPLoopBody(S, JumpDest());
  3944. CGF.EmitStopPoint(&S);
  3945. },
  3946. [](CodeGenFunction &) {});
  3947. // Emit: if (PreCond) - end.
  3948. if (ContBlock) {
  3949. CGF.EmitBranch(ContBlock);
  3950. CGF.EmitBlock(ContBlock, true);
  3951. }
  3952. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  3953. if (HasLastprivateClause) {
  3954. CGF.EmitOMPLastprivateClauseFinal(
  3955. S, isOpenMPSimdDirective(S.getDirectiveKind()),
  3956. CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
  3957. CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
  3958. (*LIP)->getType(), S.getLocStart())));
  3959. }
  3960. };
  3961. auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
  3962. IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
  3963. const OMPTaskDataTy &Data) {
  3964. auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
  3965. OMPLoopScope PreInitScope(CGF, S);
  3966. CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
  3967. OutlinedFn, SharedsTy,
  3968. CapturedStruct, IfCond, Data);
  3969. };
  3970. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
  3971. CodeGen);
  3972. };
  3973. EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
  3974. }
  3975. void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
  3976. EmitOMPTaskLoopBasedDirective(S);
  3977. }
  3978. void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
  3979. const OMPTaskLoopSimdDirective &S) {
  3980. EmitOMPTaskLoopBasedDirective(S);
  3981. }
  3982. // Generate the instructions for '#pragma omp target update' directive.
  3983. void CodeGenFunction::EmitOMPTargetUpdateDirective(
  3984. const OMPTargetUpdateDirective &S) {
  3985. // If we don't have target devices, don't bother emitting the data mapping
  3986. // code.
  3987. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3988. return;
  3989. // Check if we have any if clause associated with the directive.
  3990. const Expr *IfCond = nullptr;
  3991. if (auto *C = S.getSingleClause<OMPIfClause>())
  3992. IfCond = C->getCondition();
  3993. // Check if we have any device clause associated with the directive.
  3994. const Expr *Device = nullptr;
  3995. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3996. Device = C->getDevice();
  3997. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  3998. }