CGStmtOpenMP.cpp 214 KB

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