CGOpenMPRuntime.cpp 401 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493
  1. //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This provides a class for OpenMP runtime code generation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGCXXABI.h"
  14. #include "CGCleanup.h"
  15. #include "CGOpenMPRuntime.h"
  16. #include "CGRecordLayout.h"
  17. #include "CodeGenFunction.h"
  18. #include "clang/CodeGen/ConstantInitBuilder.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/StmtOpenMP.h"
  21. #include "clang/Basic/BitmaskEnum.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/Bitcode/BitcodeReader.h"
  24. #include "llvm/IR/CallSite.h"
  25. #include "llvm/IR/DerivedTypes.h"
  26. #include "llvm/IR/GlobalValue.h"
  27. #include "llvm/IR/Value.h"
  28. #include "llvm/Support/Format.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <cassert>
  31. using namespace clang;
  32. using namespace CodeGen;
  33. namespace {
  34. /// Base class for handling code generation inside OpenMP regions.
  35. class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
  36. public:
  37. /// Kinds of OpenMP regions used in codegen.
  38. enum CGOpenMPRegionKind {
  39. /// Region with outlined function for standalone 'parallel'
  40. /// directive.
  41. ParallelOutlinedRegion,
  42. /// Region with outlined function for standalone 'task' directive.
  43. TaskOutlinedRegion,
  44. /// Region for constructs that do not require function outlining,
  45. /// like 'for', 'sections', 'atomic' etc. directives.
  46. InlinedRegion,
  47. /// Region with outlined function for standalone 'target' directive.
  48. TargetRegion,
  49. };
  50. CGOpenMPRegionInfo(const CapturedStmt &CS,
  51. const CGOpenMPRegionKind RegionKind,
  52. const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
  53. bool HasCancel)
  54. : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
  55. CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
  56. CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
  57. const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
  58. bool HasCancel)
  59. : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
  60. Kind(Kind), HasCancel(HasCancel) {}
  61. /// Get a variable or parameter for storing global thread id
  62. /// inside OpenMP construct.
  63. virtual const VarDecl *getThreadIDVariable() const = 0;
  64. /// Emit the captured statement body.
  65. void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
  66. /// Get an LValue for the current ThreadID variable.
  67. /// \return LValue for thread id variable. This LValue always has type int32*.
  68. virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
  69. virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
  70. CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
  71. OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
  72. bool hasCancel() const { return HasCancel; }
  73. static bool classof(const CGCapturedStmtInfo *Info) {
  74. return Info->getKind() == CR_OpenMP;
  75. }
  76. ~CGOpenMPRegionInfo() override = default;
  77. protected:
  78. CGOpenMPRegionKind RegionKind;
  79. RegionCodeGenTy CodeGen;
  80. OpenMPDirectiveKind Kind;
  81. bool HasCancel;
  82. };
  83. /// API for captured statement code generation in OpenMP constructs.
  84. class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
  85. public:
  86. CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
  87. const RegionCodeGenTy &CodeGen,
  88. OpenMPDirectiveKind Kind, bool HasCancel,
  89. StringRef HelperName)
  90. : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
  91. HasCancel),
  92. ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
  93. assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
  94. }
  95. /// Get a variable or parameter for storing global thread id
  96. /// inside OpenMP construct.
  97. const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
  98. /// Get the name of the capture helper.
  99. StringRef getHelperName() const override { return HelperName; }
  100. static bool classof(const CGCapturedStmtInfo *Info) {
  101. return CGOpenMPRegionInfo::classof(Info) &&
  102. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
  103. ParallelOutlinedRegion;
  104. }
  105. private:
  106. /// A variable or parameter storing global thread id for OpenMP
  107. /// constructs.
  108. const VarDecl *ThreadIDVar;
  109. StringRef HelperName;
  110. };
  111. /// API for captured statement code generation in OpenMP constructs.
  112. class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
  113. public:
  114. class UntiedTaskActionTy final : public PrePostActionTy {
  115. bool Untied;
  116. const VarDecl *PartIDVar;
  117. const RegionCodeGenTy UntiedCodeGen;
  118. llvm::SwitchInst *UntiedSwitch = nullptr;
  119. public:
  120. UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
  121. const RegionCodeGenTy &UntiedCodeGen)
  122. : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
  123. void Enter(CodeGenFunction &CGF) override {
  124. if (Untied) {
  125. // Emit task switching point.
  126. LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
  127. CGF.GetAddrOfLocalVar(PartIDVar),
  128. PartIDVar->getType()->castAs<PointerType>());
  129. llvm::Value *Res =
  130. CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
  131. llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
  132. UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
  133. CGF.EmitBlock(DoneBB);
  134. CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
  135. CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
  136. UntiedSwitch->addCase(CGF.Builder.getInt32(0),
  137. CGF.Builder.GetInsertBlock());
  138. emitUntiedSwitch(CGF);
  139. }
  140. }
  141. void emitUntiedSwitch(CodeGenFunction &CGF) const {
  142. if (Untied) {
  143. LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
  144. CGF.GetAddrOfLocalVar(PartIDVar),
  145. PartIDVar->getType()->castAs<PointerType>());
  146. CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
  147. PartIdLVal);
  148. UntiedCodeGen(CGF);
  149. CodeGenFunction::JumpDest CurPoint =
  150. CGF.getJumpDestInCurrentScope(".untied.next.");
  151. CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
  152. CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
  153. UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
  154. CGF.Builder.GetInsertBlock());
  155. CGF.EmitBranchThroughCleanup(CurPoint);
  156. CGF.EmitBlock(CurPoint.getBlock());
  157. }
  158. }
  159. unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
  160. };
  161. CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
  162. const VarDecl *ThreadIDVar,
  163. const RegionCodeGenTy &CodeGen,
  164. OpenMPDirectiveKind Kind, bool HasCancel,
  165. const UntiedTaskActionTy &Action)
  166. : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
  167. ThreadIDVar(ThreadIDVar), Action(Action) {
  168. assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
  169. }
  170. /// Get a variable or parameter for storing global thread id
  171. /// inside OpenMP construct.
  172. const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
  173. /// Get an LValue for the current ThreadID variable.
  174. LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
  175. /// Get the name of the capture helper.
  176. StringRef getHelperName() const override { return ".omp_outlined."; }
  177. void emitUntiedSwitch(CodeGenFunction &CGF) override {
  178. Action.emitUntiedSwitch(CGF);
  179. }
  180. static bool classof(const CGCapturedStmtInfo *Info) {
  181. return CGOpenMPRegionInfo::classof(Info) &&
  182. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
  183. TaskOutlinedRegion;
  184. }
  185. private:
  186. /// A variable or parameter storing global thread id for OpenMP
  187. /// constructs.
  188. const VarDecl *ThreadIDVar;
  189. /// Action for emitting code for untied tasks.
  190. const UntiedTaskActionTy &Action;
  191. };
  192. /// API for inlined captured statement code generation in OpenMP
  193. /// constructs.
  194. class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
  195. public:
  196. CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
  197. const RegionCodeGenTy &CodeGen,
  198. OpenMPDirectiveKind Kind, bool HasCancel)
  199. : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
  200. OldCSI(OldCSI),
  201. OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
  202. // Retrieve the value of the context parameter.
  203. llvm::Value *getContextValue() const override {
  204. if (OuterRegionInfo)
  205. return OuterRegionInfo->getContextValue();
  206. llvm_unreachable("No context value for inlined OpenMP region");
  207. }
  208. void setContextValue(llvm::Value *V) override {
  209. if (OuterRegionInfo) {
  210. OuterRegionInfo->setContextValue(V);
  211. return;
  212. }
  213. llvm_unreachable("No context value for inlined OpenMP region");
  214. }
  215. /// Lookup the captured field decl for a variable.
  216. const FieldDecl *lookup(const VarDecl *VD) const override {
  217. if (OuterRegionInfo)
  218. return OuterRegionInfo->lookup(VD);
  219. // If there is no outer outlined region,no need to lookup in a list of
  220. // captured variables, we can use the original one.
  221. return nullptr;
  222. }
  223. FieldDecl *getThisFieldDecl() const override {
  224. if (OuterRegionInfo)
  225. return OuterRegionInfo->getThisFieldDecl();
  226. return nullptr;
  227. }
  228. /// Get a variable or parameter for storing global thread id
  229. /// inside OpenMP construct.
  230. const VarDecl *getThreadIDVariable() const override {
  231. if (OuterRegionInfo)
  232. return OuterRegionInfo->getThreadIDVariable();
  233. return nullptr;
  234. }
  235. /// Get an LValue for the current ThreadID variable.
  236. LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
  237. if (OuterRegionInfo)
  238. return OuterRegionInfo->getThreadIDVariableLValue(CGF);
  239. llvm_unreachable("No LValue for inlined OpenMP construct");
  240. }
  241. /// Get the name of the capture helper.
  242. StringRef getHelperName() const override {
  243. if (auto *OuterRegionInfo = getOldCSI())
  244. return OuterRegionInfo->getHelperName();
  245. llvm_unreachable("No helper name for inlined OpenMP construct");
  246. }
  247. void emitUntiedSwitch(CodeGenFunction &CGF) override {
  248. if (OuterRegionInfo)
  249. OuterRegionInfo->emitUntiedSwitch(CGF);
  250. }
  251. CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
  252. static bool classof(const CGCapturedStmtInfo *Info) {
  253. return CGOpenMPRegionInfo::classof(Info) &&
  254. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
  255. }
  256. ~CGOpenMPInlinedRegionInfo() override = default;
  257. private:
  258. /// CodeGen info about outer OpenMP region.
  259. CodeGenFunction::CGCapturedStmtInfo *OldCSI;
  260. CGOpenMPRegionInfo *OuterRegionInfo;
  261. };
  262. /// API for captured statement code generation in OpenMP target
  263. /// constructs. For this captures, implicit parameters are used instead of the
  264. /// captured fields. The name of the target region has to be unique in a given
  265. /// application so it is provided by the client, because only the client has
  266. /// the information to generate that.
  267. class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
  268. public:
  269. CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
  270. const RegionCodeGenTy &CodeGen, StringRef HelperName)
  271. : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
  272. /*HasCancel=*/false),
  273. HelperName(HelperName) {}
  274. /// This is unused for target regions because each starts executing
  275. /// with a single thread.
  276. const VarDecl *getThreadIDVariable() const override { return nullptr; }
  277. /// Get the name of the capture helper.
  278. StringRef getHelperName() const override { return HelperName; }
  279. static bool classof(const CGCapturedStmtInfo *Info) {
  280. return CGOpenMPRegionInfo::classof(Info) &&
  281. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
  282. }
  283. private:
  284. StringRef HelperName;
  285. };
  286. static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
  287. llvm_unreachable("No codegen for expressions");
  288. }
  289. /// API for generation of expressions captured in a innermost OpenMP
  290. /// region.
  291. class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
  292. public:
  293. CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
  294. : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
  295. OMPD_unknown,
  296. /*HasCancel=*/false),
  297. PrivScope(CGF) {
  298. // Make sure the globals captured in the provided statement are local by
  299. // using the privatization logic. We assume the same variable is not
  300. // captured more than once.
  301. for (const auto &C : CS.captures()) {
  302. if (!C.capturesVariable() && !C.capturesVariableByCopy())
  303. continue;
  304. const VarDecl *VD = C.getCapturedVar();
  305. if (VD->isLocalVarDeclOrParm())
  306. continue;
  307. DeclRefExpr DRE(const_cast<VarDecl *>(VD),
  308. /*RefersToEnclosingVariableOrCapture=*/false,
  309. VD->getType().getNonReferenceType(), VK_LValue,
  310. C.getLocation());
  311. PrivScope.addPrivate(
  312. VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
  313. }
  314. (void)PrivScope.Privatize();
  315. }
  316. /// Lookup the captured field decl for a variable.
  317. const FieldDecl *lookup(const VarDecl *VD) const override {
  318. if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
  319. return FD;
  320. return nullptr;
  321. }
  322. /// Emit the captured statement body.
  323. void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
  324. llvm_unreachable("No body for expressions");
  325. }
  326. /// Get a variable or parameter for storing global thread id
  327. /// inside OpenMP construct.
  328. const VarDecl *getThreadIDVariable() const override {
  329. llvm_unreachable("No thread id for expressions");
  330. }
  331. /// Get the name of the capture helper.
  332. StringRef getHelperName() const override {
  333. llvm_unreachable("No helper name for expressions");
  334. }
  335. static bool classof(const CGCapturedStmtInfo *Info) { return false; }
  336. private:
  337. /// Private scope to capture global variables.
  338. CodeGenFunction::OMPPrivateScope PrivScope;
  339. };
  340. /// RAII for emitting code of OpenMP constructs.
  341. class InlinedOpenMPRegionRAII {
  342. CodeGenFunction &CGF;
  343. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  344. FieldDecl *LambdaThisCaptureField = nullptr;
  345. const CodeGen::CGBlockInfo *BlockInfo = nullptr;
  346. public:
  347. /// Constructs region for combined constructs.
  348. /// \param CodeGen Code generation sequence for combined directives. Includes
  349. /// a list of functions used for code generation of implicitly inlined
  350. /// regions.
  351. InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
  352. OpenMPDirectiveKind Kind, bool HasCancel)
  353. : CGF(CGF) {
  354. // Start emission for the construct.
  355. CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
  356. CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
  357. std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
  358. LambdaThisCaptureField = CGF.LambdaThisCaptureField;
  359. CGF.LambdaThisCaptureField = nullptr;
  360. BlockInfo = CGF.BlockInfo;
  361. CGF.BlockInfo = nullptr;
  362. }
  363. ~InlinedOpenMPRegionRAII() {
  364. // Restore original CapturedStmtInfo only if we're done with code emission.
  365. auto *OldCSI =
  366. cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
  367. delete CGF.CapturedStmtInfo;
  368. CGF.CapturedStmtInfo = OldCSI;
  369. std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
  370. CGF.LambdaThisCaptureField = LambdaThisCaptureField;
  371. CGF.BlockInfo = BlockInfo;
  372. }
  373. };
  374. /// Values for bit flags used in the ident_t to describe the fields.
  375. /// All enumeric elements are named and described in accordance with the code
  376. /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
  377. enum OpenMPLocationFlags : unsigned {
  378. /// Use trampoline for internal microtask.
  379. OMP_IDENT_IMD = 0x01,
  380. /// Use c-style ident structure.
  381. OMP_IDENT_KMPC = 0x02,
  382. /// Atomic reduction option for kmpc_reduce.
  383. OMP_ATOMIC_REDUCE = 0x10,
  384. /// Explicit 'barrier' directive.
  385. OMP_IDENT_BARRIER_EXPL = 0x20,
  386. /// Implicit barrier in code.
  387. OMP_IDENT_BARRIER_IMPL = 0x40,
  388. /// Implicit barrier in 'for' directive.
  389. OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
  390. /// Implicit barrier in 'sections' directive.
  391. OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
  392. /// Implicit barrier in 'single' directive.
  393. OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
  394. /// Call of __kmp_for_static_init for static loop.
  395. OMP_IDENT_WORK_LOOP = 0x200,
  396. /// Call of __kmp_for_static_init for sections.
  397. OMP_IDENT_WORK_SECTIONS = 0x400,
  398. /// Call of __kmp_for_static_init for distribute.
  399. OMP_IDENT_WORK_DISTRIBUTE = 0x800,
  400. LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
  401. };
  402. /// Describes ident structure that describes a source location.
  403. /// All descriptions are taken from
  404. /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
  405. /// Original structure:
  406. /// typedef struct ident {
  407. /// kmp_int32 reserved_1; /**< might be used in Fortran;
  408. /// see above */
  409. /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
  410. /// KMP_IDENT_KMPC identifies this union
  411. /// member */
  412. /// kmp_int32 reserved_2; /**< not really used in Fortran any more;
  413. /// see above */
  414. ///#if USE_ITT_BUILD
  415. /// /* but currently used for storing
  416. /// region-specific ITT */
  417. /// /* contextual information. */
  418. ///#endif /* USE_ITT_BUILD */
  419. /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
  420. /// C++ */
  421. /// char const *psource; /**< String describing the source location.
  422. /// The string is composed of semi-colon separated
  423. // fields which describe the source file,
  424. /// the function and a pair of line numbers that
  425. /// delimit the construct.
  426. /// */
  427. /// } ident_t;
  428. enum IdentFieldIndex {
  429. /// might be used in Fortran
  430. IdentField_Reserved_1,
  431. /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
  432. IdentField_Flags,
  433. /// Not really used in Fortran any more
  434. IdentField_Reserved_2,
  435. /// Source[4] in Fortran, do not use for C++
  436. IdentField_Reserved_3,
  437. /// String describing the source location. The string is composed of
  438. /// semi-colon separated fields which describe the source file, the function
  439. /// and a pair of line numbers that delimit the construct.
  440. IdentField_PSource
  441. };
  442. /// Schedule types for 'omp for' loops (these enumerators are taken from
  443. /// the enum sched_type in kmp.h).
  444. enum OpenMPSchedType {
  445. /// Lower bound for default (unordered) versions.
  446. OMP_sch_lower = 32,
  447. OMP_sch_static_chunked = 33,
  448. OMP_sch_static = 34,
  449. OMP_sch_dynamic_chunked = 35,
  450. OMP_sch_guided_chunked = 36,
  451. OMP_sch_runtime = 37,
  452. OMP_sch_auto = 38,
  453. /// static with chunk adjustment (e.g., simd)
  454. OMP_sch_static_balanced_chunked = 45,
  455. /// Lower bound for 'ordered' versions.
  456. OMP_ord_lower = 64,
  457. OMP_ord_static_chunked = 65,
  458. OMP_ord_static = 66,
  459. OMP_ord_dynamic_chunked = 67,
  460. OMP_ord_guided_chunked = 68,
  461. OMP_ord_runtime = 69,
  462. OMP_ord_auto = 70,
  463. OMP_sch_default = OMP_sch_static,
  464. /// dist_schedule types
  465. OMP_dist_sch_static_chunked = 91,
  466. OMP_dist_sch_static = 92,
  467. /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
  468. /// Set if the monotonic schedule modifier was present.
  469. OMP_sch_modifier_monotonic = (1 << 29),
  470. /// Set if the nonmonotonic schedule modifier was present.
  471. OMP_sch_modifier_nonmonotonic = (1 << 30),
  472. };
  473. enum OpenMPRTLFunction {
  474. /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
  475. /// kmpc_micro microtask, ...);
  476. OMPRTL__kmpc_fork_call,
  477. /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
  478. /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
  479. OMPRTL__kmpc_threadprivate_cached,
  480. /// Call to void __kmpc_threadprivate_register( ident_t *,
  481. /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
  482. OMPRTL__kmpc_threadprivate_register,
  483. // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
  484. OMPRTL__kmpc_global_thread_num,
  485. // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
  486. // kmp_critical_name *crit);
  487. OMPRTL__kmpc_critical,
  488. // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
  489. // global_tid, kmp_critical_name *crit, uintptr_t hint);
  490. OMPRTL__kmpc_critical_with_hint,
  491. // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
  492. // kmp_critical_name *crit);
  493. OMPRTL__kmpc_end_critical,
  494. // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
  495. // global_tid);
  496. OMPRTL__kmpc_cancel_barrier,
  497. // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
  498. OMPRTL__kmpc_barrier,
  499. // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
  500. OMPRTL__kmpc_for_static_fini,
  501. // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
  502. // global_tid);
  503. OMPRTL__kmpc_serialized_parallel,
  504. // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
  505. // global_tid);
  506. OMPRTL__kmpc_end_serialized_parallel,
  507. // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
  508. // kmp_int32 num_threads);
  509. OMPRTL__kmpc_push_num_threads,
  510. // Call to void __kmpc_flush(ident_t *loc);
  511. OMPRTL__kmpc_flush,
  512. // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
  513. OMPRTL__kmpc_master,
  514. // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
  515. OMPRTL__kmpc_end_master,
  516. // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
  517. // int end_part);
  518. OMPRTL__kmpc_omp_taskyield,
  519. // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
  520. OMPRTL__kmpc_single,
  521. // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
  522. OMPRTL__kmpc_end_single,
  523. // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  524. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  525. // kmp_routine_entry_t *task_entry);
  526. OMPRTL__kmpc_omp_task_alloc,
  527. // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
  528. // new_task);
  529. OMPRTL__kmpc_omp_task,
  530. // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
  531. // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
  532. // kmp_int32 didit);
  533. OMPRTL__kmpc_copyprivate,
  534. // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
  535. // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
  536. // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
  537. OMPRTL__kmpc_reduce,
  538. // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
  539. // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
  540. // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
  541. // *lck);
  542. OMPRTL__kmpc_reduce_nowait,
  543. // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
  544. // kmp_critical_name *lck);
  545. OMPRTL__kmpc_end_reduce,
  546. // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
  547. // kmp_critical_name *lck);
  548. OMPRTL__kmpc_end_reduce_nowait,
  549. // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
  550. // kmp_task_t * new_task);
  551. OMPRTL__kmpc_omp_task_begin_if0,
  552. // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
  553. // kmp_task_t * new_task);
  554. OMPRTL__kmpc_omp_task_complete_if0,
  555. // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
  556. OMPRTL__kmpc_ordered,
  557. // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
  558. OMPRTL__kmpc_end_ordered,
  559. // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
  560. // global_tid);
  561. OMPRTL__kmpc_omp_taskwait,
  562. // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
  563. OMPRTL__kmpc_taskgroup,
  564. // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
  565. OMPRTL__kmpc_end_taskgroup,
  566. // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
  567. // int proc_bind);
  568. OMPRTL__kmpc_push_proc_bind,
  569. // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
  570. // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
  571. // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
  572. OMPRTL__kmpc_omp_task_with_deps,
  573. // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
  574. // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
  575. // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
  576. OMPRTL__kmpc_omp_wait_deps,
  577. // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  578. // global_tid, kmp_int32 cncl_kind);
  579. OMPRTL__kmpc_cancellationpoint,
  580. // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  581. // kmp_int32 cncl_kind);
  582. OMPRTL__kmpc_cancel,
  583. // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
  584. // kmp_int32 num_teams, kmp_int32 thread_limit);
  585. OMPRTL__kmpc_push_num_teams,
  586. // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
  587. // microtask, ...);
  588. OMPRTL__kmpc_fork_teams,
  589. // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
  590. // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
  591. // sched, kmp_uint64 grainsize, void *task_dup);
  592. OMPRTL__kmpc_taskloop,
  593. // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
  594. // num_dims, struct kmp_dim *dims);
  595. OMPRTL__kmpc_doacross_init,
  596. // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
  597. OMPRTL__kmpc_doacross_fini,
  598. // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
  599. // *vec);
  600. OMPRTL__kmpc_doacross_post,
  601. // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
  602. // *vec);
  603. OMPRTL__kmpc_doacross_wait,
  604. // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
  605. // *data);
  606. OMPRTL__kmpc_task_reduction_init,
  607. // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
  608. // *d);
  609. OMPRTL__kmpc_task_reduction_get_th_data,
  610. //
  611. // Offloading related calls
  612. //
  613. // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
  614. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  615. // *arg_types);
  616. OMPRTL__tgt_target,
  617. // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
  618. // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  619. // *arg_types);
  620. OMPRTL__tgt_target_nowait,
  621. // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
  622. // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  623. // *arg_types, int32_t num_teams, int32_t thread_limit);
  624. OMPRTL__tgt_target_teams,
  625. // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
  626. // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
  627. // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
  628. OMPRTL__tgt_target_teams_nowait,
  629. // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
  630. OMPRTL__tgt_register_lib,
  631. // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
  632. OMPRTL__tgt_unregister_lib,
  633. // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
  634. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  635. OMPRTL__tgt_target_data_begin,
  636. // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
  637. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  638. // *arg_types);
  639. OMPRTL__tgt_target_data_begin_nowait,
  640. // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
  641. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  642. OMPRTL__tgt_target_data_end,
  643. // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
  644. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  645. // *arg_types);
  646. OMPRTL__tgt_target_data_end_nowait,
  647. // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
  648. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  649. OMPRTL__tgt_target_data_update,
  650. // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
  651. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  652. // *arg_types);
  653. OMPRTL__tgt_target_data_update_nowait,
  654. };
  655. /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
  656. /// region.
  657. class CleanupTy final : public EHScopeStack::Cleanup {
  658. PrePostActionTy *Action;
  659. public:
  660. explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
  661. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  662. if (!CGF.HaveInsertPoint())
  663. return;
  664. Action->Exit(CGF);
  665. }
  666. };
  667. } // anonymous namespace
  668. void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
  669. CodeGenFunction::RunCleanupsScope Scope(CGF);
  670. if (PrePostAction) {
  671. CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
  672. Callback(CodeGen, CGF, *PrePostAction);
  673. } else {
  674. PrePostActionTy Action;
  675. Callback(CodeGen, CGF, Action);
  676. }
  677. }
  678. /// Check if the combiner is a call to UDR combiner and if it is so return the
  679. /// UDR decl used for reduction.
  680. static const OMPDeclareReductionDecl *
  681. getReductionInit(const Expr *ReductionOp) {
  682. if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
  683. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
  684. if (const auto *DRE =
  685. dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
  686. if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
  687. return DRD;
  688. return nullptr;
  689. }
  690. static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
  691. const OMPDeclareReductionDecl *DRD,
  692. const Expr *InitOp,
  693. Address Private, Address Original,
  694. QualType Ty) {
  695. if (DRD->getInitializer()) {
  696. std::pair<llvm::Function *, llvm::Function *> Reduction =
  697. CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
  698. const auto *CE = cast<CallExpr>(InitOp);
  699. const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
  700. const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  701. const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  702. const auto *LHSDRE =
  703. cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
  704. const auto *RHSDRE =
  705. cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
  706. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  707. PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
  708. [=]() { return Private; });
  709. PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
  710. [=]() { return Original; });
  711. (void)PrivateScope.Privatize();
  712. RValue Func = RValue::get(Reduction.second);
  713. CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
  714. CGF.EmitIgnoredExpr(InitOp);
  715. } else {
  716. llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
  717. std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
  718. auto *GV = new llvm::GlobalVariable(
  719. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  720. llvm::GlobalValue::PrivateLinkage, Init, Name);
  721. LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
  722. RValue InitRVal;
  723. switch (CGF.getEvaluationKind(Ty)) {
  724. case TEK_Scalar:
  725. InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
  726. break;
  727. case TEK_Complex:
  728. InitRVal =
  729. RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
  730. break;
  731. case TEK_Aggregate:
  732. InitRVal = RValue::getAggregate(LV.getAddress());
  733. break;
  734. }
  735. OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
  736. CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
  737. CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
  738. /*IsInitializer=*/false);
  739. }
  740. }
  741. /// Emit initialization of arrays of complex types.
  742. /// \param DestAddr Address of the array.
  743. /// \param Type Type of array.
  744. /// \param Init Initial expression of array.
  745. /// \param SrcAddr Address of the original array.
  746. static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
  747. QualType Type, bool EmitDeclareReductionInit,
  748. const Expr *Init,
  749. const OMPDeclareReductionDecl *DRD,
  750. Address SrcAddr = Address::invalid()) {
  751. // Perform element-by-element initialization.
  752. QualType ElementTy;
  753. // Drill down to the base element type on both arrays.
  754. const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
  755. llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
  756. DestAddr =
  757. CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
  758. if (DRD)
  759. SrcAddr =
  760. CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
  761. llvm::Value *SrcBegin = nullptr;
  762. if (DRD)
  763. SrcBegin = SrcAddr.getPointer();
  764. llvm::Value *DestBegin = DestAddr.getPointer();
  765. // Cast from pointer to array type to pointer to single element.
  766. llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
  767. // The basic structure here is a while-do loop.
  768. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
  769. llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
  770. llvm::Value *IsEmpty =
  771. CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
  772. CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  773. // Enter the loop body, making that address the current address.
  774. llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
  775. CGF.EmitBlock(BodyBB);
  776. CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
  777. llvm::PHINode *SrcElementPHI = nullptr;
  778. Address SrcElementCurrent = Address::invalid();
  779. if (DRD) {
  780. SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
  781. "omp.arraycpy.srcElementPast");
  782. SrcElementPHI->addIncoming(SrcBegin, EntryBB);
  783. SrcElementCurrent =
  784. Address(SrcElementPHI,
  785. SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  786. }
  787. llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
  788. DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
  789. DestElementPHI->addIncoming(DestBegin, EntryBB);
  790. Address DestElementCurrent =
  791. Address(DestElementPHI,
  792. DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  793. // Emit copy.
  794. {
  795. CodeGenFunction::RunCleanupsScope InitScope(CGF);
  796. if (EmitDeclareReductionInit) {
  797. emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
  798. SrcElementCurrent, ElementTy);
  799. } else
  800. CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
  801. /*IsInitializer=*/false);
  802. }
  803. if (DRD) {
  804. // Shift the address forward by one element.
  805. llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
  806. SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  807. SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
  808. }
  809. // Shift the address forward by one element.
  810. llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
  811. DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  812. // Check whether we've reached the end.
  813. llvm::Value *Done =
  814. CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
  815. CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
  816. DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
  817. // Done.
  818. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  819. }
  820. LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
  821. return CGF.EmitOMPSharedLValue(E);
  822. }
  823. LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
  824. const Expr *E) {
  825. if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
  826. return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
  827. return LValue();
  828. }
  829. void ReductionCodeGen::emitAggregateInitialization(
  830. CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
  831. const OMPDeclareReductionDecl *DRD) {
  832. // Emit VarDecl with copy init for arrays.
  833. // Get the address of the original variable captured in current
  834. // captured region.
  835. const auto *PrivateVD =
  836. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  837. bool EmitDeclareReductionInit =
  838. DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
  839. EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
  840. EmitDeclareReductionInit,
  841. EmitDeclareReductionInit ? ClausesData[N].ReductionOp
  842. : PrivateVD->getInit(),
  843. DRD, SharedLVal.getAddress());
  844. }
  845. ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
  846. ArrayRef<const Expr *> Privates,
  847. ArrayRef<const Expr *> ReductionOps) {
  848. ClausesData.reserve(Shareds.size());
  849. SharedAddresses.reserve(Shareds.size());
  850. Sizes.reserve(Shareds.size());
  851. BaseDecls.reserve(Shareds.size());
  852. auto IPriv = Privates.begin();
  853. auto IRed = ReductionOps.begin();
  854. for (const Expr *Ref : Shareds) {
  855. ClausesData.emplace_back(Ref, *IPriv, *IRed);
  856. std::advance(IPriv, 1);
  857. std::advance(IRed, 1);
  858. }
  859. }
  860. void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
  861. assert(SharedAddresses.size() == N &&
  862. "Number of generated lvalues must be exactly N.");
  863. LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
  864. LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
  865. SharedAddresses.emplace_back(First, Second);
  866. }
  867. void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
  868. const auto *PrivateVD =
  869. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  870. QualType PrivateType = PrivateVD->getType();
  871. bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
  872. if (!PrivateType->isVariablyModifiedType()) {
  873. Sizes.emplace_back(
  874. CGF.getTypeSize(
  875. SharedAddresses[N].first.getType().getNonReferenceType()),
  876. nullptr);
  877. return;
  878. }
  879. llvm::Value *Size;
  880. llvm::Value *SizeInChars;
  881. auto *ElemType =
  882. cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
  883. ->getElementType();
  884. auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
  885. if (AsArraySection) {
  886. Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
  887. SharedAddresses[N].first.getPointer());
  888. Size = CGF.Builder.CreateNUWAdd(
  889. Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
  890. SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
  891. } else {
  892. SizeInChars = CGF.getTypeSize(
  893. SharedAddresses[N].first.getType().getNonReferenceType());
  894. Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
  895. }
  896. Sizes.emplace_back(SizeInChars, Size);
  897. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  898. CGF,
  899. cast<OpaqueValueExpr>(
  900. CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
  901. RValue::get(Size));
  902. CGF.EmitVariablyModifiedType(PrivateType);
  903. }
  904. void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
  905. llvm::Value *Size) {
  906. const auto *PrivateVD =
  907. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  908. QualType PrivateType = PrivateVD->getType();
  909. if (!PrivateType->isVariablyModifiedType()) {
  910. assert(!Size && !Sizes[N].second &&
  911. "Size should be nullptr for non-variably modified reduction "
  912. "items.");
  913. return;
  914. }
  915. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  916. CGF,
  917. cast<OpaqueValueExpr>(
  918. CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
  919. RValue::get(Size));
  920. CGF.EmitVariablyModifiedType(PrivateType);
  921. }
  922. void ReductionCodeGen::emitInitialization(
  923. CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
  924. llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
  925. assert(SharedAddresses.size() > N && "No variable was generated");
  926. const auto *PrivateVD =
  927. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  928. const OMPDeclareReductionDecl *DRD =
  929. getReductionInit(ClausesData[N].ReductionOp);
  930. QualType PrivateType = PrivateVD->getType();
  931. PrivateAddr = CGF.Builder.CreateElementBitCast(
  932. PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
  933. QualType SharedType = SharedAddresses[N].first.getType();
  934. SharedLVal = CGF.MakeAddrLValue(
  935. CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
  936. CGF.ConvertTypeForMem(SharedType)),
  937. SharedType, SharedAddresses[N].first.getBaseInfo(),
  938. CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
  939. if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
  940. emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
  941. } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
  942. emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
  943. PrivateAddr, SharedLVal.getAddress(),
  944. SharedLVal.getType());
  945. } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
  946. !CGF.isTrivialInitializer(PrivateVD->getInit())) {
  947. CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
  948. PrivateVD->getType().getQualifiers(),
  949. /*IsInitializer=*/false);
  950. }
  951. }
  952. bool ReductionCodeGen::needCleanups(unsigned N) {
  953. const auto *PrivateVD =
  954. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  955. QualType PrivateType = PrivateVD->getType();
  956. QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
  957. return DTorKind != QualType::DK_none;
  958. }
  959. void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
  960. Address PrivateAddr) {
  961. const auto *PrivateVD =
  962. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  963. QualType PrivateType = PrivateVD->getType();
  964. QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
  965. if (needCleanups(N)) {
  966. PrivateAddr = CGF.Builder.CreateElementBitCast(
  967. PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
  968. CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
  969. }
  970. }
  971. static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
  972. LValue BaseLV) {
  973. BaseTy = BaseTy.getNonReferenceType();
  974. while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
  975. !CGF.getContext().hasSameType(BaseTy, ElTy)) {
  976. if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
  977. BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
  978. } else {
  979. LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
  980. BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
  981. }
  982. BaseTy = BaseTy->getPointeeType();
  983. }
  984. return CGF.MakeAddrLValue(
  985. CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
  986. CGF.ConvertTypeForMem(ElTy)),
  987. BaseLV.getType(), BaseLV.getBaseInfo(),
  988. CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
  989. }
  990. static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
  991. llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
  992. llvm::Value *Addr) {
  993. Address Tmp = Address::invalid();
  994. Address TopTmp = Address::invalid();
  995. Address MostTopTmp = Address::invalid();
  996. BaseTy = BaseTy.getNonReferenceType();
  997. while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
  998. !CGF.getContext().hasSameType(BaseTy, ElTy)) {
  999. Tmp = CGF.CreateMemTemp(BaseTy);
  1000. if (TopTmp.isValid())
  1001. CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
  1002. else
  1003. MostTopTmp = Tmp;
  1004. TopTmp = Tmp;
  1005. BaseTy = BaseTy->getPointeeType();
  1006. }
  1007. llvm::Type *Ty = BaseLVType;
  1008. if (Tmp.isValid())
  1009. Ty = Tmp.getElementType();
  1010. Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
  1011. if (Tmp.isValid()) {
  1012. CGF.Builder.CreateStore(Addr, Tmp);
  1013. return MostTopTmp;
  1014. }
  1015. return Address(Addr, BaseLVAlignment);
  1016. }
  1017. static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
  1018. const VarDecl *OrigVD = nullptr;
  1019. if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
  1020. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  1021. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  1022. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  1023. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  1024. Base = TempASE->getBase()->IgnoreParenImpCasts();
  1025. DE = cast<DeclRefExpr>(Base);
  1026. OrigVD = cast<VarDecl>(DE->getDecl());
  1027. } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
  1028. const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  1029. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  1030. Base = TempASE->getBase()->IgnoreParenImpCasts();
  1031. DE = cast<DeclRefExpr>(Base);
  1032. OrigVD = cast<VarDecl>(DE->getDecl());
  1033. }
  1034. return OrigVD;
  1035. }
  1036. Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
  1037. Address PrivateAddr) {
  1038. const DeclRefExpr *DE;
  1039. if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
  1040. BaseDecls.emplace_back(OrigVD);
  1041. LValue OriginalBaseLValue = CGF.EmitLValue(DE);
  1042. LValue BaseLValue =
  1043. loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
  1044. OriginalBaseLValue);
  1045. llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
  1046. BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
  1047. llvm::Value *PrivatePointer =
  1048. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1049. PrivateAddr.getPointer(),
  1050. SharedAddresses[N].first.getAddress().getType());
  1051. llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
  1052. return castToBase(CGF, OrigVD->getType(),
  1053. SharedAddresses[N].first.getType(),
  1054. OriginalBaseLValue.getAddress().getType(),
  1055. OriginalBaseLValue.getAlignment(), Ptr);
  1056. }
  1057. BaseDecls.emplace_back(
  1058. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
  1059. return PrivateAddr;
  1060. }
  1061. bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
  1062. const OMPDeclareReductionDecl *DRD =
  1063. getReductionInit(ClausesData[N].ReductionOp);
  1064. return DRD && DRD->getInitializer();
  1065. }
  1066. LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
  1067. return CGF.EmitLoadOfPointerLValue(
  1068. CGF.GetAddrOfLocalVar(getThreadIDVariable()),
  1069. getThreadIDVariable()->getType()->castAs<PointerType>());
  1070. }
  1071. void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
  1072. if (!CGF.HaveInsertPoint())
  1073. return;
  1074. // 1.2.2 OpenMP Language Terminology
  1075. // Structured block - An executable statement with a single entry at the
  1076. // top and a single exit at the bottom.
  1077. // The point of exit cannot be a branch out of the structured block.
  1078. // longjmp() and throw() must not violate the entry/exit criteria.
  1079. CGF.EHStack.pushTerminate();
  1080. CodeGen(CGF);
  1081. CGF.EHStack.popTerminate();
  1082. }
  1083. LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
  1084. CodeGenFunction &CGF) {
  1085. return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
  1086. getThreadIDVariable()->getType(),
  1087. AlignmentSource::Decl);
  1088. }
  1089. static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
  1090. QualType FieldTy) {
  1091. auto *Field = FieldDecl::Create(
  1092. C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
  1093. C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
  1094. /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
  1095. Field->setAccess(AS_public);
  1096. DC->addDecl(Field);
  1097. return Field;
  1098. }
  1099. CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
  1100. StringRef Separator)
  1101. : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
  1102. OffloadEntriesInfoManager(CGM) {
  1103. ASTContext &C = CGM.getContext();
  1104. RecordDecl *RD = C.buildImplicitRecord("ident_t");
  1105. QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  1106. RD->startDefinition();
  1107. // reserved_1
  1108. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1109. // flags
  1110. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1111. // reserved_2
  1112. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1113. // reserved_3
  1114. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1115. // psource
  1116. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  1117. RD->completeDefinition();
  1118. IdentQTy = C.getRecordType(RD);
  1119. IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
  1120. KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
  1121. loadOffloadInfoMetadata();
  1122. }
  1123. void CGOpenMPRuntime::clear() {
  1124. InternalVars.clear();
  1125. }
  1126. std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
  1127. SmallString<128> Buffer;
  1128. llvm::raw_svector_ostream OS(Buffer);
  1129. StringRef Sep = FirstSeparator;
  1130. for (StringRef Part : Parts) {
  1131. OS << Sep << Part;
  1132. Sep = Separator;
  1133. }
  1134. return OS.str();
  1135. }
  1136. static llvm::Function *
  1137. emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
  1138. const Expr *CombinerInitializer, const VarDecl *In,
  1139. const VarDecl *Out, bool IsCombiner) {
  1140. // void .omp_combiner.(Ty *in, Ty *out);
  1141. ASTContext &C = CGM.getContext();
  1142. QualType PtrTy = C.getPointerType(Ty).withRestrict();
  1143. FunctionArgList Args;
  1144. ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
  1145. /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
  1146. ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
  1147. /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
  1148. Args.push_back(&OmpOutParm);
  1149. Args.push_back(&OmpInParm);
  1150. const CGFunctionInfo &FnInfo =
  1151. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  1152. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  1153. std::string Name = CGM.getOpenMPRuntime().getName(
  1154. {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
  1155. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  1156. Name, &CGM.getModule());
  1157. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  1158. Fn->removeFnAttr(llvm::Attribute::NoInline);
  1159. Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
  1160. Fn->addFnAttr(llvm::Attribute::AlwaysInline);
  1161. CodeGenFunction CGF(CGM);
  1162. // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
  1163. // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
  1164. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
  1165. Out->getLocation());
  1166. CodeGenFunction::OMPPrivateScope Scope(CGF);
  1167. Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
  1168. Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
  1169. return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
  1170. .getAddress();
  1171. });
  1172. Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
  1173. Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
  1174. return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
  1175. .getAddress();
  1176. });
  1177. (void)Scope.Privatize();
  1178. if (!IsCombiner && Out->hasInit() &&
  1179. !CGF.isTrivialInitializer(Out->getInit())) {
  1180. CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
  1181. Out->getType().getQualifiers(),
  1182. /*IsInitializer=*/true);
  1183. }
  1184. if (CombinerInitializer)
  1185. CGF.EmitIgnoredExpr(CombinerInitializer);
  1186. Scope.ForceCleanup();
  1187. CGF.FinishFunction();
  1188. return Fn;
  1189. }
  1190. void CGOpenMPRuntime::emitUserDefinedReduction(
  1191. CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
  1192. if (UDRMap.count(D) > 0)
  1193. return;
  1194. llvm::Function *Combiner = emitCombinerOrInitializer(
  1195. CGM, D->getType(), D->getCombiner(),
  1196. cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
  1197. cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
  1198. /*IsCombiner=*/true);
  1199. llvm::Function *Initializer = nullptr;
  1200. if (const Expr *Init = D->getInitializer()) {
  1201. Initializer = emitCombinerOrInitializer(
  1202. CGM, D->getType(),
  1203. D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
  1204. : nullptr,
  1205. cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
  1206. cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
  1207. /*IsCombiner=*/false);
  1208. }
  1209. UDRMap.try_emplace(D, Combiner, Initializer);
  1210. if (CGF) {
  1211. auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
  1212. Decls.second.push_back(D);
  1213. }
  1214. }
  1215. std::pair<llvm::Function *, llvm::Function *>
  1216. CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
  1217. auto I = UDRMap.find(D);
  1218. if (I != UDRMap.end())
  1219. return I->second;
  1220. emitUserDefinedReduction(/*CGF=*/nullptr, D);
  1221. return UDRMap.lookup(D);
  1222. }
  1223. static llvm::Value *emitParallelOrTeamsOutlinedFunction(
  1224. CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
  1225. const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
  1226. const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
  1227. assert(ThreadIDVar->getType()->isPointerType() &&
  1228. "thread id variable must be of type kmp_int32 *");
  1229. CodeGenFunction CGF(CGM, true);
  1230. bool HasCancel = false;
  1231. if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
  1232. HasCancel = OPD->hasCancel();
  1233. else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
  1234. HasCancel = OPSD->hasCancel();
  1235. else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
  1236. HasCancel = OPFD->hasCancel();
  1237. else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
  1238. HasCancel = OPFD->hasCancel();
  1239. else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
  1240. HasCancel = OPFD->hasCancel();
  1241. else if (const auto *OPFD =
  1242. dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
  1243. HasCancel = OPFD->hasCancel();
  1244. else if (const auto *OPFD =
  1245. dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
  1246. HasCancel = OPFD->hasCancel();
  1247. CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
  1248. HasCancel, OutlinedHelperName);
  1249. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  1250. return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
  1251. }
  1252. llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
  1253. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1254. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  1255. const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
  1256. return emitParallelOrTeamsOutlinedFunction(
  1257. CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
  1258. }
  1259. llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
  1260. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1261. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  1262. const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
  1263. return emitParallelOrTeamsOutlinedFunction(
  1264. CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
  1265. }
  1266. llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
  1267. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1268. const VarDecl *PartIDVar, const VarDecl *TaskTVar,
  1269. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  1270. bool Tied, unsigned &NumberOfParts) {
  1271. auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
  1272. PrePostActionTy &) {
  1273. llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
  1274. llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
  1275. llvm::Value *TaskArgs[] = {
  1276. UpLoc, ThreadID,
  1277. CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
  1278. TaskTVar->getType()->castAs<PointerType>())
  1279. .getPointer()};
  1280. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
  1281. };
  1282. CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
  1283. UntiedCodeGen);
  1284. CodeGen.setAction(Action);
  1285. assert(!ThreadIDVar->getType()->isPointerType() &&
  1286. "thread id variable must be of type kmp_int32 for tasks");
  1287. const OpenMPDirectiveKind Region =
  1288. isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
  1289. : OMPD_task;
  1290. const CapturedStmt *CS = D.getCapturedStmt(Region);
  1291. const auto *TD = dyn_cast<OMPTaskDirective>(&D);
  1292. CodeGenFunction CGF(CGM, true);
  1293. CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
  1294. InnermostKind,
  1295. TD ? TD->hasCancel() : false, Action);
  1296. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  1297. llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
  1298. if (!Tied)
  1299. NumberOfParts = Action.getNumberOfParts();
  1300. return Res;
  1301. }
  1302. static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
  1303. const RecordDecl *RD, const CGRecordLayout &RL,
  1304. ArrayRef<llvm::Constant *> Data) {
  1305. llvm::StructType *StructTy = RL.getLLVMType();
  1306. unsigned PrevIdx = 0;
  1307. ConstantInitBuilder CIBuilder(CGM);
  1308. auto DI = Data.begin();
  1309. for (const FieldDecl *FD : RD->fields()) {
  1310. unsigned Idx = RL.getLLVMFieldNo(FD);
  1311. // Fill the alignment.
  1312. for (unsigned I = PrevIdx; I < Idx; ++I)
  1313. Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
  1314. PrevIdx = Idx + 1;
  1315. Fields.add(*DI);
  1316. ++DI;
  1317. }
  1318. }
  1319. template <class... As>
  1320. static llvm::GlobalVariable *
  1321. createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
  1322. ArrayRef<llvm::Constant *> Data, const Twine &Name,
  1323. As &&... Args) {
  1324. const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
  1325. const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
  1326. ConstantInitBuilder CIBuilder(CGM);
  1327. ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
  1328. buildStructValue(Fields, CGM, RD, RL, Data);
  1329. return Fields.finishAndCreateGlobal(
  1330. Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
  1331. std::forward<As>(Args)...);
  1332. }
  1333. template <typename T>
  1334. static void
  1335. createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
  1336. ArrayRef<llvm::Constant *> Data,
  1337. T &Parent) {
  1338. const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
  1339. const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
  1340. ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
  1341. buildStructValue(Fields, CGM, RD, RL, Data);
  1342. Fields.finishAndAddTo(Parent);
  1343. }
  1344. Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
  1345. CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
  1346. llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
  1347. if (!Entry) {
  1348. if (!DefaultOpenMPPSource) {
  1349. // Initialize default location for psource field of ident_t structure of
  1350. // all ident_t objects. Format is ";file;function;line;column;;".
  1351. // Taken from
  1352. // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
  1353. DefaultOpenMPPSource =
  1354. CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
  1355. DefaultOpenMPPSource =
  1356. llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
  1357. }
  1358. llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
  1359. llvm::ConstantInt::get(CGM.Int32Ty, Flags),
  1360. llvm::ConstantInt::getNullValue(CGM.Int32Ty),
  1361. llvm::ConstantInt::getNullValue(CGM.Int32Ty),
  1362. DefaultOpenMPPSource};
  1363. llvm::GlobalValue *DefaultOpenMPLocation =
  1364. createGlobalStruct(CGM, IdentQTy, /*IsConstant=*/false, Data, "",
  1365. llvm::GlobalValue::PrivateLinkage);
  1366. DefaultOpenMPLocation->setUnnamedAddr(
  1367. llvm::GlobalValue::UnnamedAddr::Global);
  1368. OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
  1369. }
  1370. return Address(Entry, Align);
  1371. }
  1372. llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
  1373. SourceLocation Loc,
  1374. unsigned Flags) {
  1375. Flags |= OMP_IDENT_KMPC;
  1376. // If no debug info is generated - return global default location.
  1377. if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
  1378. Loc.isInvalid())
  1379. return getOrCreateDefaultLocation(Flags).getPointer();
  1380. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1381. CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
  1382. Address LocValue = Address::invalid();
  1383. auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
  1384. if (I != OpenMPLocThreadIDMap.end())
  1385. LocValue = Address(I->second.DebugLoc, Align);
  1386. // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
  1387. // GetOpenMPThreadID was called before this routine.
  1388. if (!LocValue.isValid()) {
  1389. // Generate "ident_t .kmpc_loc.addr;"
  1390. Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
  1391. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1392. Elem.second.DebugLoc = AI.getPointer();
  1393. LocValue = AI;
  1394. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  1395. CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
  1396. CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
  1397. CGF.getTypeSize(IdentQTy));
  1398. }
  1399. // char **psource = &.kmpc_loc_<flags>.addr.psource;
  1400. LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
  1401. auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
  1402. LValue PSource =
  1403. CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
  1404. llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
  1405. if (OMPDebugLoc == nullptr) {
  1406. SmallString<128> Buffer2;
  1407. llvm::raw_svector_ostream OS2(Buffer2);
  1408. // Build debug location
  1409. PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
  1410. OS2 << ";" << PLoc.getFilename() << ";";
  1411. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
  1412. OS2 << FD->getQualifiedNameAsString();
  1413. OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
  1414. OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
  1415. OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
  1416. }
  1417. // *psource = ";<File>;<Function>;<Line>;<Column>;;";
  1418. CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
  1419. // Our callers always pass this to a runtime function, so for
  1420. // convenience, go ahead and return a naked pointer.
  1421. return LocValue.getPointer();
  1422. }
  1423. llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
  1424. SourceLocation Loc) {
  1425. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1426. llvm::Value *ThreadID = nullptr;
  1427. // Check whether we've already cached a load of the thread id in this
  1428. // function.
  1429. auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
  1430. if (I != OpenMPLocThreadIDMap.end()) {
  1431. ThreadID = I->second.ThreadID;
  1432. if (ThreadID != nullptr)
  1433. return ThreadID;
  1434. }
  1435. // If exceptions are enabled, do not use parameter to avoid possible crash.
  1436. if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
  1437. !CGF.getLangOpts().CXXExceptions ||
  1438. CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
  1439. if (auto *OMPRegionInfo =
  1440. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  1441. if (OMPRegionInfo->getThreadIDVariable()) {
  1442. // Check if this an outlined function with thread id passed as argument.
  1443. LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
  1444. ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
  1445. // If value loaded in entry block, cache it and use it everywhere in
  1446. // function.
  1447. if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
  1448. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1449. Elem.second.ThreadID = ThreadID;
  1450. }
  1451. return ThreadID;
  1452. }
  1453. }
  1454. }
  1455. // This is not an outlined function region - need to call __kmpc_int32
  1456. // kmpc_global_thread_num(ident_t *loc).
  1457. // Generate thread id value and cache this value for use across the
  1458. // function.
  1459. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  1460. CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
  1461. llvm::CallInst *Call = CGF.Builder.CreateCall(
  1462. createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
  1463. emitUpdateLocation(CGF, Loc));
  1464. Call->setCallingConv(CGF.getRuntimeCC());
  1465. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1466. Elem.second.ThreadID = Call;
  1467. return Call;
  1468. }
  1469. void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
  1470. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1471. if (OpenMPLocThreadIDMap.count(CGF.CurFn))
  1472. OpenMPLocThreadIDMap.erase(CGF.CurFn);
  1473. if (FunctionUDRMap.count(CGF.CurFn) > 0) {
  1474. for(auto *D : FunctionUDRMap[CGF.CurFn])
  1475. UDRMap.erase(D);
  1476. FunctionUDRMap.erase(CGF.CurFn);
  1477. }
  1478. }
  1479. llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
  1480. return IdentTy->getPointerTo();
  1481. }
  1482. llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
  1483. if (!Kmpc_MicroTy) {
  1484. // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
  1485. llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
  1486. llvm::PointerType::getUnqual(CGM.Int32Ty)};
  1487. Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
  1488. }
  1489. return llvm::PointerType::getUnqual(Kmpc_MicroTy);
  1490. }
  1491. llvm::Constant *
  1492. CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
  1493. llvm::Constant *RTLFn = nullptr;
  1494. switch (static_cast<OpenMPRTLFunction>(Function)) {
  1495. case OMPRTL__kmpc_fork_call: {
  1496. // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
  1497. // microtask, ...);
  1498. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1499. getKmpc_MicroPointerTy()};
  1500. auto *FnTy =
  1501. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
  1502. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
  1503. break;
  1504. }
  1505. case OMPRTL__kmpc_global_thread_num: {
  1506. // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
  1507. llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
  1508. auto *FnTy =
  1509. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1510. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
  1511. break;
  1512. }
  1513. case OMPRTL__kmpc_threadprivate_cached: {
  1514. // Build void *__kmpc_threadprivate_cached(ident_t *loc,
  1515. // kmp_int32 global_tid, void *data, size_t size, void ***cache);
  1516. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1517. CGM.VoidPtrTy, CGM.SizeTy,
  1518. CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
  1519. auto *FnTy =
  1520. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
  1521. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
  1522. break;
  1523. }
  1524. case OMPRTL__kmpc_critical: {
  1525. // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
  1526. // kmp_critical_name *crit);
  1527. llvm::Type *TypeParams[] = {
  1528. getIdentTyPointerTy(), CGM.Int32Ty,
  1529. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1530. auto *FnTy =
  1531. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1532. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
  1533. break;
  1534. }
  1535. case OMPRTL__kmpc_critical_with_hint: {
  1536. // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
  1537. // kmp_critical_name *crit, uintptr_t hint);
  1538. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1539. llvm::PointerType::getUnqual(KmpCriticalNameTy),
  1540. CGM.IntPtrTy};
  1541. auto *FnTy =
  1542. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1543. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
  1544. break;
  1545. }
  1546. case OMPRTL__kmpc_threadprivate_register: {
  1547. // Build void __kmpc_threadprivate_register(ident_t *, void *data,
  1548. // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
  1549. // typedef void *(*kmpc_ctor)(void *);
  1550. auto *KmpcCtorTy =
  1551. llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
  1552. /*isVarArg*/ false)->getPointerTo();
  1553. // typedef void *(*kmpc_cctor)(void *, void *);
  1554. llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1555. auto *KmpcCopyCtorTy =
  1556. llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
  1557. /*isVarArg*/ false)
  1558. ->getPointerTo();
  1559. // typedef void (*kmpc_dtor)(void *);
  1560. auto *KmpcDtorTy =
  1561. llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
  1562. ->getPointerTo();
  1563. llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
  1564. KmpcCopyCtorTy, KmpcDtorTy};
  1565. auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
  1566. /*isVarArg*/ false);
  1567. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
  1568. break;
  1569. }
  1570. case OMPRTL__kmpc_end_critical: {
  1571. // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
  1572. // kmp_critical_name *crit);
  1573. llvm::Type *TypeParams[] = {
  1574. getIdentTyPointerTy(), CGM.Int32Ty,
  1575. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1576. auto *FnTy =
  1577. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1578. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
  1579. break;
  1580. }
  1581. case OMPRTL__kmpc_cancel_barrier: {
  1582. // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
  1583. // global_tid);
  1584. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1585. auto *FnTy =
  1586. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1587. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
  1588. break;
  1589. }
  1590. case OMPRTL__kmpc_barrier: {
  1591. // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
  1592. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1593. auto *FnTy =
  1594. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1595. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
  1596. break;
  1597. }
  1598. case OMPRTL__kmpc_for_static_fini: {
  1599. // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
  1600. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1601. auto *FnTy =
  1602. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1603. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
  1604. break;
  1605. }
  1606. case OMPRTL__kmpc_push_num_threads: {
  1607. // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
  1608. // kmp_int32 num_threads)
  1609. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1610. CGM.Int32Ty};
  1611. auto *FnTy =
  1612. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1613. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
  1614. break;
  1615. }
  1616. case OMPRTL__kmpc_serialized_parallel: {
  1617. // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
  1618. // global_tid);
  1619. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1620. auto *FnTy =
  1621. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1622. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
  1623. break;
  1624. }
  1625. case OMPRTL__kmpc_end_serialized_parallel: {
  1626. // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
  1627. // global_tid);
  1628. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1629. auto *FnTy =
  1630. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1631. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
  1632. break;
  1633. }
  1634. case OMPRTL__kmpc_flush: {
  1635. // Build void __kmpc_flush(ident_t *loc);
  1636. llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
  1637. auto *FnTy =
  1638. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1639. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
  1640. break;
  1641. }
  1642. case OMPRTL__kmpc_master: {
  1643. // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
  1644. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1645. auto *FnTy =
  1646. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1647. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
  1648. break;
  1649. }
  1650. case OMPRTL__kmpc_end_master: {
  1651. // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
  1652. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1653. auto *FnTy =
  1654. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1655. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
  1656. break;
  1657. }
  1658. case OMPRTL__kmpc_omp_taskyield: {
  1659. // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
  1660. // int end_part);
  1661. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1662. auto *FnTy =
  1663. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1664. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
  1665. break;
  1666. }
  1667. case OMPRTL__kmpc_single: {
  1668. // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
  1669. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1670. auto *FnTy =
  1671. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1672. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
  1673. break;
  1674. }
  1675. case OMPRTL__kmpc_end_single: {
  1676. // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
  1677. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1678. auto *FnTy =
  1679. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1680. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
  1681. break;
  1682. }
  1683. case OMPRTL__kmpc_omp_task_alloc: {
  1684. // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  1685. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  1686. // kmp_routine_entry_t *task_entry);
  1687. assert(KmpRoutineEntryPtrTy != nullptr &&
  1688. "Type kmp_routine_entry_t must be created.");
  1689. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  1690. CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
  1691. // Return void * and then cast to particular kmp_task_t type.
  1692. auto *FnTy =
  1693. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  1694. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
  1695. break;
  1696. }
  1697. case OMPRTL__kmpc_omp_task: {
  1698. // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1699. // *new_task);
  1700. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1701. CGM.VoidPtrTy};
  1702. auto *FnTy =
  1703. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1704. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
  1705. break;
  1706. }
  1707. case OMPRTL__kmpc_copyprivate: {
  1708. // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
  1709. // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
  1710. // kmp_int32 didit);
  1711. llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1712. auto *CpyFnTy =
  1713. llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
  1714. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
  1715. CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
  1716. CGM.Int32Ty};
  1717. auto *FnTy =
  1718. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1719. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
  1720. break;
  1721. }
  1722. case OMPRTL__kmpc_reduce: {
  1723. // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
  1724. // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
  1725. // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
  1726. llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1727. auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
  1728. /*isVarArg=*/false);
  1729. llvm::Type *TypeParams[] = {
  1730. getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
  1731. CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
  1732. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1733. auto *FnTy =
  1734. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1735. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
  1736. break;
  1737. }
  1738. case OMPRTL__kmpc_reduce_nowait: {
  1739. // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
  1740. // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
  1741. // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
  1742. // *lck);
  1743. llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1744. auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
  1745. /*isVarArg=*/false);
  1746. llvm::Type *TypeParams[] = {
  1747. getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
  1748. CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
  1749. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1750. auto *FnTy =
  1751. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1752. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
  1753. break;
  1754. }
  1755. case OMPRTL__kmpc_end_reduce: {
  1756. // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
  1757. // kmp_critical_name *lck);
  1758. llvm::Type *TypeParams[] = {
  1759. getIdentTyPointerTy(), CGM.Int32Ty,
  1760. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1761. auto *FnTy =
  1762. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1763. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
  1764. break;
  1765. }
  1766. case OMPRTL__kmpc_end_reduce_nowait: {
  1767. // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
  1768. // kmp_critical_name *lck);
  1769. llvm::Type *TypeParams[] = {
  1770. getIdentTyPointerTy(), CGM.Int32Ty,
  1771. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1772. auto *FnTy =
  1773. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1774. RTLFn =
  1775. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
  1776. break;
  1777. }
  1778. case OMPRTL__kmpc_omp_task_begin_if0: {
  1779. // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1780. // *new_task);
  1781. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1782. CGM.VoidPtrTy};
  1783. auto *FnTy =
  1784. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1785. RTLFn =
  1786. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
  1787. break;
  1788. }
  1789. case OMPRTL__kmpc_omp_task_complete_if0: {
  1790. // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1791. // *new_task);
  1792. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1793. CGM.VoidPtrTy};
  1794. auto *FnTy =
  1795. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1796. RTLFn = CGM.CreateRuntimeFunction(FnTy,
  1797. /*Name=*/"__kmpc_omp_task_complete_if0");
  1798. break;
  1799. }
  1800. case OMPRTL__kmpc_ordered: {
  1801. // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
  1802. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1803. auto *FnTy =
  1804. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1805. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
  1806. break;
  1807. }
  1808. case OMPRTL__kmpc_end_ordered: {
  1809. // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
  1810. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1811. auto *FnTy =
  1812. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1813. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
  1814. break;
  1815. }
  1816. case OMPRTL__kmpc_omp_taskwait: {
  1817. // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
  1818. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1819. auto *FnTy =
  1820. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1821. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
  1822. break;
  1823. }
  1824. case OMPRTL__kmpc_taskgroup: {
  1825. // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
  1826. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1827. auto *FnTy =
  1828. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1829. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
  1830. break;
  1831. }
  1832. case OMPRTL__kmpc_end_taskgroup: {
  1833. // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
  1834. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1835. auto *FnTy =
  1836. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1837. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
  1838. break;
  1839. }
  1840. case OMPRTL__kmpc_push_proc_bind: {
  1841. // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
  1842. // int proc_bind)
  1843. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1844. auto *FnTy =
  1845. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1846. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
  1847. break;
  1848. }
  1849. case OMPRTL__kmpc_omp_task_with_deps: {
  1850. // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
  1851. // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
  1852. // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
  1853. llvm::Type *TypeParams[] = {
  1854. getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
  1855. CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
  1856. auto *FnTy =
  1857. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1858. RTLFn =
  1859. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
  1860. break;
  1861. }
  1862. case OMPRTL__kmpc_omp_wait_deps: {
  1863. // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
  1864. // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
  1865. // kmp_depend_info_t *noalias_dep_list);
  1866. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1867. CGM.Int32Ty, CGM.VoidPtrTy,
  1868. CGM.Int32Ty, CGM.VoidPtrTy};
  1869. auto *FnTy =
  1870. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1871. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
  1872. break;
  1873. }
  1874. case OMPRTL__kmpc_cancellationpoint: {
  1875. // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  1876. // global_tid, kmp_int32 cncl_kind)
  1877. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1878. auto *FnTy =
  1879. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1880. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
  1881. break;
  1882. }
  1883. case OMPRTL__kmpc_cancel: {
  1884. // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  1885. // kmp_int32 cncl_kind)
  1886. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1887. auto *FnTy =
  1888. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1889. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
  1890. break;
  1891. }
  1892. case OMPRTL__kmpc_push_num_teams: {
  1893. // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
  1894. // kmp_int32 num_teams, kmp_int32 num_threads)
  1895. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  1896. CGM.Int32Ty};
  1897. auto *FnTy =
  1898. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1899. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
  1900. break;
  1901. }
  1902. case OMPRTL__kmpc_fork_teams: {
  1903. // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
  1904. // microtask, ...);
  1905. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1906. getKmpc_MicroPointerTy()};
  1907. auto *FnTy =
  1908. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
  1909. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
  1910. break;
  1911. }
  1912. case OMPRTL__kmpc_taskloop: {
  1913. // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
  1914. // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
  1915. // sched, kmp_uint64 grainsize, void *task_dup);
  1916. llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
  1917. CGM.IntTy,
  1918. CGM.VoidPtrTy,
  1919. CGM.IntTy,
  1920. CGM.Int64Ty->getPointerTo(),
  1921. CGM.Int64Ty->getPointerTo(),
  1922. CGM.Int64Ty,
  1923. CGM.IntTy,
  1924. CGM.IntTy,
  1925. CGM.Int64Ty,
  1926. CGM.VoidPtrTy};
  1927. auto *FnTy =
  1928. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1929. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
  1930. break;
  1931. }
  1932. case OMPRTL__kmpc_doacross_init: {
  1933. // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
  1934. // num_dims, struct kmp_dim *dims);
  1935. llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
  1936. CGM.Int32Ty,
  1937. CGM.Int32Ty,
  1938. CGM.VoidPtrTy};
  1939. auto *FnTy =
  1940. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1941. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
  1942. break;
  1943. }
  1944. case OMPRTL__kmpc_doacross_fini: {
  1945. // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
  1946. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1947. auto *FnTy =
  1948. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1949. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
  1950. break;
  1951. }
  1952. case OMPRTL__kmpc_doacross_post: {
  1953. // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
  1954. // *vec);
  1955. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1956. CGM.Int64Ty->getPointerTo()};
  1957. auto *FnTy =
  1958. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1959. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
  1960. break;
  1961. }
  1962. case OMPRTL__kmpc_doacross_wait: {
  1963. // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
  1964. // *vec);
  1965. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1966. CGM.Int64Ty->getPointerTo()};
  1967. auto *FnTy =
  1968. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1969. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
  1970. break;
  1971. }
  1972. case OMPRTL__kmpc_task_reduction_init: {
  1973. // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
  1974. // *data);
  1975. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
  1976. auto *FnTy =
  1977. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  1978. RTLFn =
  1979. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
  1980. break;
  1981. }
  1982. case OMPRTL__kmpc_task_reduction_get_th_data: {
  1983. // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
  1984. // *d);
  1985. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
  1986. auto *FnTy =
  1987. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  1988. RTLFn = CGM.CreateRuntimeFunction(
  1989. FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
  1990. break;
  1991. }
  1992. case OMPRTL__tgt_target: {
  1993. // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
  1994. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  1995. // *arg_types);
  1996. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  1997. CGM.VoidPtrTy,
  1998. CGM.Int32Ty,
  1999. CGM.VoidPtrPtrTy,
  2000. CGM.VoidPtrPtrTy,
  2001. CGM.SizeTy->getPointerTo(),
  2002. CGM.Int64Ty->getPointerTo()};
  2003. auto *FnTy =
  2004. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2005. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
  2006. break;
  2007. }
  2008. case OMPRTL__tgt_target_nowait: {
  2009. // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
  2010. // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
  2011. // int64_t *arg_types);
  2012. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2013. CGM.VoidPtrTy,
  2014. CGM.Int32Ty,
  2015. CGM.VoidPtrPtrTy,
  2016. CGM.VoidPtrPtrTy,
  2017. CGM.SizeTy->getPointerTo(),
  2018. CGM.Int64Ty->getPointerTo()};
  2019. auto *FnTy =
  2020. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2021. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
  2022. break;
  2023. }
  2024. case OMPRTL__tgt_target_teams: {
  2025. // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
  2026. // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
  2027. // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
  2028. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2029. CGM.VoidPtrTy,
  2030. CGM.Int32Ty,
  2031. CGM.VoidPtrPtrTy,
  2032. CGM.VoidPtrPtrTy,
  2033. CGM.SizeTy->getPointerTo(),
  2034. CGM.Int64Ty->getPointerTo(),
  2035. CGM.Int32Ty,
  2036. CGM.Int32Ty};
  2037. auto *FnTy =
  2038. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2039. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
  2040. break;
  2041. }
  2042. case OMPRTL__tgt_target_teams_nowait: {
  2043. // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
  2044. // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
  2045. // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
  2046. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2047. CGM.VoidPtrTy,
  2048. CGM.Int32Ty,
  2049. CGM.VoidPtrPtrTy,
  2050. CGM.VoidPtrPtrTy,
  2051. CGM.SizeTy->getPointerTo(),
  2052. CGM.Int64Ty->getPointerTo(),
  2053. CGM.Int32Ty,
  2054. CGM.Int32Ty};
  2055. auto *FnTy =
  2056. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2057. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
  2058. break;
  2059. }
  2060. case OMPRTL__tgt_register_lib: {
  2061. // Build void __tgt_register_lib(__tgt_bin_desc *desc);
  2062. QualType ParamTy =
  2063. CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
  2064. llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
  2065. auto *FnTy =
  2066. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2067. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
  2068. break;
  2069. }
  2070. case OMPRTL__tgt_unregister_lib: {
  2071. // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
  2072. QualType ParamTy =
  2073. CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
  2074. llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
  2075. auto *FnTy =
  2076. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2077. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
  2078. break;
  2079. }
  2080. case OMPRTL__tgt_target_data_begin: {
  2081. // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
  2082. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  2083. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2084. CGM.Int32Ty,
  2085. CGM.VoidPtrPtrTy,
  2086. CGM.VoidPtrPtrTy,
  2087. CGM.SizeTy->getPointerTo(),
  2088. CGM.Int64Ty->getPointerTo()};
  2089. auto *FnTy =
  2090. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2091. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
  2092. break;
  2093. }
  2094. case OMPRTL__tgt_target_data_begin_nowait: {
  2095. // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
  2096. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  2097. // *arg_types);
  2098. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2099. CGM.Int32Ty,
  2100. CGM.VoidPtrPtrTy,
  2101. CGM.VoidPtrPtrTy,
  2102. CGM.SizeTy->getPointerTo(),
  2103. CGM.Int64Ty->getPointerTo()};
  2104. auto *FnTy =
  2105. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2106. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
  2107. break;
  2108. }
  2109. case OMPRTL__tgt_target_data_end: {
  2110. // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
  2111. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  2112. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2113. CGM.Int32Ty,
  2114. CGM.VoidPtrPtrTy,
  2115. CGM.VoidPtrPtrTy,
  2116. CGM.SizeTy->getPointerTo(),
  2117. CGM.Int64Ty->getPointerTo()};
  2118. auto *FnTy =
  2119. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2120. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
  2121. break;
  2122. }
  2123. case OMPRTL__tgt_target_data_end_nowait: {
  2124. // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
  2125. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  2126. // *arg_types);
  2127. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2128. CGM.Int32Ty,
  2129. CGM.VoidPtrPtrTy,
  2130. CGM.VoidPtrPtrTy,
  2131. CGM.SizeTy->getPointerTo(),
  2132. CGM.Int64Ty->getPointerTo()};
  2133. auto *FnTy =
  2134. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2135. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
  2136. break;
  2137. }
  2138. case OMPRTL__tgt_target_data_update: {
  2139. // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
  2140. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  2141. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2142. CGM.Int32Ty,
  2143. CGM.VoidPtrPtrTy,
  2144. CGM.VoidPtrPtrTy,
  2145. CGM.SizeTy->getPointerTo(),
  2146. CGM.Int64Ty->getPointerTo()};
  2147. auto *FnTy =
  2148. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2149. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
  2150. break;
  2151. }
  2152. case OMPRTL__tgt_target_data_update_nowait: {
  2153. // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
  2154. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  2155. // *arg_types);
  2156. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2157. CGM.Int32Ty,
  2158. CGM.VoidPtrPtrTy,
  2159. CGM.VoidPtrPtrTy,
  2160. CGM.SizeTy->getPointerTo(),
  2161. CGM.Int64Ty->getPointerTo()};
  2162. auto *FnTy =
  2163. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2164. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
  2165. break;
  2166. }
  2167. }
  2168. assert(RTLFn && "Unable to find OpenMP runtime function");
  2169. return RTLFn;
  2170. }
  2171. llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
  2172. bool IVSigned) {
  2173. assert((IVSize == 32 || IVSize == 64) &&
  2174. "IV size is not compatible with the omp runtime");
  2175. StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
  2176. : "__kmpc_for_static_init_4u")
  2177. : (IVSigned ? "__kmpc_for_static_init_8"
  2178. : "__kmpc_for_static_init_8u");
  2179. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2180. auto *PtrTy = llvm::PointerType::getUnqual(ITy);
  2181. llvm::Type *TypeParams[] = {
  2182. getIdentTyPointerTy(), // loc
  2183. CGM.Int32Ty, // tid
  2184. CGM.Int32Ty, // schedtype
  2185. llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
  2186. PtrTy, // p_lower
  2187. PtrTy, // p_upper
  2188. PtrTy, // p_stride
  2189. ITy, // incr
  2190. ITy // chunk
  2191. };
  2192. auto *FnTy =
  2193. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2194. return CGM.CreateRuntimeFunction(FnTy, Name);
  2195. }
  2196. llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
  2197. bool IVSigned) {
  2198. assert((IVSize == 32 || IVSize == 64) &&
  2199. "IV size is not compatible with the omp runtime");
  2200. StringRef Name =
  2201. IVSize == 32
  2202. ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
  2203. : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
  2204. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2205. llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
  2206. CGM.Int32Ty, // tid
  2207. CGM.Int32Ty, // schedtype
  2208. ITy, // lower
  2209. ITy, // upper
  2210. ITy, // stride
  2211. ITy // chunk
  2212. };
  2213. auto *FnTy =
  2214. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2215. return CGM.CreateRuntimeFunction(FnTy, Name);
  2216. }
  2217. llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
  2218. bool IVSigned) {
  2219. assert((IVSize == 32 || IVSize == 64) &&
  2220. "IV size is not compatible with the omp runtime");
  2221. StringRef Name =
  2222. IVSize == 32
  2223. ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
  2224. : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
  2225. llvm::Type *TypeParams[] = {
  2226. getIdentTyPointerTy(), // loc
  2227. CGM.Int32Ty, // tid
  2228. };
  2229. auto *FnTy =
  2230. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2231. return CGM.CreateRuntimeFunction(FnTy, Name);
  2232. }
  2233. llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
  2234. bool IVSigned) {
  2235. assert((IVSize == 32 || IVSize == 64) &&
  2236. "IV size is not compatible with the omp runtime");
  2237. StringRef Name =
  2238. IVSize == 32
  2239. ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
  2240. : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
  2241. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2242. auto *PtrTy = llvm::PointerType::getUnqual(ITy);
  2243. llvm::Type *TypeParams[] = {
  2244. getIdentTyPointerTy(), // loc
  2245. CGM.Int32Ty, // tid
  2246. llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
  2247. PtrTy, // p_lower
  2248. PtrTy, // p_upper
  2249. PtrTy // p_stride
  2250. };
  2251. auto *FnTy =
  2252. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2253. return CGM.CreateRuntimeFunction(FnTy, Name);
  2254. }
  2255. Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
  2256. if (CGM.getLangOpts().OpenMPSimd)
  2257. return Address::invalid();
  2258. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2259. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2260. if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2261. SmallString<64> PtrName;
  2262. {
  2263. llvm::raw_svector_ostream OS(PtrName);
  2264. OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
  2265. }
  2266. llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
  2267. if (!Ptr) {
  2268. QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
  2269. Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
  2270. PtrName);
  2271. if (!CGM.getLangOpts().OpenMPIsDevice) {
  2272. auto *GV = cast<llvm::GlobalVariable>(Ptr);
  2273. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2274. GV->setInitializer(CGM.GetAddrOfGlobal(VD));
  2275. }
  2276. CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
  2277. registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
  2278. }
  2279. return Address(Ptr, CGM.getContext().getDeclAlign(VD));
  2280. }
  2281. return Address::invalid();
  2282. }
  2283. llvm::Constant *
  2284. CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
  2285. assert(!CGM.getLangOpts().OpenMPUseTLS ||
  2286. !CGM.getContext().getTargetInfo().isTLSSupported());
  2287. // Lookup the entry, lazily creating it if necessary.
  2288. std::string Suffix = getName({"cache", ""});
  2289. return getOrCreateInternalVariable(
  2290. CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
  2291. }
  2292. Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
  2293. const VarDecl *VD,
  2294. Address VDAddr,
  2295. SourceLocation Loc) {
  2296. if (CGM.getLangOpts().OpenMPUseTLS &&
  2297. CGM.getContext().getTargetInfo().isTLSSupported())
  2298. return VDAddr;
  2299. llvm::Type *VarTy = VDAddr.getElementType();
  2300. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2301. CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
  2302. CGM.Int8PtrTy),
  2303. CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
  2304. getOrCreateThreadPrivateCache(VD)};
  2305. return Address(CGF.EmitRuntimeCall(
  2306. createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
  2307. VDAddr.getAlignment());
  2308. }
  2309. void CGOpenMPRuntime::emitThreadPrivateVarInit(
  2310. CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
  2311. llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
  2312. // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
  2313. // library.
  2314. llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
  2315. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
  2316. OMPLoc);
  2317. // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
  2318. // to register constructor/destructor for variable.
  2319. llvm::Value *Args[] = {
  2320. OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
  2321. Ctor, CopyCtor, Dtor};
  2322. CGF.EmitRuntimeCall(
  2323. createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
  2324. }
  2325. llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
  2326. const VarDecl *VD, Address VDAddr, SourceLocation Loc,
  2327. bool PerformInit, CodeGenFunction *CGF) {
  2328. if (CGM.getLangOpts().OpenMPUseTLS &&
  2329. CGM.getContext().getTargetInfo().isTLSSupported())
  2330. return nullptr;
  2331. VD = VD->getDefinition(CGM.getContext());
  2332. if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
  2333. ThreadPrivateWithDefinition.insert(VD);
  2334. QualType ASTTy = VD->getType();
  2335. llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
  2336. const Expr *Init = VD->getAnyInitializer();
  2337. if (CGM.getLangOpts().CPlusPlus && PerformInit) {
  2338. // Generate function that re-emits the declaration's initializer into the
  2339. // threadprivate copy of the variable VD
  2340. CodeGenFunction CtorCGF(CGM);
  2341. FunctionArgList Args;
  2342. ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
  2343. /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
  2344. ImplicitParamDecl::Other);
  2345. Args.push_back(&Dst);
  2346. const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
  2347. CGM.getContext().VoidPtrTy, Args);
  2348. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2349. std::string Name = getName({"__kmpc_global_ctor_", ""});
  2350. llvm::Function *Fn =
  2351. CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
  2352. CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
  2353. Args, Loc, Loc);
  2354. llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
  2355. CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
  2356. CGM.getContext().VoidPtrTy, Dst.getLocation());
  2357. Address Arg = Address(ArgVal, VDAddr.getAlignment());
  2358. Arg = CtorCGF.Builder.CreateElementBitCast(
  2359. Arg, CtorCGF.ConvertTypeForMem(ASTTy));
  2360. CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
  2361. /*IsInitializer=*/true);
  2362. ArgVal = CtorCGF.EmitLoadOfScalar(
  2363. CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
  2364. CGM.getContext().VoidPtrTy, Dst.getLocation());
  2365. CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
  2366. CtorCGF.FinishFunction();
  2367. Ctor = Fn;
  2368. }
  2369. if (VD->getType().isDestructedType() != QualType::DK_none) {
  2370. // Generate function that emits destructor call for the threadprivate copy
  2371. // of the variable VD
  2372. CodeGenFunction DtorCGF(CGM);
  2373. FunctionArgList Args;
  2374. ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
  2375. /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
  2376. ImplicitParamDecl::Other);
  2377. Args.push_back(&Dst);
  2378. const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
  2379. CGM.getContext().VoidTy, Args);
  2380. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2381. std::string Name = getName({"__kmpc_global_dtor_", ""});
  2382. llvm::Function *Fn =
  2383. CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
  2384. auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
  2385. DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
  2386. Loc, Loc);
  2387. // Create a scope with an artificial location for the body of this function.
  2388. auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
  2389. llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
  2390. DtorCGF.GetAddrOfLocalVar(&Dst),
  2391. /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
  2392. DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
  2393. DtorCGF.getDestroyer(ASTTy.isDestructedType()),
  2394. DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
  2395. DtorCGF.FinishFunction();
  2396. Dtor = Fn;
  2397. }
  2398. // Do not emit init function if it is not required.
  2399. if (!Ctor && !Dtor)
  2400. return nullptr;
  2401. llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  2402. auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
  2403. /*isVarArg=*/false)
  2404. ->getPointerTo();
  2405. // Copying constructor for the threadprivate variable.
  2406. // Must be NULL - reserved by runtime, but currently it requires that this
  2407. // parameter is always NULL. Otherwise it fires assertion.
  2408. CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
  2409. if (Ctor == nullptr) {
  2410. auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
  2411. /*isVarArg=*/false)
  2412. ->getPointerTo();
  2413. Ctor = llvm::Constant::getNullValue(CtorTy);
  2414. }
  2415. if (Dtor == nullptr) {
  2416. auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
  2417. /*isVarArg=*/false)
  2418. ->getPointerTo();
  2419. Dtor = llvm::Constant::getNullValue(DtorTy);
  2420. }
  2421. if (!CGF) {
  2422. auto *InitFunctionTy =
  2423. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
  2424. std::string Name = getName({"__omp_threadprivate_init_", ""});
  2425. llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
  2426. InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
  2427. CodeGenFunction InitCGF(CGM);
  2428. FunctionArgList ArgList;
  2429. InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
  2430. CGM.getTypes().arrangeNullaryFunction(), ArgList,
  2431. Loc, Loc);
  2432. emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
  2433. InitCGF.FinishFunction();
  2434. return InitFunction;
  2435. }
  2436. emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
  2437. }
  2438. return nullptr;
  2439. }
  2440. /// Obtain information that uniquely identifies a target entry. This
  2441. /// consists of the file and device IDs as well as line number associated with
  2442. /// the relevant entry source location.
  2443. static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
  2444. unsigned &DeviceID, unsigned &FileID,
  2445. unsigned &LineNum) {
  2446. SourceManager &SM = C.getSourceManager();
  2447. // The loc should be always valid and have a file ID (the user cannot use
  2448. // #pragma directives in macros)
  2449. assert(Loc.isValid() && "Source location is expected to be always valid.");
  2450. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  2451. assert(PLoc.isValid() && "Source location is expected to be always valid.");
  2452. llvm::sys::fs::UniqueID ID;
  2453. if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
  2454. SM.getDiagnostics().Report(diag::err_cannot_open_file)
  2455. << PLoc.getFilename() << EC.message();
  2456. DeviceID = ID.getDevice();
  2457. FileID = ID.getFile();
  2458. LineNum = PLoc.getLine();
  2459. }
  2460. bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
  2461. llvm::GlobalVariable *Addr,
  2462. bool PerformInit) {
  2463. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2464. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2465. if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
  2466. return CGM.getLangOpts().OpenMPIsDevice;
  2467. VD = VD->getDefinition(CGM.getContext());
  2468. if (VD && !DeclareTargetWithDefinition.insert(VD).second)
  2469. return CGM.getLangOpts().OpenMPIsDevice;
  2470. QualType ASTTy = VD->getType();
  2471. SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
  2472. // Produce the unique prefix to identify the new target regions. We use
  2473. // the source location of the variable declaration which we know to not
  2474. // conflict with any target region.
  2475. unsigned DeviceID;
  2476. unsigned FileID;
  2477. unsigned Line;
  2478. getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
  2479. SmallString<128> Buffer, Out;
  2480. {
  2481. llvm::raw_svector_ostream OS(Buffer);
  2482. OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
  2483. << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
  2484. }
  2485. const Expr *Init = VD->getAnyInitializer();
  2486. if (CGM.getLangOpts().CPlusPlus && PerformInit) {
  2487. llvm::Constant *Ctor;
  2488. llvm::Constant *ID;
  2489. if (CGM.getLangOpts().OpenMPIsDevice) {
  2490. // Generate function that re-emits the declaration's initializer into
  2491. // the threadprivate copy of the variable VD
  2492. CodeGenFunction CtorCGF(CGM);
  2493. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2494. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2495. llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
  2496. FTy, Twine(Buffer, "_ctor"), FI, Loc);
  2497. auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
  2498. CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
  2499. FunctionArgList(), Loc, Loc);
  2500. auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
  2501. CtorCGF.EmitAnyExprToMem(Init,
  2502. Address(Addr, CGM.getContext().getDeclAlign(VD)),
  2503. Init->getType().getQualifiers(),
  2504. /*IsInitializer=*/true);
  2505. CtorCGF.FinishFunction();
  2506. Ctor = Fn;
  2507. ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  2508. CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
  2509. } else {
  2510. Ctor = new llvm::GlobalVariable(
  2511. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  2512. llvm::GlobalValue::PrivateLinkage,
  2513. llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
  2514. ID = Ctor;
  2515. }
  2516. // Register the information for the entry associated with the constructor.
  2517. Out.clear();
  2518. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  2519. DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
  2520. ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
  2521. }
  2522. if (VD->getType().isDestructedType() != QualType::DK_none) {
  2523. llvm::Constant *Dtor;
  2524. llvm::Constant *ID;
  2525. if (CGM.getLangOpts().OpenMPIsDevice) {
  2526. // Generate function that emits destructor call for the threadprivate
  2527. // copy of the variable VD
  2528. CodeGenFunction DtorCGF(CGM);
  2529. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2530. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2531. llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
  2532. FTy, Twine(Buffer, "_dtor"), FI, Loc);
  2533. auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
  2534. DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
  2535. FunctionArgList(), Loc, Loc);
  2536. // Create a scope with an artificial location for the body of this
  2537. // function.
  2538. auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
  2539. DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
  2540. ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
  2541. DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
  2542. DtorCGF.FinishFunction();
  2543. Dtor = Fn;
  2544. ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  2545. CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
  2546. } else {
  2547. Dtor = new llvm::GlobalVariable(
  2548. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  2549. llvm::GlobalValue::PrivateLinkage,
  2550. llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
  2551. ID = Dtor;
  2552. }
  2553. // Register the information for the entry associated with the destructor.
  2554. Out.clear();
  2555. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  2556. DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
  2557. ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
  2558. }
  2559. return CGM.getLangOpts().OpenMPIsDevice;
  2560. }
  2561. Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
  2562. QualType VarType,
  2563. StringRef Name) {
  2564. std::string Suffix = getName({"artificial", ""});
  2565. std::string CacheSuffix = getName({"cache", ""});
  2566. llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
  2567. llvm::Value *GAddr =
  2568. getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
  2569. llvm::Value *Args[] = {
  2570. emitUpdateLocation(CGF, SourceLocation()),
  2571. getThreadID(CGF, SourceLocation()),
  2572. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
  2573. CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
  2574. /*IsSigned=*/false),
  2575. getOrCreateInternalVariable(
  2576. CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
  2577. return Address(
  2578. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2579. CGF.EmitRuntimeCall(
  2580. createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
  2581. VarLVType->getPointerTo(/*AddrSpace=*/0)),
  2582. CGM.getPointerAlign());
  2583. }
  2584. void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
  2585. const RegionCodeGenTy &ThenGen,
  2586. const RegionCodeGenTy &ElseGen) {
  2587. CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
  2588. // If the condition constant folds and can be elided, try to avoid emitting
  2589. // the condition and the dead arm of the if/else.
  2590. bool CondConstant;
  2591. if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
  2592. if (CondConstant)
  2593. ThenGen(CGF);
  2594. else
  2595. ElseGen(CGF);
  2596. return;
  2597. }
  2598. // Otherwise, the condition did not fold, or we couldn't elide it. Just
  2599. // emit the conditional branch.
  2600. llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
  2601. llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
  2602. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
  2603. CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
  2604. // Emit the 'then' code.
  2605. CGF.EmitBlock(ThenBlock);
  2606. ThenGen(CGF);
  2607. CGF.EmitBranch(ContBlock);
  2608. // Emit the 'else' code if present.
  2609. // There is no need to emit line number for unconditional branch.
  2610. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2611. CGF.EmitBlock(ElseBlock);
  2612. ElseGen(CGF);
  2613. // There is no need to emit line number for unconditional branch.
  2614. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2615. CGF.EmitBranch(ContBlock);
  2616. // Emit the continuation block for code after the if.
  2617. CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
  2618. }
  2619. void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  2620. llvm::Value *OutlinedFn,
  2621. ArrayRef<llvm::Value *> CapturedVars,
  2622. const Expr *IfCond) {
  2623. if (!CGF.HaveInsertPoint())
  2624. return;
  2625. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  2626. auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
  2627. PrePostActionTy &) {
  2628. // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
  2629. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  2630. llvm::Value *Args[] = {
  2631. RTLoc,
  2632. CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
  2633. CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
  2634. llvm::SmallVector<llvm::Value *, 16> RealArgs;
  2635. RealArgs.append(std::begin(Args), std::end(Args));
  2636. RealArgs.append(CapturedVars.begin(), CapturedVars.end());
  2637. llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
  2638. CGF.EmitRuntimeCall(RTLFn, RealArgs);
  2639. };
  2640. auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
  2641. PrePostActionTy &) {
  2642. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  2643. llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
  2644. // Build calls:
  2645. // __kmpc_serialized_parallel(&Loc, GTid);
  2646. llvm::Value *Args[] = {RTLoc, ThreadID};
  2647. CGF.EmitRuntimeCall(
  2648. RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
  2649. // OutlinedFn(&GTid, &zero, CapturedStruct);
  2650. Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2651. /*Name*/ ".zero.addr");
  2652. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  2653. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
  2654. // ThreadId for serialized parallels is 0.
  2655. OutlinedFnArgs.push_back(ZeroAddr.getPointer());
  2656. OutlinedFnArgs.push_back(ZeroAddr.getPointer());
  2657. OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
  2658. RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
  2659. // __kmpc_end_serialized_parallel(&Loc, GTid);
  2660. llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
  2661. CGF.EmitRuntimeCall(
  2662. RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
  2663. EndArgs);
  2664. };
  2665. if (IfCond) {
  2666. emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
  2667. } else {
  2668. RegionCodeGenTy ThenRCG(ThenGen);
  2669. ThenRCG(CGF);
  2670. }
  2671. }
  2672. // If we're inside an (outlined) parallel region, use the region info's
  2673. // thread-ID variable (it is passed in a first argument of the outlined function
  2674. // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
  2675. // regular serial code region, get thread ID by calling kmp_int32
  2676. // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
  2677. // return the address of that temp.
  2678. Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
  2679. SourceLocation Loc) {
  2680. if (auto *OMPRegionInfo =
  2681. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  2682. if (OMPRegionInfo->getThreadIDVariable())
  2683. return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
  2684. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  2685. QualType Int32Ty =
  2686. CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
  2687. Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
  2688. CGF.EmitStoreOfScalar(ThreadID,
  2689. CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
  2690. return ThreadIDTemp;
  2691. }
  2692. llvm::Constant *
  2693. CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
  2694. const llvm::Twine &Name) {
  2695. SmallString<256> Buffer;
  2696. llvm::raw_svector_ostream Out(Buffer);
  2697. Out << Name;
  2698. StringRef RuntimeName = Out.str();
  2699. auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
  2700. if (Elem.second) {
  2701. assert(Elem.second->getType()->getPointerElementType() == Ty &&
  2702. "OMP internal variable has different type than requested");
  2703. return &*Elem.second;
  2704. }
  2705. return Elem.second = new llvm::GlobalVariable(
  2706. CGM.getModule(), Ty, /*IsConstant*/ false,
  2707. llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
  2708. Elem.first());
  2709. }
  2710. llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
  2711. std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
  2712. std::string Name = getName({Prefix, "var"});
  2713. return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
  2714. }
  2715. namespace {
  2716. /// Common pre(post)-action for different OpenMP constructs.
  2717. class CommonActionTy final : public PrePostActionTy {
  2718. llvm::Value *EnterCallee;
  2719. ArrayRef<llvm::Value *> EnterArgs;
  2720. llvm::Value *ExitCallee;
  2721. ArrayRef<llvm::Value *> ExitArgs;
  2722. bool Conditional;
  2723. llvm::BasicBlock *ContBlock = nullptr;
  2724. public:
  2725. CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
  2726. llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
  2727. bool Conditional = false)
  2728. : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
  2729. ExitArgs(ExitArgs), Conditional(Conditional) {}
  2730. void Enter(CodeGenFunction &CGF) override {
  2731. llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
  2732. if (Conditional) {
  2733. llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
  2734. auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
  2735. ContBlock = CGF.createBasicBlock("omp_if.end");
  2736. // Generate the branch (If-stmt)
  2737. CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
  2738. CGF.EmitBlock(ThenBlock);
  2739. }
  2740. }
  2741. void Done(CodeGenFunction &CGF) {
  2742. // Emit the rest of blocks/branches
  2743. CGF.EmitBranch(ContBlock);
  2744. CGF.EmitBlock(ContBlock, true);
  2745. }
  2746. void Exit(CodeGenFunction &CGF) override {
  2747. CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
  2748. }
  2749. };
  2750. } // anonymous namespace
  2751. void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
  2752. StringRef CriticalName,
  2753. const RegionCodeGenTy &CriticalOpGen,
  2754. SourceLocation Loc, const Expr *Hint) {
  2755. // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
  2756. // CriticalOpGen();
  2757. // __kmpc_end_critical(ident_t *, gtid, Lock);
  2758. // Prepare arguments and build a call to __kmpc_critical
  2759. if (!CGF.HaveInsertPoint())
  2760. return;
  2761. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2762. getCriticalRegionLock(CriticalName)};
  2763. llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
  2764. std::end(Args));
  2765. if (Hint) {
  2766. EnterArgs.push_back(CGF.Builder.CreateIntCast(
  2767. CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
  2768. }
  2769. CommonActionTy Action(
  2770. createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
  2771. : OMPRTL__kmpc_critical),
  2772. EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
  2773. CriticalOpGen.setAction(Action);
  2774. emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
  2775. }
  2776. void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
  2777. const RegionCodeGenTy &MasterOpGen,
  2778. SourceLocation Loc) {
  2779. if (!CGF.HaveInsertPoint())
  2780. return;
  2781. // if(__kmpc_master(ident_t *, gtid)) {
  2782. // MasterOpGen();
  2783. // __kmpc_end_master(ident_t *, gtid);
  2784. // }
  2785. // Prepare arguments and build a call to __kmpc_master
  2786. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  2787. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
  2788. createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
  2789. /*Conditional=*/true);
  2790. MasterOpGen.setAction(Action);
  2791. emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
  2792. Action.Done(CGF);
  2793. }
  2794. void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
  2795. SourceLocation Loc) {
  2796. if (!CGF.HaveInsertPoint())
  2797. return;
  2798. // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
  2799. llvm::Value *Args[] = {
  2800. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2801. llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
  2802. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
  2803. if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  2804. Region->emitUntiedSwitch(CGF);
  2805. }
  2806. void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
  2807. const RegionCodeGenTy &TaskgroupOpGen,
  2808. SourceLocation Loc) {
  2809. if (!CGF.HaveInsertPoint())
  2810. return;
  2811. // __kmpc_taskgroup(ident_t *, gtid);
  2812. // TaskgroupOpGen();
  2813. // __kmpc_end_taskgroup(ident_t *, gtid);
  2814. // Prepare arguments and build a call to __kmpc_taskgroup
  2815. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  2816. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
  2817. createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
  2818. Args);
  2819. TaskgroupOpGen.setAction(Action);
  2820. emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
  2821. }
  2822. /// Given an array of pointers to variables, project the address of a
  2823. /// given variable.
  2824. static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
  2825. unsigned Index, const VarDecl *Var) {
  2826. // Pull out the pointer to the variable.
  2827. Address PtrAddr =
  2828. CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
  2829. llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
  2830. Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
  2831. Addr = CGF.Builder.CreateElementBitCast(
  2832. Addr, CGF.ConvertTypeForMem(Var->getType()));
  2833. return Addr;
  2834. }
  2835. static llvm::Value *emitCopyprivateCopyFunction(
  2836. CodeGenModule &CGM, llvm::Type *ArgsType,
  2837. ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
  2838. ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
  2839. SourceLocation Loc) {
  2840. ASTContext &C = CGM.getContext();
  2841. // void copy_func(void *LHSArg, void *RHSArg);
  2842. FunctionArgList Args;
  2843. ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  2844. ImplicitParamDecl::Other);
  2845. ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  2846. ImplicitParamDecl::Other);
  2847. Args.push_back(&LHSArg);
  2848. Args.push_back(&RHSArg);
  2849. const auto &CGFI =
  2850. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  2851. std::string Name =
  2852. CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
  2853. auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
  2854. llvm::GlobalValue::InternalLinkage, Name,
  2855. &CGM.getModule());
  2856. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  2857. Fn->setDoesNotRecurse();
  2858. CodeGenFunction CGF(CGM);
  2859. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  2860. // Dest = (void*[n])(LHSArg);
  2861. // Src = (void*[n])(RHSArg);
  2862. Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2863. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
  2864. ArgsType), CGF.getPointerAlign());
  2865. Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2866. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
  2867. ArgsType), CGF.getPointerAlign());
  2868. // *(Type0*)Dst[0] = *(Type0*)Src[0];
  2869. // *(Type1*)Dst[1] = *(Type1*)Src[1];
  2870. // ...
  2871. // *(Typen*)Dst[n] = *(Typen*)Src[n];
  2872. for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
  2873. const auto *DestVar =
  2874. cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
  2875. Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
  2876. const auto *SrcVar =
  2877. cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
  2878. Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
  2879. const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
  2880. QualType Type = VD->getType();
  2881. CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
  2882. }
  2883. CGF.FinishFunction();
  2884. return Fn;
  2885. }
  2886. void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
  2887. const RegionCodeGenTy &SingleOpGen,
  2888. SourceLocation Loc,
  2889. ArrayRef<const Expr *> CopyprivateVars,
  2890. ArrayRef<const Expr *> SrcExprs,
  2891. ArrayRef<const Expr *> DstExprs,
  2892. ArrayRef<const Expr *> AssignmentOps) {
  2893. if (!CGF.HaveInsertPoint())
  2894. return;
  2895. assert(CopyprivateVars.size() == SrcExprs.size() &&
  2896. CopyprivateVars.size() == DstExprs.size() &&
  2897. CopyprivateVars.size() == AssignmentOps.size());
  2898. ASTContext &C = CGM.getContext();
  2899. // int32 did_it = 0;
  2900. // if(__kmpc_single(ident_t *, gtid)) {
  2901. // SingleOpGen();
  2902. // __kmpc_end_single(ident_t *, gtid);
  2903. // did_it = 1;
  2904. // }
  2905. // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
  2906. // <copy_func>, did_it);
  2907. Address DidIt = Address::invalid();
  2908. if (!CopyprivateVars.empty()) {
  2909. // int32 did_it = 0;
  2910. QualType KmpInt32Ty =
  2911. C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  2912. DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
  2913. CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
  2914. }
  2915. // Prepare arguments and build a call to __kmpc_single
  2916. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  2917. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
  2918. createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
  2919. /*Conditional=*/true);
  2920. SingleOpGen.setAction(Action);
  2921. emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
  2922. if (DidIt.isValid()) {
  2923. // did_it = 1;
  2924. CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
  2925. }
  2926. Action.Done(CGF);
  2927. // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
  2928. // <copy_func>, did_it);
  2929. if (DidIt.isValid()) {
  2930. llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
  2931. QualType CopyprivateArrayTy =
  2932. C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
  2933. /*IndexTypeQuals=*/0);
  2934. // Create a list of all private variables for copyprivate.
  2935. Address CopyprivateList =
  2936. CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
  2937. for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
  2938. Address Elem = CGF.Builder.CreateConstArrayGEP(
  2939. CopyprivateList, I, CGF.getPointerSize());
  2940. CGF.Builder.CreateStore(
  2941. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2942. CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
  2943. Elem);
  2944. }
  2945. // Build function that copies private values from single region to all other
  2946. // threads in the corresponding parallel region.
  2947. llvm::Value *CpyFn = emitCopyprivateCopyFunction(
  2948. CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
  2949. CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
  2950. llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
  2951. Address CL =
  2952. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
  2953. CGF.VoidPtrTy);
  2954. llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
  2955. llvm::Value *Args[] = {
  2956. emitUpdateLocation(CGF, Loc), // ident_t *<loc>
  2957. getThreadID(CGF, Loc), // i32 <gtid>
  2958. BufSize, // size_t <buf_size>
  2959. CL.getPointer(), // void *<copyprivate list>
  2960. CpyFn, // void (*) (void *, void *) <copy_func>
  2961. DidItVal // i32 did_it
  2962. };
  2963. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
  2964. }
  2965. }
  2966. void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
  2967. const RegionCodeGenTy &OrderedOpGen,
  2968. SourceLocation Loc, bool IsThreads) {
  2969. if (!CGF.HaveInsertPoint())
  2970. return;
  2971. // __kmpc_ordered(ident_t *, gtid);
  2972. // OrderedOpGen();
  2973. // __kmpc_end_ordered(ident_t *, gtid);
  2974. // Prepare arguments and build a call to __kmpc_ordered
  2975. if (IsThreads) {
  2976. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  2977. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
  2978. createRuntimeFunction(OMPRTL__kmpc_end_ordered),
  2979. Args);
  2980. OrderedOpGen.setAction(Action);
  2981. emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
  2982. return;
  2983. }
  2984. emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
  2985. }
  2986. void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
  2987. OpenMPDirectiveKind Kind, bool EmitChecks,
  2988. bool ForceSimpleCall) {
  2989. if (!CGF.HaveInsertPoint())
  2990. return;
  2991. // Build call __kmpc_cancel_barrier(loc, thread_id);
  2992. // Build call __kmpc_barrier(loc, thread_id);
  2993. unsigned Flags;
  2994. if (Kind == OMPD_for)
  2995. Flags = OMP_IDENT_BARRIER_IMPL_FOR;
  2996. else if (Kind == OMPD_sections)
  2997. Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
  2998. else if (Kind == OMPD_single)
  2999. Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
  3000. else if (Kind == OMPD_barrier)
  3001. Flags = OMP_IDENT_BARRIER_EXPL;
  3002. else
  3003. Flags = OMP_IDENT_BARRIER_IMPL;
  3004. // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
  3005. // thread_id);
  3006. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
  3007. getThreadID(CGF, Loc)};
  3008. if (auto *OMPRegionInfo =
  3009. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  3010. if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
  3011. llvm::Value *Result = CGF.EmitRuntimeCall(
  3012. createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
  3013. if (EmitChecks) {
  3014. // if (__kmpc_cancel_barrier()) {
  3015. // exit from construct;
  3016. // }
  3017. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  3018. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  3019. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  3020. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  3021. CGF.EmitBlock(ExitBB);
  3022. // exit from construct;
  3023. CodeGenFunction::JumpDest CancelDestination =
  3024. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  3025. CGF.EmitBranchThroughCleanup(CancelDestination);
  3026. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  3027. }
  3028. return;
  3029. }
  3030. }
  3031. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
  3032. }
  3033. /// Map the OpenMP loop schedule to the runtime enumeration.
  3034. static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
  3035. bool Chunked, bool Ordered) {
  3036. switch (ScheduleKind) {
  3037. case OMPC_SCHEDULE_static:
  3038. return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
  3039. : (Ordered ? OMP_ord_static : OMP_sch_static);
  3040. case OMPC_SCHEDULE_dynamic:
  3041. return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
  3042. case OMPC_SCHEDULE_guided:
  3043. return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
  3044. case OMPC_SCHEDULE_runtime:
  3045. return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
  3046. case OMPC_SCHEDULE_auto:
  3047. return Ordered ? OMP_ord_auto : OMP_sch_auto;
  3048. case OMPC_SCHEDULE_unknown:
  3049. assert(!Chunked && "chunk was specified but schedule kind not known");
  3050. return Ordered ? OMP_ord_static : OMP_sch_static;
  3051. }
  3052. llvm_unreachable("Unexpected runtime schedule");
  3053. }
  3054. /// Map the OpenMP distribute schedule to the runtime enumeration.
  3055. static OpenMPSchedType
  3056. getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
  3057. // only static is allowed for dist_schedule
  3058. return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
  3059. }
  3060. bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
  3061. bool Chunked) const {
  3062. OpenMPSchedType Schedule =
  3063. getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
  3064. return Schedule == OMP_sch_static;
  3065. }
  3066. bool CGOpenMPRuntime::isStaticNonchunked(
  3067. OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
  3068. OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
  3069. return Schedule == OMP_dist_sch_static;
  3070. }
  3071. bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
  3072. OpenMPSchedType Schedule =
  3073. getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
  3074. assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
  3075. return Schedule != OMP_sch_static;
  3076. }
  3077. static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
  3078. OpenMPScheduleClauseModifier M1,
  3079. OpenMPScheduleClauseModifier M2) {
  3080. int Modifier = 0;
  3081. switch (M1) {
  3082. case OMPC_SCHEDULE_MODIFIER_monotonic:
  3083. Modifier = OMP_sch_modifier_monotonic;
  3084. break;
  3085. case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
  3086. Modifier = OMP_sch_modifier_nonmonotonic;
  3087. break;
  3088. case OMPC_SCHEDULE_MODIFIER_simd:
  3089. if (Schedule == OMP_sch_static_chunked)
  3090. Schedule = OMP_sch_static_balanced_chunked;
  3091. break;
  3092. case OMPC_SCHEDULE_MODIFIER_last:
  3093. case OMPC_SCHEDULE_MODIFIER_unknown:
  3094. break;
  3095. }
  3096. switch (M2) {
  3097. case OMPC_SCHEDULE_MODIFIER_monotonic:
  3098. Modifier = OMP_sch_modifier_monotonic;
  3099. break;
  3100. case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
  3101. Modifier = OMP_sch_modifier_nonmonotonic;
  3102. break;
  3103. case OMPC_SCHEDULE_MODIFIER_simd:
  3104. if (Schedule == OMP_sch_static_chunked)
  3105. Schedule = OMP_sch_static_balanced_chunked;
  3106. break;
  3107. case OMPC_SCHEDULE_MODIFIER_last:
  3108. case OMPC_SCHEDULE_MODIFIER_unknown:
  3109. break;
  3110. }
  3111. return Schedule | Modifier;
  3112. }
  3113. void CGOpenMPRuntime::emitForDispatchInit(
  3114. CodeGenFunction &CGF, SourceLocation Loc,
  3115. const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
  3116. bool Ordered, const DispatchRTInput &DispatchValues) {
  3117. if (!CGF.HaveInsertPoint())
  3118. return;
  3119. OpenMPSchedType Schedule = getRuntimeSchedule(
  3120. ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
  3121. assert(Ordered ||
  3122. (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
  3123. Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
  3124. Schedule != OMP_sch_static_balanced_chunked));
  3125. // Call __kmpc_dispatch_init(
  3126. // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
  3127. // kmp_int[32|64] lower, kmp_int[32|64] upper,
  3128. // kmp_int[32|64] stride, kmp_int[32|64] chunk);
  3129. // If the Chunk was not specified in the clause - use default value 1.
  3130. llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
  3131. : CGF.Builder.getIntN(IVSize, 1);
  3132. llvm::Value *Args[] = {
  3133. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3134. CGF.Builder.getInt32(addMonoNonMonoModifier(
  3135. Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
  3136. DispatchValues.LB, // Lower
  3137. DispatchValues.UB, // Upper
  3138. CGF.Builder.getIntN(IVSize, 1), // Stride
  3139. Chunk // Chunk
  3140. };
  3141. CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
  3142. }
  3143. static void emitForStaticInitCall(
  3144. CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
  3145. llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
  3146. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  3147. const CGOpenMPRuntime::StaticRTInput &Values) {
  3148. if (!CGF.HaveInsertPoint())
  3149. return;
  3150. assert(!Values.Ordered);
  3151. assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
  3152. Schedule == OMP_sch_static_balanced_chunked ||
  3153. Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
  3154. Schedule == OMP_dist_sch_static ||
  3155. Schedule == OMP_dist_sch_static_chunked);
  3156. // Call __kmpc_for_static_init(
  3157. // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
  3158. // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
  3159. // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
  3160. // kmp_int[32|64] incr, kmp_int[32|64] chunk);
  3161. llvm::Value *Chunk = Values.Chunk;
  3162. if (Chunk == nullptr) {
  3163. assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
  3164. Schedule == OMP_dist_sch_static) &&
  3165. "expected static non-chunked schedule");
  3166. // If the Chunk was not specified in the clause - use default value 1.
  3167. Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
  3168. } else {
  3169. assert((Schedule == OMP_sch_static_chunked ||
  3170. Schedule == OMP_sch_static_balanced_chunked ||
  3171. Schedule == OMP_ord_static_chunked ||
  3172. Schedule == OMP_dist_sch_static_chunked) &&
  3173. "expected static chunked schedule");
  3174. }
  3175. llvm::Value *Args[] = {
  3176. UpdateLocation,
  3177. ThreadId,
  3178. CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
  3179. M2)), // Schedule type
  3180. Values.IL.getPointer(), // &isLastIter
  3181. Values.LB.getPointer(), // &LB
  3182. Values.UB.getPointer(), // &UB
  3183. Values.ST.getPointer(), // &Stride
  3184. CGF.Builder.getIntN(Values.IVSize, 1), // Incr
  3185. Chunk // Chunk
  3186. };
  3187. CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
  3188. }
  3189. void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
  3190. SourceLocation Loc,
  3191. OpenMPDirectiveKind DKind,
  3192. const OpenMPScheduleTy &ScheduleKind,
  3193. const StaticRTInput &Values) {
  3194. OpenMPSchedType ScheduleNum = getRuntimeSchedule(
  3195. ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
  3196. assert(isOpenMPWorksharingDirective(DKind) &&
  3197. "Expected loop-based or sections-based directive.");
  3198. llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
  3199. isOpenMPLoopDirective(DKind)
  3200. ? OMP_IDENT_WORK_LOOP
  3201. : OMP_IDENT_WORK_SECTIONS);
  3202. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  3203. llvm::Constant *StaticInitFunction =
  3204. createForStaticInitFunction(Values.IVSize, Values.IVSigned);
  3205. emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
  3206. ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
  3207. }
  3208. void CGOpenMPRuntime::emitDistributeStaticInit(
  3209. CodeGenFunction &CGF, SourceLocation Loc,
  3210. OpenMPDistScheduleClauseKind SchedKind,
  3211. const CGOpenMPRuntime::StaticRTInput &Values) {
  3212. OpenMPSchedType ScheduleNum =
  3213. getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
  3214. llvm::Value *UpdatedLocation =
  3215. emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
  3216. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  3217. llvm::Constant *StaticInitFunction =
  3218. createForStaticInitFunction(Values.IVSize, Values.IVSigned);
  3219. emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
  3220. ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
  3221. OMPC_SCHEDULE_MODIFIER_unknown, Values);
  3222. }
  3223. void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
  3224. SourceLocation Loc,
  3225. OpenMPDirectiveKind DKind) {
  3226. if (!CGF.HaveInsertPoint())
  3227. return;
  3228. // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
  3229. llvm::Value *Args[] = {
  3230. emitUpdateLocation(CGF, Loc,
  3231. isOpenMPDistributeDirective(DKind)
  3232. ? OMP_IDENT_WORK_DISTRIBUTE
  3233. : isOpenMPLoopDirective(DKind)
  3234. ? OMP_IDENT_WORK_LOOP
  3235. : OMP_IDENT_WORK_SECTIONS),
  3236. getThreadID(CGF, Loc)};
  3237. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
  3238. Args);
  3239. }
  3240. void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
  3241. SourceLocation Loc,
  3242. unsigned IVSize,
  3243. bool IVSigned) {
  3244. if (!CGF.HaveInsertPoint())
  3245. return;
  3246. // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
  3247. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3248. CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
  3249. }
  3250. llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
  3251. SourceLocation Loc, unsigned IVSize,
  3252. bool IVSigned, Address IL,
  3253. Address LB, Address UB,
  3254. Address ST) {
  3255. // Call __kmpc_dispatch_next(
  3256. // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
  3257. // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
  3258. // kmp_int[32|64] *p_stride);
  3259. llvm::Value *Args[] = {
  3260. emitUpdateLocation(CGF, Loc),
  3261. getThreadID(CGF, Loc),
  3262. IL.getPointer(), // &isLastIter
  3263. LB.getPointer(), // &Lower
  3264. UB.getPointer(), // &Upper
  3265. ST.getPointer() // &Stride
  3266. };
  3267. llvm::Value *Call =
  3268. CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
  3269. return CGF.EmitScalarConversion(
  3270. Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
  3271. CGF.getContext().BoolTy, Loc);
  3272. }
  3273. void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
  3274. llvm::Value *NumThreads,
  3275. SourceLocation Loc) {
  3276. if (!CGF.HaveInsertPoint())
  3277. return;
  3278. // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
  3279. llvm::Value *Args[] = {
  3280. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3281. CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
  3282. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
  3283. Args);
  3284. }
  3285. void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
  3286. OpenMPProcBindClauseKind ProcBind,
  3287. SourceLocation Loc) {
  3288. if (!CGF.HaveInsertPoint())
  3289. return;
  3290. // Constants for proc bind value accepted by the runtime.
  3291. enum ProcBindTy {
  3292. ProcBindFalse = 0,
  3293. ProcBindTrue,
  3294. ProcBindMaster,
  3295. ProcBindClose,
  3296. ProcBindSpread,
  3297. ProcBindIntel,
  3298. ProcBindDefault
  3299. } RuntimeProcBind;
  3300. switch (ProcBind) {
  3301. case OMPC_PROC_BIND_master:
  3302. RuntimeProcBind = ProcBindMaster;
  3303. break;
  3304. case OMPC_PROC_BIND_close:
  3305. RuntimeProcBind = ProcBindClose;
  3306. break;
  3307. case OMPC_PROC_BIND_spread:
  3308. RuntimeProcBind = ProcBindSpread;
  3309. break;
  3310. case OMPC_PROC_BIND_unknown:
  3311. llvm_unreachable("Unsupported proc_bind value.");
  3312. }
  3313. // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
  3314. llvm::Value *Args[] = {
  3315. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3316. llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
  3317. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
  3318. }
  3319. void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
  3320. SourceLocation Loc) {
  3321. if (!CGF.HaveInsertPoint())
  3322. return;
  3323. // Build call void __kmpc_flush(ident_t *loc)
  3324. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
  3325. emitUpdateLocation(CGF, Loc));
  3326. }
  3327. namespace {
  3328. /// Indexes of fields for type kmp_task_t.
  3329. enum KmpTaskTFields {
  3330. /// List of shared variables.
  3331. KmpTaskTShareds,
  3332. /// Task routine.
  3333. KmpTaskTRoutine,
  3334. /// Partition id for the untied tasks.
  3335. KmpTaskTPartId,
  3336. /// Function with call of destructors for private variables.
  3337. Data1,
  3338. /// Task priority.
  3339. Data2,
  3340. /// (Taskloops only) Lower bound.
  3341. KmpTaskTLowerBound,
  3342. /// (Taskloops only) Upper bound.
  3343. KmpTaskTUpperBound,
  3344. /// (Taskloops only) Stride.
  3345. KmpTaskTStride,
  3346. /// (Taskloops only) Is last iteration flag.
  3347. KmpTaskTLastIter,
  3348. /// (Taskloops only) Reduction data.
  3349. KmpTaskTReductions,
  3350. };
  3351. } // anonymous namespace
  3352. bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
  3353. return OffloadEntriesTargetRegion.empty() &&
  3354. OffloadEntriesDeviceGlobalVar.empty();
  3355. }
  3356. /// Initialize target region entry.
  3357. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3358. initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
  3359. StringRef ParentName, unsigned LineNum,
  3360. unsigned Order) {
  3361. assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
  3362. "only required for the device "
  3363. "code generation.");
  3364. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
  3365. OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
  3366. OMPTargetRegionEntryTargetRegion);
  3367. ++OffloadingEntriesNum;
  3368. }
  3369. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3370. registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
  3371. StringRef ParentName, unsigned LineNum,
  3372. llvm::Constant *Addr, llvm::Constant *ID,
  3373. OMPTargetRegionEntryKind Flags) {
  3374. // If we are emitting code for a target, the entry is already initialized,
  3375. // only has to be registered.
  3376. if (CGM.getLangOpts().OpenMPIsDevice) {
  3377. if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
  3378. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3379. DiagnosticsEngine::Error,
  3380. "Unable to find target region on line '%0' in the device code.");
  3381. CGM.getDiags().Report(DiagID) << LineNum;
  3382. return;
  3383. }
  3384. auto &Entry =
  3385. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
  3386. assert(Entry.isValid() && "Entry not initialized!");
  3387. Entry.setAddress(Addr);
  3388. Entry.setID(ID);
  3389. Entry.setFlags(Flags);
  3390. } else {
  3391. OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
  3392. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
  3393. ++OffloadingEntriesNum;
  3394. }
  3395. }
  3396. bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
  3397. unsigned DeviceID, unsigned FileID, StringRef ParentName,
  3398. unsigned LineNum) const {
  3399. auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
  3400. if (PerDevice == OffloadEntriesTargetRegion.end())
  3401. return false;
  3402. auto PerFile = PerDevice->second.find(FileID);
  3403. if (PerFile == PerDevice->second.end())
  3404. return false;
  3405. auto PerParentName = PerFile->second.find(ParentName);
  3406. if (PerParentName == PerFile->second.end())
  3407. return false;
  3408. auto PerLine = PerParentName->second.find(LineNum);
  3409. if (PerLine == PerParentName->second.end())
  3410. return false;
  3411. // Fail if this entry is already registered.
  3412. if (PerLine->second.getAddress() || PerLine->second.getID())
  3413. return false;
  3414. return true;
  3415. }
  3416. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
  3417. const OffloadTargetRegionEntryInfoActTy &Action) {
  3418. // Scan all target region entries and perform the provided action.
  3419. for (const auto &D : OffloadEntriesTargetRegion)
  3420. for (const auto &F : D.second)
  3421. for (const auto &P : F.second)
  3422. for (const auto &L : P.second)
  3423. Action(D.first, F.first, P.first(), L.first, L.second);
  3424. }
  3425. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3426. initializeDeviceGlobalVarEntryInfo(StringRef Name,
  3427. OMPTargetGlobalVarEntryKind Flags,
  3428. unsigned Order) {
  3429. assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
  3430. "only required for the device "
  3431. "code generation.");
  3432. OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
  3433. ++OffloadingEntriesNum;
  3434. }
  3435. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3436. registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
  3437. CharUnits VarSize,
  3438. OMPTargetGlobalVarEntryKind Flags,
  3439. llvm::GlobalValue::LinkageTypes Linkage) {
  3440. if (CGM.getLangOpts().OpenMPIsDevice) {
  3441. auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
  3442. assert(Entry.isValid() && Entry.getFlags() == Flags &&
  3443. "Entry not initialized!");
  3444. assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
  3445. "Resetting with the new address.");
  3446. if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
  3447. return;
  3448. Entry.setAddress(Addr);
  3449. Entry.setVarSize(VarSize);
  3450. Entry.setLinkage(Linkage);
  3451. } else {
  3452. if (hasDeviceGlobalVarEntryInfo(VarName))
  3453. return;
  3454. OffloadEntriesDeviceGlobalVar.try_emplace(
  3455. VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
  3456. ++OffloadingEntriesNum;
  3457. }
  3458. }
  3459. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3460. actOnDeviceGlobalVarEntriesInfo(
  3461. const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
  3462. // Scan all target region entries and perform the provided action.
  3463. for (const auto &E : OffloadEntriesDeviceGlobalVar)
  3464. Action(E.getKey(), E.getValue());
  3465. }
  3466. llvm::Function *
  3467. CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
  3468. // If we don't have entries or if we are emitting code for the device, we
  3469. // don't need to do anything.
  3470. if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
  3471. return nullptr;
  3472. llvm::Module &M = CGM.getModule();
  3473. ASTContext &C = CGM.getContext();
  3474. // Get list of devices we care about
  3475. const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
  3476. // We should be creating an offloading descriptor only if there are devices
  3477. // specified.
  3478. assert(!Devices.empty() && "No OpenMP offloading devices??");
  3479. // Create the external variables that will point to the begin and end of the
  3480. // host entries section. These will be defined by the linker.
  3481. llvm::Type *OffloadEntryTy =
  3482. CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
  3483. std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
  3484. auto *HostEntriesBegin = new llvm::GlobalVariable(
  3485. M, OffloadEntryTy, /*isConstant=*/true,
  3486. llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
  3487. EntriesBeginName);
  3488. std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
  3489. auto *HostEntriesEnd =
  3490. new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
  3491. llvm::GlobalValue::ExternalLinkage,
  3492. /*Initializer=*/nullptr, EntriesEndName);
  3493. // Create all device images
  3494. auto *DeviceImageTy = cast<llvm::StructType>(
  3495. CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
  3496. ConstantInitBuilder DeviceImagesBuilder(CGM);
  3497. ConstantArrayBuilder DeviceImagesEntries =
  3498. DeviceImagesBuilder.beginArray(DeviceImageTy);
  3499. for (const llvm::Triple &Device : Devices) {
  3500. StringRef T = Device.getTriple();
  3501. std::string BeginName = getName({"omp_offloading", "img_start", ""});
  3502. auto *ImgBegin = new llvm::GlobalVariable(
  3503. M, CGM.Int8Ty, /*isConstant=*/true,
  3504. llvm::GlobalValue::ExternalWeakLinkage,
  3505. /*Initializer=*/nullptr, Twine(BeginName).concat(T));
  3506. std::string EndName = getName({"omp_offloading", "img_end", ""});
  3507. auto *ImgEnd = new llvm::GlobalVariable(
  3508. M, CGM.Int8Ty, /*isConstant=*/true,
  3509. llvm::GlobalValue::ExternalWeakLinkage,
  3510. /*Initializer=*/nullptr, Twine(EndName).concat(T));
  3511. llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
  3512. HostEntriesEnd};
  3513. createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
  3514. DeviceImagesEntries);
  3515. }
  3516. // Create device images global array.
  3517. std::string ImagesName = getName({"omp_offloading", "device_images"});
  3518. llvm::GlobalVariable *DeviceImages =
  3519. DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
  3520. CGM.getPointerAlign(),
  3521. /*isConstant=*/true);
  3522. DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3523. // This is a Zero array to be used in the creation of the constant expressions
  3524. llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
  3525. llvm::Constant::getNullValue(CGM.Int32Ty)};
  3526. // Create the target region descriptor.
  3527. llvm::Constant *Data[] = {
  3528. llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
  3529. llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
  3530. DeviceImages, Index),
  3531. HostEntriesBegin, HostEntriesEnd};
  3532. std::string Descriptor = getName({"omp_offloading", "descriptor"});
  3533. llvm::GlobalVariable *Desc = createGlobalStruct(
  3534. CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
  3535. // Emit code to register or unregister the descriptor at execution
  3536. // startup or closing, respectively.
  3537. llvm::Function *UnRegFn;
  3538. {
  3539. FunctionArgList Args;
  3540. ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
  3541. Args.push_back(&DummyPtr);
  3542. CodeGenFunction CGF(CGM);
  3543. // Disable debug info for global (de-)initializer because they are not part
  3544. // of some particular construct.
  3545. CGF.disableDebugInfo();
  3546. const auto &FI =
  3547. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3548. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  3549. std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
  3550. UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
  3551. CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
  3552. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
  3553. Desc);
  3554. CGF.FinishFunction();
  3555. }
  3556. llvm::Function *RegFn;
  3557. {
  3558. CodeGenFunction CGF(CGM);
  3559. // Disable debug info for global (de-)initializer because they are not part
  3560. // of some particular construct.
  3561. CGF.disableDebugInfo();
  3562. const auto &FI = CGM.getTypes().arrangeNullaryFunction();
  3563. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  3564. // Encode offload target triples into the registration function name. It
  3565. // will serve as a comdat key for the registration/unregistration code for
  3566. // this particular combination of offloading targets.
  3567. SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
  3568. RegFnNameParts[0] = "omp_offloading";
  3569. RegFnNameParts[1] = "descriptor_reg";
  3570. llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
  3571. [](const llvm::Triple &T) -> const std::string& {
  3572. return T.getTriple();
  3573. });
  3574. llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
  3575. std::string Descriptor = getName(RegFnNameParts);
  3576. RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
  3577. CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
  3578. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
  3579. // Create a variable to drive the registration and unregistration of the
  3580. // descriptor, so we can reuse the logic that emits Ctors and Dtors.
  3581. ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
  3582. SourceLocation(), nullptr, C.CharTy,
  3583. ImplicitParamDecl::Other);
  3584. CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
  3585. CGF.FinishFunction();
  3586. }
  3587. if (CGM.supportsCOMDAT()) {
  3588. // It is sufficient to call registration function only once, so create a
  3589. // COMDAT group for registration/unregistration functions and associated
  3590. // data. That would reduce startup time and code size. Registration
  3591. // function serves as a COMDAT group key.
  3592. llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
  3593. RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
  3594. RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
  3595. RegFn->setComdat(ComdatKey);
  3596. UnRegFn->setComdat(ComdatKey);
  3597. DeviceImages->setComdat(ComdatKey);
  3598. Desc->setComdat(ComdatKey);
  3599. }
  3600. return RegFn;
  3601. }
  3602. void CGOpenMPRuntime::createOffloadEntry(
  3603. llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
  3604. llvm::GlobalValue::LinkageTypes Linkage) {
  3605. StringRef Name = Addr->getName();
  3606. llvm::Module &M = CGM.getModule();
  3607. llvm::LLVMContext &C = M.getContext();
  3608. // Create constant string with the name.
  3609. llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
  3610. std::string StringName = getName({"omp_offloading", "entry_name"});
  3611. auto *Str = new llvm::GlobalVariable(
  3612. M, StrPtrInit->getType(), /*isConstant=*/true,
  3613. llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
  3614. Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3615. llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
  3616. llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
  3617. llvm::ConstantInt::get(CGM.SizeTy, Size),
  3618. llvm::ConstantInt::get(CGM.Int32Ty, Flags),
  3619. llvm::ConstantInt::get(CGM.Int32Ty, 0)};
  3620. std::string EntryName = getName({"omp_offloading", "entry", ""});
  3621. llvm::GlobalVariable *Entry = createGlobalStruct(
  3622. CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
  3623. Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
  3624. // The entry has to be created in the section the linker expects it to be.
  3625. std::string Section = getName({"omp_offloading", "entries"});
  3626. Entry->setSection(Section);
  3627. }
  3628. void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
  3629. // Emit the offloading entries and metadata so that the device codegen side
  3630. // can easily figure out what to emit. The produced metadata looks like
  3631. // this:
  3632. //
  3633. // !omp_offload.info = !{!1, ...}
  3634. //
  3635. // Right now we only generate metadata for function that contain target
  3636. // regions.
  3637. // If we do not have entries, we don't need to do anything.
  3638. if (OffloadEntriesInfoManager.empty())
  3639. return;
  3640. llvm::Module &M = CGM.getModule();
  3641. llvm::LLVMContext &C = M.getContext();
  3642. SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
  3643. OrderedEntries(OffloadEntriesInfoManager.size());
  3644. // Auxiliary methods to create metadata values and strings.
  3645. auto &&GetMDInt = [this](unsigned V) {
  3646. return llvm::ConstantAsMetadata::get(
  3647. llvm::ConstantInt::get(CGM.Int32Ty, V));
  3648. };
  3649. auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
  3650. // Create the offloading info metadata node.
  3651. llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
  3652. // Create function that emits metadata for each target region entry;
  3653. auto &&TargetRegionMetadataEmitter =
  3654. [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
  3655. unsigned DeviceID, unsigned FileID, StringRef ParentName,
  3656. unsigned Line,
  3657. const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
  3658. // Generate metadata for target regions. Each entry of this metadata
  3659. // contains:
  3660. // - Entry 0 -> Kind of this type of metadata (0).
  3661. // - Entry 1 -> Device ID of the file where the entry was identified.
  3662. // - Entry 2 -> File ID of the file where the entry was identified.
  3663. // - Entry 3 -> Mangled name of the function where the entry was
  3664. // identified.
  3665. // - Entry 4 -> Line in the file where the entry was identified.
  3666. // - Entry 5 -> Order the entry was created.
  3667. // The first element of the metadata node is the kind.
  3668. llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
  3669. GetMDInt(FileID), GetMDString(ParentName),
  3670. GetMDInt(Line), GetMDInt(E.getOrder())};
  3671. // Save this entry in the right position of the ordered entries array.
  3672. OrderedEntries[E.getOrder()] = &E;
  3673. // Add metadata to the named metadata node.
  3674. MD->addOperand(llvm::MDNode::get(C, Ops));
  3675. };
  3676. OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
  3677. TargetRegionMetadataEmitter);
  3678. // Create function that emits metadata for each device global variable entry;
  3679. auto &&DeviceGlobalVarMetadataEmitter =
  3680. [&C, &OrderedEntries, &GetMDInt, &GetMDString,
  3681. MD](StringRef MangledName,
  3682. const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
  3683. &E) {
  3684. // Generate metadata for global variables. Each entry of this metadata
  3685. // contains:
  3686. // - Entry 0 -> Kind of this type of metadata (1).
  3687. // - Entry 1 -> Mangled name of the variable.
  3688. // - Entry 2 -> Declare target kind.
  3689. // - Entry 3 -> Order the entry was created.
  3690. // The first element of the metadata node is the kind.
  3691. llvm::Metadata *Ops[] = {
  3692. GetMDInt(E.getKind()), GetMDString(MangledName),
  3693. GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
  3694. // Save this entry in the right position of the ordered entries array.
  3695. OrderedEntries[E.getOrder()] = &E;
  3696. // Add metadata to the named metadata node.
  3697. MD->addOperand(llvm::MDNode::get(C, Ops));
  3698. };
  3699. OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
  3700. DeviceGlobalVarMetadataEmitter);
  3701. for (const auto *E : OrderedEntries) {
  3702. assert(E && "All ordered entries must exist!");
  3703. if (const auto *CE =
  3704. dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
  3705. E)) {
  3706. if (!CE->getID() || !CE->getAddress()) {
  3707. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3708. DiagnosticsEngine::Error,
  3709. "Offloading entry for target region is incorrect: either the "
  3710. "address or the ID is invalid.");
  3711. CGM.getDiags().Report(DiagID);
  3712. continue;
  3713. }
  3714. createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
  3715. CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
  3716. } else if (const auto *CE =
  3717. dyn_cast<OffloadEntriesInfoManagerTy::
  3718. OffloadEntryInfoDeviceGlobalVar>(E)) {
  3719. OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
  3720. static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
  3721. CE->getFlags());
  3722. switch (Flags) {
  3723. case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
  3724. if (!CE->getAddress()) {
  3725. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3726. DiagnosticsEngine::Error,
  3727. "Offloading entry for declare target variable is incorrect: the "
  3728. "address is invalid.");
  3729. CGM.getDiags().Report(DiagID);
  3730. continue;
  3731. }
  3732. // The vaiable has no definition - no need to add the entry.
  3733. if (CE->getVarSize().isZero())
  3734. continue;
  3735. break;
  3736. }
  3737. case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
  3738. assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
  3739. (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
  3740. "Declaret target link address is set.");
  3741. if (CGM.getLangOpts().OpenMPIsDevice)
  3742. continue;
  3743. if (!CE->getAddress()) {
  3744. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3745. DiagnosticsEngine::Error,
  3746. "Offloading entry for declare target variable is incorrect: the "
  3747. "address is invalid.");
  3748. CGM.getDiags().Report(DiagID);
  3749. continue;
  3750. }
  3751. break;
  3752. }
  3753. createOffloadEntry(CE->getAddress(), CE->getAddress(),
  3754. CE->getVarSize().getQuantity(), Flags,
  3755. CE->getLinkage());
  3756. } else {
  3757. llvm_unreachable("Unsupported entry kind.");
  3758. }
  3759. }
  3760. }
  3761. /// Loads all the offload entries information from the host IR
  3762. /// metadata.
  3763. void CGOpenMPRuntime::loadOffloadInfoMetadata() {
  3764. // If we are in target mode, load the metadata from the host IR. This code has
  3765. // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
  3766. if (!CGM.getLangOpts().OpenMPIsDevice)
  3767. return;
  3768. if (CGM.getLangOpts().OMPHostIRFile.empty())
  3769. return;
  3770. auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
  3771. if (auto EC = Buf.getError()) {
  3772. CGM.getDiags().Report(diag::err_cannot_open_file)
  3773. << CGM.getLangOpts().OMPHostIRFile << EC.message();
  3774. return;
  3775. }
  3776. llvm::LLVMContext C;
  3777. auto ME = expectedToErrorOrAndEmitErrors(
  3778. C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
  3779. if (auto EC = ME.getError()) {
  3780. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3781. DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
  3782. CGM.getDiags().Report(DiagID)
  3783. << CGM.getLangOpts().OMPHostIRFile << EC.message();
  3784. return;
  3785. }
  3786. llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
  3787. if (!MD)
  3788. return;
  3789. for (llvm::MDNode *MN : MD->operands()) {
  3790. auto &&GetMDInt = [MN](unsigned Idx) {
  3791. auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
  3792. return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
  3793. };
  3794. auto &&GetMDString = [MN](unsigned Idx) {
  3795. auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
  3796. return V->getString();
  3797. };
  3798. switch (GetMDInt(0)) {
  3799. default:
  3800. llvm_unreachable("Unexpected metadata!");
  3801. break;
  3802. case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
  3803. OffloadingEntryInfoTargetRegion:
  3804. OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
  3805. /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
  3806. /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
  3807. /*Order=*/GetMDInt(5));
  3808. break;
  3809. case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
  3810. OffloadingEntryInfoDeviceGlobalVar:
  3811. OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
  3812. /*MangledName=*/GetMDString(1),
  3813. static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
  3814. /*Flags=*/GetMDInt(2)),
  3815. /*Order=*/GetMDInt(3));
  3816. break;
  3817. }
  3818. }
  3819. }
  3820. void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
  3821. if (!KmpRoutineEntryPtrTy) {
  3822. // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
  3823. ASTContext &C = CGM.getContext();
  3824. QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
  3825. FunctionProtoType::ExtProtoInfo EPI;
  3826. KmpRoutineEntryPtrQTy = C.getPointerType(
  3827. C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
  3828. KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
  3829. }
  3830. }
  3831. QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
  3832. // Make sure the type of the entry is already created. This is the type we
  3833. // have to create:
  3834. // struct __tgt_offload_entry{
  3835. // void *addr; // Pointer to the offload entry info.
  3836. // // (function or global)
  3837. // char *name; // Name of the function or global.
  3838. // size_t size; // Size of the entry info (0 if it a function).
  3839. // int32_t flags; // Flags associated with the entry, e.g. 'link'.
  3840. // int32_t reserved; // Reserved, to use by the runtime library.
  3841. // };
  3842. if (TgtOffloadEntryQTy.isNull()) {
  3843. ASTContext &C = CGM.getContext();
  3844. RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
  3845. RD->startDefinition();
  3846. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  3847. addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
  3848. addFieldToRecordDecl(C, RD, C.getSizeType());
  3849. addFieldToRecordDecl(
  3850. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  3851. addFieldToRecordDecl(
  3852. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  3853. RD->completeDefinition();
  3854. RD->addAttr(PackedAttr::CreateImplicit(C));
  3855. TgtOffloadEntryQTy = C.getRecordType(RD);
  3856. }
  3857. return TgtOffloadEntryQTy;
  3858. }
  3859. QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
  3860. // These are the types we need to build:
  3861. // struct __tgt_device_image{
  3862. // void *ImageStart; // Pointer to the target code start.
  3863. // void *ImageEnd; // Pointer to the target code end.
  3864. // // We also add the host entries to the device image, as it may be useful
  3865. // // for the target runtime to have access to that information.
  3866. // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
  3867. // // the entries.
  3868. // __tgt_offload_entry *EntriesEnd; // End of the table with all the
  3869. // // entries (non inclusive).
  3870. // };
  3871. if (TgtDeviceImageQTy.isNull()) {
  3872. ASTContext &C = CGM.getContext();
  3873. RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
  3874. RD->startDefinition();
  3875. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  3876. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  3877. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  3878. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  3879. RD->completeDefinition();
  3880. TgtDeviceImageQTy = C.getRecordType(RD);
  3881. }
  3882. return TgtDeviceImageQTy;
  3883. }
  3884. QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
  3885. // struct __tgt_bin_desc{
  3886. // int32_t NumDevices; // Number of devices supported.
  3887. // __tgt_device_image *DeviceImages; // Arrays of device images
  3888. // // (one per device).
  3889. // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
  3890. // // entries.
  3891. // __tgt_offload_entry *EntriesEnd; // End of the table with all the
  3892. // // entries (non inclusive).
  3893. // };
  3894. if (TgtBinaryDescriptorQTy.isNull()) {
  3895. ASTContext &C = CGM.getContext();
  3896. RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
  3897. RD->startDefinition();
  3898. addFieldToRecordDecl(
  3899. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  3900. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
  3901. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  3902. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  3903. RD->completeDefinition();
  3904. TgtBinaryDescriptorQTy = C.getRecordType(RD);
  3905. }
  3906. return TgtBinaryDescriptorQTy;
  3907. }
  3908. namespace {
  3909. struct PrivateHelpersTy {
  3910. PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
  3911. const VarDecl *PrivateElemInit)
  3912. : Original(Original), PrivateCopy(PrivateCopy),
  3913. PrivateElemInit(PrivateElemInit) {}
  3914. const VarDecl *Original;
  3915. const VarDecl *PrivateCopy;
  3916. const VarDecl *PrivateElemInit;
  3917. };
  3918. typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
  3919. } // anonymous namespace
  3920. static RecordDecl *
  3921. createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
  3922. if (!Privates.empty()) {
  3923. ASTContext &C = CGM.getContext();
  3924. // Build struct .kmp_privates_t. {
  3925. // /* private vars */
  3926. // };
  3927. RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
  3928. RD->startDefinition();
  3929. for (const auto &Pair : Privates) {
  3930. const VarDecl *VD = Pair.second.Original;
  3931. QualType Type = VD->getType().getNonReferenceType();
  3932. FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
  3933. if (VD->hasAttrs()) {
  3934. for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
  3935. E(VD->getAttrs().end());
  3936. I != E; ++I)
  3937. FD->addAttr(*I);
  3938. }
  3939. }
  3940. RD->completeDefinition();
  3941. return RD;
  3942. }
  3943. return nullptr;
  3944. }
  3945. static RecordDecl *
  3946. createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
  3947. QualType KmpInt32Ty,
  3948. QualType KmpRoutineEntryPointerQTy) {
  3949. ASTContext &C = CGM.getContext();
  3950. // Build struct kmp_task_t {
  3951. // void * shareds;
  3952. // kmp_routine_entry_t routine;
  3953. // kmp_int32 part_id;
  3954. // kmp_cmplrdata_t data1;
  3955. // kmp_cmplrdata_t data2;
  3956. // For taskloops additional fields:
  3957. // kmp_uint64 lb;
  3958. // kmp_uint64 ub;
  3959. // kmp_int64 st;
  3960. // kmp_int32 liter;
  3961. // void * reductions;
  3962. // };
  3963. RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
  3964. UD->startDefinition();
  3965. addFieldToRecordDecl(C, UD, KmpInt32Ty);
  3966. addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
  3967. UD->completeDefinition();
  3968. QualType KmpCmplrdataTy = C.getRecordType(UD);
  3969. RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
  3970. RD->startDefinition();
  3971. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  3972. addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
  3973. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  3974. addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
  3975. addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
  3976. if (isOpenMPTaskLoopDirective(Kind)) {
  3977. QualType KmpUInt64Ty =
  3978. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  3979. QualType KmpInt64Ty =
  3980. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  3981. addFieldToRecordDecl(C, RD, KmpUInt64Ty);
  3982. addFieldToRecordDecl(C, RD, KmpUInt64Ty);
  3983. addFieldToRecordDecl(C, RD, KmpInt64Ty);
  3984. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  3985. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  3986. }
  3987. RD->completeDefinition();
  3988. return RD;
  3989. }
  3990. static RecordDecl *
  3991. createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
  3992. ArrayRef<PrivateDataTy> Privates) {
  3993. ASTContext &C = CGM.getContext();
  3994. // Build struct kmp_task_t_with_privates {
  3995. // kmp_task_t task_data;
  3996. // .kmp_privates_t. privates;
  3997. // };
  3998. RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
  3999. RD->startDefinition();
  4000. addFieldToRecordDecl(C, RD, KmpTaskTQTy);
  4001. if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
  4002. addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
  4003. RD->completeDefinition();
  4004. return RD;
  4005. }
  4006. /// Emit a proxy function which accepts kmp_task_t as the second
  4007. /// argument.
  4008. /// \code
  4009. /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
  4010. /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
  4011. /// For taskloops:
  4012. /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
  4013. /// tt->reductions, tt->shareds);
  4014. /// return 0;
  4015. /// }
  4016. /// \endcode
  4017. static llvm::Value *
  4018. emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
  4019. OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
  4020. QualType KmpTaskTWithPrivatesPtrQTy,
  4021. QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
  4022. QualType SharedsPtrTy, llvm::Value *TaskFunction,
  4023. llvm::Value *TaskPrivatesMap) {
  4024. ASTContext &C = CGM.getContext();
  4025. FunctionArgList Args;
  4026. ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
  4027. ImplicitParamDecl::Other);
  4028. ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4029. KmpTaskTWithPrivatesPtrQTy.withRestrict(),
  4030. ImplicitParamDecl::Other);
  4031. Args.push_back(&GtidArg);
  4032. Args.push_back(&TaskTypeArg);
  4033. const auto &TaskEntryFnInfo =
  4034. CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
  4035. llvm::FunctionType *TaskEntryTy =
  4036. CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
  4037. std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
  4038. auto *TaskEntry = llvm::Function::Create(
  4039. TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
  4040. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
  4041. TaskEntry->setDoesNotRecurse();
  4042. CodeGenFunction CGF(CGM);
  4043. CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
  4044. Loc, Loc);
  4045. // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
  4046. // tt,
  4047. // For taskloops:
  4048. // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
  4049. // tt->task_data.shareds);
  4050. llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
  4051. CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
  4052. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4053. CGF.GetAddrOfLocalVar(&TaskTypeArg),
  4054. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4055. const auto *KmpTaskTWithPrivatesQTyRD =
  4056. cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
  4057. LValue Base =
  4058. CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4059. const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
  4060. auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
  4061. LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
  4062. llvm::Value *PartidParam = PartIdLVal.getPointer();
  4063. auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
  4064. LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
  4065. llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4066. CGF.EmitLoadOfScalar(SharedsLVal, Loc),
  4067. CGF.ConvertTypeForMem(SharedsPtrTy));
  4068. auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
  4069. llvm::Value *PrivatesParam;
  4070. if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
  4071. LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
  4072. PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4073. PrivatesLVal.getPointer(), CGF.VoidPtrTy);
  4074. } else {
  4075. PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  4076. }
  4077. llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
  4078. TaskPrivatesMap,
  4079. CGF.Builder
  4080. .CreatePointerBitCastOrAddrSpaceCast(
  4081. TDBase.getAddress(), CGF.VoidPtrTy)
  4082. .getPointer()};
  4083. SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
  4084. std::end(CommonArgs));
  4085. if (isOpenMPTaskLoopDirective(Kind)) {
  4086. auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
  4087. LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
  4088. llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
  4089. auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
  4090. LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
  4091. llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
  4092. auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
  4093. LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
  4094. llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
  4095. auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
  4096. LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
  4097. llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
  4098. auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
  4099. LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
  4100. llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
  4101. CallArgs.push_back(LBParam);
  4102. CallArgs.push_back(UBParam);
  4103. CallArgs.push_back(StParam);
  4104. CallArgs.push_back(LIParam);
  4105. CallArgs.push_back(RParam);
  4106. }
  4107. CallArgs.push_back(SharedsParam);
  4108. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
  4109. CallArgs);
  4110. CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
  4111. CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
  4112. CGF.FinishFunction();
  4113. return TaskEntry;
  4114. }
  4115. static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
  4116. SourceLocation Loc,
  4117. QualType KmpInt32Ty,
  4118. QualType KmpTaskTWithPrivatesPtrQTy,
  4119. QualType KmpTaskTWithPrivatesQTy) {
  4120. ASTContext &C = CGM.getContext();
  4121. FunctionArgList Args;
  4122. ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
  4123. ImplicitParamDecl::Other);
  4124. ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4125. KmpTaskTWithPrivatesPtrQTy.withRestrict(),
  4126. ImplicitParamDecl::Other);
  4127. Args.push_back(&GtidArg);
  4128. Args.push_back(&TaskTypeArg);
  4129. const auto &DestructorFnInfo =
  4130. CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
  4131. llvm::FunctionType *DestructorFnTy =
  4132. CGM.getTypes().GetFunctionType(DestructorFnInfo);
  4133. std::string Name =
  4134. CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
  4135. auto *DestructorFn =
  4136. llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
  4137. Name, &CGM.getModule());
  4138. CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
  4139. DestructorFnInfo);
  4140. DestructorFn->setDoesNotRecurse();
  4141. CodeGenFunction CGF(CGM);
  4142. CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
  4143. Args, Loc, Loc);
  4144. LValue Base = CGF.EmitLoadOfPointerLValue(
  4145. CGF.GetAddrOfLocalVar(&TaskTypeArg),
  4146. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4147. const auto *KmpTaskTWithPrivatesQTyRD =
  4148. cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
  4149. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4150. Base = CGF.EmitLValueForField(Base, *FI);
  4151. for (const auto *Field :
  4152. cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
  4153. if (QualType::DestructionKind DtorKind =
  4154. Field->getType().isDestructedType()) {
  4155. LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
  4156. CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
  4157. }
  4158. }
  4159. CGF.FinishFunction();
  4160. return DestructorFn;
  4161. }
  4162. /// Emit a privates mapping function for correct handling of private and
  4163. /// firstprivate variables.
  4164. /// \code
  4165. /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
  4166. /// **noalias priv1,..., <tyn> **noalias privn) {
  4167. /// *priv1 = &.privates.priv1;
  4168. /// ...;
  4169. /// *privn = &.privates.privn;
  4170. /// }
  4171. /// \endcode
  4172. static llvm::Value *
  4173. emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
  4174. ArrayRef<const Expr *> PrivateVars,
  4175. ArrayRef<const Expr *> FirstprivateVars,
  4176. ArrayRef<const Expr *> LastprivateVars,
  4177. QualType PrivatesQTy,
  4178. ArrayRef<PrivateDataTy> Privates) {
  4179. ASTContext &C = CGM.getContext();
  4180. FunctionArgList Args;
  4181. ImplicitParamDecl TaskPrivatesArg(
  4182. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4183. C.getPointerType(PrivatesQTy).withConst().withRestrict(),
  4184. ImplicitParamDecl::Other);
  4185. Args.push_back(&TaskPrivatesArg);
  4186. llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
  4187. unsigned Counter = 1;
  4188. for (const Expr *E : PrivateVars) {
  4189. Args.push_back(ImplicitParamDecl::Create(
  4190. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4191. C.getPointerType(C.getPointerType(E->getType()))
  4192. .withConst()
  4193. .withRestrict(),
  4194. ImplicitParamDecl::Other));
  4195. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4196. PrivateVarsPos[VD] = Counter;
  4197. ++Counter;
  4198. }
  4199. for (const Expr *E : FirstprivateVars) {
  4200. Args.push_back(ImplicitParamDecl::Create(
  4201. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4202. C.getPointerType(C.getPointerType(E->getType()))
  4203. .withConst()
  4204. .withRestrict(),
  4205. ImplicitParamDecl::Other));
  4206. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4207. PrivateVarsPos[VD] = Counter;
  4208. ++Counter;
  4209. }
  4210. for (const Expr *E : LastprivateVars) {
  4211. Args.push_back(ImplicitParamDecl::Create(
  4212. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4213. C.getPointerType(C.getPointerType(E->getType()))
  4214. .withConst()
  4215. .withRestrict(),
  4216. ImplicitParamDecl::Other));
  4217. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4218. PrivateVarsPos[VD] = Counter;
  4219. ++Counter;
  4220. }
  4221. const auto &TaskPrivatesMapFnInfo =
  4222. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  4223. llvm::FunctionType *TaskPrivatesMapTy =
  4224. CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
  4225. std::string Name =
  4226. CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
  4227. auto *TaskPrivatesMap = llvm::Function::Create(
  4228. TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
  4229. &CGM.getModule());
  4230. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
  4231. TaskPrivatesMapFnInfo);
  4232. TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
  4233. TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
  4234. TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
  4235. CodeGenFunction CGF(CGM);
  4236. CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
  4237. TaskPrivatesMapFnInfo, Args, Loc, Loc);
  4238. // *privi = &.privates.privi;
  4239. LValue Base = CGF.EmitLoadOfPointerLValue(
  4240. CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
  4241. TaskPrivatesArg.getType()->castAs<PointerType>());
  4242. const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
  4243. Counter = 0;
  4244. for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
  4245. LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
  4246. const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
  4247. LValue RefLVal =
  4248. CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
  4249. LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
  4250. RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
  4251. CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
  4252. ++Counter;
  4253. }
  4254. CGF.FinishFunction();
  4255. return TaskPrivatesMap;
  4256. }
  4257. static bool stable_sort_comparator(const PrivateDataTy P1,
  4258. const PrivateDataTy P2) {
  4259. return P1.first > P2.first;
  4260. }
  4261. /// Emit initialization for private variables in task-based directives.
  4262. static void emitPrivatesInit(CodeGenFunction &CGF,
  4263. const OMPExecutableDirective &D,
  4264. Address KmpTaskSharedsPtr, LValue TDBase,
  4265. const RecordDecl *KmpTaskTWithPrivatesQTyRD,
  4266. QualType SharedsTy, QualType SharedsPtrTy,
  4267. const OMPTaskDataTy &Data,
  4268. ArrayRef<PrivateDataTy> Privates, bool ForDup) {
  4269. ASTContext &C = CGF.getContext();
  4270. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4271. LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
  4272. OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
  4273. ? OMPD_taskloop
  4274. : OMPD_task;
  4275. const CapturedStmt &CS = *D.getCapturedStmt(Kind);
  4276. CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
  4277. LValue SrcBase;
  4278. bool IsTargetTask =
  4279. isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
  4280. isOpenMPTargetExecutionDirective(D.getDirectiveKind());
  4281. // For target-based directives skip 3 firstprivate arrays BasePointersArray,
  4282. // PointersArray and SizesArray. The original variables for these arrays are
  4283. // not captured and we get their addresses explicitly.
  4284. if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
  4285. (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
  4286. SrcBase = CGF.MakeAddrLValue(
  4287. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4288. KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
  4289. SharedsTy);
  4290. }
  4291. FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
  4292. for (const PrivateDataTy &Pair : Privates) {
  4293. const VarDecl *VD = Pair.second.PrivateCopy;
  4294. const Expr *Init = VD->getAnyInitializer();
  4295. if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
  4296. !CGF.isTrivialInitializer(Init)))) {
  4297. LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
  4298. if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
  4299. const VarDecl *OriginalVD = Pair.second.Original;
  4300. // Check if the variable is the target-based BasePointersArray,
  4301. // PointersArray or SizesArray.
  4302. LValue SharedRefLValue;
  4303. QualType Type = OriginalVD->getType();
  4304. const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
  4305. if (IsTargetTask && !SharedField) {
  4306. assert(isa<ImplicitParamDecl>(OriginalVD) &&
  4307. isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
  4308. cast<CapturedDecl>(OriginalVD->getDeclContext())
  4309. ->getNumParams() == 0 &&
  4310. isa<TranslationUnitDecl>(
  4311. cast<CapturedDecl>(OriginalVD->getDeclContext())
  4312. ->getDeclContext()) &&
  4313. "Expected artificial target data variable.");
  4314. SharedRefLValue =
  4315. CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
  4316. } else {
  4317. SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
  4318. SharedRefLValue = CGF.MakeAddrLValue(
  4319. Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
  4320. SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
  4321. SharedRefLValue.getTBAAInfo());
  4322. }
  4323. if (Type->isArrayType()) {
  4324. // Initialize firstprivate array.
  4325. if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
  4326. // Perform simple memcpy.
  4327. CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
  4328. } else {
  4329. // Initialize firstprivate array using element-by-element
  4330. // initialization.
  4331. CGF.EmitOMPAggregateAssign(
  4332. PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
  4333. [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
  4334. Address SrcElement) {
  4335. // Clean up any temporaries needed by the initialization.
  4336. CodeGenFunction::OMPPrivateScope InitScope(CGF);
  4337. InitScope.addPrivate(
  4338. Elem, [SrcElement]() -> Address { return SrcElement; });
  4339. (void)InitScope.Privatize();
  4340. // Emit initialization for single element.
  4341. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
  4342. CGF, &CapturesInfo);
  4343. CGF.EmitAnyExprToMem(Init, DestElement,
  4344. Init->getType().getQualifiers(),
  4345. /*IsInitializer=*/false);
  4346. });
  4347. }
  4348. } else {
  4349. CodeGenFunction::OMPPrivateScope InitScope(CGF);
  4350. InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
  4351. return SharedRefLValue.getAddress();
  4352. });
  4353. (void)InitScope.Privatize();
  4354. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
  4355. CGF.EmitExprAsInit(Init, VD, PrivateLValue,
  4356. /*capturedByInit=*/false);
  4357. }
  4358. } else {
  4359. CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
  4360. }
  4361. }
  4362. ++FI;
  4363. }
  4364. }
  4365. /// Check if duplication function is required for taskloops.
  4366. static bool checkInitIsRequired(CodeGenFunction &CGF,
  4367. ArrayRef<PrivateDataTy> Privates) {
  4368. bool InitRequired = false;
  4369. for (const PrivateDataTy &Pair : Privates) {
  4370. const VarDecl *VD = Pair.second.PrivateCopy;
  4371. const Expr *Init = VD->getAnyInitializer();
  4372. InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
  4373. !CGF.isTrivialInitializer(Init));
  4374. if (InitRequired)
  4375. break;
  4376. }
  4377. return InitRequired;
  4378. }
  4379. /// Emit task_dup function (for initialization of
  4380. /// private/firstprivate/lastprivate vars and last_iter flag)
  4381. /// \code
  4382. /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
  4383. /// lastpriv) {
  4384. /// // setup lastprivate flag
  4385. /// task_dst->last = lastpriv;
  4386. /// // could be constructor calls here...
  4387. /// }
  4388. /// \endcode
  4389. static llvm::Value *
  4390. emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
  4391. const OMPExecutableDirective &D,
  4392. QualType KmpTaskTWithPrivatesPtrQTy,
  4393. const RecordDecl *KmpTaskTWithPrivatesQTyRD,
  4394. const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
  4395. QualType SharedsPtrTy, const OMPTaskDataTy &Data,
  4396. ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
  4397. ASTContext &C = CGM.getContext();
  4398. FunctionArgList Args;
  4399. ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4400. KmpTaskTWithPrivatesPtrQTy,
  4401. ImplicitParamDecl::Other);
  4402. ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4403. KmpTaskTWithPrivatesPtrQTy,
  4404. ImplicitParamDecl::Other);
  4405. ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  4406. ImplicitParamDecl::Other);
  4407. Args.push_back(&DstArg);
  4408. Args.push_back(&SrcArg);
  4409. Args.push_back(&LastprivArg);
  4410. const auto &TaskDupFnInfo =
  4411. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  4412. llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
  4413. std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
  4414. auto *TaskDup = llvm::Function::Create(
  4415. TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
  4416. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
  4417. TaskDup->setDoesNotRecurse();
  4418. CodeGenFunction CGF(CGM);
  4419. CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
  4420. Loc);
  4421. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4422. CGF.GetAddrOfLocalVar(&DstArg),
  4423. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4424. // task_dst->liter = lastpriv;
  4425. if (WithLastIter) {
  4426. auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
  4427. LValue Base = CGF.EmitLValueForField(
  4428. TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4429. LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
  4430. llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
  4431. CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
  4432. CGF.EmitStoreOfScalar(Lastpriv, LILVal);
  4433. }
  4434. // Emit initial values for private copies (if any).
  4435. assert(!Privates.empty());
  4436. Address KmpTaskSharedsPtr = Address::invalid();
  4437. if (!Data.FirstprivateVars.empty()) {
  4438. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4439. CGF.GetAddrOfLocalVar(&SrcArg),
  4440. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4441. LValue Base = CGF.EmitLValueForField(
  4442. TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4443. KmpTaskSharedsPtr = Address(
  4444. CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
  4445. Base, *std::next(KmpTaskTQTyRD->field_begin(),
  4446. KmpTaskTShareds)),
  4447. Loc),
  4448. CGF.getNaturalTypeAlignment(SharedsTy));
  4449. }
  4450. emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
  4451. SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
  4452. CGF.FinishFunction();
  4453. return TaskDup;
  4454. }
  4455. /// Checks if destructor function is required to be generated.
  4456. /// \return true if cleanups are required, false otherwise.
  4457. static bool
  4458. checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
  4459. bool NeedsCleanup = false;
  4460. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
  4461. const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
  4462. for (const FieldDecl *FD : PrivateRD->fields()) {
  4463. NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
  4464. if (NeedsCleanup)
  4465. break;
  4466. }
  4467. return NeedsCleanup;
  4468. }
  4469. CGOpenMPRuntime::TaskResultTy
  4470. CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
  4471. const OMPExecutableDirective &D,
  4472. llvm::Value *TaskFunction, QualType SharedsTy,
  4473. Address Shareds, const OMPTaskDataTy &Data) {
  4474. ASTContext &C = CGM.getContext();
  4475. llvm::SmallVector<PrivateDataTy, 4> Privates;
  4476. // Aggregate privates and sort them by the alignment.
  4477. auto I = Data.PrivateCopies.begin();
  4478. for (const Expr *E : Data.PrivateVars) {
  4479. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4480. Privates.emplace_back(
  4481. C.getDeclAlign(VD),
  4482. PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4483. /*PrivateElemInit=*/nullptr));
  4484. ++I;
  4485. }
  4486. I = Data.FirstprivateCopies.begin();
  4487. auto IElemInitRef = Data.FirstprivateInits.begin();
  4488. for (const Expr *E : Data.FirstprivateVars) {
  4489. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4490. Privates.emplace_back(
  4491. C.getDeclAlign(VD),
  4492. PrivateHelpersTy(
  4493. VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4494. cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
  4495. ++I;
  4496. ++IElemInitRef;
  4497. }
  4498. I = Data.LastprivateCopies.begin();
  4499. for (const Expr *E : Data.LastprivateVars) {
  4500. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4501. Privates.emplace_back(
  4502. C.getDeclAlign(VD),
  4503. PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4504. /*PrivateElemInit=*/nullptr));
  4505. ++I;
  4506. }
  4507. std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
  4508. QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  4509. // Build type kmp_routine_entry_t (if not built yet).
  4510. emitKmpRoutineEntryT(KmpInt32Ty);
  4511. // Build type kmp_task_t (if not built yet).
  4512. if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
  4513. if (SavedKmpTaskloopTQTy.isNull()) {
  4514. SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
  4515. CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
  4516. }
  4517. KmpTaskTQTy = SavedKmpTaskloopTQTy;
  4518. } else {
  4519. assert((D.getDirectiveKind() == OMPD_task ||
  4520. isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
  4521. isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
  4522. "Expected taskloop, task or target directive");
  4523. if (SavedKmpTaskTQTy.isNull()) {
  4524. SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
  4525. CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
  4526. }
  4527. KmpTaskTQTy = SavedKmpTaskTQTy;
  4528. }
  4529. const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
  4530. // Build particular struct kmp_task_t for the given task.
  4531. const RecordDecl *KmpTaskTWithPrivatesQTyRD =
  4532. createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
  4533. QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
  4534. QualType KmpTaskTWithPrivatesPtrQTy =
  4535. C.getPointerType(KmpTaskTWithPrivatesQTy);
  4536. llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
  4537. llvm::Type *KmpTaskTWithPrivatesPtrTy =
  4538. KmpTaskTWithPrivatesTy->getPointerTo();
  4539. llvm::Value *KmpTaskTWithPrivatesTySize =
  4540. CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
  4541. QualType SharedsPtrTy = C.getPointerType(SharedsTy);
  4542. // Emit initial values for private copies (if any).
  4543. llvm::Value *TaskPrivatesMap = nullptr;
  4544. llvm::Type *TaskPrivatesMapTy =
  4545. std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
  4546. if (!Privates.empty()) {
  4547. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4548. TaskPrivatesMap = emitTaskPrivateMappingFunction(
  4549. CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
  4550. FI->getType(), Privates);
  4551. TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4552. TaskPrivatesMap, TaskPrivatesMapTy);
  4553. } else {
  4554. TaskPrivatesMap = llvm::ConstantPointerNull::get(
  4555. cast<llvm::PointerType>(TaskPrivatesMapTy));
  4556. }
  4557. // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
  4558. // kmp_task_t *tt);
  4559. llvm::Value *TaskEntry = emitProxyTaskFunction(
  4560. CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
  4561. KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
  4562. TaskPrivatesMap);
  4563. // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  4564. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  4565. // kmp_routine_entry_t *task_entry);
  4566. // Task flags. Format is taken from
  4567. // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
  4568. // description of kmp_tasking_flags struct.
  4569. enum {
  4570. TiedFlag = 0x1,
  4571. FinalFlag = 0x2,
  4572. DestructorsFlag = 0x8,
  4573. PriorityFlag = 0x20
  4574. };
  4575. unsigned Flags = Data.Tied ? TiedFlag : 0;
  4576. bool NeedsCleanup = false;
  4577. if (!Privates.empty()) {
  4578. NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
  4579. if (NeedsCleanup)
  4580. Flags = Flags | DestructorsFlag;
  4581. }
  4582. if (Data.Priority.getInt())
  4583. Flags = Flags | PriorityFlag;
  4584. llvm::Value *TaskFlags =
  4585. Data.Final.getPointer()
  4586. ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
  4587. CGF.Builder.getInt32(FinalFlag),
  4588. CGF.Builder.getInt32(/*C=*/0))
  4589. : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
  4590. TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
  4591. llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
  4592. llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
  4593. getThreadID(CGF, Loc), TaskFlags,
  4594. KmpTaskTWithPrivatesTySize, SharedsSize,
  4595. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4596. TaskEntry, KmpRoutineEntryPtrTy)};
  4597. llvm::Value *NewTask = CGF.EmitRuntimeCall(
  4598. createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
  4599. llvm::Value *NewTaskNewTaskTTy =
  4600. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4601. NewTask, KmpTaskTWithPrivatesPtrTy);
  4602. LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
  4603. KmpTaskTWithPrivatesQTy);
  4604. LValue TDBase =
  4605. CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4606. // Fill the data in the resulting kmp_task_t record.
  4607. // Copy shareds if there are any.
  4608. Address KmpTaskSharedsPtr = Address::invalid();
  4609. if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
  4610. KmpTaskSharedsPtr =
  4611. Address(CGF.EmitLoadOfScalar(
  4612. CGF.EmitLValueForField(
  4613. TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
  4614. KmpTaskTShareds)),
  4615. Loc),
  4616. CGF.getNaturalTypeAlignment(SharedsTy));
  4617. LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
  4618. LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
  4619. CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
  4620. }
  4621. // Emit initial values for private copies (if any).
  4622. TaskResultTy Result;
  4623. if (!Privates.empty()) {
  4624. emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
  4625. SharedsTy, SharedsPtrTy, Data, Privates,
  4626. /*ForDup=*/false);
  4627. if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
  4628. (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
  4629. Result.TaskDupFn = emitTaskDupFunction(
  4630. CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
  4631. KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
  4632. /*WithLastIter=*/!Data.LastprivateVars.empty());
  4633. }
  4634. }
  4635. // Fields of union "kmp_cmplrdata_t" for destructors and priority.
  4636. enum { Priority = 0, Destructors = 1 };
  4637. // Provide pointer to function with destructors for privates.
  4638. auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
  4639. const RecordDecl *KmpCmplrdataUD =
  4640. (*FI)->getType()->getAsUnionType()->getDecl();
  4641. if (NeedsCleanup) {
  4642. llvm::Value *DestructorFn = emitDestructorsFunction(
  4643. CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
  4644. KmpTaskTWithPrivatesQTy);
  4645. LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
  4646. LValue DestructorsLV = CGF.EmitLValueForField(
  4647. Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
  4648. CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4649. DestructorFn, KmpRoutineEntryPtrTy),
  4650. DestructorsLV);
  4651. }
  4652. // Set priority.
  4653. if (Data.Priority.getInt()) {
  4654. LValue Data2LV = CGF.EmitLValueForField(
  4655. TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
  4656. LValue PriorityLV = CGF.EmitLValueForField(
  4657. Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
  4658. CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
  4659. }
  4660. Result.NewTask = NewTask;
  4661. Result.TaskEntry = TaskEntry;
  4662. Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
  4663. Result.TDBase = TDBase;
  4664. Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
  4665. return Result;
  4666. }
  4667. void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
  4668. const OMPExecutableDirective &D,
  4669. llvm::Value *TaskFunction,
  4670. QualType SharedsTy, Address Shareds,
  4671. const Expr *IfCond,
  4672. const OMPTaskDataTy &Data) {
  4673. if (!CGF.HaveInsertPoint())
  4674. return;
  4675. TaskResultTy Result =
  4676. emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
  4677. llvm::Value *NewTask = Result.NewTask;
  4678. llvm::Value *TaskEntry = Result.TaskEntry;
  4679. llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
  4680. LValue TDBase = Result.TDBase;
  4681. const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
  4682. ASTContext &C = CGM.getContext();
  4683. // Process list of dependences.
  4684. Address DependenciesArray = Address::invalid();
  4685. unsigned NumDependencies = Data.Dependences.size();
  4686. if (NumDependencies) {
  4687. // Dependence kind for RTL.
  4688. enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
  4689. enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
  4690. RecordDecl *KmpDependInfoRD;
  4691. QualType FlagsTy =
  4692. C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
  4693. llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
  4694. if (KmpDependInfoTy.isNull()) {
  4695. KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
  4696. KmpDependInfoRD->startDefinition();
  4697. addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
  4698. addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
  4699. addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
  4700. KmpDependInfoRD->completeDefinition();
  4701. KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
  4702. } else {
  4703. KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
  4704. }
  4705. CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
  4706. // Define type kmp_depend_info[<Dependences.size()>];
  4707. QualType KmpDependInfoArrayTy = C.getConstantArrayType(
  4708. KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
  4709. ArrayType::Normal, /*IndexTypeQuals=*/0);
  4710. // kmp_depend_info[<Dependences.size()>] deps;
  4711. DependenciesArray =
  4712. CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
  4713. for (unsigned I = 0; I < NumDependencies; ++I) {
  4714. const Expr *E = Data.Dependences[I].second;
  4715. LValue Addr = CGF.EmitLValue(E);
  4716. llvm::Value *Size;
  4717. QualType Ty = E->getType();
  4718. if (const auto *ASE =
  4719. dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
  4720. LValue UpAddrLVal =
  4721. CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
  4722. llvm::Value *UpAddr =
  4723. CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
  4724. llvm::Value *LowIntPtr =
  4725. CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
  4726. llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
  4727. Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
  4728. } else {
  4729. Size = CGF.getTypeSize(Ty);
  4730. }
  4731. LValue Base = CGF.MakeAddrLValue(
  4732. CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
  4733. KmpDependInfoTy);
  4734. // deps[i].base_addr = &<Dependences[i].second>;
  4735. LValue BaseAddrLVal = CGF.EmitLValueForField(
  4736. Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
  4737. CGF.EmitStoreOfScalar(
  4738. CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
  4739. BaseAddrLVal);
  4740. // deps[i].len = sizeof(<Dependences[i].second>);
  4741. LValue LenLVal = CGF.EmitLValueForField(
  4742. Base, *std::next(KmpDependInfoRD->field_begin(), Len));
  4743. CGF.EmitStoreOfScalar(Size, LenLVal);
  4744. // deps[i].flags = <Dependences[i].first>;
  4745. RTLDependenceKindTy DepKind;
  4746. switch (Data.Dependences[I].first) {
  4747. case OMPC_DEPEND_in:
  4748. DepKind = DepIn;
  4749. break;
  4750. // Out and InOut dependencies must use the same code.
  4751. case OMPC_DEPEND_out:
  4752. case OMPC_DEPEND_inout:
  4753. DepKind = DepInOut;
  4754. break;
  4755. case OMPC_DEPEND_source:
  4756. case OMPC_DEPEND_sink:
  4757. case OMPC_DEPEND_unknown:
  4758. llvm_unreachable("Unknown task dependence type");
  4759. }
  4760. LValue FlagsLVal = CGF.EmitLValueForField(
  4761. Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
  4762. CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
  4763. FlagsLVal);
  4764. }
  4765. DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4766. CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
  4767. CGF.VoidPtrTy);
  4768. }
  4769. // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
  4770. // libcall.
  4771. // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
  4772. // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
  4773. // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
  4774. // list is not empty
  4775. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  4776. llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
  4777. llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
  4778. llvm::Value *DepTaskArgs[7];
  4779. if (NumDependencies) {
  4780. DepTaskArgs[0] = UpLoc;
  4781. DepTaskArgs[1] = ThreadID;
  4782. DepTaskArgs[2] = NewTask;
  4783. DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
  4784. DepTaskArgs[4] = DependenciesArray.getPointer();
  4785. DepTaskArgs[5] = CGF.Builder.getInt32(0);
  4786. DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  4787. }
  4788. auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
  4789. &TaskArgs,
  4790. &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
  4791. if (!Data.Tied) {
  4792. auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
  4793. LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
  4794. CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
  4795. }
  4796. if (NumDependencies) {
  4797. CGF.EmitRuntimeCall(
  4798. createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
  4799. } else {
  4800. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
  4801. TaskArgs);
  4802. }
  4803. // Check if parent region is untied and build return for untied task;
  4804. if (auto *Region =
  4805. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  4806. Region->emitUntiedSwitch(CGF);
  4807. };
  4808. llvm::Value *DepWaitTaskArgs[6];
  4809. if (NumDependencies) {
  4810. DepWaitTaskArgs[0] = UpLoc;
  4811. DepWaitTaskArgs[1] = ThreadID;
  4812. DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
  4813. DepWaitTaskArgs[3] = DependenciesArray.getPointer();
  4814. DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
  4815. DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  4816. }
  4817. auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
  4818. NumDependencies, &DepWaitTaskArgs,
  4819. Loc](CodeGenFunction &CGF, PrePostActionTy &) {
  4820. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  4821. CodeGenFunction::RunCleanupsScope LocalScope(CGF);
  4822. // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
  4823. // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
  4824. // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
  4825. // is specified.
  4826. if (NumDependencies)
  4827. CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
  4828. DepWaitTaskArgs);
  4829. // Call proxy_task_entry(gtid, new_task);
  4830. auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
  4831. Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4832. Action.Enter(CGF);
  4833. llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
  4834. CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
  4835. OutlinedFnArgs);
  4836. };
  4837. // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
  4838. // kmp_task_t *new_task);
  4839. // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
  4840. // kmp_task_t *new_task);
  4841. RegionCodeGenTy RCG(CodeGen);
  4842. CommonActionTy Action(
  4843. RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
  4844. RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
  4845. RCG.setAction(Action);
  4846. RCG(CGF);
  4847. };
  4848. if (IfCond) {
  4849. emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
  4850. } else {
  4851. RegionCodeGenTy ThenRCG(ThenCodeGen);
  4852. ThenRCG(CGF);
  4853. }
  4854. }
  4855. void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
  4856. const OMPLoopDirective &D,
  4857. llvm::Value *TaskFunction,
  4858. QualType SharedsTy, Address Shareds,
  4859. const Expr *IfCond,
  4860. const OMPTaskDataTy &Data) {
  4861. if (!CGF.HaveInsertPoint())
  4862. return;
  4863. TaskResultTy Result =
  4864. emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
  4865. // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
  4866. // libcall.
  4867. // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
  4868. // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
  4869. // sched, kmp_uint64 grainsize, void *task_dup);
  4870. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  4871. llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
  4872. llvm::Value *IfVal;
  4873. if (IfCond) {
  4874. IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
  4875. /*isSigned=*/true);
  4876. } else {
  4877. IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
  4878. }
  4879. LValue LBLVal = CGF.EmitLValueForField(
  4880. Result.TDBase,
  4881. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
  4882. const auto *LBVar =
  4883. cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
  4884. CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
  4885. /*IsInitializer=*/true);
  4886. LValue UBLVal = CGF.EmitLValueForField(
  4887. Result.TDBase,
  4888. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
  4889. const auto *UBVar =
  4890. cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
  4891. CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
  4892. /*IsInitializer=*/true);
  4893. LValue StLVal = CGF.EmitLValueForField(
  4894. Result.TDBase,
  4895. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
  4896. const auto *StVar =
  4897. cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
  4898. CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
  4899. /*IsInitializer=*/true);
  4900. // Store reductions address.
  4901. LValue RedLVal = CGF.EmitLValueForField(
  4902. Result.TDBase,
  4903. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
  4904. if (Data.Reductions) {
  4905. CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
  4906. } else {
  4907. CGF.EmitNullInitialization(RedLVal.getAddress(),
  4908. CGF.getContext().VoidPtrTy);
  4909. }
  4910. enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
  4911. llvm::Value *TaskArgs[] = {
  4912. UpLoc,
  4913. ThreadID,
  4914. Result.NewTask,
  4915. IfVal,
  4916. LBLVal.getPointer(),
  4917. UBLVal.getPointer(),
  4918. CGF.EmitLoadOfScalar(StLVal, Loc),
  4919. llvm::ConstantInt::getNullValue(
  4920. CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
  4921. llvm::ConstantInt::getSigned(
  4922. CGF.IntTy, Data.Schedule.getPointer()
  4923. ? Data.Schedule.getInt() ? NumTasks : Grainsize
  4924. : NoSchedule),
  4925. Data.Schedule.getPointer()
  4926. ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
  4927. /*isSigned=*/false)
  4928. : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
  4929. Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4930. Result.TaskDupFn, CGF.VoidPtrTy)
  4931. : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
  4932. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
  4933. }
  4934. /// Emit reduction operation for each element of array (required for
  4935. /// array sections) LHS op = RHS.
  4936. /// \param Type Type of array.
  4937. /// \param LHSVar Variable on the left side of the reduction operation
  4938. /// (references element of array in original variable).
  4939. /// \param RHSVar Variable on the right side of the reduction operation
  4940. /// (references element of array in original variable).
  4941. /// \param RedOpGen Generator of reduction operation with use of LHSVar and
  4942. /// RHSVar.
  4943. static void EmitOMPAggregateReduction(
  4944. CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
  4945. const VarDecl *RHSVar,
  4946. const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
  4947. const Expr *, const Expr *)> &RedOpGen,
  4948. const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
  4949. const Expr *UpExpr = nullptr) {
  4950. // Perform element-by-element initialization.
  4951. QualType ElementTy;
  4952. Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
  4953. Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
  4954. // Drill down to the base element type on both arrays.
  4955. const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
  4956. llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
  4957. llvm::Value *RHSBegin = RHSAddr.getPointer();
  4958. llvm::Value *LHSBegin = LHSAddr.getPointer();
  4959. // Cast from pointer to array type to pointer to single element.
  4960. llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
  4961. // The basic structure here is a while-do loop.
  4962. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
  4963. llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
  4964. llvm::Value *IsEmpty =
  4965. CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
  4966. CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  4967. // Enter the loop body, making that address the current address.
  4968. llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
  4969. CGF.EmitBlock(BodyBB);
  4970. CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
  4971. llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
  4972. RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
  4973. RHSElementPHI->addIncoming(RHSBegin, EntryBB);
  4974. Address RHSElementCurrent =
  4975. Address(RHSElementPHI,
  4976. RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  4977. llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
  4978. LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
  4979. LHSElementPHI->addIncoming(LHSBegin, EntryBB);
  4980. Address LHSElementCurrent =
  4981. Address(LHSElementPHI,
  4982. LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  4983. // Emit copy.
  4984. CodeGenFunction::OMPPrivateScope Scope(CGF);
  4985. Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
  4986. Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
  4987. Scope.Privatize();
  4988. RedOpGen(CGF, XExpr, EExpr, UpExpr);
  4989. Scope.ForceCleanup();
  4990. // Shift the address forward by one element.
  4991. llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
  4992. LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  4993. llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
  4994. RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
  4995. // Check whether we've reached the end.
  4996. llvm::Value *Done =
  4997. CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
  4998. CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
  4999. LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
  5000. RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
  5001. // Done.
  5002. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  5003. }
  5004. /// Emit reduction combiner. If the combiner is a simple expression emit it as
  5005. /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
  5006. /// UDR combiner function.
  5007. static void emitReductionCombiner(CodeGenFunction &CGF,
  5008. const Expr *ReductionOp) {
  5009. if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
  5010. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
  5011. if (const auto *DRE =
  5012. dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
  5013. if (const auto *DRD =
  5014. dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
  5015. std::pair<llvm::Function *, llvm::Function *> Reduction =
  5016. CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
  5017. RValue Func = RValue::get(Reduction.first);
  5018. CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
  5019. CGF.EmitIgnoredExpr(ReductionOp);
  5020. return;
  5021. }
  5022. CGF.EmitIgnoredExpr(ReductionOp);
  5023. }
  5024. llvm::Value *CGOpenMPRuntime::emitReductionFunction(
  5025. CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
  5026. ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
  5027. ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
  5028. ASTContext &C = CGM.getContext();
  5029. // void reduction_func(void *LHSArg, void *RHSArg);
  5030. FunctionArgList Args;
  5031. ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5032. ImplicitParamDecl::Other);
  5033. ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5034. ImplicitParamDecl::Other);
  5035. Args.push_back(&LHSArg);
  5036. Args.push_back(&RHSArg);
  5037. const auto &CGFI =
  5038. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5039. std::string Name = getName({"omp", "reduction", "reduction_func"});
  5040. auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
  5041. llvm::GlobalValue::InternalLinkage, Name,
  5042. &CGM.getModule());
  5043. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  5044. Fn->setDoesNotRecurse();
  5045. CodeGenFunction CGF(CGM);
  5046. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  5047. // Dst = (void*[n])(LHSArg);
  5048. // Src = (void*[n])(RHSArg);
  5049. Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5050. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
  5051. ArgsType), CGF.getPointerAlign());
  5052. Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5053. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
  5054. ArgsType), CGF.getPointerAlign());
  5055. // ...
  5056. // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
  5057. // ...
  5058. CodeGenFunction::OMPPrivateScope Scope(CGF);
  5059. auto IPriv = Privates.begin();
  5060. unsigned Idx = 0;
  5061. for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
  5062. const auto *RHSVar =
  5063. cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
  5064. Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
  5065. return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
  5066. });
  5067. const auto *LHSVar =
  5068. cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
  5069. Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
  5070. return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
  5071. });
  5072. QualType PrivTy = (*IPriv)->getType();
  5073. if (PrivTy->isVariablyModifiedType()) {
  5074. // Get array size and emit VLA type.
  5075. ++Idx;
  5076. Address Elem =
  5077. CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
  5078. llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
  5079. const VariableArrayType *VLA =
  5080. CGF.getContext().getAsVariableArrayType(PrivTy);
  5081. const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
  5082. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  5083. CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
  5084. CGF.EmitVariablyModifiedType(PrivTy);
  5085. }
  5086. }
  5087. Scope.Privatize();
  5088. IPriv = Privates.begin();
  5089. auto ILHS = LHSExprs.begin();
  5090. auto IRHS = RHSExprs.begin();
  5091. for (const Expr *E : ReductionOps) {
  5092. if ((*IPriv)->getType()->isArrayType()) {
  5093. // Emit reduction for array section.
  5094. const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5095. const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5096. EmitOMPAggregateReduction(
  5097. CGF, (*IPriv)->getType(), LHSVar, RHSVar,
  5098. [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
  5099. emitReductionCombiner(CGF, E);
  5100. });
  5101. } else {
  5102. // Emit reduction for array subscript or single variable.
  5103. emitReductionCombiner(CGF, E);
  5104. }
  5105. ++IPriv;
  5106. ++ILHS;
  5107. ++IRHS;
  5108. }
  5109. Scope.ForceCleanup();
  5110. CGF.FinishFunction();
  5111. return Fn;
  5112. }
  5113. void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
  5114. const Expr *ReductionOp,
  5115. const Expr *PrivateRef,
  5116. const DeclRefExpr *LHS,
  5117. const DeclRefExpr *RHS) {
  5118. if (PrivateRef->getType()->isArrayType()) {
  5119. // Emit reduction for array section.
  5120. const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
  5121. const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
  5122. EmitOMPAggregateReduction(
  5123. CGF, PrivateRef->getType(), LHSVar, RHSVar,
  5124. [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
  5125. emitReductionCombiner(CGF, ReductionOp);
  5126. });
  5127. } else {
  5128. // Emit reduction for array subscript or single variable.
  5129. emitReductionCombiner(CGF, ReductionOp);
  5130. }
  5131. }
  5132. void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
  5133. ArrayRef<const Expr *> Privates,
  5134. ArrayRef<const Expr *> LHSExprs,
  5135. ArrayRef<const Expr *> RHSExprs,
  5136. ArrayRef<const Expr *> ReductionOps,
  5137. ReductionOptionsTy Options) {
  5138. if (!CGF.HaveInsertPoint())
  5139. return;
  5140. bool WithNowait = Options.WithNowait;
  5141. bool SimpleReduction = Options.SimpleReduction;
  5142. // Next code should be emitted for reduction:
  5143. //
  5144. // static kmp_critical_name lock = { 0 };
  5145. //
  5146. // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
  5147. // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
  5148. // ...
  5149. // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
  5150. // *(Type<n>-1*)rhs[<n>-1]);
  5151. // }
  5152. //
  5153. // ...
  5154. // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
  5155. // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
  5156. // RedList, reduce_func, &<lock>)) {
  5157. // case 1:
  5158. // ...
  5159. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5160. // ...
  5161. // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5162. // break;
  5163. // case 2:
  5164. // ...
  5165. // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
  5166. // ...
  5167. // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
  5168. // break;
  5169. // default:;
  5170. // }
  5171. //
  5172. // if SimpleReduction is true, only the next code is generated:
  5173. // ...
  5174. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5175. // ...
  5176. ASTContext &C = CGM.getContext();
  5177. if (SimpleReduction) {
  5178. CodeGenFunction::RunCleanupsScope Scope(CGF);
  5179. auto IPriv = Privates.begin();
  5180. auto ILHS = LHSExprs.begin();
  5181. auto IRHS = RHSExprs.begin();
  5182. for (const Expr *E : ReductionOps) {
  5183. emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
  5184. cast<DeclRefExpr>(*IRHS));
  5185. ++IPriv;
  5186. ++ILHS;
  5187. ++IRHS;
  5188. }
  5189. return;
  5190. }
  5191. // 1. Build a list of reduction variables.
  5192. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  5193. auto Size = RHSExprs.size();
  5194. for (const Expr *E : Privates) {
  5195. if (E->getType()->isVariablyModifiedType())
  5196. // Reserve place for array size.
  5197. ++Size;
  5198. }
  5199. llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
  5200. QualType ReductionArrayTy =
  5201. C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
  5202. /*IndexTypeQuals=*/0);
  5203. Address ReductionList =
  5204. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  5205. auto IPriv = Privates.begin();
  5206. unsigned Idx = 0;
  5207. for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
  5208. Address Elem =
  5209. CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
  5210. CGF.Builder.CreateStore(
  5211. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5212. CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
  5213. Elem);
  5214. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  5215. // Store array size.
  5216. ++Idx;
  5217. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
  5218. CGF.getPointerSize());
  5219. llvm::Value *Size = CGF.Builder.CreateIntCast(
  5220. CGF.getVLASize(
  5221. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  5222. .NumElts,
  5223. CGF.SizeTy, /*isSigned=*/false);
  5224. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  5225. Elem);
  5226. }
  5227. }
  5228. // 2. Emit reduce_func().
  5229. llvm::Value *ReductionFn = emitReductionFunction(
  5230. CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
  5231. Privates, LHSExprs, RHSExprs, ReductionOps);
  5232. // 3. Create static kmp_critical_name lock = { 0 };
  5233. std::string Name = getName({"reduction"});
  5234. llvm::Value *Lock = getCriticalRegionLock(Name);
  5235. // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
  5236. // RedList, reduce_func, &<lock>);
  5237. llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
  5238. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  5239. llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
  5240. llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5241. ReductionList.getPointer(), CGF.VoidPtrTy);
  5242. llvm::Value *Args[] = {
  5243. IdentTLoc, // ident_t *<loc>
  5244. ThreadId, // i32 <gtid>
  5245. CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
  5246. ReductionArrayTySize, // size_type sizeof(RedList)
  5247. RL, // void *RedList
  5248. ReductionFn, // void (*) (void *, void *) <reduce_func>
  5249. Lock // kmp_critical_name *&<lock>
  5250. };
  5251. llvm::Value *Res = CGF.EmitRuntimeCall(
  5252. createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
  5253. : OMPRTL__kmpc_reduce),
  5254. Args);
  5255. // 5. Build switch(res)
  5256. llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
  5257. llvm::SwitchInst *SwInst =
  5258. CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
  5259. // 6. Build case 1:
  5260. // ...
  5261. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5262. // ...
  5263. // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5264. // break;
  5265. llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
  5266. SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
  5267. CGF.EmitBlock(Case1BB);
  5268. // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5269. llvm::Value *EndArgs[] = {
  5270. IdentTLoc, // ident_t *<loc>
  5271. ThreadId, // i32 <gtid>
  5272. Lock // kmp_critical_name *&<lock>
  5273. };
  5274. auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
  5275. CodeGenFunction &CGF, PrePostActionTy &Action) {
  5276. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5277. auto IPriv = Privates.begin();
  5278. auto ILHS = LHSExprs.begin();
  5279. auto IRHS = RHSExprs.begin();
  5280. for (const Expr *E : ReductionOps) {
  5281. RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
  5282. cast<DeclRefExpr>(*IRHS));
  5283. ++IPriv;
  5284. ++ILHS;
  5285. ++IRHS;
  5286. }
  5287. };
  5288. RegionCodeGenTy RCG(CodeGen);
  5289. CommonActionTy Action(
  5290. nullptr, llvm::None,
  5291. createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
  5292. : OMPRTL__kmpc_end_reduce),
  5293. EndArgs);
  5294. RCG.setAction(Action);
  5295. RCG(CGF);
  5296. CGF.EmitBranch(DefaultBB);
  5297. // 7. Build case 2:
  5298. // ...
  5299. // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
  5300. // ...
  5301. // break;
  5302. llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
  5303. SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
  5304. CGF.EmitBlock(Case2BB);
  5305. auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
  5306. CodeGenFunction &CGF, PrePostActionTy &Action) {
  5307. auto ILHS = LHSExprs.begin();
  5308. auto IRHS = RHSExprs.begin();
  5309. auto IPriv = Privates.begin();
  5310. for (const Expr *E : ReductionOps) {
  5311. const Expr *XExpr = nullptr;
  5312. const Expr *EExpr = nullptr;
  5313. const Expr *UpExpr = nullptr;
  5314. BinaryOperatorKind BO = BO_Comma;
  5315. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  5316. if (BO->getOpcode() == BO_Assign) {
  5317. XExpr = BO->getLHS();
  5318. UpExpr = BO->getRHS();
  5319. }
  5320. }
  5321. // Try to emit update expression as a simple atomic.
  5322. const Expr *RHSExpr = UpExpr;
  5323. if (RHSExpr) {
  5324. // Analyze RHS part of the whole expression.
  5325. if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
  5326. RHSExpr->IgnoreParenImpCasts())) {
  5327. // If this is a conditional operator, analyze its condition for
  5328. // min/max reduction operator.
  5329. RHSExpr = ACO->getCond();
  5330. }
  5331. if (const auto *BORHS =
  5332. dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
  5333. EExpr = BORHS->getRHS();
  5334. BO = BORHS->getOpcode();
  5335. }
  5336. }
  5337. if (XExpr) {
  5338. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5339. auto &&AtomicRedGen = [BO, VD,
  5340. Loc](CodeGenFunction &CGF, const Expr *XExpr,
  5341. const Expr *EExpr, const Expr *UpExpr) {
  5342. LValue X = CGF.EmitLValue(XExpr);
  5343. RValue E;
  5344. if (EExpr)
  5345. E = CGF.EmitAnyExpr(EExpr);
  5346. CGF.EmitOMPAtomicSimpleUpdateExpr(
  5347. X, E, BO, /*IsXLHSInRHSPart=*/true,
  5348. llvm::AtomicOrdering::Monotonic, Loc,
  5349. [&CGF, UpExpr, VD, Loc](RValue XRValue) {
  5350. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  5351. PrivateScope.addPrivate(
  5352. VD, [&CGF, VD, XRValue, Loc]() {
  5353. Address LHSTemp = CGF.CreateMemTemp(VD->getType());
  5354. CGF.emitOMPSimpleStore(
  5355. CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
  5356. VD->getType().getNonReferenceType(), Loc);
  5357. return LHSTemp;
  5358. });
  5359. (void)PrivateScope.Privatize();
  5360. return CGF.EmitAnyExpr(UpExpr);
  5361. });
  5362. };
  5363. if ((*IPriv)->getType()->isArrayType()) {
  5364. // Emit atomic reduction for array section.
  5365. const auto *RHSVar =
  5366. cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5367. EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
  5368. AtomicRedGen, XExpr, EExpr, UpExpr);
  5369. } else {
  5370. // Emit atomic reduction for array subscript or single variable.
  5371. AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
  5372. }
  5373. } else {
  5374. // Emit as a critical region.
  5375. auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
  5376. const Expr *, const Expr *) {
  5377. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5378. std::string Name = RT.getName({"atomic_reduction"});
  5379. RT.emitCriticalRegion(
  5380. CGF, Name,
  5381. [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
  5382. Action.Enter(CGF);
  5383. emitReductionCombiner(CGF, E);
  5384. },
  5385. Loc);
  5386. };
  5387. if ((*IPriv)->getType()->isArrayType()) {
  5388. const auto *LHSVar =
  5389. cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5390. const auto *RHSVar =
  5391. cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5392. EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
  5393. CritRedGen);
  5394. } else {
  5395. CritRedGen(CGF, nullptr, nullptr, nullptr);
  5396. }
  5397. }
  5398. ++ILHS;
  5399. ++IRHS;
  5400. ++IPriv;
  5401. }
  5402. };
  5403. RegionCodeGenTy AtomicRCG(AtomicCodeGen);
  5404. if (!WithNowait) {
  5405. // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
  5406. llvm::Value *EndArgs[] = {
  5407. IdentTLoc, // ident_t *<loc>
  5408. ThreadId, // i32 <gtid>
  5409. Lock // kmp_critical_name *&<lock>
  5410. };
  5411. CommonActionTy Action(nullptr, llvm::None,
  5412. createRuntimeFunction(OMPRTL__kmpc_end_reduce),
  5413. EndArgs);
  5414. AtomicRCG.setAction(Action);
  5415. AtomicRCG(CGF);
  5416. } else {
  5417. AtomicRCG(CGF);
  5418. }
  5419. CGF.EmitBranch(DefaultBB);
  5420. CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
  5421. }
  5422. /// Generates unique name for artificial threadprivate variables.
  5423. /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
  5424. static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
  5425. const Expr *Ref) {
  5426. SmallString<256> Buffer;
  5427. llvm::raw_svector_ostream Out(Buffer);
  5428. const clang::DeclRefExpr *DE;
  5429. const VarDecl *D = ::getBaseDecl(Ref, DE);
  5430. if (!D)
  5431. D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
  5432. D = D->getCanonicalDecl();
  5433. std::string Name = CGM.getOpenMPRuntime().getName(
  5434. {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
  5435. Out << Prefix << Name << "_"
  5436. << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
  5437. return Out.str();
  5438. }
  5439. /// Emits reduction initializer function:
  5440. /// \code
  5441. /// void @.red_init(void* %arg) {
  5442. /// %0 = bitcast void* %arg to <type>*
  5443. /// store <type> <init>, <type>* %0
  5444. /// ret void
  5445. /// }
  5446. /// \endcode
  5447. static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
  5448. SourceLocation Loc,
  5449. ReductionCodeGen &RCG, unsigned N) {
  5450. ASTContext &C = CGM.getContext();
  5451. FunctionArgList Args;
  5452. ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5453. ImplicitParamDecl::Other);
  5454. Args.emplace_back(&Param);
  5455. const auto &FnInfo =
  5456. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5457. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5458. std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
  5459. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5460. Name, &CGM.getModule());
  5461. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5462. Fn->setDoesNotRecurse();
  5463. CodeGenFunction CGF(CGM);
  5464. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5465. Address PrivateAddr = CGF.EmitLoadOfPointer(
  5466. CGF.GetAddrOfLocalVar(&Param),
  5467. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5468. llvm::Value *Size = nullptr;
  5469. // If the size of the reduction item is non-constant, load it from global
  5470. // threadprivate variable.
  5471. if (RCG.getSizes(N).second) {
  5472. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5473. CGF, CGM.getContext().getSizeType(),
  5474. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5475. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5476. CGM.getContext().getSizeType(), Loc);
  5477. }
  5478. RCG.emitAggregateType(CGF, N, Size);
  5479. LValue SharedLVal;
  5480. // If initializer uses initializer from declare reduction construct, emit a
  5481. // pointer to the address of the original reduction item (reuired by reduction
  5482. // initializer)
  5483. if (RCG.usesReductionInitializer(N)) {
  5484. Address SharedAddr =
  5485. CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5486. CGF, CGM.getContext().VoidPtrTy,
  5487. generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
  5488. SharedAddr = CGF.EmitLoadOfPointer(
  5489. SharedAddr,
  5490. CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
  5491. SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
  5492. } else {
  5493. SharedLVal = CGF.MakeNaturalAlignAddrLValue(
  5494. llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
  5495. CGM.getContext().VoidPtrTy);
  5496. }
  5497. // Emit the initializer:
  5498. // %0 = bitcast void* %arg to <type>*
  5499. // store <type> <init>, <type>* %0
  5500. RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
  5501. [](CodeGenFunction &) { return false; });
  5502. CGF.FinishFunction();
  5503. return Fn;
  5504. }
  5505. /// Emits reduction combiner function:
  5506. /// \code
  5507. /// void @.red_comb(void* %arg0, void* %arg1) {
  5508. /// %lhs = bitcast void* %arg0 to <type>*
  5509. /// %rhs = bitcast void* %arg1 to <type>*
  5510. /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
  5511. /// store <type> %2, <type>* %lhs
  5512. /// ret void
  5513. /// }
  5514. /// \endcode
  5515. static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
  5516. SourceLocation Loc,
  5517. ReductionCodeGen &RCG, unsigned N,
  5518. const Expr *ReductionOp,
  5519. const Expr *LHS, const Expr *RHS,
  5520. const Expr *PrivateRef) {
  5521. ASTContext &C = CGM.getContext();
  5522. const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
  5523. const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
  5524. FunctionArgList Args;
  5525. ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  5526. C.VoidPtrTy, ImplicitParamDecl::Other);
  5527. ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5528. ImplicitParamDecl::Other);
  5529. Args.emplace_back(&ParamInOut);
  5530. Args.emplace_back(&ParamIn);
  5531. const auto &FnInfo =
  5532. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5533. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5534. std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
  5535. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5536. Name, &CGM.getModule());
  5537. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5538. Fn->setDoesNotRecurse();
  5539. CodeGenFunction CGF(CGM);
  5540. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5541. llvm::Value *Size = nullptr;
  5542. // If the size of the reduction item is non-constant, load it from global
  5543. // threadprivate variable.
  5544. if (RCG.getSizes(N).second) {
  5545. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5546. CGF, CGM.getContext().getSizeType(),
  5547. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5548. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5549. CGM.getContext().getSizeType(), Loc);
  5550. }
  5551. RCG.emitAggregateType(CGF, N, Size);
  5552. // Remap lhs and rhs variables to the addresses of the function arguments.
  5553. // %lhs = bitcast void* %arg0 to <type>*
  5554. // %rhs = bitcast void* %arg1 to <type>*
  5555. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  5556. PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
  5557. // Pull out the pointer to the variable.
  5558. Address PtrAddr = CGF.EmitLoadOfPointer(
  5559. CGF.GetAddrOfLocalVar(&ParamInOut),
  5560. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5561. return CGF.Builder.CreateElementBitCast(
  5562. PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
  5563. });
  5564. PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
  5565. // Pull out the pointer to the variable.
  5566. Address PtrAddr = CGF.EmitLoadOfPointer(
  5567. CGF.GetAddrOfLocalVar(&ParamIn),
  5568. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5569. return CGF.Builder.CreateElementBitCast(
  5570. PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
  5571. });
  5572. PrivateScope.Privatize();
  5573. // Emit the combiner body:
  5574. // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
  5575. // store <type> %2, <type>* %lhs
  5576. CGM.getOpenMPRuntime().emitSingleReductionCombiner(
  5577. CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
  5578. cast<DeclRefExpr>(RHS));
  5579. CGF.FinishFunction();
  5580. return Fn;
  5581. }
  5582. /// Emits reduction finalizer function:
  5583. /// \code
  5584. /// void @.red_fini(void* %arg) {
  5585. /// %0 = bitcast void* %arg to <type>*
  5586. /// <destroy>(<type>* %0)
  5587. /// ret void
  5588. /// }
  5589. /// \endcode
  5590. static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
  5591. SourceLocation Loc,
  5592. ReductionCodeGen &RCG, unsigned N) {
  5593. if (!RCG.needCleanups(N))
  5594. return nullptr;
  5595. ASTContext &C = CGM.getContext();
  5596. FunctionArgList Args;
  5597. ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5598. ImplicitParamDecl::Other);
  5599. Args.emplace_back(&Param);
  5600. const auto &FnInfo =
  5601. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5602. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5603. std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
  5604. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5605. Name, &CGM.getModule());
  5606. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5607. Fn->setDoesNotRecurse();
  5608. CodeGenFunction CGF(CGM);
  5609. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5610. Address PrivateAddr = CGF.EmitLoadOfPointer(
  5611. CGF.GetAddrOfLocalVar(&Param),
  5612. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5613. llvm::Value *Size = nullptr;
  5614. // If the size of the reduction item is non-constant, load it from global
  5615. // threadprivate variable.
  5616. if (RCG.getSizes(N).second) {
  5617. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5618. CGF, CGM.getContext().getSizeType(),
  5619. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5620. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5621. CGM.getContext().getSizeType(), Loc);
  5622. }
  5623. RCG.emitAggregateType(CGF, N, Size);
  5624. // Emit the finalizer body:
  5625. // <destroy>(<type>* %0)
  5626. RCG.emitCleanups(CGF, N, PrivateAddr);
  5627. CGF.FinishFunction();
  5628. return Fn;
  5629. }
  5630. llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
  5631. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
  5632. ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
  5633. if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
  5634. return nullptr;
  5635. // Build typedef struct:
  5636. // kmp_task_red_input {
  5637. // void *reduce_shar; // shared reduction item
  5638. // size_t reduce_size; // size of data item
  5639. // void *reduce_init; // data initialization routine
  5640. // void *reduce_fini; // data finalization routine
  5641. // void *reduce_comb; // data combiner routine
  5642. // kmp_task_red_flags_t flags; // flags for additional info from compiler
  5643. // } kmp_task_red_input_t;
  5644. ASTContext &C = CGM.getContext();
  5645. RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
  5646. RD->startDefinition();
  5647. const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5648. const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
  5649. const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5650. const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5651. const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5652. const FieldDecl *FlagsFD = addFieldToRecordDecl(
  5653. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
  5654. RD->completeDefinition();
  5655. QualType RDType = C.getRecordType(RD);
  5656. unsigned Size = Data.ReductionVars.size();
  5657. llvm::APInt ArraySize(/*numBits=*/64, Size);
  5658. QualType ArrayRDType = C.getConstantArrayType(
  5659. RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
  5660. // kmp_task_red_input_t .rd_input.[Size];
  5661. Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
  5662. ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
  5663. Data.ReductionOps);
  5664. for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
  5665. // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
  5666. llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
  5667. llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
  5668. llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
  5669. TaskRedInput.getPointer(), Idxs,
  5670. /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
  5671. ".rd_input.gep.");
  5672. LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
  5673. // ElemLVal.reduce_shar = &Shareds[Cnt];
  5674. LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
  5675. RCG.emitSharedLValue(CGF, Cnt);
  5676. llvm::Value *CastedShared =
  5677. CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
  5678. CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
  5679. RCG.emitAggregateType(CGF, Cnt);
  5680. llvm::Value *SizeValInChars;
  5681. llvm::Value *SizeVal;
  5682. std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
  5683. // We use delayed creation/initialization for VLAs, array sections and
  5684. // custom reduction initializations. It is required because runtime does not
  5685. // provide the way to pass the sizes of VLAs/array sections to
  5686. // initializer/combiner/finalizer functions and does not pass the pointer to
  5687. // original reduction item to the initializer. Instead threadprivate global
  5688. // variables are used to store these values and use them in the functions.
  5689. bool DelayedCreation = !!SizeVal;
  5690. SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
  5691. /*isSigned=*/false);
  5692. LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
  5693. CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
  5694. // ElemLVal.reduce_init = init;
  5695. LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
  5696. llvm::Value *InitAddr =
  5697. CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
  5698. CGF.EmitStoreOfScalar(InitAddr, InitLVal);
  5699. DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
  5700. // ElemLVal.reduce_fini = fini;
  5701. LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
  5702. llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
  5703. llvm::Value *FiniAddr = Fini
  5704. ? CGF.EmitCastToVoidPtr(Fini)
  5705. : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
  5706. CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
  5707. // ElemLVal.reduce_comb = comb;
  5708. LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
  5709. llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
  5710. CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
  5711. RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
  5712. CGF.EmitStoreOfScalar(CombAddr, CombLVal);
  5713. // ElemLVal.flags = 0;
  5714. LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
  5715. if (DelayedCreation) {
  5716. CGF.EmitStoreOfScalar(
  5717. llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
  5718. FlagsLVal);
  5719. } else
  5720. CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
  5721. }
  5722. // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
  5723. // *data);
  5724. llvm::Value *Args[] = {
  5725. CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
  5726. /*isSigned=*/true),
  5727. llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
  5728. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
  5729. CGM.VoidPtrTy)};
  5730. return CGF.EmitRuntimeCall(
  5731. createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
  5732. }
  5733. void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
  5734. SourceLocation Loc,
  5735. ReductionCodeGen &RCG,
  5736. unsigned N) {
  5737. auto Sizes = RCG.getSizes(N);
  5738. // Emit threadprivate global variable if the type is non-constant
  5739. // (Sizes.second = nullptr).
  5740. if (Sizes.second) {
  5741. llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
  5742. /*isSigned=*/false);
  5743. Address SizeAddr = getAddrOfArtificialThreadPrivate(
  5744. CGF, CGM.getContext().getSizeType(),
  5745. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5746. CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
  5747. }
  5748. // Store address of the original reduction item if custom initializer is used.
  5749. if (RCG.usesReductionInitializer(N)) {
  5750. Address SharedAddr = getAddrOfArtificialThreadPrivate(
  5751. CGF, CGM.getContext().VoidPtrTy,
  5752. generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
  5753. CGF.Builder.CreateStore(
  5754. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5755. RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
  5756. SharedAddr, /*IsVolatile=*/false);
  5757. }
  5758. }
  5759. Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
  5760. SourceLocation Loc,
  5761. llvm::Value *ReductionsPtr,
  5762. LValue SharedLVal) {
  5763. // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
  5764. // *d);
  5765. llvm::Value *Args[] = {
  5766. CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
  5767. /*isSigned=*/true),
  5768. ReductionsPtr,
  5769. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
  5770. CGM.VoidPtrTy)};
  5771. return Address(
  5772. CGF.EmitRuntimeCall(
  5773. createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
  5774. SharedLVal.getAlignment());
  5775. }
  5776. void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
  5777. SourceLocation Loc) {
  5778. if (!CGF.HaveInsertPoint())
  5779. return;
  5780. // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
  5781. // global_tid);
  5782. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  5783. // Ignore return result until untied tasks are supported.
  5784. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
  5785. if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  5786. Region->emitUntiedSwitch(CGF);
  5787. }
  5788. void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
  5789. OpenMPDirectiveKind InnerKind,
  5790. const RegionCodeGenTy &CodeGen,
  5791. bool HasCancel) {
  5792. if (!CGF.HaveInsertPoint())
  5793. return;
  5794. InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
  5795. CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
  5796. }
  5797. namespace {
  5798. enum RTCancelKind {
  5799. CancelNoreq = 0,
  5800. CancelParallel = 1,
  5801. CancelLoop = 2,
  5802. CancelSections = 3,
  5803. CancelTaskgroup = 4
  5804. };
  5805. } // anonymous namespace
  5806. static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
  5807. RTCancelKind CancelKind = CancelNoreq;
  5808. if (CancelRegion == OMPD_parallel)
  5809. CancelKind = CancelParallel;
  5810. else if (CancelRegion == OMPD_for)
  5811. CancelKind = CancelLoop;
  5812. else if (CancelRegion == OMPD_sections)
  5813. CancelKind = CancelSections;
  5814. else {
  5815. assert(CancelRegion == OMPD_taskgroup);
  5816. CancelKind = CancelTaskgroup;
  5817. }
  5818. return CancelKind;
  5819. }
  5820. void CGOpenMPRuntime::emitCancellationPointCall(
  5821. CodeGenFunction &CGF, SourceLocation Loc,
  5822. OpenMPDirectiveKind CancelRegion) {
  5823. if (!CGF.HaveInsertPoint())
  5824. return;
  5825. // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  5826. // global_tid, kmp_int32 cncl_kind);
  5827. if (auto *OMPRegionInfo =
  5828. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  5829. // For 'cancellation point taskgroup', the task region info may not have a
  5830. // cancel. This may instead happen in another adjacent task.
  5831. if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
  5832. llvm::Value *Args[] = {
  5833. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  5834. CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
  5835. // Ignore return result until untied tasks are supported.
  5836. llvm::Value *Result = CGF.EmitRuntimeCall(
  5837. createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
  5838. // if (__kmpc_cancellationpoint()) {
  5839. // exit from construct;
  5840. // }
  5841. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  5842. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  5843. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  5844. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  5845. CGF.EmitBlock(ExitBB);
  5846. // exit from construct;
  5847. CodeGenFunction::JumpDest CancelDest =
  5848. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  5849. CGF.EmitBranchThroughCleanup(CancelDest);
  5850. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  5851. }
  5852. }
  5853. }
  5854. void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
  5855. const Expr *IfCond,
  5856. OpenMPDirectiveKind CancelRegion) {
  5857. if (!CGF.HaveInsertPoint())
  5858. return;
  5859. // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  5860. // kmp_int32 cncl_kind);
  5861. if (auto *OMPRegionInfo =
  5862. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  5863. auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
  5864. PrePostActionTy &) {
  5865. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5866. llvm::Value *Args[] = {
  5867. RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
  5868. CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
  5869. // Ignore return result until untied tasks are supported.
  5870. llvm::Value *Result = CGF.EmitRuntimeCall(
  5871. RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
  5872. // if (__kmpc_cancel()) {
  5873. // exit from construct;
  5874. // }
  5875. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  5876. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  5877. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  5878. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  5879. CGF.EmitBlock(ExitBB);
  5880. // exit from construct;
  5881. CodeGenFunction::JumpDest CancelDest =
  5882. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  5883. CGF.EmitBranchThroughCleanup(CancelDest);
  5884. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  5885. };
  5886. if (IfCond) {
  5887. emitOMPIfClause(CGF, IfCond, ThenGen,
  5888. [](CodeGenFunction &, PrePostActionTy &) {});
  5889. } else {
  5890. RegionCodeGenTy ThenRCG(ThenGen);
  5891. ThenRCG(CGF);
  5892. }
  5893. }
  5894. }
  5895. void CGOpenMPRuntime::emitTargetOutlinedFunction(
  5896. const OMPExecutableDirective &D, StringRef ParentName,
  5897. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  5898. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  5899. assert(!ParentName.empty() && "Invalid target region parent name!");
  5900. emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
  5901. IsOffloadEntry, CodeGen);
  5902. }
  5903. void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
  5904. const OMPExecutableDirective &D, StringRef ParentName,
  5905. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  5906. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  5907. // Create a unique name for the entry function using the source location
  5908. // information of the current target region. The name will be something like:
  5909. //
  5910. // __omp_offloading_DD_FFFF_PP_lBB
  5911. //
  5912. // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
  5913. // mangled name of the function that encloses the target region and BB is the
  5914. // line number of the target region.
  5915. unsigned DeviceID;
  5916. unsigned FileID;
  5917. unsigned Line;
  5918. getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
  5919. Line);
  5920. SmallString<64> EntryFnName;
  5921. {
  5922. llvm::raw_svector_ostream OS(EntryFnName);
  5923. OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
  5924. << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
  5925. }
  5926. const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
  5927. CodeGenFunction CGF(CGM, true);
  5928. CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
  5929. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  5930. OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
  5931. // If this target outline function is not an offload entry, we don't need to
  5932. // register it.
  5933. if (!IsOffloadEntry)
  5934. return;
  5935. // The target region ID is used by the runtime library to identify the current
  5936. // target region, so it only has to be unique and not necessarily point to
  5937. // anything. It could be the pointer to the outlined function that implements
  5938. // the target region, but we aren't using that so that the compiler doesn't
  5939. // need to keep that, and could therefore inline the host function if proven
  5940. // worthwhile during optimization. In the other hand, if emitting code for the
  5941. // device, the ID has to be the function address so that it can retrieved from
  5942. // the offloading entry and launched by the runtime library. We also mark the
  5943. // outlined function to have external linkage in case we are emitting code for
  5944. // the device, because these functions will be entry points to the device.
  5945. if (CGM.getLangOpts().OpenMPIsDevice) {
  5946. OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
  5947. OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
  5948. OutlinedFn->setDSOLocal(false);
  5949. } else {
  5950. std::string Name = getName({EntryFnName, "region_id"});
  5951. OutlinedFnID = new llvm::GlobalVariable(
  5952. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  5953. llvm::GlobalValue::WeakAnyLinkage,
  5954. llvm::Constant::getNullValue(CGM.Int8Ty), Name);
  5955. }
  5956. // Register the information for the entry associated with this target region.
  5957. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  5958. DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
  5959. OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
  5960. }
  5961. /// discard all CompoundStmts intervening between two constructs
  5962. static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
  5963. while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
  5964. Body = CS->body_front();
  5965. return Body;
  5966. }
  5967. /// Emit the number of teams for a target directive. Inspect the num_teams
  5968. /// clause associated with a teams construct combined or closely nested
  5969. /// with the target directive.
  5970. ///
  5971. /// Emit a team of size one for directives such as 'target parallel' that
  5972. /// have no associated teams construct.
  5973. ///
  5974. /// Otherwise, return nullptr.
  5975. static llvm::Value *
  5976. emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
  5977. CodeGenFunction &CGF,
  5978. const OMPExecutableDirective &D) {
  5979. assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
  5980. "teams directive expected to be "
  5981. "emitted only for the host!");
  5982. CGBuilderTy &Bld = CGF.Builder;
  5983. // If the target directive is combined with a teams directive:
  5984. // Return the value in the num_teams clause, if any.
  5985. // Otherwise, return 0 to denote the runtime default.
  5986. if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
  5987. if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
  5988. CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
  5989. llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
  5990. /*IgnoreResultAssign*/ true);
  5991. return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
  5992. /*IsSigned=*/true);
  5993. }
  5994. // The default value is 0.
  5995. return Bld.getInt32(0);
  5996. }
  5997. // If the target directive is combined with a parallel directive but not a
  5998. // teams directive, start one team.
  5999. if (isOpenMPParallelDirective(D.getDirectiveKind()))
  6000. return Bld.getInt32(1);
  6001. // If the current target region has a teams region enclosed, we need to get
  6002. // the number of teams to pass to the runtime function call. This is done
  6003. // by generating the expression in a inlined region. This is required because
  6004. // the expression is captured in the enclosing target environment when the
  6005. // teams directive is not combined with target.
  6006. const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
  6007. if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
  6008. ignoreCompoundStmts(CS.getCapturedStmt()))) {
  6009. if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
  6010. if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
  6011. CGOpenMPInnerExprInfo CGInfo(CGF, CS);
  6012. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6013. llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
  6014. return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
  6015. /*IsSigned=*/true);
  6016. }
  6017. // If we have an enclosed teams directive but no num_teams clause we use
  6018. // the default value 0.
  6019. return Bld.getInt32(0);
  6020. }
  6021. }
  6022. // No teams associated with the directive.
  6023. return nullptr;
  6024. }
  6025. /// Emit the number of threads for a target directive. Inspect the
  6026. /// thread_limit clause associated with a teams construct combined or closely
  6027. /// nested with the target directive.
  6028. ///
  6029. /// Emit the num_threads clause for directives such as 'target parallel' that
  6030. /// have no associated teams construct.
  6031. ///
  6032. /// Otherwise, return nullptr.
  6033. static llvm::Value *
  6034. emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
  6035. CodeGenFunction &CGF,
  6036. const OMPExecutableDirective &D) {
  6037. assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
  6038. "teams directive expected to be "
  6039. "emitted only for the host!");
  6040. CGBuilderTy &Bld = CGF.Builder;
  6041. //
  6042. // If the target directive is combined with a teams directive:
  6043. // Return the value in the thread_limit clause, if any.
  6044. //
  6045. // If the target directive is combined with a parallel directive:
  6046. // Return the value in the num_threads clause, if any.
  6047. //
  6048. // If both clauses are set, select the minimum of the two.
  6049. //
  6050. // If neither teams or parallel combined directives set the number of threads
  6051. // in a team, return 0 to denote the runtime default.
  6052. //
  6053. // If this is not a teams directive return nullptr.
  6054. if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
  6055. isOpenMPParallelDirective(D.getDirectiveKind())) {
  6056. llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
  6057. llvm::Value *NumThreadsVal = nullptr;
  6058. llvm::Value *ThreadLimitVal = nullptr;
  6059. if (const auto *ThreadLimitClause =
  6060. D.getSingleClause<OMPThreadLimitClause>()) {
  6061. CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
  6062. llvm::Value *ThreadLimit =
  6063. CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
  6064. /*IgnoreResultAssign*/ true);
  6065. ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
  6066. /*IsSigned=*/true);
  6067. }
  6068. if (const auto *NumThreadsClause =
  6069. D.getSingleClause<OMPNumThreadsClause>()) {
  6070. CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
  6071. llvm::Value *NumThreads =
  6072. CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
  6073. /*IgnoreResultAssign*/ true);
  6074. NumThreadsVal =
  6075. Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
  6076. }
  6077. // Select the lesser of thread_limit and num_threads.
  6078. if (NumThreadsVal)
  6079. ThreadLimitVal = ThreadLimitVal
  6080. ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
  6081. ThreadLimitVal),
  6082. NumThreadsVal, ThreadLimitVal)
  6083. : NumThreadsVal;
  6084. // Set default value passed to the runtime if either teams or a target
  6085. // parallel type directive is found but no clause is specified.
  6086. if (!ThreadLimitVal)
  6087. ThreadLimitVal = DefaultThreadLimitVal;
  6088. return ThreadLimitVal;
  6089. }
  6090. // If the current target region has a teams region enclosed, we need to get
  6091. // the thread limit to pass to the runtime function call. This is done
  6092. // by generating the expression in a inlined region. This is required because
  6093. // the expression is captured in the enclosing target environment when the
  6094. // teams directive is not combined with target.
  6095. const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
  6096. if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
  6097. ignoreCompoundStmts(CS.getCapturedStmt()))) {
  6098. if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
  6099. if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
  6100. CGOpenMPInnerExprInfo CGInfo(CGF, CS);
  6101. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6102. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
  6103. return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
  6104. /*IsSigned=*/true);
  6105. }
  6106. // If we have an enclosed teams directive but no thread_limit clause we
  6107. // use the default value 0.
  6108. return CGF.Builder.getInt32(0);
  6109. }
  6110. }
  6111. // No teams associated with the directive.
  6112. return nullptr;
  6113. }
  6114. namespace {
  6115. LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
  6116. // Utility to handle information from clauses associated with a given
  6117. // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
  6118. // It provides a convenient interface to obtain the information and generate
  6119. // code for that information.
  6120. class MappableExprsHandler {
  6121. public:
  6122. /// Values for bit flags used to specify the mapping type for
  6123. /// offloading.
  6124. enum OpenMPOffloadMappingFlags : uint64_t {
  6125. /// No flags
  6126. OMP_MAP_NONE = 0x0,
  6127. /// Allocate memory on the device and move data from host to device.
  6128. OMP_MAP_TO = 0x01,
  6129. /// Allocate memory on the device and move data from device to host.
  6130. OMP_MAP_FROM = 0x02,
  6131. /// Always perform the requested mapping action on the element, even
  6132. /// if it was already mapped before.
  6133. OMP_MAP_ALWAYS = 0x04,
  6134. /// Delete the element from the device environment, ignoring the
  6135. /// current reference count associated with the element.
  6136. OMP_MAP_DELETE = 0x08,
  6137. /// The element being mapped is a pointer-pointee pair; both the
  6138. /// pointer and the pointee should be mapped.
  6139. OMP_MAP_PTR_AND_OBJ = 0x10,
  6140. /// This flags signals that the base address of an entry should be
  6141. /// passed to the target kernel as an argument.
  6142. OMP_MAP_TARGET_PARAM = 0x20,
  6143. /// Signal that the runtime library has to return the device pointer
  6144. /// in the current position for the data being mapped. Used when we have the
  6145. /// use_device_ptr clause.
  6146. OMP_MAP_RETURN_PARAM = 0x40,
  6147. /// This flag signals that the reference being passed is a pointer to
  6148. /// private data.
  6149. OMP_MAP_PRIVATE = 0x80,
  6150. /// Pass the element to the device by value.
  6151. OMP_MAP_LITERAL = 0x100,
  6152. /// Implicit map
  6153. OMP_MAP_IMPLICIT = 0x200,
  6154. /// The 16 MSBs of the flags indicate whether the entry is member of some
  6155. /// struct/class.
  6156. OMP_MAP_MEMBER_OF = 0xffff000000000000,
  6157. LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
  6158. };
  6159. /// Class that associates information with a base pointer to be passed to the
  6160. /// runtime library.
  6161. class BasePointerInfo {
  6162. /// The base pointer.
  6163. llvm::Value *Ptr = nullptr;
  6164. /// The base declaration that refers to this device pointer, or null if
  6165. /// there is none.
  6166. const ValueDecl *DevPtrDecl = nullptr;
  6167. public:
  6168. BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
  6169. : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
  6170. llvm::Value *operator*() const { return Ptr; }
  6171. const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
  6172. void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
  6173. };
  6174. using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
  6175. using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
  6176. using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
  6177. /// Map between a struct and the its lowest & highest elements which have been
  6178. /// mapped.
  6179. /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
  6180. /// HE(FieldIndex, Pointer)}
  6181. struct StructRangeInfoTy {
  6182. std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
  6183. 0, Address::invalid()};
  6184. std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
  6185. 0, Address::invalid()};
  6186. Address Base = Address::invalid();
  6187. };
  6188. private:
  6189. /// Kind that defines how a device pointer has to be returned.
  6190. struct MapInfo {
  6191. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  6192. OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
  6193. OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
  6194. bool ReturnDevicePointer = false;
  6195. bool IsImplicit = false;
  6196. MapInfo() = default;
  6197. MapInfo(
  6198. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  6199. OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
  6200. bool ReturnDevicePointer, bool IsImplicit)
  6201. : Components(Components), MapType(MapType),
  6202. MapTypeModifier(MapTypeModifier),
  6203. ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
  6204. };
  6205. /// If use_device_ptr is used on a pointer which is a struct member and there
  6206. /// is no map information about it, then emission of that entry is deferred
  6207. /// until the whole struct has been processed.
  6208. struct DeferredDevicePtrEntryTy {
  6209. const Expr *IE = nullptr;
  6210. const ValueDecl *VD = nullptr;
  6211. DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
  6212. : IE(IE), VD(VD) {}
  6213. };
  6214. /// Directive from where the map clauses were extracted.
  6215. const OMPExecutableDirective &CurDir;
  6216. /// Function the directive is being generated for.
  6217. CodeGenFunction &CGF;
  6218. /// Set of all first private variables in the current directive.
  6219. llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
  6220. /// Map between device pointer declarations and their expression components.
  6221. /// The key value for declarations in 'this' is null.
  6222. llvm::DenseMap<
  6223. const ValueDecl *,
  6224. SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
  6225. DevPointersMap;
  6226. llvm::Value *getExprTypeSize(const Expr *E) const {
  6227. QualType ExprTy = E->getType().getCanonicalType();
  6228. // Reference types are ignored for mapping purposes.
  6229. if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
  6230. ExprTy = RefTy->getPointeeType().getCanonicalType();
  6231. // Given that an array section is considered a built-in type, we need to
  6232. // do the calculation based on the length of the section instead of relying
  6233. // on CGF.getTypeSize(E->getType()).
  6234. if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
  6235. QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
  6236. OAE->getBase()->IgnoreParenImpCasts())
  6237. .getCanonicalType();
  6238. // If there is no length associated with the expression, that means we
  6239. // are using the whole length of the base.
  6240. if (!OAE->getLength() && OAE->getColonLoc().isValid())
  6241. return CGF.getTypeSize(BaseTy);
  6242. llvm::Value *ElemSize;
  6243. if (const auto *PTy = BaseTy->getAs<PointerType>()) {
  6244. ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
  6245. } else {
  6246. const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
  6247. assert(ATy && "Expecting array type if not a pointer type.");
  6248. ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
  6249. }
  6250. // If we don't have a length at this point, that is because we have an
  6251. // array section with a single element.
  6252. if (!OAE->getLength())
  6253. return ElemSize;
  6254. llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
  6255. LengthVal =
  6256. CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
  6257. return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
  6258. }
  6259. return CGF.getTypeSize(ExprTy);
  6260. }
  6261. /// Return the corresponding bits for a given map clause modifier. Add
  6262. /// a flag marking the map as a pointer if requested. Add a flag marking the
  6263. /// map as the first one of a series of maps that relate to the same map
  6264. /// expression.
  6265. OpenMPOffloadMappingFlags getMapTypeBits(OpenMPMapClauseKind MapType,
  6266. OpenMPMapClauseKind MapTypeModifier,
  6267. bool IsImplicit, bool AddPtrFlag,
  6268. bool AddIsTargetParamFlag) const {
  6269. OpenMPOffloadMappingFlags Bits =
  6270. IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
  6271. switch (MapType) {
  6272. case OMPC_MAP_alloc:
  6273. case OMPC_MAP_release:
  6274. // alloc and release is the default behavior in the runtime library, i.e.
  6275. // if we don't pass any bits alloc/release that is what the runtime is
  6276. // going to do. Therefore, we don't need to signal anything for these two
  6277. // type modifiers.
  6278. break;
  6279. case OMPC_MAP_to:
  6280. Bits |= OMP_MAP_TO;
  6281. break;
  6282. case OMPC_MAP_from:
  6283. Bits |= OMP_MAP_FROM;
  6284. break;
  6285. case OMPC_MAP_tofrom:
  6286. Bits |= OMP_MAP_TO | OMP_MAP_FROM;
  6287. break;
  6288. case OMPC_MAP_delete:
  6289. Bits |= OMP_MAP_DELETE;
  6290. break;
  6291. case OMPC_MAP_always:
  6292. case OMPC_MAP_unknown:
  6293. llvm_unreachable("Unexpected map type!");
  6294. }
  6295. if (AddPtrFlag)
  6296. Bits |= OMP_MAP_PTR_AND_OBJ;
  6297. if (AddIsTargetParamFlag)
  6298. Bits |= OMP_MAP_TARGET_PARAM;
  6299. if (MapTypeModifier == OMPC_MAP_always)
  6300. Bits |= OMP_MAP_ALWAYS;
  6301. return Bits;
  6302. }
  6303. /// Return true if the provided expression is a final array section. A
  6304. /// final array section, is one whose length can't be proved to be one.
  6305. bool isFinalArraySectionExpression(const Expr *E) const {
  6306. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  6307. // It is not an array section and therefore not a unity-size one.
  6308. if (!OASE)
  6309. return false;
  6310. // An array section with no colon always refer to a single element.
  6311. if (OASE->getColonLoc().isInvalid())
  6312. return false;
  6313. const Expr *Length = OASE->getLength();
  6314. // If we don't have a length we have to check if the array has size 1
  6315. // for this dimension. Also, we should always expect a length if the
  6316. // base type is pointer.
  6317. if (!Length) {
  6318. QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
  6319. OASE->getBase()->IgnoreParenImpCasts())
  6320. .getCanonicalType();
  6321. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  6322. return ATy->getSize().getSExtValue() != 1;
  6323. // If we don't have a constant dimension length, we have to consider
  6324. // the current section as having any size, so it is not necessarily
  6325. // unitary. If it happen to be unity size, that's user fault.
  6326. return true;
  6327. }
  6328. // Check if the length evaluates to 1.
  6329. llvm::APSInt ConstLength;
  6330. if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
  6331. return true; // Can have more that size 1.
  6332. return ConstLength.getSExtValue() != 1;
  6333. }
  6334. /// Generate the base pointers, section pointers, sizes and map type
  6335. /// bits for the provided map type, map modifier, and expression components.
  6336. /// \a IsFirstComponent should be set to true if the provided set of
  6337. /// components is the first associated with a capture.
  6338. void generateInfoForComponentList(
  6339. OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
  6340. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  6341. MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
  6342. MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
  6343. StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
  6344. bool IsImplicit,
  6345. ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
  6346. OverlappedElements = llvm::None) const {
  6347. // The following summarizes what has to be generated for each map and the
  6348. // types below. The generated information is expressed in this order:
  6349. // base pointer, section pointer, size, flags
  6350. // (to add to the ones that come from the map type and modifier).
  6351. //
  6352. // double d;
  6353. // int i[100];
  6354. // float *p;
  6355. //
  6356. // struct S1 {
  6357. // int i;
  6358. // float f[50];
  6359. // }
  6360. // struct S2 {
  6361. // int i;
  6362. // float f[50];
  6363. // S1 s;
  6364. // double *p;
  6365. // struct S2 *ps;
  6366. // }
  6367. // S2 s;
  6368. // S2 *ps;
  6369. //
  6370. // map(d)
  6371. // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
  6372. //
  6373. // map(i)
  6374. // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
  6375. //
  6376. // map(i[1:23])
  6377. // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
  6378. //
  6379. // map(p)
  6380. // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
  6381. //
  6382. // map(p[1:24])
  6383. // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
  6384. //
  6385. // map(s)
  6386. // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
  6387. //
  6388. // map(s.i)
  6389. // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
  6390. //
  6391. // map(s.s.f)
  6392. // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
  6393. //
  6394. // map(s.p)
  6395. // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
  6396. //
  6397. // map(to: s.p[:22])
  6398. // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
  6399. // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
  6400. // &(s.p), &(s.p[0]), 22*sizeof(double),
  6401. // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
  6402. // (*) alloc space for struct members, only this is a target parameter
  6403. // (**) map the pointer (nothing to be mapped in this example) (the compiler
  6404. // optimizes this entry out, same in the examples below)
  6405. // (***) map the pointee (map: to)
  6406. //
  6407. // map(s.ps)
  6408. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
  6409. //
  6410. // map(from: s.ps->s.i)
  6411. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  6412. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  6413. // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  6414. //
  6415. // map(to: s.ps->ps)
  6416. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  6417. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  6418. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
  6419. //
  6420. // map(s.ps->ps->ps)
  6421. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  6422. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  6423. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  6424. // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
  6425. //
  6426. // map(to: s.ps->ps->s.f[:22])
  6427. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  6428. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  6429. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  6430. // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
  6431. //
  6432. // map(ps)
  6433. // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
  6434. //
  6435. // map(ps->i)
  6436. // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
  6437. //
  6438. // map(ps->s.f)
  6439. // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
  6440. //
  6441. // map(from: ps->p)
  6442. // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
  6443. //
  6444. // map(to: ps->p[:22])
  6445. // ps, &(ps->p), sizeof(double*), TARGET_PARAM
  6446. // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
  6447. // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
  6448. //
  6449. // map(ps->ps)
  6450. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
  6451. //
  6452. // map(from: ps->ps->s.i)
  6453. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  6454. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  6455. // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  6456. //
  6457. // map(from: ps->ps->ps)
  6458. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  6459. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  6460. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  6461. //
  6462. // map(ps->ps->ps->ps)
  6463. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  6464. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  6465. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  6466. // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
  6467. //
  6468. // map(to: ps->ps->ps->s.f[:22])
  6469. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  6470. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  6471. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  6472. // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
  6473. //
  6474. // map(to: s.f[:22]) map(from: s.p[:33])
  6475. // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
  6476. // sizeof(double*) (**), TARGET_PARAM
  6477. // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
  6478. // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
  6479. // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  6480. // (*) allocate contiguous space needed to fit all mapped members even if
  6481. // we allocate space for members not mapped (in this example,
  6482. // s.f[22..49] and s.s are not mapped, yet we must allocate space for
  6483. // them as well because they fall between &s.f[0] and &s.p)
  6484. //
  6485. // map(from: s.f[:22]) map(to: ps->p[:33])
  6486. // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
  6487. // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
  6488. // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
  6489. // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
  6490. // (*) the struct this entry pertains to is the 2nd element in the list of
  6491. // arguments, hence MEMBER_OF(2)
  6492. //
  6493. // map(from: s.f[:22], s.s) map(to: ps->p[:33])
  6494. // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
  6495. // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
  6496. // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
  6497. // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
  6498. // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
  6499. // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
  6500. // (*) the struct this entry pertains to is the 4th element in the list
  6501. // of arguments, hence MEMBER_OF(4)
  6502. // Track if the map information being generated is the first for a capture.
  6503. bool IsCaptureFirstInfo = IsFirstComponentList;
  6504. bool IsLink = false; // Is this variable a "declare target link"?
  6505. // Scan the components from the base to the complete expression.
  6506. auto CI = Components.rbegin();
  6507. auto CE = Components.rend();
  6508. auto I = CI;
  6509. // Track if the map information being generated is the first for a list of
  6510. // components.
  6511. bool IsExpressionFirstInfo = true;
  6512. Address BP = Address::invalid();
  6513. if (isa<MemberExpr>(I->getAssociatedExpression())) {
  6514. // The base is the 'this' pointer. The content of the pointer is going
  6515. // to be the base of the field being mapped.
  6516. BP = CGF.LoadCXXThisAddress();
  6517. } else {
  6518. // The base is the reference to the variable.
  6519. // BP = &Var.
  6520. BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
  6521. if (const auto *VD =
  6522. dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
  6523. if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  6524. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  6525. if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
  6526. IsLink = true;
  6527. BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
  6528. }
  6529. }
  6530. // If the variable is a pointer and is being dereferenced (i.e. is not
  6531. // the last component), the base has to be the pointer itself, not its
  6532. // reference. References are ignored for mapping purposes.
  6533. QualType Ty =
  6534. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  6535. if (Ty->isAnyPointerType() && std::next(I) != CE) {
  6536. BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
  6537. // We do not need to generate individual map information for the
  6538. // pointer, it can be associated with the combined storage.
  6539. ++I;
  6540. }
  6541. }
  6542. // Track whether a component of the list should be marked as MEMBER_OF some
  6543. // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
  6544. // in a component list should be marked as MEMBER_OF, all subsequent entries
  6545. // do not belong to the base struct. E.g.
  6546. // struct S2 s;
  6547. // s.ps->ps->ps->f[:]
  6548. // (1) (2) (3) (4)
  6549. // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
  6550. // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
  6551. // is the pointee of ps(2) which is not member of struct s, so it should not
  6552. // be marked as such (it is still PTR_AND_OBJ).
  6553. // The variable is initialized to false so that PTR_AND_OBJ entries which
  6554. // are not struct members are not considered (e.g. array of pointers to
  6555. // data).
  6556. bool ShouldBeMemberOf = false;
  6557. // Variable keeping track of whether or not we have encountered a component
  6558. // in the component list which is a member expression. Useful when we have a
  6559. // pointer or a final array section, in which case it is the previous
  6560. // component in the list which tells us whether we have a member expression.
  6561. // E.g. X.f[:]
  6562. // While processing the final array section "[:]" it is "f" which tells us
  6563. // whether we are dealing with a member of a declared struct.
  6564. const MemberExpr *EncounteredME = nullptr;
  6565. for (; I != CE; ++I) {
  6566. // If the current component is member of a struct (parent struct) mark it.
  6567. if (!EncounteredME) {
  6568. EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
  6569. // If we encounter a PTR_AND_OBJ entry from now on it should be marked
  6570. // as MEMBER_OF the parent struct.
  6571. if (EncounteredME)
  6572. ShouldBeMemberOf = true;
  6573. }
  6574. auto Next = std::next(I);
  6575. // We need to generate the addresses and sizes if this is the last
  6576. // component, if the component is a pointer or if it is an array section
  6577. // whose length can't be proved to be one. If this is a pointer, it
  6578. // becomes the base address for the following components.
  6579. // A final array section, is one whose length can't be proved to be one.
  6580. bool IsFinalArraySection =
  6581. isFinalArraySectionExpression(I->getAssociatedExpression());
  6582. // Get information on whether the element is a pointer. Have to do a
  6583. // special treatment for array sections given that they are built-in
  6584. // types.
  6585. const auto *OASE =
  6586. dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
  6587. bool IsPointer =
  6588. (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
  6589. .getCanonicalType()
  6590. ->isAnyPointerType()) ||
  6591. I->getAssociatedExpression()->getType()->isAnyPointerType();
  6592. if (Next == CE || IsPointer || IsFinalArraySection) {
  6593. // If this is not the last component, we expect the pointer to be
  6594. // associated with an array expression or member expression.
  6595. assert((Next == CE ||
  6596. isa<MemberExpr>(Next->getAssociatedExpression()) ||
  6597. isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
  6598. isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
  6599. "Unexpected expression");
  6600. Address LB =
  6601. CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
  6602. // If this component is a pointer inside the base struct then we don't
  6603. // need to create any entry for it - it will be combined with the object
  6604. // it is pointing to into a single PTR_AND_OBJ entry.
  6605. bool IsMemberPointer =
  6606. IsPointer && EncounteredME &&
  6607. (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
  6608. EncounteredME);
  6609. if (!OverlappedElements.empty()) {
  6610. // Handle base element with the info for overlapped elements.
  6611. assert(!PartialStruct.Base.isValid() && "The base element is set.");
  6612. assert(Next == CE &&
  6613. "Expected last element for the overlapped elements.");
  6614. assert(!IsPointer &&
  6615. "Unexpected base element with the pointer type.");
  6616. // Mark the whole struct as the struct that requires allocation on the
  6617. // device.
  6618. PartialStruct.LowestElem = {0, LB};
  6619. CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
  6620. I->getAssociatedExpression()->getType());
  6621. Address HB = CGF.Builder.CreateConstGEP(
  6622. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
  6623. CGF.VoidPtrTy),
  6624. TypeSize.getQuantity() - 1, CharUnits::One());
  6625. PartialStruct.HighestElem = {
  6626. std::numeric_limits<decltype(
  6627. PartialStruct.HighestElem.first)>::max(),
  6628. HB};
  6629. PartialStruct.Base = BP;
  6630. // Emit data for non-overlapped data.
  6631. OpenMPOffloadMappingFlags Flags =
  6632. OMP_MAP_MEMBER_OF |
  6633. getMapTypeBits(MapType, MapTypeModifier, IsImplicit,
  6634. /*AddPtrFlag=*/false,
  6635. /*AddIsTargetParamFlag=*/false);
  6636. LB = BP;
  6637. llvm::Value *Size = nullptr;
  6638. // Do bitcopy of all non-overlapped structure elements.
  6639. for (OMPClauseMappableExprCommon::MappableExprComponentListRef
  6640. Component : OverlappedElements) {
  6641. Address ComponentLB = Address::invalid();
  6642. for (const OMPClauseMappableExprCommon::MappableComponent &MC :
  6643. Component) {
  6644. if (MC.getAssociatedDeclaration()) {
  6645. ComponentLB =
  6646. CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
  6647. .getAddress();
  6648. Size = CGF.Builder.CreatePtrDiff(
  6649. CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
  6650. CGF.EmitCastToVoidPtr(LB.getPointer()));
  6651. break;
  6652. }
  6653. }
  6654. BasePointers.push_back(BP.getPointer());
  6655. Pointers.push_back(LB.getPointer());
  6656. Sizes.push_back(Size);
  6657. Types.push_back(Flags);
  6658. LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
  6659. CGF.getPointerSize());
  6660. }
  6661. BasePointers.push_back(BP.getPointer());
  6662. Pointers.push_back(LB.getPointer());
  6663. Size = CGF.Builder.CreatePtrDiff(
  6664. CGF.EmitCastToVoidPtr(
  6665. CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
  6666. .getPointer()),
  6667. CGF.EmitCastToVoidPtr(LB.getPointer()));
  6668. Sizes.push_back(Size);
  6669. Types.push_back(Flags);
  6670. break;
  6671. }
  6672. llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
  6673. if (!IsMemberPointer) {
  6674. BasePointers.push_back(BP.getPointer());
  6675. Pointers.push_back(LB.getPointer());
  6676. Sizes.push_back(Size);
  6677. // We need to add a pointer flag for each map that comes from the
  6678. // same expression except for the first one. We also need to signal
  6679. // this map is the first one that relates with the current capture
  6680. // (there is a set of entries for each capture).
  6681. OpenMPOffloadMappingFlags Flags = getMapTypeBits(
  6682. MapType, MapTypeModifier, IsImplicit,
  6683. !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
  6684. if (!IsExpressionFirstInfo) {
  6685. // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
  6686. // then we reset the TO/FROM/ALWAYS/DELETE flags.
  6687. if (IsPointer)
  6688. Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
  6689. OMP_MAP_DELETE);
  6690. if (ShouldBeMemberOf) {
  6691. // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
  6692. // should be later updated with the correct value of MEMBER_OF.
  6693. Flags |= OMP_MAP_MEMBER_OF;
  6694. // From now on, all subsequent PTR_AND_OBJ entries should not be
  6695. // marked as MEMBER_OF.
  6696. ShouldBeMemberOf = false;
  6697. }
  6698. }
  6699. Types.push_back(Flags);
  6700. }
  6701. // If we have encountered a member expression so far, keep track of the
  6702. // mapped member. If the parent is "*this", then the value declaration
  6703. // is nullptr.
  6704. if (EncounteredME) {
  6705. const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
  6706. unsigned FieldIndex = FD->getFieldIndex();
  6707. // Update info about the lowest and highest elements for this struct
  6708. if (!PartialStruct.Base.isValid()) {
  6709. PartialStruct.LowestElem = {FieldIndex, LB};
  6710. PartialStruct.HighestElem = {FieldIndex, LB};
  6711. PartialStruct.Base = BP;
  6712. } else if (FieldIndex < PartialStruct.LowestElem.first) {
  6713. PartialStruct.LowestElem = {FieldIndex, LB};
  6714. } else if (FieldIndex > PartialStruct.HighestElem.first) {
  6715. PartialStruct.HighestElem = {FieldIndex, LB};
  6716. }
  6717. }
  6718. // If we have a final array section, we are done with this expression.
  6719. if (IsFinalArraySection)
  6720. break;
  6721. // The pointer becomes the base for the next element.
  6722. if (Next != CE)
  6723. BP = LB;
  6724. IsExpressionFirstInfo = false;
  6725. IsCaptureFirstInfo = false;
  6726. }
  6727. }
  6728. }
  6729. /// Return the adjusted map modifiers if the declaration a capture refers to
  6730. /// appears in a first-private clause. This is expected to be used only with
  6731. /// directives that start with 'target'.
  6732. MappableExprsHandler::OpenMPOffloadMappingFlags
  6733. getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
  6734. assert(Cap.capturesVariable() && "Expected capture by reference only!");
  6735. // A first private variable captured by reference will use only the
  6736. // 'private ptr' and 'map to' flag. Return the right flags if the captured
  6737. // declaration is known as first-private in this handler.
  6738. if (FirstPrivateDecls.count(Cap.getCapturedVar()))
  6739. return MappableExprsHandler::OMP_MAP_PRIVATE |
  6740. MappableExprsHandler::OMP_MAP_TO;
  6741. return MappableExprsHandler::OMP_MAP_TO |
  6742. MappableExprsHandler::OMP_MAP_FROM;
  6743. }
  6744. static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
  6745. // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
  6746. return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
  6747. << 48);
  6748. }
  6749. static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
  6750. OpenMPOffloadMappingFlags MemberOfFlag) {
  6751. // If the entry is PTR_AND_OBJ but has not been marked with the special
  6752. // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
  6753. // marked as MEMBER_OF.
  6754. if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
  6755. ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
  6756. return;
  6757. // Reset the placeholder value to prepare the flag for the assignment of the
  6758. // proper MEMBER_OF value.
  6759. Flags &= ~OMP_MAP_MEMBER_OF;
  6760. Flags |= MemberOfFlag;
  6761. }
  6762. void getPlainLayout(const CXXRecordDecl *RD,
  6763. llvm::SmallVectorImpl<const FieldDecl *> &Layout,
  6764. bool AsBase) const {
  6765. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  6766. llvm::StructType *St =
  6767. AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
  6768. unsigned NumElements = St->getNumElements();
  6769. llvm::SmallVector<
  6770. llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
  6771. RecordLayout(NumElements);
  6772. // Fill bases.
  6773. for (const auto &I : RD->bases()) {
  6774. if (I.isVirtual())
  6775. continue;
  6776. const auto *Base = I.getType()->getAsCXXRecordDecl();
  6777. // Ignore empty bases.
  6778. if (Base->isEmpty() || CGF.getContext()
  6779. .getASTRecordLayout(Base)
  6780. .getNonVirtualSize()
  6781. .isZero())
  6782. continue;
  6783. unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
  6784. RecordLayout[FieldIndex] = Base;
  6785. }
  6786. // Fill in virtual bases.
  6787. for (const auto &I : RD->vbases()) {
  6788. const auto *Base = I.getType()->getAsCXXRecordDecl();
  6789. // Ignore empty bases.
  6790. if (Base->isEmpty())
  6791. continue;
  6792. unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
  6793. if (RecordLayout[FieldIndex])
  6794. continue;
  6795. RecordLayout[FieldIndex] = Base;
  6796. }
  6797. // Fill in all the fields.
  6798. assert(!RD->isUnion() && "Unexpected union.");
  6799. for (const auto *Field : RD->fields()) {
  6800. // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
  6801. // will fill in later.)
  6802. if (!Field->isBitField()) {
  6803. unsigned FieldIndex = RL.getLLVMFieldNo(Field);
  6804. RecordLayout[FieldIndex] = Field;
  6805. }
  6806. }
  6807. for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
  6808. &Data : RecordLayout) {
  6809. if (Data.isNull())
  6810. continue;
  6811. if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
  6812. getPlainLayout(Base, Layout, /*AsBase=*/true);
  6813. else
  6814. Layout.push_back(Data.get<const FieldDecl *>());
  6815. }
  6816. }
  6817. public:
  6818. MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
  6819. : CurDir(Dir), CGF(CGF) {
  6820. // Extract firstprivate clause information.
  6821. for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
  6822. for (const auto *D : C->varlists())
  6823. FirstPrivateDecls.insert(
  6824. cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
  6825. // Extract device pointer clause information.
  6826. for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
  6827. for (auto L : C->component_lists())
  6828. DevPointersMap[L.first].push_back(L.second);
  6829. }
  6830. /// Generate code for the combined entry if we have a partially mapped struct
  6831. /// and take care of the mapping flags of the arguments corresponding to
  6832. /// individual struct members.
  6833. void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
  6834. MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
  6835. MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
  6836. const StructRangeInfoTy &PartialStruct) const {
  6837. // Base is the base of the struct
  6838. BasePointers.push_back(PartialStruct.Base.getPointer());
  6839. // Pointer is the address of the lowest element
  6840. llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
  6841. Pointers.push_back(LB);
  6842. // Size is (addr of {highest+1} element) - (addr of lowest element)
  6843. llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
  6844. llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
  6845. llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
  6846. llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
  6847. llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
  6848. llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
  6849. /*isSinged=*/false);
  6850. Sizes.push_back(Size);
  6851. // Map type is always TARGET_PARAM
  6852. Types.push_back(OMP_MAP_TARGET_PARAM);
  6853. // Remove TARGET_PARAM flag from the first element
  6854. (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
  6855. // All other current entries will be MEMBER_OF the combined entry
  6856. // (except for PTR_AND_OBJ entries which do not have a placeholder value
  6857. // 0xFFFF in the MEMBER_OF field).
  6858. OpenMPOffloadMappingFlags MemberOfFlag =
  6859. getMemberOfFlag(BasePointers.size() - 1);
  6860. for (auto &M : CurTypes)
  6861. setCorrectMemberOfFlag(M, MemberOfFlag);
  6862. }
  6863. /// Generate all the base pointers, section pointers, sizes and map
  6864. /// types for the extracted mappable expressions. Also, for each item that
  6865. /// relates with a device pointer, a pair of the relevant declaration and
  6866. /// index where it occurs is appended to the device pointers info array.
  6867. void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
  6868. MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
  6869. MapFlagsArrayTy &Types) const {
  6870. // We have to process the component lists that relate with the same
  6871. // declaration in a single chunk so that we can generate the map flags
  6872. // correctly. Therefore, we organize all lists in a map.
  6873. llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
  6874. // Helper function to fill the information map for the different supported
  6875. // clauses.
  6876. auto &&InfoGen = [&Info](
  6877. const ValueDecl *D,
  6878. OMPClauseMappableExprCommon::MappableExprComponentListRef L,
  6879. OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
  6880. bool ReturnDevicePointer, bool IsImplicit) {
  6881. const ValueDecl *VD =
  6882. D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
  6883. Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
  6884. IsImplicit);
  6885. };
  6886. // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
  6887. for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
  6888. for (const auto &L : C->component_lists()) {
  6889. InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
  6890. /*ReturnDevicePointer=*/false, C->isImplicit());
  6891. }
  6892. for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
  6893. for (const auto &L : C->component_lists()) {
  6894. InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
  6895. /*ReturnDevicePointer=*/false, C->isImplicit());
  6896. }
  6897. for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
  6898. for (const auto &L : C->component_lists()) {
  6899. InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
  6900. /*ReturnDevicePointer=*/false, C->isImplicit());
  6901. }
  6902. // Look at the use_device_ptr clause information and mark the existing map
  6903. // entries as such. If there is no map information for an entry in the
  6904. // use_device_ptr list, we create one with map type 'alloc' and zero size
  6905. // section. It is the user fault if that was not mapped before. If there is
  6906. // no map information and the pointer is a struct member, then we defer the
  6907. // emission of that entry until the whole struct has been processed.
  6908. llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
  6909. DeferredInfo;
  6910. // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
  6911. for (const auto *C :
  6912. this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
  6913. for (const auto &L : C->component_lists()) {
  6914. assert(!L.second.empty() && "Not expecting empty list of components!");
  6915. const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
  6916. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  6917. const Expr *IE = L.second.back().getAssociatedExpression();
  6918. // If the first component is a member expression, we have to look into
  6919. // 'this', which maps to null in the map of map information. Otherwise
  6920. // look directly for the information.
  6921. auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
  6922. // We potentially have map information for this declaration already.
  6923. // Look for the first set of components that refer to it.
  6924. if (It != Info.end()) {
  6925. auto CI = std::find_if(
  6926. It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
  6927. return MI.Components.back().getAssociatedDeclaration() == VD;
  6928. });
  6929. // If we found a map entry, signal that the pointer has to be returned
  6930. // and move on to the next declaration.
  6931. if (CI != It->second.end()) {
  6932. CI->ReturnDevicePointer = true;
  6933. continue;
  6934. }
  6935. }
  6936. // We didn't find any match in our map information - generate a zero
  6937. // size array section - if the pointer is a struct member we defer this
  6938. // action until the whole struct has been processed.
  6939. // FIXME: MSVC 2013 seems to require this-> to find member CGF.
  6940. if (isa<MemberExpr>(IE)) {
  6941. // Insert the pointer into Info to be processed by
  6942. // generateInfoForComponentList. Because it is a member pointer
  6943. // without a pointee, no entry will be generated for it, therefore
  6944. // we need to generate one after the whole struct has been processed.
  6945. // Nonetheless, generateInfoForComponentList must be called to take
  6946. // the pointer into account for the calculation of the range of the
  6947. // partial struct.
  6948. InfoGen(nullptr, L.second, OMPC_MAP_unknown, OMPC_MAP_unknown,
  6949. /*ReturnDevicePointer=*/false, C->isImplicit());
  6950. DeferredInfo[nullptr].emplace_back(IE, VD);
  6951. } else {
  6952. llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
  6953. this->CGF.EmitLValue(IE), IE->getExprLoc());
  6954. BasePointers.emplace_back(Ptr, VD);
  6955. Pointers.push_back(Ptr);
  6956. Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
  6957. Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
  6958. }
  6959. }
  6960. }
  6961. for (const auto &M : Info) {
  6962. // We need to know when we generate information for the first component
  6963. // associated with a capture, because the mapping flags depend on it.
  6964. bool IsFirstComponentList = true;
  6965. // Temporary versions of arrays
  6966. MapBaseValuesArrayTy CurBasePointers;
  6967. MapValuesArrayTy CurPointers;
  6968. MapValuesArrayTy CurSizes;
  6969. MapFlagsArrayTy CurTypes;
  6970. StructRangeInfoTy PartialStruct;
  6971. for (const MapInfo &L : M.second) {
  6972. assert(!L.Components.empty() &&
  6973. "Not expecting declaration with no component lists.");
  6974. // Remember the current base pointer index.
  6975. unsigned CurrentBasePointersIdx = CurBasePointers.size();
  6976. // FIXME: MSVC 2013 seems to require this-> to find the member method.
  6977. this->generateInfoForComponentList(
  6978. L.MapType, L.MapTypeModifier, L.Components, CurBasePointers,
  6979. CurPointers, CurSizes, CurTypes, PartialStruct,
  6980. IsFirstComponentList, L.IsImplicit);
  6981. // If this entry relates with a device pointer, set the relevant
  6982. // declaration and add the 'return pointer' flag.
  6983. if (L.ReturnDevicePointer) {
  6984. assert(CurBasePointers.size() > CurrentBasePointersIdx &&
  6985. "Unexpected number of mapped base pointers.");
  6986. const ValueDecl *RelevantVD =
  6987. L.Components.back().getAssociatedDeclaration();
  6988. assert(RelevantVD &&
  6989. "No relevant declaration related with device pointer??");
  6990. CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
  6991. CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
  6992. }
  6993. IsFirstComponentList = false;
  6994. }
  6995. // Append any pending zero-length pointers which are struct members and
  6996. // used with use_device_ptr.
  6997. auto CI = DeferredInfo.find(M.first);
  6998. if (CI != DeferredInfo.end()) {
  6999. for (const DeferredDevicePtrEntryTy &L : CI->second) {
  7000. llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
  7001. llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
  7002. this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
  7003. CurBasePointers.emplace_back(BasePtr, L.VD);
  7004. CurPointers.push_back(Ptr);
  7005. CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
  7006. // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
  7007. // value MEMBER_OF=FFFF so that the entry is later updated with the
  7008. // correct value of MEMBER_OF.
  7009. CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
  7010. OMP_MAP_MEMBER_OF);
  7011. }
  7012. }
  7013. // If there is an entry in PartialStruct it means we have a struct with
  7014. // individual members mapped. Emit an extra combined entry.
  7015. if (PartialStruct.Base.isValid())
  7016. emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
  7017. PartialStruct);
  7018. // We need to append the results of this capture to what we already have.
  7019. BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
  7020. Pointers.append(CurPointers.begin(), CurPointers.end());
  7021. Sizes.append(CurSizes.begin(), CurSizes.end());
  7022. Types.append(CurTypes.begin(), CurTypes.end());
  7023. }
  7024. }
  7025. /// Generate the base pointers, section pointers, sizes and map types
  7026. /// associated to a given capture.
  7027. void generateInfoForCapture(const CapturedStmt::Capture *Cap,
  7028. llvm::Value *Arg,
  7029. MapBaseValuesArrayTy &BasePointers,
  7030. MapValuesArrayTy &Pointers,
  7031. MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
  7032. StructRangeInfoTy &PartialStruct) const {
  7033. assert(!Cap->capturesVariableArrayType() &&
  7034. "Not expecting to generate map info for a variable array type!");
  7035. // We need to know when we generating information for the first component
  7036. const ValueDecl *VD = Cap->capturesThis()
  7037. ? nullptr
  7038. : Cap->getCapturedVar()->getCanonicalDecl();
  7039. // If this declaration appears in a is_device_ptr clause we just have to
  7040. // pass the pointer by value. If it is a reference to a declaration, we just
  7041. // pass its value.
  7042. if (DevPointersMap.count(VD)) {
  7043. BasePointers.emplace_back(Arg, VD);
  7044. Pointers.push_back(Arg);
  7045. Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
  7046. Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
  7047. return;
  7048. }
  7049. using MapData =
  7050. std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
  7051. OpenMPMapClauseKind, OpenMPMapClauseKind, bool>;
  7052. SmallVector<MapData, 4> DeclComponentLists;
  7053. // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
  7054. for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
  7055. for (const auto &L : C->decl_component_lists(VD)) {
  7056. assert(L.first == VD &&
  7057. "We got information for the wrong declaration??");
  7058. assert(!L.second.empty() &&
  7059. "Not expecting declaration with no component lists.");
  7060. DeclComponentLists.emplace_back(L.second, C->getMapType(),
  7061. C->getMapTypeModifier(),
  7062. C->isImplicit());
  7063. }
  7064. }
  7065. // Find overlapping elements (including the offset from the base element).
  7066. llvm::SmallDenseMap<
  7067. const MapData *,
  7068. llvm::SmallVector<
  7069. OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
  7070. 4>
  7071. OverlappedData;
  7072. size_t Count = 0;
  7073. for (const MapData &L : DeclComponentLists) {
  7074. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7075. OpenMPMapClauseKind MapType;
  7076. OpenMPMapClauseKind MapTypeModifier;
  7077. bool IsImplicit;
  7078. std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
  7079. ++Count;
  7080. for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
  7081. OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
  7082. std::tie(Components1, MapType, MapTypeModifier, IsImplicit) = L1;
  7083. auto CI = Components.rbegin();
  7084. auto CE = Components.rend();
  7085. auto SI = Components1.rbegin();
  7086. auto SE = Components1.rend();
  7087. for (; CI != CE && SI != SE; ++CI, ++SI) {
  7088. if (CI->getAssociatedExpression()->getStmtClass() !=
  7089. SI->getAssociatedExpression()->getStmtClass())
  7090. break;
  7091. // Are we dealing with different variables/fields?
  7092. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  7093. break;
  7094. }
  7095. // Found overlapping if, at least for one component, reached the head of
  7096. // the components list.
  7097. if (CI == CE || SI == SE) {
  7098. assert((CI != CE || SI != SE) &&
  7099. "Unexpected full match of the mapping components.");
  7100. const MapData &BaseData = CI == CE ? L : L1;
  7101. OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
  7102. SI == SE ? Components : Components1;
  7103. auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
  7104. OverlappedElements.getSecond().push_back(SubData);
  7105. }
  7106. }
  7107. }
  7108. // Sort the overlapped elements for each item.
  7109. llvm::SmallVector<const FieldDecl *, 4> Layout;
  7110. if (!OverlappedData.empty()) {
  7111. if (const auto *CRD =
  7112. VD->getType().getCanonicalType()->getAsCXXRecordDecl())
  7113. getPlainLayout(CRD, Layout, /*AsBase=*/false);
  7114. else {
  7115. const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
  7116. Layout.append(RD->field_begin(), RD->field_end());
  7117. }
  7118. }
  7119. for (auto &Pair : OverlappedData) {
  7120. llvm::sort(
  7121. Pair.getSecond(),
  7122. [&Layout](
  7123. OMPClauseMappableExprCommon::MappableExprComponentListRef First,
  7124. OMPClauseMappableExprCommon::MappableExprComponentListRef
  7125. Second) {
  7126. auto CI = First.rbegin();
  7127. auto CE = First.rend();
  7128. auto SI = Second.rbegin();
  7129. auto SE = Second.rend();
  7130. for (; CI != CE && SI != SE; ++CI, ++SI) {
  7131. if (CI->getAssociatedExpression()->getStmtClass() !=
  7132. SI->getAssociatedExpression()->getStmtClass())
  7133. break;
  7134. // Are we dealing with different variables/fields?
  7135. if (CI->getAssociatedDeclaration() !=
  7136. SI->getAssociatedDeclaration())
  7137. break;
  7138. }
  7139. // Lists contain the same elements.
  7140. if (CI == CE && SI == SE)
  7141. return false;
  7142. // List with less elements is less than list with more elements.
  7143. if (CI == CE || SI == SE)
  7144. return CI == CE;
  7145. const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
  7146. const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
  7147. if (FD1->getParent() == FD2->getParent())
  7148. return FD1->getFieldIndex() < FD2->getFieldIndex();
  7149. const auto It =
  7150. llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
  7151. return FD == FD1 || FD == FD2;
  7152. });
  7153. return *It == FD1;
  7154. });
  7155. }
  7156. // Associated with a capture, because the mapping flags depend on it.
  7157. // Go through all of the elements with the overlapped elements.
  7158. for (const auto &Pair : OverlappedData) {
  7159. const MapData &L = *Pair.getFirst();
  7160. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7161. OpenMPMapClauseKind MapType;
  7162. OpenMPMapClauseKind MapTypeModifier;
  7163. bool IsImplicit;
  7164. std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
  7165. ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
  7166. OverlappedComponents = Pair.getSecond();
  7167. bool IsFirstComponentList = true;
  7168. generateInfoForComponentList(MapType, MapTypeModifier, Components,
  7169. BasePointers, Pointers, Sizes, Types,
  7170. PartialStruct, IsFirstComponentList,
  7171. IsImplicit, OverlappedComponents);
  7172. }
  7173. // Go through other elements without overlapped elements.
  7174. bool IsFirstComponentList = OverlappedData.empty();
  7175. for (const MapData &L : DeclComponentLists) {
  7176. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7177. OpenMPMapClauseKind MapType;
  7178. OpenMPMapClauseKind MapTypeModifier;
  7179. bool IsImplicit;
  7180. std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
  7181. auto It = OverlappedData.find(&L);
  7182. if (It == OverlappedData.end())
  7183. generateInfoForComponentList(MapType, MapTypeModifier, Components,
  7184. BasePointers, Pointers, Sizes, Types,
  7185. PartialStruct, IsFirstComponentList,
  7186. IsImplicit);
  7187. IsFirstComponentList = false;
  7188. }
  7189. }
  7190. /// Generate the base pointers, section pointers, sizes and map types
  7191. /// associated with the declare target link variables.
  7192. void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
  7193. MapValuesArrayTy &Pointers,
  7194. MapValuesArrayTy &Sizes,
  7195. MapFlagsArrayTy &Types) const {
  7196. // Map other list items in the map clause which are not captured variables
  7197. // but "declare target link" global variables.,
  7198. for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
  7199. for (const auto &L : C->component_lists()) {
  7200. if (!L.first)
  7201. continue;
  7202. const auto *VD = dyn_cast<VarDecl>(L.first);
  7203. if (!VD)
  7204. continue;
  7205. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  7206. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  7207. if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
  7208. continue;
  7209. StructRangeInfoTy PartialStruct;
  7210. generateInfoForComponentList(
  7211. C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
  7212. Pointers, Sizes, Types, PartialStruct,
  7213. /*IsFirstComponentList=*/true, C->isImplicit());
  7214. assert(!PartialStruct.Base.isValid() &&
  7215. "No partial structs for declare target link expected.");
  7216. }
  7217. }
  7218. }
  7219. /// Generate the default map information for a given capture \a CI,
  7220. /// record field declaration \a RI and captured value \a CV.
  7221. void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
  7222. const FieldDecl &RI, llvm::Value *CV,
  7223. MapBaseValuesArrayTy &CurBasePointers,
  7224. MapValuesArrayTy &CurPointers,
  7225. MapValuesArrayTy &CurSizes,
  7226. MapFlagsArrayTy &CurMapTypes) const {
  7227. // Do the default mapping.
  7228. if (CI.capturesThis()) {
  7229. CurBasePointers.push_back(CV);
  7230. CurPointers.push_back(CV);
  7231. const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
  7232. CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
  7233. // Default map type.
  7234. CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
  7235. } else if (CI.capturesVariableByCopy()) {
  7236. CurBasePointers.push_back(CV);
  7237. CurPointers.push_back(CV);
  7238. if (!RI.getType()->isAnyPointerType()) {
  7239. // We have to signal to the runtime captures passed by value that are
  7240. // not pointers.
  7241. CurMapTypes.push_back(OMP_MAP_LITERAL);
  7242. CurSizes.push_back(CGF.getTypeSize(RI.getType()));
  7243. } else {
  7244. // Pointers are implicitly mapped with a zero size and no flags
  7245. // (other than first map that is added for all implicit maps).
  7246. CurMapTypes.push_back(OMP_MAP_NONE);
  7247. CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
  7248. }
  7249. } else {
  7250. assert(CI.capturesVariable() && "Expected captured reference.");
  7251. CurBasePointers.push_back(CV);
  7252. CurPointers.push_back(CV);
  7253. const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
  7254. QualType ElementType = PtrTy->getPointeeType();
  7255. CurSizes.push_back(CGF.getTypeSize(ElementType));
  7256. // The default map type for a scalar/complex type is 'to' because by
  7257. // default the value doesn't have to be retrieved. For an aggregate
  7258. // type, the default is 'tofrom'.
  7259. CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
  7260. }
  7261. // Every default map produces a single argument which is a target parameter.
  7262. CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
  7263. // Add flag stating this is an implicit map.
  7264. CurMapTypes.back() |= OMP_MAP_IMPLICIT;
  7265. }
  7266. };
  7267. enum OpenMPOffloadingReservedDeviceIDs {
  7268. /// Device ID if the device was not defined, runtime should get it
  7269. /// from environment variables in the spec.
  7270. OMP_DEVICEID_UNDEF = -1,
  7271. };
  7272. } // anonymous namespace
  7273. /// Emit the arrays used to pass the captures and map information to the
  7274. /// offloading runtime library. If there is no map or capture information,
  7275. /// return nullptr by reference.
  7276. static void
  7277. emitOffloadingArrays(CodeGenFunction &CGF,
  7278. MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
  7279. MappableExprsHandler::MapValuesArrayTy &Pointers,
  7280. MappableExprsHandler::MapValuesArrayTy &Sizes,
  7281. MappableExprsHandler::MapFlagsArrayTy &MapTypes,
  7282. CGOpenMPRuntime::TargetDataInfo &Info) {
  7283. CodeGenModule &CGM = CGF.CGM;
  7284. ASTContext &Ctx = CGF.getContext();
  7285. // Reset the array information.
  7286. Info.clearArrayInfo();
  7287. Info.NumberOfPtrs = BasePointers.size();
  7288. if (Info.NumberOfPtrs) {
  7289. // Detect if we have any capture size requiring runtime evaluation of the
  7290. // size so that a constant array could be eventually used.
  7291. bool hasRuntimeEvaluationCaptureSize = false;
  7292. for (llvm::Value *S : Sizes)
  7293. if (!isa<llvm::Constant>(S)) {
  7294. hasRuntimeEvaluationCaptureSize = true;
  7295. break;
  7296. }
  7297. llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
  7298. QualType PointerArrayType =
  7299. Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
  7300. /*IndexTypeQuals=*/0);
  7301. Info.BasePointersArray =
  7302. CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
  7303. Info.PointersArray =
  7304. CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
  7305. // If we don't have any VLA types or other types that require runtime
  7306. // evaluation, we can use a constant array for the map sizes, otherwise we
  7307. // need to fill up the arrays as we do for the pointers.
  7308. if (hasRuntimeEvaluationCaptureSize) {
  7309. QualType SizeArrayType = Ctx.getConstantArrayType(
  7310. Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
  7311. /*IndexTypeQuals=*/0);
  7312. Info.SizesArray =
  7313. CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
  7314. } else {
  7315. // We expect all the sizes to be constant, so we collect them to create
  7316. // a constant array.
  7317. SmallVector<llvm::Constant *, 16> ConstSizes;
  7318. for (llvm::Value *S : Sizes)
  7319. ConstSizes.push_back(cast<llvm::Constant>(S));
  7320. auto *SizesArrayInit = llvm::ConstantArray::get(
  7321. llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
  7322. std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
  7323. auto *SizesArrayGbl = new llvm::GlobalVariable(
  7324. CGM.getModule(), SizesArrayInit->getType(),
  7325. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
  7326. SizesArrayInit, Name);
  7327. SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  7328. Info.SizesArray = SizesArrayGbl;
  7329. }
  7330. // The map types are always constant so we don't need to generate code to
  7331. // fill arrays. Instead, we create an array constant.
  7332. SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
  7333. llvm::copy(MapTypes, Mapping.begin());
  7334. llvm::Constant *MapTypesArrayInit =
  7335. llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
  7336. std::string MaptypesName =
  7337. CGM.getOpenMPRuntime().getName({"offload_maptypes"});
  7338. auto *MapTypesArrayGbl = new llvm::GlobalVariable(
  7339. CGM.getModule(), MapTypesArrayInit->getType(),
  7340. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
  7341. MapTypesArrayInit, MaptypesName);
  7342. MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  7343. Info.MapTypesArray = MapTypesArrayGbl;
  7344. for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
  7345. llvm::Value *BPVal = *BasePointers[I];
  7346. llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
  7347. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  7348. Info.BasePointersArray, 0, I);
  7349. BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  7350. BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
  7351. Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
  7352. CGF.Builder.CreateStore(BPVal, BPAddr);
  7353. if (Info.requiresDevicePointerInfo())
  7354. if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
  7355. Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
  7356. llvm::Value *PVal = Pointers[I];
  7357. llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
  7358. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  7359. Info.PointersArray, 0, I);
  7360. P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  7361. P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
  7362. Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
  7363. CGF.Builder.CreateStore(PVal, PAddr);
  7364. if (hasRuntimeEvaluationCaptureSize) {
  7365. llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
  7366. llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
  7367. Info.SizesArray,
  7368. /*Idx0=*/0,
  7369. /*Idx1=*/I);
  7370. Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
  7371. CGF.Builder.CreateStore(
  7372. CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
  7373. SAddr);
  7374. }
  7375. }
  7376. }
  7377. }
  7378. /// Emit the arguments to be passed to the runtime library based on the
  7379. /// arrays of pointers, sizes and map types.
  7380. static void emitOffloadingArraysArgument(
  7381. CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
  7382. llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
  7383. llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
  7384. CodeGenModule &CGM = CGF.CGM;
  7385. if (Info.NumberOfPtrs) {
  7386. BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  7387. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  7388. Info.BasePointersArray,
  7389. /*Idx0=*/0, /*Idx1=*/0);
  7390. PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  7391. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  7392. Info.PointersArray,
  7393. /*Idx0=*/0,
  7394. /*Idx1=*/0);
  7395. SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  7396. llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
  7397. /*Idx0=*/0, /*Idx1=*/0);
  7398. MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  7399. llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
  7400. Info.MapTypesArray,
  7401. /*Idx0=*/0,
  7402. /*Idx1=*/0);
  7403. } else {
  7404. BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
  7405. PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
  7406. SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
  7407. MapTypesArrayArg =
  7408. llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
  7409. }
  7410. }
  7411. void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
  7412. const OMPExecutableDirective &D,
  7413. llvm::Value *OutlinedFn,
  7414. llvm::Value *OutlinedFnID,
  7415. const Expr *IfCond, const Expr *Device) {
  7416. if (!CGF.HaveInsertPoint())
  7417. return;
  7418. assert(OutlinedFn && "Invalid outlined function!");
  7419. const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
  7420. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  7421. const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
  7422. auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
  7423. PrePostActionTy &) {
  7424. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  7425. };
  7426. emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
  7427. CodeGenFunction::OMPTargetDataInfo InputInfo;
  7428. llvm::Value *MapTypesArray = nullptr;
  7429. // Fill up the pointer arrays and transfer execution to the device.
  7430. auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
  7431. &MapTypesArray, &CS, RequiresOuterTask,
  7432. &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
  7433. // On top of the arrays that were filled up, the target offloading call
  7434. // takes as arguments the device id as well as the host pointer. The host
  7435. // pointer is used by the runtime library to identify the current target
  7436. // region, so it only has to be unique and not necessarily point to
  7437. // anything. It could be the pointer to the outlined function that
  7438. // implements the target region, but we aren't using that so that the
  7439. // compiler doesn't need to keep that, and could therefore inline the host
  7440. // function if proven worthwhile during optimization.
  7441. // From this point on, we need to have an ID of the target region defined.
  7442. assert(OutlinedFnID && "Invalid outlined function ID!");
  7443. // Emit device ID if any.
  7444. llvm::Value *DeviceID;
  7445. if (Device) {
  7446. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  7447. CGF.Int64Ty, /*isSigned=*/true);
  7448. } else {
  7449. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  7450. }
  7451. // Emit the number of elements in the offloading arrays.
  7452. llvm::Value *PointerNum =
  7453. CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
  7454. // Return value of the runtime offloading call.
  7455. llvm::Value *Return;
  7456. llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
  7457. llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
  7458. bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
  7459. // The target region is an outlined function launched by the runtime
  7460. // via calls __tgt_target() or __tgt_target_teams().
  7461. //
  7462. // __tgt_target() launches a target region with one team and one thread,
  7463. // executing a serial region. This master thread may in turn launch
  7464. // more threads within its team upon encountering a parallel region,
  7465. // however, no additional teams can be launched on the device.
  7466. //
  7467. // __tgt_target_teams() launches a target region with one or more teams,
  7468. // each with one or more threads. This call is required for target
  7469. // constructs such as:
  7470. // 'target teams'
  7471. // 'target' / 'teams'
  7472. // 'target teams distribute parallel for'
  7473. // 'target parallel'
  7474. // and so on.
  7475. //
  7476. // Note that on the host and CPU targets, the runtime implementation of
  7477. // these calls simply call the outlined function without forking threads.
  7478. // The outlined functions themselves have runtime calls to
  7479. // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
  7480. // the compiler in emitTeamsCall() and emitParallelCall().
  7481. //
  7482. // In contrast, on the NVPTX target, the implementation of
  7483. // __tgt_target_teams() launches a GPU kernel with the requested number
  7484. // of teams and threads so no additional calls to the runtime are required.
  7485. if (NumTeams) {
  7486. // If we have NumTeams defined this means that we have an enclosed teams
  7487. // region. Therefore we also expect to have NumThreads defined. These two
  7488. // values should be defined in the presence of a teams directive,
  7489. // regardless of having any clauses associated. If the user is using teams
  7490. // but no clauses, these two values will be the default that should be
  7491. // passed to the runtime library - a 32-bit integer with the value zero.
  7492. assert(NumThreads && "Thread limit expression should be available along "
  7493. "with number of teams.");
  7494. llvm::Value *OffloadingArgs[] = {DeviceID,
  7495. OutlinedFnID,
  7496. PointerNum,
  7497. InputInfo.BasePointersArray.getPointer(),
  7498. InputInfo.PointersArray.getPointer(),
  7499. InputInfo.SizesArray.getPointer(),
  7500. MapTypesArray,
  7501. NumTeams,
  7502. NumThreads};
  7503. Return = CGF.EmitRuntimeCall(
  7504. createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
  7505. : OMPRTL__tgt_target_teams),
  7506. OffloadingArgs);
  7507. } else {
  7508. llvm::Value *OffloadingArgs[] = {DeviceID,
  7509. OutlinedFnID,
  7510. PointerNum,
  7511. InputInfo.BasePointersArray.getPointer(),
  7512. InputInfo.PointersArray.getPointer(),
  7513. InputInfo.SizesArray.getPointer(),
  7514. MapTypesArray};
  7515. Return = CGF.EmitRuntimeCall(
  7516. createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
  7517. : OMPRTL__tgt_target),
  7518. OffloadingArgs);
  7519. }
  7520. // Check the error code and execute the host version if required.
  7521. llvm::BasicBlock *OffloadFailedBlock =
  7522. CGF.createBasicBlock("omp_offload.failed");
  7523. llvm::BasicBlock *OffloadContBlock =
  7524. CGF.createBasicBlock("omp_offload.cont");
  7525. llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
  7526. CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
  7527. CGF.EmitBlock(OffloadFailedBlock);
  7528. if (RequiresOuterTask) {
  7529. CapturedVars.clear();
  7530. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  7531. }
  7532. emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
  7533. CGF.EmitBranch(OffloadContBlock);
  7534. CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
  7535. };
  7536. // Notify that the host version must be executed.
  7537. auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
  7538. RequiresOuterTask](CodeGenFunction &CGF,
  7539. PrePostActionTy &) {
  7540. if (RequiresOuterTask) {
  7541. CapturedVars.clear();
  7542. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  7543. }
  7544. emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
  7545. };
  7546. auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
  7547. &CapturedVars, RequiresOuterTask,
  7548. &CS](CodeGenFunction &CGF, PrePostActionTy &) {
  7549. // Fill up the arrays with all the captured variables.
  7550. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  7551. MappableExprsHandler::MapValuesArrayTy Pointers;
  7552. MappableExprsHandler::MapValuesArrayTy Sizes;
  7553. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  7554. // Get mappable expression information.
  7555. MappableExprsHandler MEHandler(D, CGF);
  7556. auto RI = CS.getCapturedRecordDecl()->field_begin();
  7557. auto CV = CapturedVars.begin();
  7558. for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
  7559. CE = CS.capture_end();
  7560. CI != CE; ++CI, ++RI, ++CV) {
  7561. MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
  7562. MappableExprsHandler::MapValuesArrayTy CurPointers;
  7563. MappableExprsHandler::MapValuesArrayTy CurSizes;
  7564. MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
  7565. MappableExprsHandler::StructRangeInfoTy PartialStruct;
  7566. // VLA sizes are passed to the outlined region by copy and do not have map
  7567. // information associated.
  7568. if (CI->capturesVariableArrayType()) {
  7569. CurBasePointers.push_back(*CV);
  7570. CurPointers.push_back(*CV);
  7571. CurSizes.push_back(CGF.getTypeSize(RI->getType()));
  7572. // Copy to the device as an argument. No need to retrieve it.
  7573. CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
  7574. MappableExprsHandler::OMP_MAP_TARGET_PARAM);
  7575. } else {
  7576. // If we have any information in the map clause, we use it, otherwise we
  7577. // just do a default mapping.
  7578. MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
  7579. CurSizes, CurMapTypes, PartialStruct);
  7580. if (CurBasePointers.empty())
  7581. MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
  7582. CurPointers, CurSizes, CurMapTypes);
  7583. }
  7584. // We expect to have at least an element of information for this capture.
  7585. assert(!CurBasePointers.empty() &&
  7586. "Non-existing map pointer for capture!");
  7587. assert(CurBasePointers.size() == CurPointers.size() &&
  7588. CurBasePointers.size() == CurSizes.size() &&
  7589. CurBasePointers.size() == CurMapTypes.size() &&
  7590. "Inconsistent map information sizes!");
  7591. // If there is an entry in PartialStruct it means we have a struct with
  7592. // individual members mapped. Emit an extra combined entry.
  7593. if (PartialStruct.Base.isValid())
  7594. MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
  7595. CurMapTypes, PartialStruct);
  7596. // We need to append the results of this capture to what we already have.
  7597. BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
  7598. Pointers.append(CurPointers.begin(), CurPointers.end());
  7599. Sizes.append(CurSizes.begin(), CurSizes.end());
  7600. MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
  7601. }
  7602. // Map other list items in the map clause which are not captured variables
  7603. // but "declare target link" global variables.
  7604. MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
  7605. MapTypes);
  7606. TargetDataInfo Info;
  7607. // Fill up the arrays and create the arguments.
  7608. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  7609. emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
  7610. Info.PointersArray, Info.SizesArray,
  7611. Info.MapTypesArray, Info);
  7612. InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
  7613. InputInfo.BasePointersArray =
  7614. Address(Info.BasePointersArray, CGM.getPointerAlign());
  7615. InputInfo.PointersArray =
  7616. Address(Info.PointersArray, CGM.getPointerAlign());
  7617. InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
  7618. MapTypesArray = Info.MapTypesArray;
  7619. if (RequiresOuterTask)
  7620. CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
  7621. else
  7622. emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
  7623. };
  7624. auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
  7625. CodeGenFunction &CGF, PrePostActionTy &) {
  7626. if (RequiresOuterTask) {
  7627. CodeGenFunction::OMPTargetDataInfo InputInfo;
  7628. CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
  7629. } else {
  7630. emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
  7631. }
  7632. };
  7633. // If we have a target function ID it means that we need to support
  7634. // offloading, otherwise, just execute on the host. We need to execute on host
  7635. // regardless of the conditional in the if clause if, e.g., the user do not
  7636. // specify target triples.
  7637. if (OutlinedFnID) {
  7638. if (IfCond) {
  7639. emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
  7640. } else {
  7641. RegionCodeGenTy ThenRCG(TargetThenGen);
  7642. ThenRCG(CGF);
  7643. }
  7644. } else {
  7645. RegionCodeGenTy ElseRCG(TargetElseGen);
  7646. ElseRCG(CGF);
  7647. }
  7648. }
  7649. void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
  7650. StringRef ParentName) {
  7651. if (!S)
  7652. return;
  7653. // Codegen OMP target directives that offload compute to the device.
  7654. bool RequiresDeviceCodegen =
  7655. isa<OMPExecutableDirective>(S) &&
  7656. isOpenMPTargetExecutionDirective(
  7657. cast<OMPExecutableDirective>(S)->getDirectiveKind());
  7658. if (RequiresDeviceCodegen) {
  7659. const auto &E = *cast<OMPExecutableDirective>(S);
  7660. unsigned DeviceID;
  7661. unsigned FileID;
  7662. unsigned Line;
  7663. getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
  7664. FileID, Line);
  7665. // Is this a target region that should not be emitted as an entry point? If
  7666. // so just signal we are done with this target region.
  7667. if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
  7668. ParentName, Line))
  7669. return;
  7670. switch (E.getDirectiveKind()) {
  7671. case OMPD_target:
  7672. CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
  7673. cast<OMPTargetDirective>(E));
  7674. break;
  7675. case OMPD_target_parallel:
  7676. CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
  7677. CGM, ParentName, cast<OMPTargetParallelDirective>(E));
  7678. break;
  7679. case OMPD_target_teams:
  7680. CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
  7681. CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
  7682. break;
  7683. case OMPD_target_teams_distribute:
  7684. CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
  7685. CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
  7686. break;
  7687. case OMPD_target_teams_distribute_simd:
  7688. CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  7689. CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
  7690. break;
  7691. case OMPD_target_parallel_for:
  7692. CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
  7693. CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
  7694. break;
  7695. case OMPD_target_parallel_for_simd:
  7696. CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
  7697. CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
  7698. break;
  7699. case OMPD_target_simd:
  7700. CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
  7701. CGM, ParentName, cast<OMPTargetSimdDirective>(E));
  7702. break;
  7703. case OMPD_target_teams_distribute_parallel_for:
  7704. CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
  7705. CGM, ParentName,
  7706. cast<OMPTargetTeamsDistributeParallelForDirective>(E));
  7707. break;
  7708. case OMPD_target_teams_distribute_parallel_for_simd:
  7709. CodeGenFunction::
  7710. EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
  7711. CGM, ParentName,
  7712. cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
  7713. break;
  7714. case OMPD_parallel:
  7715. case OMPD_for:
  7716. case OMPD_parallel_for:
  7717. case OMPD_parallel_sections:
  7718. case OMPD_for_simd:
  7719. case OMPD_parallel_for_simd:
  7720. case OMPD_cancel:
  7721. case OMPD_cancellation_point:
  7722. case OMPD_ordered:
  7723. case OMPD_threadprivate:
  7724. case OMPD_task:
  7725. case OMPD_simd:
  7726. case OMPD_sections:
  7727. case OMPD_section:
  7728. case OMPD_single:
  7729. case OMPD_master:
  7730. case OMPD_critical:
  7731. case OMPD_taskyield:
  7732. case OMPD_barrier:
  7733. case OMPD_taskwait:
  7734. case OMPD_taskgroup:
  7735. case OMPD_atomic:
  7736. case OMPD_flush:
  7737. case OMPD_teams:
  7738. case OMPD_target_data:
  7739. case OMPD_target_exit_data:
  7740. case OMPD_target_enter_data:
  7741. case OMPD_distribute:
  7742. case OMPD_distribute_simd:
  7743. case OMPD_distribute_parallel_for:
  7744. case OMPD_distribute_parallel_for_simd:
  7745. case OMPD_teams_distribute:
  7746. case OMPD_teams_distribute_simd:
  7747. case OMPD_teams_distribute_parallel_for:
  7748. case OMPD_teams_distribute_parallel_for_simd:
  7749. case OMPD_target_update:
  7750. case OMPD_declare_simd:
  7751. case OMPD_declare_target:
  7752. case OMPD_end_declare_target:
  7753. case OMPD_declare_reduction:
  7754. case OMPD_taskloop:
  7755. case OMPD_taskloop_simd:
  7756. case OMPD_requires:
  7757. case OMPD_unknown:
  7758. llvm_unreachable("Unknown target directive for OpenMP device codegen.");
  7759. }
  7760. return;
  7761. }
  7762. if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
  7763. if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
  7764. return;
  7765. scanForTargetRegionsFunctions(
  7766. E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
  7767. return;
  7768. }
  7769. // If this is a lambda function, look into its body.
  7770. if (const auto *L = dyn_cast<LambdaExpr>(S))
  7771. S = L->getBody();
  7772. // Keep looking for target regions recursively.
  7773. for (const Stmt *II : S->children())
  7774. scanForTargetRegionsFunctions(II, ParentName);
  7775. }
  7776. bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
  7777. // If emitting code for the host, we do not process FD here. Instead we do
  7778. // the normal code generation.
  7779. if (!CGM.getLangOpts().OpenMPIsDevice)
  7780. return false;
  7781. // Try to detect target regions in the function.
  7782. const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
  7783. if (const auto *FD = dyn_cast<FunctionDecl>(VD))
  7784. scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
  7785. // Do not to emit function if it is not marked as declare target.
  7786. return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  7787. AlreadyEmittedTargetFunctions.count(VD->getCanonicalDecl()) == 0;
  7788. }
  7789. bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
  7790. if (!CGM.getLangOpts().OpenMPIsDevice)
  7791. return false;
  7792. // Check if there are Ctors/Dtors in this declaration and look for target
  7793. // regions in it. We use the complete variant to produce the kernel name
  7794. // mangling.
  7795. QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
  7796. if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
  7797. for (const CXXConstructorDecl *Ctor : RD->ctors()) {
  7798. StringRef ParentName =
  7799. CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
  7800. scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
  7801. }
  7802. if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
  7803. StringRef ParentName =
  7804. CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
  7805. scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
  7806. }
  7807. }
  7808. // Do not to emit variable if it is not marked as declare target.
  7809. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  7810. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  7811. cast<VarDecl>(GD.getDecl()));
  7812. if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  7813. DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
  7814. return true;
  7815. }
  7816. return false;
  7817. }
  7818. void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
  7819. llvm::Constant *Addr) {
  7820. if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  7821. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  7822. OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
  7823. StringRef VarName;
  7824. CharUnits VarSize;
  7825. llvm::GlobalValue::LinkageTypes Linkage;
  7826. switch (*Res) {
  7827. case OMPDeclareTargetDeclAttr::MT_To:
  7828. Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
  7829. VarName = CGM.getMangledName(VD);
  7830. if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
  7831. VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
  7832. assert(!VarSize.isZero() && "Expected non-zero size of the variable");
  7833. } else {
  7834. VarSize = CharUnits::Zero();
  7835. }
  7836. Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
  7837. // Temp solution to prevent optimizations of the internal variables.
  7838. if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
  7839. std::string RefName = getName({VarName, "ref"});
  7840. if (!CGM.GetGlobalValue(RefName)) {
  7841. llvm::Constant *AddrRef =
  7842. getOrCreateInternalVariable(Addr->getType(), RefName);
  7843. auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
  7844. GVAddrRef->setConstant(/*Val=*/true);
  7845. GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
  7846. GVAddrRef->setInitializer(Addr);
  7847. CGM.addCompilerUsedGlobal(GVAddrRef);
  7848. }
  7849. }
  7850. break;
  7851. case OMPDeclareTargetDeclAttr::MT_Link:
  7852. Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
  7853. if (CGM.getLangOpts().OpenMPIsDevice) {
  7854. VarName = Addr->getName();
  7855. Addr = nullptr;
  7856. } else {
  7857. VarName = getAddrOfDeclareTargetLink(VD).getName();
  7858. Addr =
  7859. cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
  7860. }
  7861. VarSize = CGM.getPointerSize();
  7862. Linkage = llvm::GlobalValue::WeakAnyLinkage;
  7863. break;
  7864. }
  7865. OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
  7866. VarName, Addr, VarSize, Flags, Linkage);
  7867. }
  7868. }
  7869. bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
  7870. if (isa<FunctionDecl>(GD.getDecl()) ||
  7871. isa<OMPDeclareReductionDecl>(GD.getDecl()))
  7872. return emitTargetFunctions(GD);
  7873. return emitTargetGlobalVariable(GD);
  7874. }
  7875. void CGOpenMPRuntime::emitDeferredTargetDecls() const {
  7876. for (const VarDecl *VD : DeferredGlobalVariables) {
  7877. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  7878. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  7879. if (!Res)
  7880. continue;
  7881. if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
  7882. CGM.EmitGlobal(VD);
  7883. } else {
  7884. assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
  7885. "Expected to or link clauses.");
  7886. (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
  7887. }
  7888. }
  7889. }
  7890. CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
  7891. CodeGenModule &CGM)
  7892. : CGM(CGM) {
  7893. if (CGM.getLangOpts().OpenMPIsDevice) {
  7894. SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
  7895. CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
  7896. }
  7897. }
  7898. CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
  7899. if (CGM.getLangOpts().OpenMPIsDevice)
  7900. CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
  7901. }
  7902. bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
  7903. if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
  7904. return true;
  7905. const auto *D = cast<FunctionDecl>(GD.getDecl());
  7906. const FunctionDecl *FD = D->getCanonicalDecl();
  7907. // Do not to emit function if it is marked as declare target as it was already
  7908. // emitted.
  7909. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
  7910. if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
  7911. if (auto *F = dyn_cast_or_null<llvm::Function>(
  7912. CGM.GetGlobalValue(CGM.getMangledName(GD))))
  7913. return !F->isDeclaration();
  7914. return false;
  7915. }
  7916. return true;
  7917. }
  7918. return !AlreadyEmittedTargetFunctions.insert(FD).second;
  7919. }
  7920. llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
  7921. // If we have offloading in the current module, we need to emit the entries
  7922. // now and register the offloading descriptor.
  7923. createOffloadEntriesAndInfoMetadata();
  7924. // Create and register the offloading binary descriptors. This is the main
  7925. // entity that captures all the information about offloading in the current
  7926. // compilation unit.
  7927. return createOffloadingBinaryDescriptorRegistration();
  7928. }
  7929. void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
  7930. const OMPExecutableDirective &D,
  7931. SourceLocation Loc,
  7932. llvm::Value *OutlinedFn,
  7933. ArrayRef<llvm::Value *> CapturedVars) {
  7934. if (!CGF.HaveInsertPoint())
  7935. return;
  7936. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  7937. CodeGenFunction::RunCleanupsScope Scope(CGF);
  7938. // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
  7939. llvm::Value *Args[] = {
  7940. RTLoc,
  7941. CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
  7942. CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
  7943. llvm::SmallVector<llvm::Value *, 16> RealArgs;
  7944. RealArgs.append(std::begin(Args), std::end(Args));
  7945. RealArgs.append(CapturedVars.begin(), CapturedVars.end());
  7946. llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
  7947. CGF.EmitRuntimeCall(RTLFn, RealArgs);
  7948. }
  7949. void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
  7950. const Expr *NumTeams,
  7951. const Expr *ThreadLimit,
  7952. SourceLocation Loc) {
  7953. if (!CGF.HaveInsertPoint())
  7954. return;
  7955. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  7956. llvm::Value *NumTeamsVal =
  7957. NumTeams
  7958. ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
  7959. CGF.CGM.Int32Ty, /* isSigned = */ true)
  7960. : CGF.Builder.getInt32(0);
  7961. llvm::Value *ThreadLimitVal =
  7962. ThreadLimit
  7963. ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
  7964. CGF.CGM.Int32Ty, /* isSigned = */ true)
  7965. : CGF.Builder.getInt32(0);
  7966. // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
  7967. llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
  7968. ThreadLimitVal};
  7969. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
  7970. PushNumTeamsArgs);
  7971. }
  7972. void CGOpenMPRuntime::emitTargetDataCalls(
  7973. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  7974. const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
  7975. if (!CGF.HaveInsertPoint())
  7976. return;
  7977. // Action used to replace the default codegen action and turn privatization
  7978. // off.
  7979. PrePostActionTy NoPrivAction;
  7980. // Generate the code for the opening of the data environment. Capture all the
  7981. // arguments of the runtime call by reference because they are used in the
  7982. // closing of the region.
  7983. auto &&BeginThenGen = [this, &D, Device, &Info,
  7984. &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
  7985. // Fill up the arrays with all the mapped variables.
  7986. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  7987. MappableExprsHandler::MapValuesArrayTy Pointers;
  7988. MappableExprsHandler::MapValuesArrayTy Sizes;
  7989. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  7990. // Get map clause information.
  7991. MappableExprsHandler MCHandler(D, CGF);
  7992. MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
  7993. // Fill up the arrays and create the arguments.
  7994. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  7995. llvm::Value *BasePointersArrayArg = nullptr;
  7996. llvm::Value *PointersArrayArg = nullptr;
  7997. llvm::Value *SizesArrayArg = nullptr;
  7998. llvm::Value *MapTypesArrayArg = nullptr;
  7999. emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
  8000. SizesArrayArg, MapTypesArrayArg, Info);
  8001. // Emit device ID if any.
  8002. llvm::Value *DeviceID = nullptr;
  8003. if (Device) {
  8004. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  8005. CGF.Int64Ty, /*isSigned=*/true);
  8006. } else {
  8007. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  8008. }
  8009. // Emit the number of elements in the offloading arrays.
  8010. llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
  8011. llvm::Value *OffloadingArgs[] = {
  8012. DeviceID, PointerNum, BasePointersArrayArg,
  8013. PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
  8014. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
  8015. OffloadingArgs);
  8016. // If device pointer privatization is required, emit the body of the region
  8017. // here. It will have to be duplicated: with and without privatization.
  8018. if (!Info.CaptureDeviceAddrMap.empty())
  8019. CodeGen(CGF);
  8020. };
  8021. // Generate code for the closing of the data region.
  8022. auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
  8023. PrePostActionTy &) {
  8024. assert(Info.isValid() && "Invalid data environment closing arguments.");
  8025. llvm::Value *BasePointersArrayArg = nullptr;
  8026. llvm::Value *PointersArrayArg = nullptr;
  8027. llvm::Value *SizesArrayArg = nullptr;
  8028. llvm::Value *MapTypesArrayArg = nullptr;
  8029. emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
  8030. SizesArrayArg, MapTypesArrayArg, Info);
  8031. // Emit device ID if any.
  8032. llvm::Value *DeviceID = nullptr;
  8033. if (Device) {
  8034. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  8035. CGF.Int64Ty, /*isSigned=*/true);
  8036. } else {
  8037. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  8038. }
  8039. // Emit the number of elements in the offloading arrays.
  8040. llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
  8041. llvm::Value *OffloadingArgs[] = {
  8042. DeviceID, PointerNum, BasePointersArrayArg,
  8043. PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
  8044. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
  8045. OffloadingArgs);
  8046. };
  8047. // If we need device pointer privatization, we need to emit the body of the
  8048. // region with no privatization in the 'else' branch of the conditional.
  8049. // Otherwise, we don't have to do anything.
  8050. auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
  8051. PrePostActionTy &) {
  8052. if (!Info.CaptureDeviceAddrMap.empty()) {
  8053. CodeGen.setAction(NoPrivAction);
  8054. CodeGen(CGF);
  8055. }
  8056. };
  8057. // We don't have to do anything to close the region if the if clause evaluates
  8058. // to false.
  8059. auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
  8060. if (IfCond) {
  8061. emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
  8062. } else {
  8063. RegionCodeGenTy RCG(BeginThenGen);
  8064. RCG(CGF);
  8065. }
  8066. // If we don't require privatization of device pointers, we emit the body in
  8067. // between the runtime calls. This avoids duplicating the body code.
  8068. if (Info.CaptureDeviceAddrMap.empty()) {
  8069. CodeGen.setAction(NoPrivAction);
  8070. CodeGen(CGF);
  8071. }
  8072. if (IfCond) {
  8073. emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
  8074. } else {
  8075. RegionCodeGenTy RCG(EndThenGen);
  8076. RCG(CGF);
  8077. }
  8078. }
  8079. void CGOpenMPRuntime::emitTargetDataStandAloneCall(
  8080. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  8081. const Expr *Device) {
  8082. if (!CGF.HaveInsertPoint())
  8083. return;
  8084. assert((isa<OMPTargetEnterDataDirective>(D) ||
  8085. isa<OMPTargetExitDataDirective>(D) ||
  8086. isa<OMPTargetUpdateDirective>(D)) &&
  8087. "Expecting either target enter, exit data, or update directives.");
  8088. CodeGenFunction::OMPTargetDataInfo InputInfo;
  8089. llvm::Value *MapTypesArray = nullptr;
  8090. // Generate the code for the opening of the data environment.
  8091. auto &&ThenGen = [this, &D, Device, &InputInfo,
  8092. &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
  8093. // Emit device ID if any.
  8094. llvm::Value *DeviceID = nullptr;
  8095. if (Device) {
  8096. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  8097. CGF.Int64Ty, /*isSigned=*/true);
  8098. } else {
  8099. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  8100. }
  8101. // Emit the number of elements in the offloading arrays.
  8102. llvm::Constant *PointerNum =
  8103. CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
  8104. llvm::Value *OffloadingArgs[] = {DeviceID,
  8105. PointerNum,
  8106. InputInfo.BasePointersArray.getPointer(),
  8107. InputInfo.PointersArray.getPointer(),
  8108. InputInfo.SizesArray.getPointer(),
  8109. MapTypesArray};
  8110. // Select the right runtime function call for each expected standalone
  8111. // directive.
  8112. const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
  8113. OpenMPRTLFunction RTLFn;
  8114. switch (D.getDirectiveKind()) {
  8115. case OMPD_target_enter_data:
  8116. RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
  8117. : OMPRTL__tgt_target_data_begin;
  8118. break;
  8119. case OMPD_target_exit_data:
  8120. RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
  8121. : OMPRTL__tgt_target_data_end;
  8122. break;
  8123. case OMPD_target_update:
  8124. RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
  8125. : OMPRTL__tgt_target_data_update;
  8126. break;
  8127. case OMPD_parallel:
  8128. case OMPD_for:
  8129. case OMPD_parallel_for:
  8130. case OMPD_parallel_sections:
  8131. case OMPD_for_simd:
  8132. case OMPD_parallel_for_simd:
  8133. case OMPD_cancel:
  8134. case OMPD_cancellation_point:
  8135. case OMPD_ordered:
  8136. case OMPD_threadprivate:
  8137. case OMPD_task:
  8138. case OMPD_simd:
  8139. case OMPD_sections:
  8140. case OMPD_section:
  8141. case OMPD_single:
  8142. case OMPD_master:
  8143. case OMPD_critical:
  8144. case OMPD_taskyield:
  8145. case OMPD_barrier:
  8146. case OMPD_taskwait:
  8147. case OMPD_taskgroup:
  8148. case OMPD_atomic:
  8149. case OMPD_flush:
  8150. case OMPD_teams:
  8151. case OMPD_target_data:
  8152. case OMPD_distribute:
  8153. case OMPD_distribute_simd:
  8154. case OMPD_distribute_parallel_for:
  8155. case OMPD_distribute_parallel_for_simd:
  8156. case OMPD_teams_distribute:
  8157. case OMPD_teams_distribute_simd:
  8158. case OMPD_teams_distribute_parallel_for:
  8159. case OMPD_teams_distribute_parallel_for_simd:
  8160. case OMPD_declare_simd:
  8161. case OMPD_declare_target:
  8162. case OMPD_end_declare_target:
  8163. case OMPD_declare_reduction:
  8164. case OMPD_taskloop:
  8165. case OMPD_taskloop_simd:
  8166. case OMPD_target:
  8167. case OMPD_target_simd:
  8168. case OMPD_target_teams_distribute:
  8169. case OMPD_target_teams_distribute_simd:
  8170. case OMPD_target_teams_distribute_parallel_for:
  8171. case OMPD_target_teams_distribute_parallel_for_simd:
  8172. case OMPD_target_teams:
  8173. case OMPD_target_parallel:
  8174. case OMPD_target_parallel_for:
  8175. case OMPD_target_parallel_for_simd:
  8176. case OMPD_requires:
  8177. case OMPD_unknown:
  8178. llvm_unreachable("Unexpected standalone target data directive.");
  8179. break;
  8180. }
  8181. CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
  8182. };
  8183. auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
  8184. CodeGenFunction &CGF, PrePostActionTy &) {
  8185. // Fill up the arrays with all the mapped variables.
  8186. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  8187. MappableExprsHandler::MapValuesArrayTy Pointers;
  8188. MappableExprsHandler::MapValuesArrayTy Sizes;
  8189. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  8190. // Get map clause information.
  8191. MappableExprsHandler MEHandler(D, CGF);
  8192. MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
  8193. TargetDataInfo Info;
  8194. // Fill up the arrays and create the arguments.
  8195. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  8196. emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
  8197. Info.PointersArray, Info.SizesArray,
  8198. Info.MapTypesArray, Info);
  8199. InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
  8200. InputInfo.BasePointersArray =
  8201. Address(Info.BasePointersArray, CGM.getPointerAlign());
  8202. InputInfo.PointersArray =
  8203. Address(Info.PointersArray, CGM.getPointerAlign());
  8204. InputInfo.SizesArray =
  8205. Address(Info.SizesArray, CGM.getPointerAlign());
  8206. MapTypesArray = Info.MapTypesArray;
  8207. if (D.hasClausesOfKind<OMPDependClause>())
  8208. CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
  8209. else
  8210. emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
  8211. };
  8212. if (IfCond) {
  8213. emitOMPIfClause(CGF, IfCond, TargetThenGen,
  8214. [](CodeGenFunction &CGF, PrePostActionTy &) {});
  8215. } else {
  8216. RegionCodeGenTy ThenRCG(TargetThenGen);
  8217. ThenRCG(CGF);
  8218. }
  8219. }
  8220. namespace {
  8221. /// Kind of parameter in a function with 'declare simd' directive.
  8222. enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
  8223. /// Attribute set of the parameter.
  8224. struct ParamAttrTy {
  8225. ParamKindTy Kind = Vector;
  8226. llvm::APSInt StrideOrArg;
  8227. llvm::APSInt Alignment;
  8228. };
  8229. } // namespace
  8230. static unsigned evaluateCDTSize(const FunctionDecl *FD,
  8231. ArrayRef<ParamAttrTy> ParamAttrs) {
  8232. // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
  8233. // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
  8234. // of that clause. The VLEN value must be power of 2.
  8235. // In other case the notion of the function`s "characteristic data type" (CDT)
  8236. // is used to compute the vector length.
  8237. // CDT is defined in the following order:
  8238. // a) For non-void function, the CDT is the return type.
  8239. // b) If the function has any non-uniform, non-linear parameters, then the
  8240. // CDT is the type of the first such parameter.
  8241. // c) If the CDT determined by a) or b) above is struct, union, or class
  8242. // type which is pass-by-value (except for the type that maps to the
  8243. // built-in complex data type), the characteristic data type is int.
  8244. // d) If none of the above three cases is applicable, the CDT is int.
  8245. // The VLEN is then determined based on the CDT and the size of vector
  8246. // register of that ISA for which current vector version is generated. The
  8247. // VLEN is computed using the formula below:
  8248. // VLEN = sizeof(vector_register) / sizeof(CDT),
  8249. // where vector register size specified in section 3.2.1 Registers and the
  8250. // Stack Frame of original AMD64 ABI document.
  8251. QualType RetType = FD->getReturnType();
  8252. if (RetType.isNull())
  8253. return 0;
  8254. ASTContext &C = FD->getASTContext();
  8255. QualType CDT;
  8256. if (!RetType.isNull() && !RetType->isVoidType()) {
  8257. CDT = RetType;
  8258. } else {
  8259. unsigned Offset = 0;
  8260. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  8261. if (ParamAttrs[Offset].Kind == Vector)
  8262. CDT = C.getPointerType(C.getRecordType(MD->getParent()));
  8263. ++Offset;
  8264. }
  8265. if (CDT.isNull()) {
  8266. for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
  8267. if (ParamAttrs[I + Offset].Kind == Vector) {
  8268. CDT = FD->getParamDecl(I)->getType();
  8269. break;
  8270. }
  8271. }
  8272. }
  8273. }
  8274. if (CDT.isNull())
  8275. CDT = C.IntTy;
  8276. CDT = CDT->getCanonicalTypeUnqualified();
  8277. if (CDT->isRecordType() || CDT->isUnionType())
  8278. CDT = C.IntTy;
  8279. return C.getTypeSize(CDT);
  8280. }
  8281. static void
  8282. emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
  8283. const llvm::APSInt &VLENVal,
  8284. ArrayRef<ParamAttrTy> ParamAttrs,
  8285. OMPDeclareSimdDeclAttr::BranchStateTy State) {
  8286. struct ISADataTy {
  8287. char ISA;
  8288. unsigned VecRegSize;
  8289. };
  8290. ISADataTy ISAData[] = {
  8291. {
  8292. 'b', 128
  8293. }, // SSE
  8294. {
  8295. 'c', 256
  8296. }, // AVX
  8297. {
  8298. 'd', 256
  8299. }, // AVX2
  8300. {
  8301. 'e', 512
  8302. }, // AVX512
  8303. };
  8304. llvm::SmallVector<char, 2> Masked;
  8305. switch (State) {
  8306. case OMPDeclareSimdDeclAttr::BS_Undefined:
  8307. Masked.push_back('N');
  8308. Masked.push_back('M');
  8309. break;
  8310. case OMPDeclareSimdDeclAttr::BS_Notinbranch:
  8311. Masked.push_back('N');
  8312. break;
  8313. case OMPDeclareSimdDeclAttr::BS_Inbranch:
  8314. Masked.push_back('M');
  8315. break;
  8316. }
  8317. for (char Mask : Masked) {
  8318. for (const ISADataTy &Data : ISAData) {
  8319. SmallString<256> Buffer;
  8320. llvm::raw_svector_ostream Out(Buffer);
  8321. Out << "_ZGV" << Data.ISA << Mask;
  8322. if (!VLENVal) {
  8323. Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
  8324. evaluateCDTSize(FD, ParamAttrs));
  8325. } else {
  8326. Out << VLENVal;
  8327. }
  8328. for (const ParamAttrTy &ParamAttr : ParamAttrs) {
  8329. switch (ParamAttr.Kind){
  8330. case LinearWithVarStride:
  8331. Out << 's' << ParamAttr.StrideOrArg;
  8332. break;
  8333. case Linear:
  8334. Out << 'l';
  8335. if (!!ParamAttr.StrideOrArg)
  8336. Out << ParamAttr.StrideOrArg;
  8337. break;
  8338. case Uniform:
  8339. Out << 'u';
  8340. break;
  8341. case Vector:
  8342. Out << 'v';
  8343. break;
  8344. }
  8345. if (!!ParamAttr.Alignment)
  8346. Out << 'a' << ParamAttr.Alignment;
  8347. }
  8348. Out << '_' << Fn->getName();
  8349. Fn->addFnAttr(Out.str());
  8350. }
  8351. }
  8352. }
  8353. void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
  8354. llvm::Function *Fn) {
  8355. ASTContext &C = CGM.getContext();
  8356. FD = FD->getMostRecentDecl();
  8357. // Map params to their positions in function decl.
  8358. llvm::DenseMap<const Decl *, unsigned> ParamPositions;
  8359. if (isa<CXXMethodDecl>(FD))
  8360. ParamPositions.try_emplace(FD, 0);
  8361. unsigned ParamPos = ParamPositions.size();
  8362. for (const ParmVarDecl *P : FD->parameters()) {
  8363. ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
  8364. ++ParamPos;
  8365. }
  8366. while (FD) {
  8367. for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
  8368. llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
  8369. // Mark uniform parameters.
  8370. for (const Expr *E : Attr->uniforms()) {
  8371. E = E->IgnoreParenImpCasts();
  8372. unsigned Pos;
  8373. if (isa<CXXThisExpr>(E)) {
  8374. Pos = ParamPositions[FD];
  8375. } else {
  8376. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  8377. ->getCanonicalDecl();
  8378. Pos = ParamPositions[PVD];
  8379. }
  8380. ParamAttrs[Pos].Kind = Uniform;
  8381. }
  8382. // Get alignment info.
  8383. auto NI = Attr->alignments_begin();
  8384. for (const Expr *E : Attr->aligneds()) {
  8385. E = E->IgnoreParenImpCasts();
  8386. unsigned Pos;
  8387. QualType ParmTy;
  8388. if (isa<CXXThisExpr>(E)) {
  8389. Pos = ParamPositions[FD];
  8390. ParmTy = E->getType();
  8391. } else {
  8392. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  8393. ->getCanonicalDecl();
  8394. Pos = ParamPositions[PVD];
  8395. ParmTy = PVD->getType();
  8396. }
  8397. ParamAttrs[Pos].Alignment =
  8398. (*NI)
  8399. ? (*NI)->EvaluateKnownConstInt(C)
  8400. : llvm::APSInt::getUnsigned(
  8401. C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
  8402. .getQuantity());
  8403. ++NI;
  8404. }
  8405. // Mark linear parameters.
  8406. auto SI = Attr->steps_begin();
  8407. auto MI = Attr->modifiers_begin();
  8408. for (const Expr *E : Attr->linears()) {
  8409. E = E->IgnoreParenImpCasts();
  8410. unsigned Pos;
  8411. if (isa<CXXThisExpr>(E)) {
  8412. Pos = ParamPositions[FD];
  8413. } else {
  8414. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  8415. ->getCanonicalDecl();
  8416. Pos = ParamPositions[PVD];
  8417. }
  8418. ParamAttrTy &ParamAttr = ParamAttrs[Pos];
  8419. ParamAttr.Kind = Linear;
  8420. if (*SI) {
  8421. if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
  8422. Expr::SE_AllowSideEffects)) {
  8423. if (const auto *DRE =
  8424. cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
  8425. if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
  8426. ParamAttr.Kind = LinearWithVarStride;
  8427. ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
  8428. ParamPositions[StridePVD->getCanonicalDecl()]);
  8429. }
  8430. }
  8431. }
  8432. }
  8433. ++SI;
  8434. ++MI;
  8435. }
  8436. llvm::APSInt VLENVal;
  8437. if (const Expr *VLEN = Attr->getSimdlen())
  8438. VLENVal = VLEN->EvaluateKnownConstInt(C);
  8439. OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
  8440. if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
  8441. CGM.getTriple().getArch() == llvm::Triple::x86_64)
  8442. emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
  8443. }
  8444. FD = FD->getPreviousDecl();
  8445. }
  8446. }
  8447. namespace {
  8448. /// Cleanup action for doacross support.
  8449. class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
  8450. public:
  8451. static const int DoacrossFinArgs = 2;
  8452. private:
  8453. llvm::Value *RTLFn;
  8454. llvm::Value *Args[DoacrossFinArgs];
  8455. public:
  8456. DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
  8457. : RTLFn(RTLFn) {
  8458. assert(CallArgs.size() == DoacrossFinArgs);
  8459. std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
  8460. }
  8461. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  8462. if (!CGF.HaveInsertPoint())
  8463. return;
  8464. CGF.EmitRuntimeCall(RTLFn, Args);
  8465. }
  8466. };
  8467. } // namespace
  8468. void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
  8469. const OMPLoopDirective &D,
  8470. ArrayRef<Expr *> NumIterations) {
  8471. if (!CGF.HaveInsertPoint())
  8472. return;
  8473. ASTContext &C = CGM.getContext();
  8474. QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
  8475. RecordDecl *RD;
  8476. if (KmpDimTy.isNull()) {
  8477. // Build struct kmp_dim { // loop bounds info casted to kmp_int64
  8478. // kmp_int64 lo; // lower
  8479. // kmp_int64 up; // upper
  8480. // kmp_int64 st; // stride
  8481. // };
  8482. RD = C.buildImplicitRecord("kmp_dim");
  8483. RD->startDefinition();
  8484. addFieldToRecordDecl(C, RD, Int64Ty);
  8485. addFieldToRecordDecl(C, RD, Int64Ty);
  8486. addFieldToRecordDecl(C, RD, Int64Ty);
  8487. RD->completeDefinition();
  8488. KmpDimTy = C.getRecordType(RD);
  8489. } else {
  8490. RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
  8491. }
  8492. llvm::APInt Size(/*numBits=*/32, NumIterations.size());
  8493. QualType ArrayTy =
  8494. C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
  8495. Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
  8496. CGF.EmitNullInitialization(DimsAddr, ArrayTy);
  8497. enum { LowerFD = 0, UpperFD, StrideFD };
  8498. // Fill dims with data.
  8499. for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
  8500. LValue DimsLVal =
  8501. CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
  8502. DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
  8503. KmpDimTy);
  8504. // dims.upper = num_iterations;
  8505. LValue UpperLVal = CGF.EmitLValueForField(
  8506. DimsLVal, *std::next(RD->field_begin(), UpperFD));
  8507. llvm::Value *NumIterVal =
  8508. CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
  8509. D.getNumIterations()->getType(), Int64Ty,
  8510. D.getNumIterations()->getExprLoc());
  8511. CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
  8512. // dims.stride = 1;
  8513. LValue StrideLVal = CGF.EmitLValueForField(
  8514. DimsLVal, *std::next(RD->field_begin(), StrideFD));
  8515. CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
  8516. StrideLVal);
  8517. }
  8518. // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
  8519. // kmp_int32 num_dims, struct kmp_dim * dims);
  8520. llvm::Value *Args[] = {
  8521. emitUpdateLocation(CGF, D.getBeginLoc()),
  8522. getThreadID(CGF, D.getBeginLoc()),
  8523. llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
  8524. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  8525. CGF.Builder
  8526. .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
  8527. .getPointer(),
  8528. CGM.VoidPtrTy)};
  8529. llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
  8530. CGF.EmitRuntimeCall(RTLFn, Args);
  8531. llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
  8532. emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
  8533. llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
  8534. CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
  8535. llvm::makeArrayRef(FiniArgs));
  8536. }
  8537. void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
  8538. const OMPDependClause *C) {
  8539. QualType Int64Ty =
  8540. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  8541. llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
  8542. QualType ArrayTy = CGM.getContext().getConstantArrayType(
  8543. Int64Ty, Size, ArrayType::Normal, 0);
  8544. Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
  8545. for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
  8546. const Expr *CounterVal = C->getLoopData(I);
  8547. assert(CounterVal);
  8548. llvm::Value *CntVal = CGF.EmitScalarConversion(
  8549. CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
  8550. CounterVal->getExprLoc());
  8551. CGF.EmitStoreOfScalar(
  8552. CntVal,
  8553. CGF.Builder.CreateConstArrayGEP(
  8554. CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
  8555. /*Volatile=*/false, Int64Ty);
  8556. }
  8557. llvm::Value *Args[] = {
  8558. emitUpdateLocation(CGF, C->getBeginLoc()),
  8559. getThreadID(CGF, C->getBeginLoc()),
  8560. CGF.Builder
  8561. .CreateConstArrayGEP(CntAddr, 0,
  8562. CGM.getContext().getTypeSizeInChars(Int64Ty))
  8563. .getPointer()};
  8564. llvm::Value *RTLFn;
  8565. if (C->getDependencyKind() == OMPC_DEPEND_source) {
  8566. RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
  8567. } else {
  8568. assert(C->getDependencyKind() == OMPC_DEPEND_sink);
  8569. RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
  8570. }
  8571. CGF.EmitRuntimeCall(RTLFn, Args);
  8572. }
  8573. void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
  8574. llvm::Value *Callee,
  8575. ArrayRef<llvm::Value *> Args) const {
  8576. assert(Loc.isValid() && "Outlined function call location must be valid.");
  8577. auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
  8578. if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
  8579. if (Fn->doesNotThrow()) {
  8580. CGF.EmitNounwindRuntimeCall(Fn, Args);
  8581. return;
  8582. }
  8583. }
  8584. CGF.EmitRuntimeCall(Callee, Args);
  8585. }
  8586. void CGOpenMPRuntime::emitOutlinedFunctionCall(
  8587. CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
  8588. ArrayRef<llvm::Value *> Args) const {
  8589. emitCall(CGF, Loc, OutlinedFn, Args);
  8590. }
  8591. Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
  8592. const VarDecl *NativeParam,
  8593. const VarDecl *TargetParam) const {
  8594. return CGF.GetAddrOfLocalVar(NativeParam);
  8595. }
  8596. Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
  8597. const VarDecl *VD) {
  8598. return Address::invalid();
  8599. }
  8600. llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
  8601. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  8602. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  8603. llvm_unreachable("Not supported in SIMD-only mode");
  8604. }
  8605. llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
  8606. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  8607. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  8608. llvm_unreachable("Not supported in SIMD-only mode");
  8609. }
  8610. llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
  8611. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  8612. const VarDecl *PartIDVar, const VarDecl *TaskTVar,
  8613. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  8614. bool Tied, unsigned &NumberOfParts) {
  8615. llvm_unreachable("Not supported in SIMD-only mode");
  8616. }
  8617. void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
  8618. SourceLocation Loc,
  8619. llvm::Value *OutlinedFn,
  8620. ArrayRef<llvm::Value *> CapturedVars,
  8621. const Expr *IfCond) {
  8622. llvm_unreachable("Not supported in SIMD-only mode");
  8623. }
  8624. void CGOpenMPSIMDRuntime::emitCriticalRegion(
  8625. CodeGenFunction &CGF, StringRef CriticalName,
  8626. const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
  8627. const Expr *Hint) {
  8628. llvm_unreachable("Not supported in SIMD-only mode");
  8629. }
  8630. void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
  8631. const RegionCodeGenTy &MasterOpGen,
  8632. SourceLocation Loc) {
  8633. llvm_unreachable("Not supported in SIMD-only mode");
  8634. }
  8635. void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
  8636. SourceLocation Loc) {
  8637. llvm_unreachable("Not supported in SIMD-only mode");
  8638. }
  8639. void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
  8640. CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
  8641. SourceLocation Loc) {
  8642. llvm_unreachable("Not supported in SIMD-only mode");
  8643. }
  8644. void CGOpenMPSIMDRuntime::emitSingleRegion(
  8645. CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
  8646. SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
  8647. ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
  8648. ArrayRef<const Expr *> AssignmentOps) {
  8649. llvm_unreachable("Not supported in SIMD-only mode");
  8650. }
  8651. void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
  8652. const RegionCodeGenTy &OrderedOpGen,
  8653. SourceLocation Loc,
  8654. bool IsThreads) {
  8655. llvm_unreachable("Not supported in SIMD-only mode");
  8656. }
  8657. void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
  8658. SourceLocation Loc,
  8659. OpenMPDirectiveKind Kind,
  8660. bool EmitChecks,
  8661. bool ForceSimpleCall) {
  8662. llvm_unreachable("Not supported in SIMD-only mode");
  8663. }
  8664. void CGOpenMPSIMDRuntime::emitForDispatchInit(
  8665. CodeGenFunction &CGF, SourceLocation Loc,
  8666. const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
  8667. bool Ordered, const DispatchRTInput &DispatchValues) {
  8668. llvm_unreachable("Not supported in SIMD-only mode");
  8669. }
  8670. void CGOpenMPSIMDRuntime::emitForStaticInit(
  8671. CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
  8672. const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
  8673. llvm_unreachable("Not supported in SIMD-only mode");
  8674. }
  8675. void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
  8676. CodeGenFunction &CGF, SourceLocation Loc,
  8677. OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
  8678. llvm_unreachable("Not supported in SIMD-only mode");
  8679. }
  8680. void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
  8681. SourceLocation Loc,
  8682. unsigned IVSize,
  8683. bool IVSigned) {
  8684. llvm_unreachable("Not supported in SIMD-only mode");
  8685. }
  8686. void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
  8687. SourceLocation Loc,
  8688. OpenMPDirectiveKind DKind) {
  8689. llvm_unreachable("Not supported in SIMD-only mode");
  8690. }
  8691. llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
  8692. SourceLocation Loc,
  8693. unsigned IVSize, bool IVSigned,
  8694. Address IL, Address LB,
  8695. Address UB, Address ST) {
  8696. llvm_unreachable("Not supported in SIMD-only mode");
  8697. }
  8698. void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
  8699. llvm::Value *NumThreads,
  8700. SourceLocation Loc) {
  8701. llvm_unreachable("Not supported in SIMD-only mode");
  8702. }
  8703. void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
  8704. OpenMPProcBindClauseKind ProcBind,
  8705. SourceLocation Loc) {
  8706. llvm_unreachable("Not supported in SIMD-only mode");
  8707. }
  8708. Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
  8709. const VarDecl *VD,
  8710. Address VDAddr,
  8711. SourceLocation Loc) {
  8712. llvm_unreachable("Not supported in SIMD-only mode");
  8713. }
  8714. llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
  8715. const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
  8716. CodeGenFunction *CGF) {
  8717. llvm_unreachable("Not supported in SIMD-only mode");
  8718. }
  8719. Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
  8720. CodeGenFunction &CGF, QualType VarType, StringRef Name) {
  8721. llvm_unreachable("Not supported in SIMD-only mode");
  8722. }
  8723. void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
  8724. ArrayRef<const Expr *> Vars,
  8725. SourceLocation Loc) {
  8726. llvm_unreachable("Not supported in SIMD-only mode");
  8727. }
  8728. void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
  8729. const OMPExecutableDirective &D,
  8730. llvm::Value *TaskFunction,
  8731. QualType SharedsTy, Address Shareds,
  8732. const Expr *IfCond,
  8733. const OMPTaskDataTy &Data) {
  8734. llvm_unreachable("Not supported in SIMD-only mode");
  8735. }
  8736. void CGOpenMPSIMDRuntime::emitTaskLoopCall(
  8737. CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
  8738. llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
  8739. const Expr *IfCond, const OMPTaskDataTy &Data) {
  8740. llvm_unreachable("Not supported in SIMD-only mode");
  8741. }
  8742. void CGOpenMPSIMDRuntime::emitReduction(
  8743. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
  8744. ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
  8745. ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
  8746. assert(Options.SimpleReduction && "Only simple reduction is expected.");
  8747. CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
  8748. ReductionOps, Options);
  8749. }
  8750. llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
  8751. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
  8752. ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
  8753. llvm_unreachable("Not supported in SIMD-only mode");
  8754. }
  8755. void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
  8756. SourceLocation Loc,
  8757. ReductionCodeGen &RCG,
  8758. unsigned N) {
  8759. llvm_unreachable("Not supported in SIMD-only mode");
  8760. }
  8761. Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
  8762. SourceLocation Loc,
  8763. llvm::Value *ReductionsPtr,
  8764. LValue SharedLVal) {
  8765. llvm_unreachable("Not supported in SIMD-only mode");
  8766. }
  8767. void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
  8768. SourceLocation Loc) {
  8769. llvm_unreachable("Not supported in SIMD-only mode");
  8770. }
  8771. void CGOpenMPSIMDRuntime::emitCancellationPointCall(
  8772. CodeGenFunction &CGF, SourceLocation Loc,
  8773. OpenMPDirectiveKind CancelRegion) {
  8774. llvm_unreachable("Not supported in SIMD-only mode");
  8775. }
  8776. void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
  8777. SourceLocation Loc, const Expr *IfCond,
  8778. OpenMPDirectiveKind CancelRegion) {
  8779. llvm_unreachable("Not supported in SIMD-only mode");
  8780. }
  8781. void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
  8782. const OMPExecutableDirective &D, StringRef ParentName,
  8783. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  8784. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  8785. llvm_unreachable("Not supported in SIMD-only mode");
  8786. }
  8787. void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
  8788. const OMPExecutableDirective &D,
  8789. llvm::Value *OutlinedFn,
  8790. llvm::Value *OutlinedFnID,
  8791. const Expr *IfCond, const Expr *Device) {
  8792. llvm_unreachable("Not supported in SIMD-only mode");
  8793. }
  8794. bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
  8795. llvm_unreachable("Not supported in SIMD-only mode");
  8796. }
  8797. bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
  8798. llvm_unreachable("Not supported in SIMD-only mode");
  8799. }
  8800. bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
  8801. return false;
  8802. }
  8803. llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
  8804. return nullptr;
  8805. }
  8806. void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
  8807. const OMPExecutableDirective &D,
  8808. SourceLocation Loc,
  8809. llvm::Value *OutlinedFn,
  8810. ArrayRef<llvm::Value *> CapturedVars) {
  8811. llvm_unreachable("Not supported in SIMD-only mode");
  8812. }
  8813. void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
  8814. const Expr *NumTeams,
  8815. const Expr *ThreadLimit,
  8816. SourceLocation Loc) {
  8817. llvm_unreachable("Not supported in SIMD-only mode");
  8818. }
  8819. void CGOpenMPSIMDRuntime::emitTargetDataCalls(
  8820. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  8821. const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
  8822. llvm_unreachable("Not supported in SIMD-only mode");
  8823. }
  8824. void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
  8825. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  8826. const Expr *Device) {
  8827. llvm_unreachable("Not supported in SIMD-only mode");
  8828. }
  8829. void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
  8830. const OMPLoopDirective &D,
  8831. ArrayRef<Expr *> NumIterations) {
  8832. llvm_unreachable("Not supported in SIMD-only mode");
  8833. }
  8834. void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
  8835. const OMPDependClause *C) {
  8836. llvm_unreachable("Not supported in SIMD-only mode");
  8837. }
  8838. const VarDecl *
  8839. CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
  8840. const VarDecl *NativeParam) const {
  8841. llvm_unreachable("Not supported in SIMD-only mode");
  8842. }
  8843. Address
  8844. CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
  8845. const VarDecl *NativeParam,
  8846. const VarDecl *TargetParam) const {
  8847. llvm_unreachable("Not supported in SIMD-only mode");
  8848. }