CGStmtOpenMP.cpp 218 KB

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