CGOpenMPRuntime.cpp 453 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825
  1. //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This provides a class for OpenMP runtime code generation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGCleanup.h"
  14. #include "CGOpenMPRuntime.h"
  15. #include "CGRecordLayout.h"
  16. #include "CodeGenFunction.h"
  17. #include "clang/CodeGen/ConstantInitBuilder.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/StmtOpenMP.h"
  20. #include "clang/Basic/BitmaskEnum.h"
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/Bitcode/BitcodeReader.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/GlobalValue.h"
  25. #include "llvm/IR/Value.h"
  26. #include "llvm/Support/Format.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <cassert>
  29. using namespace clang;
  30. using namespace CodeGen;
  31. namespace {
  32. /// Base class for handling code generation inside OpenMP regions.
  33. class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
  34. public:
  35. /// Kinds of OpenMP regions used in codegen.
  36. enum CGOpenMPRegionKind {
  37. /// Region with outlined function for standalone 'parallel'
  38. /// directive.
  39. ParallelOutlinedRegion,
  40. /// Region with outlined function for standalone 'task' directive.
  41. TaskOutlinedRegion,
  42. /// Region for constructs that do not require function outlining,
  43. /// like 'for', 'sections', 'atomic' etc. directives.
  44. InlinedRegion,
  45. /// Region with outlined function for standalone 'target' directive.
  46. TargetRegion,
  47. };
  48. CGOpenMPRegionInfo(const CapturedStmt &CS,
  49. const CGOpenMPRegionKind RegionKind,
  50. const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
  51. bool HasCancel)
  52. : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
  53. CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
  54. CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
  55. const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
  56. bool HasCancel)
  57. : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
  58. Kind(Kind), HasCancel(HasCancel) {}
  59. /// Get a variable or parameter for storing global thread id
  60. /// inside OpenMP construct.
  61. virtual const VarDecl *getThreadIDVariable() const = 0;
  62. /// Emit the captured statement body.
  63. void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
  64. /// Get an LValue for the current ThreadID variable.
  65. /// \return LValue for thread id variable. This LValue always has type int32*.
  66. virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
  67. virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
  68. CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
  69. OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
  70. bool hasCancel() const { return HasCancel; }
  71. static bool classof(const CGCapturedStmtInfo *Info) {
  72. return Info->getKind() == CR_OpenMP;
  73. }
  74. ~CGOpenMPRegionInfo() override = default;
  75. protected:
  76. CGOpenMPRegionKind RegionKind;
  77. RegionCodeGenTy CodeGen;
  78. OpenMPDirectiveKind Kind;
  79. bool HasCancel;
  80. };
  81. /// API for captured statement code generation in OpenMP constructs.
  82. class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
  83. public:
  84. CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
  85. const RegionCodeGenTy &CodeGen,
  86. OpenMPDirectiveKind Kind, bool HasCancel,
  87. StringRef HelperName)
  88. : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
  89. HasCancel),
  90. ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
  91. assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
  92. }
  93. /// Get a variable or parameter for storing global thread id
  94. /// inside OpenMP construct.
  95. const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
  96. /// Get the name of the capture helper.
  97. StringRef getHelperName() const override { return HelperName; }
  98. static bool classof(const CGCapturedStmtInfo *Info) {
  99. return CGOpenMPRegionInfo::classof(Info) &&
  100. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
  101. ParallelOutlinedRegion;
  102. }
  103. private:
  104. /// A variable or parameter storing global thread id for OpenMP
  105. /// constructs.
  106. const VarDecl *ThreadIDVar;
  107. StringRef HelperName;
  108. };
  109. /// API for captured statement code generation in OpenMP constructs.
  110. class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
  111. public:
  112. class UntiedTaskActionTy final : public PrePostActionTy {
  113. bool Untied;
  114. const VarDecl *PartIDVar;
  115. const RegionCodeGenTy UntiedCodeGen;
  116. llvm::SwitchInst *UntiedSwitch = nullptr;
  117. public:
  118. UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
  119. const RegionCodeGenTy &UntiedCodeGen)
  120. : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
  121. void Enter(CodeGenFunction &CGF) override {
  122. if (Untied) {
  123. // Emit task switching point.
  124. LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
  125. CGF.GetAddrOfLocalVar(PartIDVar),
  126. PartIDVar->getType()->castAs<PointerType>());
  127. llvm::Value *Res =
  128. CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
  129. llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
  130. UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
  131. CGF.EmitBlock(DoneBB);
  132. CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
  133. CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
  134. UntiedSwitch->addCase(CGF.Builder.getInt32(0),
  135. CGF.Builder.GetInsertBlock());
  136. emitUntiedSwitch(CGF);
  137. }
  138. }
  139. void emitUntiedSwitch(CodeGenFunction &CGF) const {
  140. if (Untied) {
  141. LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
  142. CGF.GetAddrOfLocalVar(PartIDVar),
  143. PartIDVar->getType()->castAs<PointerType>());
  144. CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
  145. PartIdLVal);
  146. UntiedCodeGen(CGF);
  147. CodeGenFunction::JumpDest CurPoint =
  148. CGF.getJumpDestInCurrentScope(".untied.next.");
  149. CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
  150. CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
  151. UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
  152. CGF.Builder.GetInsertBlock());
  153. CGF.EmitBranchThroughCleanup(CurPoint);
  154. CGF.EmitBlock(CurPoint.getBlock());
  155. }
  156. }
  157. unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
  158. };
  159. CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
  160. const VarDecl *ThreadIDVar,
  161. const RegionCodeGenTy &CodeGen,
  162. OpenMPDirectiveKind Kind, bool HasCancel,
  163. const UntiedTaskActionTy &Action)
  164. : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
  165. ThreadIDVar(ThreadIDVar), Action(Action) {
  166. assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
  167. }
  168. /// Get a variable or parameter for storing global thread id
  169. /// inside OpenMP construct.
  170. const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
  171. /// Get an LValue for the current ThreadID variable.
  172. LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
  173. /// Get the name of the capture helper.
  174. StringRef getHelperName() const override { return ".omp_outlined."; }
  175. void emitUntiedSwitch(CodeGenFunction &CGF) override {
  176. Action.emitUntiedSwitch(CGF);
  177. }
  178. static bool classof(const CGCapturedStmtInfo *Info) {
  179. return CGOpenMPRegionInfo::classof(Info) &&
  180. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
  181. TaskOutlinedRegion;
  182. }
  183. private:
  184. /// A variable or parameter storing global thread id for OpenMP
  185. /// constructs.
  186. const VarDecl *ThreadIDVar;
  187. /// Action for emitting code for untied tasks.
  188. const UntiedTaskActionTy &Action;
  189. };
  190. /// API for inlined captured statement code generation in OpenMP
  191. /// constructs.
  192. class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
  193. public:
  194. CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
  195. const RegionCodeGenTy &CodeGen,
  196. OpenMPDirectiveKind Kind, bool HasCancel)
  197. : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
  198. OldCSI(OldCSI),
  199. OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
  200. // Retrieve the value of the context parameter.
  201. llvm::Value *getContextValue() const override {
  202. if (OuterRegionInfo)
  203. return OuterRegionInfo->getContextValue();
  204. llvm_unreachable("No context value for inlined OpenMP region");
  205. }
  206. void setContextValue(llvm::Value *V) override {
  207. if (OuterRegionInfo) {
  208. OuterRegionInfo->setContextValue(V);
  209. return;
  210. }
  211. llvm_unreachable("No context value for inlined OpenMP region");
  212. }
  213. /// Lookup the captured field decl for a variable.
  214. const FieldDecl *lookup(const VarDecl *VD) const override {
  215. if (OuterRegionInfo)
  216. return OuterRegionInfo->lookup(VD);
  217. // If there is no outer outlined region,no need to lookup in a list of
  218. // captured variables, we can use the original one.
  219. return nullptr;
  220. }
  221. FieldDecl *getThisFieldDecl() const override {
  222. if (OuterRegionInfo)
  223. return OuterRegionInfo->getThisFieldDecl();
  224. return nullptr;
  225. }
  226. /// Get a variable or parameter for storing global thread id
  227. /// inside OpenMP construct.
  228. const VarDecl *getThreadIDVariable() const override {
  229. if (OuterRegionInfo)
  230. return OuterRegionInfo->getThreadIDVariable();
  231. return nullptr;
  232. }
  233. /// Get an LValue for the current ThreadID variable.
  234. LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
  235. if (OuterRegionInfo)
  236. return OuterRegionInfo->getThreadIDVariableLValue(CGF);
  237. llvm_unreachable("No LValue for inlined OpenMP construct");
  238. }
  239. /// Get the name of the capture helper.
  240. StringRef getHelperName() const override {
  241. if (auto *OuterRegionInfo = getOldCSI())
  242. return OuterRegionInfo->getHelperName();
  243. llvm_unreachable("No helper name for inlined OpenMP construct");
  244. }
  245. void emitUntiedSwitch(CodeGenFunction &CGF) override {
  246. if (OuterRegionInfo)
  247. OuterRegionInfo->emitUntiedSwitch(CGF);
  248. }
  249. CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
  250. static bool classof(const CGCapturedStmtInfo *Info) {
  251. return CGOpenMPRegionInfo::classof(Info) &&
  252. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
  253. }
  254. ~CGOpenMPInlinedRegionInfo() override = default;
  255. private:
  256. /// CodeGen info about outer OpenMP region.
  257. CodeGenFunction::CGCapturedStmtInfo *OldCSI;
  258. CGOpenMPRegionInfo *OuterRegionInfo;
  259. };
  260. /// API for captured statement code generation in OpenMP target
  261. /// constructs. For this captures, implicit parameters are used instead of the
  262. /// captured fields. The name of the target region has to be unique in a given
  263. /// application so it is provided by the client, because only the client has
  264. /// the information to generate that.
  265. class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
  266. public:
  267. CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
  268. const RegionCodeGenTy &CodeGen, StringRef HelperName)
  269. : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
  270. /*HasCancel=*/false),
  271. HelperName(HelperName) {}
  272. /// This is unused for target regions because each starts executing
  273. /// with a single thread.
  274. const VarDecl *getThreadIDVariable() const override { return nullptr; }
  275. /// Get the name of the capture helper.
  276. StringRef getHelperName() const override { return HelperName; }
  277. static bool classof(const CGCapturedStmtInfo *Info) {
  278. return CGOpenMPRegionInfo::classof(Info) &&
  279. cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
  280. }
  281. private:
  282. StringRef HelperName;
  283. };
  284. static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
  285. llvm_unreachable("No codegen for expressions");
  286. }
  287. /// API for generation of expressions captured in a innermost OpenMP
  288. /// region.
  289. class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
  290. public:
  291. CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
  292. : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
  293. OMPD_unknown,
  294. /*HasCancel=*/false),
  295. PrivScope(CGF) {
  296. // Make sure the globals captured in the provided statement are local by
  297. // using the privatization logic. We assume the same variable is not
  298. // captured more than once.
  299. for (const auto &C : CS.captures()) {
  300. if (!C.capturesVariable() && !C.capturesVariableByCopy())
  301. continue;
  302. const VarDecl *VD = C.getCapturedVar();
  303. if (VD->isLocalVarDeclOrParm())
  304. continue;
  305. DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
  306. /*RefersToEnclosingVariableOrCapture=*/false,
  307. VD->getType().getNonReferenceType(), VK_LValue,
  308. C.getLocation());
  309. PrivScope.addPrivate(
  310. VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
  311. }
  312. (void)PrivScope.Privatize();
  313. }
  314. /// Lookup the captured field decl for a variable.
  315. const FieldDecl *lookup(const VarDecl *VD) const override {
  316. if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
  317. return FD;
  318. return nullptr;
  319. }
  320. /// Emit the captured statement body.
  321. void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
  322. llvm_unreachable("No body for expressions");
  323. }
  324. /// Get a variable or parameter for storing global thread id
  325. /// inside OpenMP construct.
  326. const VarDecl *getThreadIDVariable() const override {
  327. llvm_unreachable("No thread id for expressions");
  328. }
  329. /// Get the name of the capture helper.
  330. StringRef getHelperName() const override {
  331. llvm_unreachable("No helper name for expressions");
  332. }
  333. static bool classof(const CGCapturedStmtInfo *Info) { return false; }
  334. private:
  335. /// Private scope to capture global variables.
  336. CodeGenFunction::OMPPrivateScope PrivScope;
  337. };
  338. /// RAII for emitting code of OpenMP constructs.
  339. class InlinedOpenMPRegionRAII {
  340. CodeGenFunction &CGF;
  341. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  342. FieldDecl *LambdaThisCaptureField = nullptr;
  343. const CodeGen::CGBlockInfo *BlockInfo = nullptr;
  344. public:
  345. /// Constructs region for combined constructs.
  346. /// \param CodeGen Code generation sequence for combined directives. Includes
  347. /// a list of functions used for code generation of implicitly inlined
  348. /// regions.
  349. InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
  350. OpenMPDirectiveKind Kind, bool HasCancel)
  351. : CGF(CGF) {
  352. // Start emission for the construct.
  353. CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
  354. CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
  355. std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
  356. LambdaThisCaptureField = CGF.LambdaThisCaptureField;
  357. CGF.LambdaThisCaptureField = nullptr;
  358. BlockInfo = CGF.BlockInfo;
  359. CGF.BlockInfo = nullptr;
  360. }
  361. ~InlinedOpenMPRegionRAII() {
  362. // Restore original CapturedStmtInfo only if we're done with code emission.
  363. auto *OldCSI =
  364. cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
  365. delete CGF.CapturedStmtInfo;
  366. CGF.CapturedStmtInfo = OldCSI;
  367. std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
  368. CGF.LambdaThisCaptureField = LambdaThisCaptureField;
  369. CGF.BlockInfo = BlockInfo;
  370. }
  371. };
  372. /// Values for bit flags used in the ident_t to describe the fields.
  373. /// All enumeric elements are named and described in accordance with the code
  374. /// from https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h
  375. enum OpenMPLocationFlags : unsigned {
  376. /// Use trampoline for internal microtask.
  377. OMP_IDENT_IMD = 0x01,
  378. /// Use c-style ident structure.
  379. OMP_IDENT_KMPC = 0x02,
  380. /// Atomic reduction option for kmpc_reduce.
  381. OMP_ATOMIC_REDUCE = 0x10,
  382. /// Explicit 'barrier' directive.
  383. OMP_IDENT_BARRIER_EXPL = 0x20,
  384. /// Implicit barrier in code.
  385. OMP_IDENT_BARRIER_IMPL = 0x40,
  386. /// Implicit barrier in 'for' directive.
  387. OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
  388. /// Implicit barrier in 'sections' directive.
  389. OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
  390. /// Implicit barrier in 'single' directive.
  391. OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
  392. /// Call of __kmp_for_static_init for static loop.
  393. OMP_IDENT_WORK_LOOP = 0x200,
  394. /// Call of __kmp_for_static_init for sections.
  395. OMP_IDENT_WORK_SECTIONS = 0x400,
  396. /// Call of __kmp_for_static_init for distribute.
  397. OMP_IDENT_WORK_DISTRIBUTE = 0x800,
  398. LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
  399. };
  400. namespace {
  401. LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
  402. /// Values for bit flags for marking which requires clauses have been used.
  403. enum OpenMPOffloadingRequiresDirFlags : int64_t {
  404. /// flag undefined.
  405. OMP_REQ_UNDEFINED = 0x000,
  406. /// no requires clause present.
  407. OMP_REQ_NONE = 0x001,
  408. /// reverse_offload clause.
  409. OMP_REQ_REVERSE_OFFLOAD = 0x002,
  410. /// unified_address clause.
  411. OMP_REQ_UNIFIED_ADDRESS = 0x004,
  412. /// unified_shared_memory clause.
  413. OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,
  414. /// dynamic_allocators clause.
  415. OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,
  416. LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)
  417. };
  418. enum OpenMPOffloadingReservedDeviceIDs {
  419. /// Device ID if the device was not defined, runtime should get it
  420. /// from environment variables in the spec.
  421. OMP_DEVICEID_UNDEF = -1,
  422. };
  423. } // anonymous namespace
  424. /// Describes ident structure that describes a source location.
  425. /// All descriptions are taken from
  426. /// https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h
  427. /// Original structure:
  428. /// typedef struct ident {
  429. /// kmp_int32 reserved_1; /**< might be used in Fortran;
  430. /// see above */
  431. /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
  432. /// KMP_IDENT_KMPC identifies this union
  433. /// member */
  434. /// kmp_int32 reserved_2; /**< not really used in Fortran any more;
  435. /// see above */
  436. ///#if USE_ITT_BUILD
  437. /// /* but currently used for storing
  438. /// region-specific ITT */
  439. /// /* contextual information. */
  440. ///#endif /* USE_ITT_BUILD */
  441. /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
  442. /// C++ */
  443. /// char const *psource; /**< String describing the source location.
  444. /// The string is composed of semi-colon separated
  445. // fields which describe the source file,
  446. /// the function and a pair of line numbers that
  447. /// delimit the construct.
  448. /// */
  449. /// } ident_t;
  450. enum IdentFieldIndex {
  451. /// might be used in Fortran
  452. IdentField_Reserved_1,
  453. /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
  454. IdentField_Flags,
  455. /// Not really used in Fortran any more
  456. IdentField_Reserved_2,
  457. /// Source[4] in Fortran, do not use for C++
  458. IdentField_Reserved_3,
  459. /// String describing the source location. The string is composed of
  460. /// semi-colon separated fields which describe the source file, the function
  461. /// and a pair of line numbers that delimit the construct.
  462. IdentField_PSource
  463. };
  464. /// Schedule types for 'omp for' loops (these enumerators are taken from
  465. /// the enum sched_type in kmp.h).
  466. enum OpenMPSchedType {
  467. /// Lower bound for default (unordered) versions.
  468. OMP_sch_lower = 32,
  469. OMP_sch_static_chunked = 33,
  470. OMP_sch_static = 34,
  471. OMP_sch_dynamic_chunked = 35,
  472. OMP_sch_guided_chunked = 36,
  473. OMP_sch_runtime = 37,
  474. OMP_sch_auto = 38,
  475. /// static with chunk adjustment (e.g., simd)
  476. OMP_sch_static_balanced_chunked = 45,
  477. /// Lower bound for 'ordered' versions.
  478. OMP_ord_lower = 64,
  479. OMP_ord_static_chunked = 65,
  480. OMP_ord_static = 66,
  481. OMP_ord_dynamic_chunked = 67,
  482. OMP_ord_guided_chunked = 68,
  483. OMP_ord_runtime = 69,
  484. OMP_ord_auto = 70,
  485. OMP_sch_default = OMP_sch_static,
  486. /// dist_schedule types
  487. OMP_dist_sch_static_chunked = 91,
  488. OMP_dist_sch_static = 92,
  489. /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
  490. /// Set if the monotonic schedule modifier was present.
  491. OMP_sch_modifier_monotonic = (1 << 29),
  492. /// Set if the nonmonotonic schedule modifier was present.
  493. OMP_sch_modifier_nonmonotonic = (1 << 30),
  494. };
  495. enum OpenMPRTLFunction {
  496. /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
  497. /// kmpc_micro microtask, ...);
  498. OMPRTL__kmpc_fork_call,
  499. /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
  500. /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
  501. OMPRTL__kmpc_threadprivate_cached,
  502. /// Call to void __kmpc_threadprivate_register( ident_t *,
  503. /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
  504. OMPRTL__kmpc_threadprivate_register,
  505. // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
  506. OMPRTL__kmpc_global_thread_num,
  507. // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
  508. // kmp_critical_name *crit);
  509. OMPRTL__kmpc_critical,
  510. // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
  511. // global_tid, kmp_critical_name *crit, uintptr_t hint);
  512. OMPRTL__kmpc_critical_with_hint,
  513. // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
  514. // kmp_critical_name *crit);
  515. OMPRTL__kmpc_end_critical,
  516. // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
  517. // global_tid);
  518. OMPRTL__kmpc_cancel_barrier,
  519. // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
  520. OMPRTL__kmpc_barrier,
  521. // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
  522. OMPRTL__kmpc_for_static_fini,
  523. // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
  524. // global_tid);
  525. OMPRTL__kmpc_serialized_parallel,
  526. // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
  527. // global_tid);
  528. OMPRTL__kmpc_end_serialized_parallel,
  529. // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
  530. // kmp_int32 num_threads);
  531. OMPRTL__kmpc_push_num_threads,
  532. // Call to void __kmpc_flush(ident_t *loc);
  533. OMPRTL__kmpc_flush,
  534. // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
  535. OMPRTL__kmpc_master,
  536. // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
  537. OMPRTL__kmpc_end_master,
  538. // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
  539. // int end_part);
  540. OMPRTL__kmpc_omp_taskyield,
  541. // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
  542. OMPRTL__kmpc_single,
  543. // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
  544. OMPRTL__kmpc_end_single,
  545. // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  546. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  547. // kmp_routine_entry_t *task_entry);
  548. OMPRTL__kmpc_omp_task_alloc,
  549. // Call to kmp_task_t * __kmpc_omp_target_task_alloc(ident_t *,
  550. // kmp_int32 gtid, kmp_int32 flags, size_t sizeof_kmp_task_t,
  551. // size_t sizeof_shareds, kmp_routine_entry_t *task_entry,
  552. // kmp_int64 device_id);
  553. OMPRTL__kmpc_omp_target_task_alloc,
  554. // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
  555. // new_task);
  556. OMPRTL__kmpc_omp_task,
  557. // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
  558. // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
  559. // kmp_int32 didit);
  560. OMPRTL__kmpc_copyprivate,
  561. // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
  562. // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
  563. // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
  564. OMPRTL__kmpc_reduce,
  565. // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
  566. // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
  567. // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
  568. // *lck);
  569. OMPRTL__kmpc_reduce_nowait,
  570. // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
  571. // kmp_critical_name *lck);
  572. OMPRTL__kmpc_end_reduce,
  573. // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
  574. // kmp_critical_name *lck);
  575. OMPRTL__kmpc_end_reduce_nowait,
  576. // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
  577. // kmp_task_t * new_task);
  578. OMPRTL__kmpc_omp_task_begin_if0,
  579. // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
  580. // kmp_task_t * new_task);
  581. OMPRTL__kmpc_omp_task_complete_if0,
  582. // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
  583. OMPRTL__kmpc_ordered,
  584. // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
  585. OMPRTL__kmpc_end_ordered,
  586. // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
  587. // global_tid);
  588. OMPRTL__kmpc_omp_taskwait,
  589. // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
  590. OMPRTL__kmpc_taskgroup,
  591. // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
  592. OMPRTL__kmpc_end_taskgroup,
  593. // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
  594. // int proc_bind);
  595. OMPRTL__kmpc_push_proc_bind,
  596. // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
  597. // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
  598. // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
  599. OMPRTL__kmpc_omp_task_with_deps,
  600. // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
  601. // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
  602. // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
  603. OMPRTL__kmpc_omp_wait_deps,
  604. // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  605. // global_tid, kmp_int32 cncl_kind);
  606. OMPRTL__kmpc_cancellationpoint,
  607. // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  608. // kmp_int32 cncl_kind);
  609. OMPRTL__kmpc_cancel,
  610. // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
  611. // kmp_int32 num_teams, kmp_int32 thread_limit);
  612. OMPRTL__kmpc_push_num_teams,
  613. // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
  614. // microtask, ...);
  615. OMPRTL__kmpc_fork_teams,
  616. // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
  617. // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
  618. // sched, kmp_uint64 grainsize, void *task_dup);
  619. OMPRTL__kmpc_taskloop,
  620. // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
  621. // num_dims, struct kmp_dim *dims);
  622. OMPRTL__kmpc_doacross_init,
  623. // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
  624. OMPRTL__kmpc_doacross_fini,
  625. // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
  626. // *vec);
  627. OMPRTL__kmpc_doacross_post,
  628. // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
  629. // *vec);
  630. OMPRTL__kmpc_doacross_wait,
  631. // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
  632. // *data);
  633. OMPRTL__kmpc_task_reduction_init,
  634. // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
  635. // *d);
  636. OMPRTL__kmpc_task_reduction_get_th_data,
  637. // Call to void *__kmpc_alloc(int gtid, size_t sz, omp_allocator_handle_t al);
  638. OMPRTL__kmpc_alloc,
  639. // Call to void __kmpc_free(int gtid, void *ptr, omp_allocator_handle_t al);
  640. OMPRTL__kmpc_free,
  641. //
  642. // Offloading related calls
  643. //
  644. // Call to void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
  645. // size);
  646. OMPRTL__kmpc_push_target_tripcount,
  647. // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
  648. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  649. // *arg_types);
  650. OMPRTL__tgt_target,
  651. // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
  652. // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  653. // *arg_types);
  654. OMPRTL__tgt_target_nowait,
  655. // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
  656. // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  657. // *arg_types, int32_t num_teams, int32_t thread_limit);
  658. OMPRTL__tgt_target_teams,
  659. // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
  660. // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
  661. // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
  662. OMPRTL__tgt_target_teams_nowait,
  663. // Call to void __tgt_register_requires(int64_t flags);
  664. OMPRTL__tgt_register_requires,
  665. // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
  666. OMPRTL__tgt_register_lib,
  667. // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
  668. OMPRTL__tgt_unregister_lib,
  669. // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
  670. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  671. OMPRTL__tgt_target_data_begin,
  672. // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
  673. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  674. // *arg_types);
  675. OMPRTL__tgt_target_data_begin_nowait,
  676. // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
  677. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  678. OMPRTL__tgt_target_data_end,
  679. // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
  680. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  681. // *arg_types);
  682. OMPRTL__tgt_target_data_end_nowait,
  683. // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
  684. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  685. OMPRTL__tgt_target_data_update,
  686. // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
  687. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  688. // *arg_types);
  689. OMPRTL__tgt_target_data_update_nowait,
  690. };
  691. /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
  692. /// region.
  693. class CleanupTy final : public EHScopeStack::Cleanup {
  694. PrePostActionTy *Action;
  695. public:
  696. explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
  697. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  698. if (!CGF.HaveInsertPoint())
  699. return;
  700. Action->Exit(CGF);
  701. }
  702. };
  703. } // anonymous namespace
  704. void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
  705. CodeGenFunction::RunCleanupsScope Scope(CGF);
  706. if (PrePostAction) {
  707. CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
  708. Callback(CodeGen, CGF, *PrePostAction);
  709. } else {
  710. PrePostActionTy Action;
  711. Callback(CodeGen, CGF, Action);
  712. }
  713. }
  714. /// Check if the combiner is a call to UDR combiner and if it is so return the
  715. /// UDR decl used for reduction.
  716. static const OMPDeclareReductionDecl *
  717. getReductionInit(const Expr *ReductionOp) {
  718. if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
  719. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
  720. if (const auto *DRE =
  721. dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
  722. if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
  723. return DRD;
  724. return nullptr;
  725. }
  726. static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
  727. const OMPDeclareReductionDecl *DRD,
  728. const Expr *InitOp,
  729. Address Private, Address Original,
  730. QualType Ty) {
  731. if (DRD->getInitializer()) {
  732. std::pair<llvm::Function *, llvm::Function *> Reduction =
  733. CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
  734. const auto *CE = cast<CallExpr>(InitOp);
  735. const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
  736. const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  737. const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  738. const auto *LHSDRE =
  739. cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
  740. const auto *RHSDRE =
  741. cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
  742. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  743. PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
  744. [=]() { return Private; });
  745. PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
  746. [=]() { return Original; });
  747. (void)PrivateScope.Privatize();
  748. RValue Func = RValue::get(Reduction.second);
  749. CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
  750. CGF.EmitIgnoredExpr(InitOp);
  751. } else {
  752. llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
  753. std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
  754. auto *GV = new llvm::GlobalVariable(
  755. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  756. llvm::GlobalValue::PrivateLinkage, Init, Name);
  757. LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
  758. RValue InitRVal;
  759. switch (CGF.getEvaluationKind(Ty)) {
  760. case TEK_Scalar:
  761. InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
  762. break;
  763. case TEK_Complex:
  764. InitRVal =
  765. RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
  766. break;
  767. case TEK_Aggregate:
  768. InitRVal = RValue::getAggregate(LV.getAddress());
  769. break;
  770. }
  771. OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
  772. CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
  773. CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
  774. /*IsInitializer=*/false);
  775. }
  776. }
  777. /// Emit initialization of arrays of complex types.
  778. /// \param DestAddr Address of the array.
  779. /// \param Type Type of array.
  780. /// \param Init Initial expression of array.
  781. /// \param SrcAddr Address of the original array.
  782. static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
  783. QualType Type, bool EmitDeclareReductionInit,
  784. const Expr *Init,
  785. const OMPDeclareReductionDecl *DRD,
  786. Address SrcAddr = Address::invalid()) {
  787. // Perform element-by-element initialization.
  788. QualType ElementTy;
  789. // Drill down to the base element type on both arrays.
  790. const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
  791. llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
  792. DestAddr =
  793. CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
  794. if (DRD)
  795. SrcAddr =
  796. CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
  797. llvm::Value *SrcBegin = nullptr;
  798. if (DRD)
  799. SrcBegin = SrcAddr.getPointer();
  800. llvm::Value *DestBegin = DestAddr.getPointer();
  801. // Cast from pointer to array type to pointer to single element.
  802. llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
  803. // The basic structure here is a while-do loop.
  804. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
  805. llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
  806. llvm::Value *IsEmpty =
  807. CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
  808. CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  809. // Enter the loop body, making that address the current address.
  810. llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
  811. CGF.EmitBlock(BodyBB);
  812. CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
  813. llvm::PHINode *SrcElementPHI = nullptr;
  814. Address SrcElementCurrent = Address::invalid();
  815. if (DRD) {
  816. SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
  817. "omp.arraycpy.srcElementPast");
  818. SrcElementPHI->addIncoming(SrcBegin, EntryBB);
  819. SrcElementCurrent =
  820. Address(SrcElementPHI,
  821. SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  822. }
  823. llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
  824. DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
  825. DestElementPHI->addIncoming(DestBegin, EntryBB);
  826. Address DestElementCurrent =
  827. Address(DestElementPHI,
  828. DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  829. // Emit copy.
  830. {
  831. CodeGenFunction::RunCleanupsScope InitScope(CGF);
  832. if (EmitDeclareReductionInit) {
  833. emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
  834. SrcElementCurrent, ElementTy);
  835. } else
  836. CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
  837. /*IsInitializer=*/false);
  838. }
  839. if (DRD) {
  840. // Shift the address forward by one element.
  841. llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
  842. SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  843. SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
  844. }
  845. // Shift the address forward by one element.
  846. llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
  847. DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  848. // Check whether we've reached the end.
  849. llvm::Value *Done =
  850. CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
  851. CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
  852. DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
  853. // Done.
  854. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  855. }
  856. LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
  857. return CGF.EmitOMPSharedLValue(E);
  858. }
  859. LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
  860. const Expr *E) {
  861. if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
  862. return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
  863. return LValue();
  864. }
  865. void ReductionCodeGen::emitAggregateInitialization(
  866. CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
  867. const OMPDeclareReductionDecl *DRD) {
  868. // Emit VarDecl with copy init for arrays.
  869. // Get the address of the original variable captured in current
  870. // captured region.
  871. const auto *PrivateVD =
  872. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  873. bool EmitDeclareReductionInit =
  874. DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
  875. EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
  876. EmitDeclareReductionInit,
  877. EmitDeclareReductionInit ? ClausesData[N].ReductionOp
  878. : PrivateVD->getInit(),
  879. DRD, SharedLVal.getAddress());
  880. }
  881. ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
  882. ArrayRef<const Expr *> Privates,
  883. ArrayRef<const Expr *> ReductionOps) {
  884. ClausesData.reserve(Shareds.size());
  885. SharedAddresses.reserve(Shareds.size());
  886. Sizes.reserve(Shareds.size());
  887. BaseDecls.reserve(Shareds.size());
  888. auto IPriv = Privates.begin();
  889. auto IRed = ReductionOps.begin();
  890. for (const Expr *Ref : Shareds) {
  891. ClausesData.emplace_back(Ref, *IPriv, *IRed);
  892. std::advance(IPriv, 1);
  893. std::advance(IRed, 1);
  894. }
  895. }
  896. void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
  897. assert(SharedAddresses.size() == N &&
  898. "Number of generated lvalues must be exactly N.");
  899. LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
  900. LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
  901. SharedAddresses.emplace_back(First, Second);
  902. }
  903. void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
  904. const auto *PrivateVD =
  905. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  906. QualType PrivateType = PrivateVD->getType();
  907. bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
  908. if (!PrivateType->isVariablyModifiedType()) {
  909. Sizes.emplace_back(
  910. CGF.getTypeSize(
  911. SharedAddresses[N].first.getType().getNonReferenceType()),
  912. nullptr);
  913. return;
  914. }
  915. llvm::Value *Size;
  916. llvm::Value *SizeInChars;
  917. auto *ElemType =
  918. cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
  919. ->getElementType();
  920. auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
  921. if (AsArraySection) {
  922. Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
  923. SharedAddresses[N].first.getPointer());
  924. Size = CGF.Builder.CreateNUWAdd(
  925. Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
  926. SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
  927. } else {
  928. SizeInChars = CGF.getTypeSize(
  929. SharedAddresses[N].first.getType().getNonReferenceType());
  930. Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
  931. }
  932. Sizes.emplace_back(SizeInChars, Size);
  933. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  934. CGF,
  935. cast<OpaqueValueExpr>(
  936. CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
  937. RValue::get(Size));
  938. CGF.EmitVariablyModifiedType(PrivateType);
  939. }
  940. void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
  941. llvm::Value *Size) {
  942. const auto *PrivateVD =
  943. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  944. QualType PrivateType = PrivateVD->getType();
  945. if (!PrivateType->isVariablyModifiedType()) {
  946. assert(!Size && !Sizes[N].second &&
  947. "Size should be nullptr for non-variably modified reduction "
  948. "items.");
  949. return;
  950. }
  951. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  952. CGF,
  953. cast<OpaqueValueExpr>(
  954. CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
  955. RValue::get(Size));
  956. CGF.EmitVariablyModifiedType(PrivateType);
  957. }
  958. void ReductionCodeGen::emitInitialization(
  959. CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
  960. llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
  961. assert(SharedAddresses.size() > N && "No variable was generated");
  962. const auto *PrivateVD =
  963. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  964. const OMPDeclareReductionDecl *DRD =
  965. getReductionInit(ClausesData[N].ReductionOp);
  966. QualType PrivateType = PrivateVD->getType();
  967. PrivateAddr = CGF.Builder.CreateElementBitCast(
  968. PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
  969. QualType SharedType = SharedAddresses[N].first.getType();
  970. SharedLVal = CGF.MakeAddrLValue(
  971. CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
  972. CGF.ConvertTypeForMem(SharedType)),
  973. SharedType, SharedAddresses[N].first.getBaseInfo(),
  974. CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
  975. if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
  976. emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
  977. } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
  978. emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
  979. PrivateAddr, SharedLVal.getAddress(),
  980. SharedLVal.getType());
  981. } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
  982. !CGF.isTrivialInitializer(PrivateVD->getInit())) {
  983. CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
  984. PrivateVD->getType().getQualifiers(),
  985. /*IsInitializer=*/false);
  986. }
  987. }
  988. bool ReductionCodeGen::needCleanups(unsigned N) {
  989. const auto *PrivateVD =
  990. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  991. QualType PrivateType = PrivateVD->getType();
  992. QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
  993. return DTorKind != QualType::DK_none;
  994. }
  995. void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
  996. Address PrivateAddr) {
  997. const auto *PrivateVD =
  998. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  999. QualType PrivateType = PrivateVD->getType();
  1000. QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
  1001. if (needCleanups(N)) {
  1002. PrivateAddr = CGF.Builder.CreateElementBitCast(
  1003. PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
  1004. CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
  1005. }
  1006. }
  1007. static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
  1008. LValue BaseLV) {
  1009. BaseTy = BaseTy.getNonReferenceType();
  1010. while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
  1011. !CGF.getContext().hasSameType(BaseTy, ElTy)) {
  1012. if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
  1013. BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
  1014. } else {
  1015. LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
  1016. BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
  1017. }
  1018. BaseTy = BaseTy->getPointeeType();
  1019. }
  1020. return CGF.MakeAddrLValue(
  1021. CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
  1022. CGF.ConvertTypeForMem(ElTy)),
  1023. BaseLV.getType(), BaseLV.getBaseInfo(),
  1024. CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
  1025. }
  1026. static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
  1027. llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
  1028. llvm::Value *Addr) {
  1029. Address Tmp = Address::invalid();
  1030. Address TopTmp = Address::invalid();
  1031. Address MostTopTmp = Address::invalid();
  1032. BaseTy = BaseTy.getNonReferenceType();
  1033. while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
  1034. !CGF.getContext().hasSameType(BaseTy, ElTy)) {
  1035. Tmp = CGF.CreateMemTemp(BaseTy);
  1036. if (TopTmp.isValid())
  1037. CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
  1038. else
  1039. MostTopTmp = Tmp;
  1040. TopTmp = Tmp;
  1041. BaseTy = BaseTy->getPointeeType();
  1042. }
  1043. llvm::Type *Ty = BaseLVType;
  1044. if (Tmp.isValid())
  1045. Ty = Tmp.getElementType();
  1046. Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
  1047. if (Tmp.isValid()) {
  1048. CGF.Builder.CreateStore(Addr, Tmp);
  1049. return MostTopTmp;
  1050. }
  1051. return Address(Addr, BaseLVAlignment);
  1052. }
  1053. static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
  1054. const VarDecl *OrigVD = nullptr;
  1055. if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
  1056. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  1057. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  1058. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  1059. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  1060. Base = TempASE->getBase()->IgnoreParenImpCasts();
  1061. DE = cast<DeclRefExpr>(Base);
  1062. OrigVD = cast<VarDecl>(DE->getDecl());
  1063. } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
  1064. const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  1065. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  1066. Base = TempASE->getBase()->IgnoreParenImpCasts();
  1067. DE = cast<DeclRefExpr>(Base);
  1068. OrigVD = cast<VarDecl>(DE->getDecl());
  1069. }
  1070. return OrigVD;
  1071. }
  1072. Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
  1073. Address PrivateAddr) {
  1074. const DeclRefExpr *DE;
  1075. if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
  1076. BaseDecls.emplace_back(OrigVD);
  1077. LValue OriginalBaseLValue = CGF.EmitLValue(DE);
  1078. LValue BaseLValue =
  1079. loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
  1080. OriginalBaseLValue);
  1081. llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
  1082. BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
  1083. llvm::Value *PrivatePointer =
  1084. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1085. PrivateAddr.getPointer(),
  1086. SharedAddresses[N].first.getAddress().getType());
  1087. llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
  1088. return castToBase(CGF, OrigVD->getType(),
  1089. SharedAddresses[N].first.getType(),
  1090. OriginalBaseLValue.getAddress().getType(),
  1091. OriginalBaseLValue.getAlignment(), Ptr);
  1092. }
  1093. BaseDecls.emplace_back(
  1094. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
  1095. return PrivateAddr;
  1096. }
  1097. bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
  1098. const OMPDeclareReductionDecl *DRD =
  1099. getReductionInit(ClausesData[N].ReductionOp);
  1100. return DRD && DRD->getInitializer();
  1101. }
  1102. LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
  1103. return CGF.EmitLoadOfPointerLValue(
  1104. CGF.GetAddrOfLocalVar(getThreadIDVariable()),
  1105. getThreadIDVariable()->getType()->castAs<PointerType>());
  1106. }
  1107. void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
  1108. if (!CGF.HaveInsertPoint())
  1109. return;
  1110. // 1.2.2 OpenMP Language Terminology
  1111. // Structured block - An executable statement with a single entry at the
  1112. // top and a single exit at the bottom.
  1113. // The point of exit cannot be a branch out of the structured block.
  1114. // longjmp() and throw() must not violate the entry/exit criteria.
  1115. CGF.EHStack.pushTerminate();
  1116. CodeGen(CGF);
  1117. CGF.EHStack.popTerminate();
  1118. }
  1119. LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
  1120. CodeGenFunction &CGF) {
  1121. return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
  1122. getThreadIDVariable()->getType(),
  1123. AlignmentSource::Decl);
  1124. }
  1125. static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
  1126. QualType FieldTy) {
  1127. auto *Field = FieldDecl::Create(
  1128. C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
  1129. C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
  1130. /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
  1131. Field->setAccess(AS_public);
  1132. DC->addDecl(Field);
  1133. return Field;
  1134. }
  1135. CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
  1136. StringRef Separator)
  1137. : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
  1138. OffloadEntriesInfoManager(CGM) {
  1139. ASTContext &C = CGM.getContext();
  1140. RecordDecl *RD = C.buildImplicitRecord("ident_t");
  1141. QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  1142. RD->startDefinition();
  1143. // reserved_1
  1144. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1145. // flags
  1146. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1147. // reserved_2
  1148. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1149. // reserved_3
  1150. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1151. // psource
  1152. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  1153. RD->completeDefinition();
  1154. IdentQTy = C.getRecordType(RD);
  1155. IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
  1156. KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
  1157. loadOffloadInfoMetadata();
  1158. }
  1159. void CGOpenMPRuntime::clear() {
  1160. InternalVars.clear();
  1161. // Clean non-target variable declarations possibly used only in debug info.
  1162. for (const auto &Data : EmittedNonTargetVariables) {
  1163. if (!Data.getValue().pointsToAliveValue())
  1164. continue;
  1165. auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
  1166. if (!GV)
  1167. continue;
  1168. if (!GV->isDeclaration() || GV->getNumUses() > 0)
  1169. continue;
  1170. GV->eraseFromParent();
  1171. }
  1172. }
  1173. std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
  1174. SmallString<128> Buffer;
  1175. llvm::raw_svector_ostream OS(Buffer);
  1176. StringRef Sep = FirstSeparator;
  1177. for (StringRef Part : Parts) {
  1178. OS << Sep << Part;
  1179. Sep = Separator;
  1180. }
  1181. return OS.str();
  1182. }
  1183. static llvm::Function *
  1184. emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
  1185. const Expr *CombinerInitializer, const VarDecl *In,
  1186. const VarDecl *Out, bool IsCombiner) {
  1187. // void .omp_combiner.(Ty *in, Ty *out);
  1188. ASTContext &C = CGM.getContext();
  1189. QualType PtrTy = C.getPointerType(Ty).withRestrict();
  1190. FunctionArgList Args;
  1191. ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
  1192. /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
  1193. ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
  1194. /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
  1195. Args.push_back(&OmpOutParm);
  1196. Args.push_back(&OmpInParm);
  1197. const CGFunctionInfo &FnInfo =
  1198. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  1199. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  1200. std::string Name = CGM.getOpenMPRuntime().getName(
  1201. {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
  1202. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  1203. Name, &CGM.getModule());
  1204. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  1205. if (CGM.getLangOpts().Optimize) {
  1206. Fn->removeFnAttr(llvm::Attribute::NoInline);
  1207. Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
  1208. Fn->addFnAttr(llvm::Attribute::AlwaysInline);
  1209. }
  1210. CodeGenFunction CGF(CGM);
  1211. // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
  1212. // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
  1213. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
  1214. Out->getLocation());
  1215. CodeGenFunction::OMPPrivateScope Scope(CGF);
  1216. Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
  1217. Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
  1218. return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
  1219. .getAddress();
  1220. });
  1221. Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
  1222. Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
  1223. return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
  1224. .getAddress();
  1225. });
  1226. (void)Scope.Privatize();
  1227. if (!IsCombiner && Out->hasInit() &&
  1228. !CGF.isTrivialInitializer(Out->getInit())) {
  1229. CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
  1230. Out->getType().getQualifiers(),
  1231. /*IsInitializer=*/true);
  1232. }
  1233. if (CombinerInitializer)
  1234. CGF.EmitIgnoredExpr(CombinerInitializer);
  1235. Scope.ForceCleanup();
  1236. CGF.FinishFunction();
  1237. return Fn;
  1238. }
  1239. void CGOpenMPRuntime::emitUserDefinedReduction(
  1240. CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
  1241. if (UDRMap.count(D) > 0)
  1242. return;
  1243. llvm::Function *Combiner = emitCombinerOrInitializer(
  1244. CGM, D->getType(), D->getCombiner(),
  1245. cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
  1246. cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
  1247. /*IsCombiner=*/true);
  1248. llvm::Function *Initializer = nullptr;
  1249. if (const Expr *Init = D->getInitializer()) {
  1250. Initializer = emitCombinerOrInitializer(
  1251. CGM, D->getType(),
  1252. D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
  1253. : nullptr,
  1254. cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
  1255. cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
  1256. /*IsCombiner=*/false);
  1257. }
  1258. UDRMap.try_emplace(D, Combiner, Initializer);
  1259. if (CGF) {
  1260. auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
  1261. Decls.second.push_back(D);
  1262. }
  1263. }
  1264. std::pair<llvm::Function *, llvm::Function *>
  1265. CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
  1266. auto I = UDRMap.find(D);
  1267. if (I != UDRMap.end())
  1268. return I->second;
  1269. emitUserDefinedReduction(/*CGF=*/nullptr, D);
  1270. return UDRMap.lookup(D);
  1271. }
  1272. static llvm::Function *emitParallelOrTeamsOutlinedFunction(
  1273. CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
  1274. const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
  1275. const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
  1276. assert(ThreadIDVar->getType()->isPointerType() &&
  1277. "thread id variable must be of type kmp_int32 *");
  1278. CodeGenFunction CGF(CGM, true);
  1279. bool HasCancel = false;
  1280. if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
  1281. HasCancel = OPD->hasCancel();
  1282. else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
  1283. HasCancel = OPSD->hasCancel();
  1284. else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
  1285. HasCancel = OPFD->hasCancel();
  1286. else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
  1287. HasCancel = OPFD->hasCancel();
  1288. else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
  1289. HasCancel = OPFD->hasCancel();
  1290. else if (const auto *OPFD =
  1291. dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
  1292. HasCancel = OPFD->hasCancel();
  1293. else if (const auto *OPFD =
  1294. dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
  1295. HasCancel = OPFD->hasCancel();
  1296. CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
  1297. HasCancel, OutlinedHelperName);
  1298. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  1299. return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
  1300. }
  1301. llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction(
  1302. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1303. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  1304. const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
  1305. return emitParallelOrTeamsOutlinedFunction(
  1306. CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
  1307. }
  1308. llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction(
  1309. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1310. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  1311. const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
  1312. return emitParallelOrTeamsOutlinedFunction(
  1313. CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
  1314. }
  1315. llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction(
  1316. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1317. const VarDecl *PartIDVar, const VarDecl *TaskTVar,
  1318. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  1319. bool Tied, unsigned &NumberOfParts) {
  1320. auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
  1321. PrePostActionTy &) {
  1322. llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
  1323. llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
  1324. llvm::Value *TaskArgs[] = {
  1325. UpLoc, ThreadID,
  1326. CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
  1327. TaskTVar->getType()->castAs<PointerType>())
  1328. .getPointer()};
  1329. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
  1330. };
  1331. CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
  1332. UntiedCodeGen);
  1333. CodeGen.setAction(Action);
  1334. assert(!ThreadIDVar->getType()->isPointerType() &&
  1335. "thread id variable must be of type kmp_int32 for tasks");
  1336. const OpenMPDirectiveKind Region =
  1337. isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
  1338. : OMPD_task;
  1339. const CapturedStmt *CS = D.getCapturedStmt(Region);
  1340. const auto *TD = dyn_cast<OMPTaskDirective>(&D);
  1341. CodeGenFunction CGF(CGM, true);
  1342. CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
  1343. InnermostKind,
  1344. TD ? TD->hasCancel() : false, Action);
  1345. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  1346. llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS);
  1347. if (!Tied)
  1348. NumberOfParts = Action.getNumberOfParts();
  1349. return Res;
  1350. }
  1351. static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
  1352. const RecordDecl *RD, const CGRecordLayout &RL,
  1353. ArrayRef<llvm::Constant *> Data) {
  1354. llvm::StructType *StructTy = RL.getLLVMType();
  1355. unsigned PrevIdx = 0;
  1356. ConstantInitBuilder CIBuilder(CGM);
  1357. auto DI = Data.begin();
  1358. for (const FieldDecl *FD : RD->fields()) {
  1359. unsigned Idx = RL.getLLVMFieldNo(FD);
  1360. // Fill the alignment.
  1361. for (unsigned I = PrevIdx; I < Idx; ++I)
  1362. Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
  1363. PrevIdx = Idx + 1;
  1364. Fields.add(*DI);
  1365. ++DI;
  1366. }
  1367. }
  1368. template <class... As>
  1369. static llvm::GlobalVariable *
  1370. createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
  1371. ArrayRef<llvm::Constant *> Data, const Twine &Name,
  1372. As &&... Args) {
  1373. const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
  1374. const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
  1375. ConstantInitBuilder CIBuilder(CGM);
  1376. ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
  1377. buildStructValue(Fields, CGM, RD, RL, Data);
  1378. return Fields.finishAndCreateGlobal(
  1379. Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
  1380. std::forward<As>(Args)...);
  1381. }
  1382. template <typename T>
  1383. static void
  1384. createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
  1385. ArrayRef<llvm::Constant *> Data,
  1386. T &Parent) {
  1387. const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
  1388. const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
  1389. ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
  1390. buildStructValue(Fields, CGM, RD, RL, Data);
  1391. Fields.finishAndAddTo(Parent);
  1392. }
  1393. Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
  1394. CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
  1395. unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
  1396. FlagsTy FlagsKey(Flags, Reserved2Flags);
  1397. llvm::Value *Entry = OpenMPDefaultLocMap.lookup(FlagsKey);
  1398. if (!Entry) {
  1399. if (!DefaultOpenMPPSource) {
  1400. // Initialize default location for psource field of ident_t structure of
  1401. // all ident_t objects. Format is ";file;function;line;column;;".
  1402. // Taken from
  1403. // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp_str.cpp
  1404. DefaultOpenMPPSource =
  1405. CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
  1406. DefaultOpenMPPSource =
  1407. llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
  1408. }
  1409. llvm::Constant *Data[] = {
  1410. llvm::ConstantInt::getNullValue(CGM.Int32Ty),
  1411. llvm::ConstantInt::get(CGM.Int32Ty, Flags),
  1412. llvm::ConstantInt::get(CGM.Int32Ty, Reserved2Flags),
  1413. llvm::ConstantInt::getNullValue(CGM.Int32Ty), DefaultOpenMPPSource};
  1414. llvm::GlobalValue *DefaultOpenMPLocation =
  1415. createGlobalStruct(CGM, IdentQTy, isDefaultLocationConstant(), Data, "",
  1416. llvm::GlobalValue::PrivateLinkage);
  1417. DefaultOpenMPLocation->setUnnamedAddr(
  1418. llvm::GlobalValue::UnnamedAddr::Global);
  1419. OpenMPDefaultLocMap[FlagsKey] = Entry = DefaultOpenMPLocation;
  1420. }
  1421. return Address(Entry, Align);
  1422. }
  1423. void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
  1424. bool AtCurrentPoint) {
  1425. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1426. assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
  1427. llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
  1428. if (AtCurrentPoint) {
  1429. Elem.second.ServiceInsertPt = new llvm::BitCastInst(
  1430. Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
  1431. } else {
  1432. Elem.second.ServiceInsertPt =
  1433. new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
  1434. Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
  1435. }
  1436. }
  1437. void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
  1438. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1439. if (Elem.second.ServiceInsertPt) {
  1440. llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
  1441. Elem.second.ServiceInsertPt = nullptr;
  1442. Ptr->eraseFromParent();
  1443. }
  1444. }
  1445. llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
  1446. SourceLocation Loc,
  1447. unsigned Flags) {
  1448. Flags |= OMP_IDENT_KMPC;
  1449. // If no debug info is generated - return global default location.
  1450. if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
  1451. Loc.isInvalid())
  1452. return getOrCreateDefaultLocation(Flags).getPointer();
  1453. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1454. CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
  1455. Address LocValue = Address::invalid();
  1456. auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
  1457. if (I != OpenMPLocThreadIDMap.end())
  1458. LocValue = Address(I->second.DebugLoc, Align);
  1459. // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
  1460. // GetOpenMPThreadID was called before this routine.
  1461. if (!LocValue.isValid()) {
  1462. // Generate "ident_t .kmpc_loc.addr;"
  1463. Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
  1464. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1465. Elem.second.DebugLoc = AI.getPointer();
  1466. LocValue = AI;
  1467. if (!Elem.second.ServiceInsertPt)
  1468. setLocThreadIdInsertPt(CGF);
  1469. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  1470. CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
  1471. CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
  1472. CGF.getTypeSize(IdentQTy));
  1473. }
  1474. // char **psource = &.kmpc_loc_<flags>.addr.psource;
  1475. LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
  1476. auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
  1477. LValue PSource =
  1478. CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
  1479. llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
  1480. if (OMPDebugLoc == nullptr) {
  1481. SmallString<128> Buffer2;
  1482. llvm::raw_svector_ostream OS2(Buffer2);
  1483. // Build debug location
  1484. PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
  1485. OS2 << ";" << PLoc.getFilename() << ";";
  1486. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
  1487. OS2 << FD->getQualifiedNameAsString();
  1488. OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
  1489. OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
  1490. OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
  1491. }
  1492. // *psource = ";<File>;<Function>;<Line>;<Column>;;";
  1493. CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
  1494. // Our callers always pass this to a runtime function, so for
  1495. // convenience, go ahead and return a naked pointer.
  1496. return LocValue.getPointer();
  1497. }
  1498. llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
  1499. SourceLocation Loc) {
  1500. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1501. llvm::Value *ThreadID = nullptr;
  1502. // Check whether we've already cached a load of the thread id in this
  1503. // function.
  1504. auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
  1505. if (I != OpenMPLocThreadIDMap.end()) {
  1506. ThreadID = I->second.ThreadID;
  1507. if (ThreadID != nullptr)
  1508. return ThreadID;
  1509. }
  1510. // If exceptions are enabled, do not use parameter to avoid possible crash.
  1511. if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
  1512. !CGF.getLangOpts().CXXExceptions ||
  1513. CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
  1514. if (auto *OMPRegionInfo =
  1515. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  1516. if (OMPRegionInfo->getThreadIDVariable()) {
  1517. // Check if this an outlined function with thread id passed as argument.
  1518. LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
  1519. ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
  1520. // If value loaded in entry block, cache it and use it everywhere in
  1521. // function.
  1522. if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
  1523. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1524. Elem.second.ThreadID = ThreadID;
  1525. }
  1526. return ThreadID;
  1527. }
  1528. }
  1529. }
  1530. // This is not an outlined function region - need to call __kmpc_int32
  1531. // kmpc_global_thread_num(ident_t *loc).
  1532. // Generate thread id value and cache this value for use across the
  1533. // function.
  1534. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1535. if (!Elem.second.ServiceInsertPt)
  1536. setLocThreadIdInsertPt(CGF);
  1537. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  1538. CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
  1539. llvm::CallInst *Call = CGF.Builder.CreateCall(
  1540. createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
  1541. emitUpdateLocation(CGF, Loc));
  1542. Call->setCallingConv(CGF.getRuntimeCC());
  1543. Elem.second.ThreadID = Call;
  1544. return Call;
  1545. }
  1546. void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
  1547. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1548. if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
  1549. clearLocThreadIdInsertPt(CGF);
  1550. OpenMPLocThreadIDMap.erase(CGF.CurFn);
  1551. }
  1552. if (FunctionUDRMap.count(CGF.CurFn) > 0) {
  1553. for(auto *D : FunctionUDRMap[CGF.CurFn])
  1554. UDRMap.erase(D);
  1555. FunctionUDRMap.erase(CGF.CurFn);
  1556. }
  1557. }
  1558. llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
  1559. return IdentTy->getPointerTo();
  1560. }
  1561. llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
  1562. if (!Kmpc_MicroTy) {
  1563. // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
  1564. llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
  1565. llvm::PointerType::getUnqual(CGM.Int32Ty)};
  1566. Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
  1567. }
  1568. return llvm::PointerType::getUnqual(Kmpc_MicroTy);
  1569. }
  1570. llvm::FunctionCallee CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
  1571. llvm::FunctionCallee RTLFn = nullptr;
  1572. switch (static_cast<OpenMPRTLFunction>(Function)) {
  1573. case OMPRTL__kmpc_fork_call: {
  1574. // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
  1575. // microtask, ...);
  1576. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1577. getKmpc_MicroPointerTy()};
  1578. auto *FnTy =
  1579. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
  1580. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
  1581. if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
  1582. if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
  1583. llvm::LLVMContext &Ctx = F->getContext();
  1584. llvm::MDBuilder MDB(Ctx);
  1585. // Annotate the callback behavior of the __kmpc_fork_call:
  1586. // - The callback callee is argument number 2 (microtask).
  1587. // - The first two arguments of the callback callee are unknown (-1).
  1588. // - All variadic arguments to the __kmpc_fork_call are passed to the
  1589. // callback callee.
  1590. F->addMetadata(
  1591. llvm::LLVMContext::MD_callback,
  1592. *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
  1593. 2, {-1, -1},
  1594. /* VarArgsArePassed */ true)}));
  1595. }
  1596. }
  1597. break;
  1598. }
  1599. case OMPRTL__kmpc_global_thread_num: {
  1600. // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
  1601. llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
  1602. auto *FnTy =
  1603. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1604. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
  1605. break;
  1606. }
  1607. case OMPRTL__kmpc_threadprivate_cached: {
  1608. // Build void *__kmpc_threadprivate_cached(ident_t *loc,
  1609. // kmp_int32 global_tid, void *data, size_t size, void ***cache);
  1610. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1611. CGM.VoidPtrTy, CGM.SizeTy,
  1612. CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
  1613. auto *FnTy =
  1614. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
  1615. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
  1616. break;
  1617. }
  1618. case OMPRTL__kmpc_critical: {
  1619. // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
  1620. // kmp_critical_name *crit);
  1621. llvm::Type *TypeParams[] = {
  1622. getIdentTyPointerTy(), CGM.Int32Ty,
  1623. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1624. auto *FnTy =
  1625. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1626. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
  1627. break;
  1628. }
  1629. case OMPRTL__kmpc_critical_with_hint: {
  1630. // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
  1631. // kmp_critical_name *crit, uintptr_t hint);
  1632. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1633. llvm::PointerType::getUnqual(KmpCriticalNameTy),
  1634. CGM.IntPtrTy};
  1635. auto *FnTy =
  1636. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1637. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
  1638. break;
  1639. }
  1640. case OMPRTL__kmpc_threadprivate_register: {
  1641. // Build void __kmpc_threadprivate_register(ident_t *, void *data,
  1642. // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
  1643. // typedef void *(*kmpc_ctor)(void *);
  1644. auto *KmpcCtorTy =
  1645. llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
  1646. /*isVarArg*/ false)->getPointerTo();
  1647. // typedef void *(*kmpc_cctor)(void *, void *);
  1648. llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1649. auto *KmpcCopyCtorTy =
  1650. llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
  1651. /*isVarArg*/ false)
  1652. ->getPointerTo();
  1653. // typedef void (*kmpc_dtor)(void *);
  1654. auto *KmpcDtorTy =
  1655. llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
  1656. ->getPointerTo();
  1657. llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
  1658. KmpcCopyCtorTy, KmpcDtorTy};
  1659. auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
  1660. /*isVarArg*/ false);
  1661. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
  1662. break;
  1663. }
  1664. case OMPRTL__kmpc_end_critical: {
  1665. // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
  1666. // kmp_critical_name *crit);
  1667. llvm::Type *TypeParams[] = {
  1668. getIdentTyPointerTy(), CGM.Int32Ty,
  1669. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1670. auto *FnTy =
  1671. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1672. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
  1673. break;
  1674. }
  1675. case OMPRTL__kmpc_cancel_barrier: {
  1676. // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
  1677. // global_tid);
  1678. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1679. auto *FnTy =
  1680. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1681. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
  1682. break;
  1683. }
  1684. case OMPRTL__kmpc_barrier: {
  1685. // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
  1686. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1687. auto *FnTy =
  1688. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1689. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
  1690. break;
  1691. }
  1692. case OMPRTL__kmpc_for_static_fini: {
  1693. // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
  1694. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1695. auto *FnTy =
  1696. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1697. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
  1698. break;
  1699. }
  1700. case OMPRTL__kmpc_push_num_threads: {
  1701. // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
  1702. // kmp_int32 num_threads)
  1703. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1704. CGM.Int32Ty};
  1705. auto *FnTy =
  1706. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1707. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
  1708. break;
  1709. }
  1710. case OMPRTL__kmpc_serialized_parallel: {
  1711. // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
  1712. // global_tid);
  1713. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1714. auto *FnTy =
  1715. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1716. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
  1717. break;
  1718. }
  1719. case OMPRTL__kmpc_end_serialized_parallel: {
  1720. // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
  1721. // global_tid);
  1722. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1723. auto *FnTy =
  1724. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1725. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
  1726. break;
  1727. }
  1728. case OMPRTL__kmpc_flush: {
  1729. // Build void __kmpc_flush(ident_t *loc);
  1730. llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
  1731. auto *FnTy =
  1732. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1733. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
  1734. break;
  1735. }
  1736. case OMPRTL__kmpc_master: {
  1737. // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
  1738. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1739. auto *FnTy =
  1740. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1741. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
  1742. break;
  1743. }
  1744. case OMPRTL__kmpc_end_master: {
  1745. // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
  1746. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1747. auto *FnTy =
  1748. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1749. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
  1750. break;
  1751. }
  1752. case OMPRTL__kmpc_omp_taskyield: {
  1753. // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
  1754. // int end_part);
  1755. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1756. auto *FnTy =
  1757. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1758. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
  1759. break;
  1760. }
  1761. case OMPRTL__kmpc_single: {
  1762. // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
  1763. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1764. auto *FnTy =
  1765. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1766. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
  1767. break;
  1768. }
  1769. case OMPRTL__kmpc_end_single: {
  1770. // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
  1771. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1772. auto *FnTy =
  1773. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1774. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
  1775. break;
  1776. }
  1777. case OMPRTL__kmpc_omp_task_alloc: {
  1778. // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  1779. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  1780. // kmp_routine_entry_t *task_entry);
  1781. assert(KmpRoutineEntryPtrTy != nullptr &&
  1782. "Type kmp_routine_entry_t must be created.");
  1783. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  1784. CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
  1785. // Return void * and then cast to particular kmp_task_t type.
  1786. auto *FnTy =
  1787. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  1788. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
  1789. break;
  1790. }
  1791. case OMPRTL__kmpc_omp_target_task_alloc: {
  1792. // Build kmp_task_t *__kmpc_omp_target_task_alloc(ident_t *, kmp_int32 gtid,
  1793. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  1794. // kmp_routine_entry_t *task_entry, kmp_int64 device_id);
  1795. assert(KmpRoutineEntryPtrTy != nullptr &&
  1796. "Type kmp_routine_entry_t must be created.");
  1797. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  1798. CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy,
  1799. CGM.Int64Ty};
  1800. // Return void * and then cast to particular kmp_task_t type.
  1801. auto *FnTy =
  1802. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  1803. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_target_task_alloc");
  1804. break;
  1805. }
  1806. case OMPRTL__kmpc_omp_task: {
  1807. // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1808. // *new_task);
  1809. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1810. CGM.VoidPtrTy};
  1811. auto *FnTy =
  1812. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1813. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
  1814. break;
  1815. }
  1816. case OMPRTL__kmpc_copyprivate: {
  1817. // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
  1818. // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
  1819. // kmp_int32 didit);
  1820. llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1821. auto *CpyFnTy =
  1822. llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
  1823. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
  1824. CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
  1825. CGM.Int32Ty};
  1826. auto *FnTy =
  1827. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1828. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
  1829. break;
  1830. }
  1831. case OMPRTL__kmpc_reduce: {
  1832. // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
  1833. // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
  1834. // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
  1835. llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1836. auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
  1837. /*isVarArg=*/false);
  1838. llvm::Type *TypeParams[] = {
  1839. getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
  1840. CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
  1841. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1842. auto *FnTy =
  1843. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1844. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
  1845. break;
  1846. }
  1847. case OMPRTL__kmpc_reduce_nowait: {
  1848. // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
  1849. // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
  1850. // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
  1851. // *lck);
  1852. llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1853. auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
  1854. /*isVarArg=*/false);
  1855. llvm::Type *TypeParams[] = {
  1856. getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
  1857. CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
  1858. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1859. auto *FnTy =
  1860. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1861. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
  1862. break;
  1863. }
  1864. case OMPRTL__kmpc_end_reduce: {
  1865. // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
  1866. // kmp_critical_name *lck);
  1867. llvm::Type *TypeParams[] = {
  1868. getIdentTyPointerTy(), CGM.Int32Ty,
  1869. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1870. auto *FnTy =
  1871. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1872. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
  1873. break;
  1874. }
  1875. case OMPRTL__kmpc_end_reduce_nowait: {
  1876. // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
  1877. // kmp_critical_name *lck);
  1878. llvm::Type *TypeParams[] = {
  1879. getIdentTyPointerTy(), CGM.Int32Ty,
  1880. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1881. auto *FnTy =
  1882. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1883. RTLFn =
  1884. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
  1885. break;
  1886. }
  1887. case OMPRTL__kmpc_omp_task_begin_if0: {
  1888. // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1889. // *new_task);
  1890. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1891. CGM.VoidPtrTy};
  1892. auto *FnTy =
  1893. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1894. RTLFn =
  1895. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
  1896. break;
  1897. }
  1898. case OMPRTL__kmpc_omp_task_complete_if0: {
  1899. // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1900. // *new_task);
  1901. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1902. CGM.VoidPtrTy};
  1903. auto *FnTy =
  1904. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1905. RTLFn = CGM.CreateRuntimeFunction(FnTy,
  1906. /*Name=*/"__kmpc_omp_task_complete_if0");
  1907. break;
  1908. }
  1909. case OMPRTL__kmpc_ordered: {
  1910. // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
  1911. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1912. auto *FnTy =
  1913. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1914. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
  1915. break;
  1916. }
  1917. case OMPRTL__kmpc_end_ordered: {
  1918. // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
  1919. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1920. auto *FnTy =
  1921. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1922. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
  1923. break;
  1924. }
  1925. case OMPRTL__kmpc_omp_taskwait: {
  1926. // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
  1927. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1928. auto *FnTy =
  1929. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1930. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
  1931. break;
  1932. }
  1933. case OMPRTL__kmpc_taskgroup: {
  1934. // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
  1935. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1936. auto *FnTy =
  1937. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1938. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
  1939. break;
  1940. }
  1941. case OMPRTL__kmpc_end_taskgroup: {
  1942. // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
  1943. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1944. auto *FnTy =
  1945. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1946. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
  1947. break;
  1948. }
  1949. case OMPRTL__kmpc_push_proc_bind: {
  1950. // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
  1951. // int proc_bind)
  1952. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1953. auto *FnTy =
  1954. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1955. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
  1956. break;
  1957. }
  1958. case OMPRTL__kmpc_omp_task_with_deps: {
  1959. // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
  1960. // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
  1961. // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
  1962. llvm::Type *TypeParams[] = {
  1963. getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
  1964. CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
  1965. auto *FnTy =
  1966. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1967. RTLFn =
  1968. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
  1969. break;
  1970. }
  1971. case OMPRTL__kmpc_omp_wait_deps: {
  1972. // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
  1973. // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
  1974. // kmp_depend_info_t *noalias_dep_list);
  1975. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1976. CGM.Int32Ty, CGM.VoidPtrTy,
  1977. CGM.Int32Ty, CGM.VoidPtrTy};
  1978. auto *FnTy =
  1979. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1980. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
  1981. break;
  1982. }
  1983. case OMPRTL__kmpc_cancellationpoint: {
  1984. // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  1985. // global_tid, kmp_int32 cncl_kind)
  1986. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1987. auto *FnTy =
  1988. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1989. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
  1990. break;
  1991. }
  1992. case OMPRTL__kmpc_cancel: {
  1993. // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  1994. // kmp_int32 cncl_kind)
  1995. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1996. auto *FnTy =
  1997. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1998. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
  1999. break;
  2000. }
  2001. case OMPRTL__kmpc_push_num_teams: {
  2002. // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
  2003. // kmp_int32 num_teams, kmp_int32 num_threads)
  2004. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  2005. CGM.Int32Ty};
  2006. auto *FnTy =
  2007. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2008. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
  2009. break;
  2010. }
  2011. case OMPRTL__kmpc_fork_teams: {
  2012. // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
  2013. // microtask, ...);
  2014. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  2015. getKmpc_MicroPointerTy()};
  2016. auto *FnTy =
  2017. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
  2018. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
  2019. if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
  2020. if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
  2021. llvm::LLVMContext &Ctx = F->getContext();
  2022. llvm::MDBuilder MDB(Ctx);
  2023. // Annotate the callback behavior of the __kmpc_fork_teams:
  2024. // - The callback callee is argument number 2 (microtask).
  2025. // - The first two arguments of the callback callee are unknown (-1).
  2026. // - All variadic arguments to the __kmpc_fork_teams are passed to the
  2027. // callback callee.
  2028. F->addMetadata(
  2029. llvm::LLVMContext::MD_callback,
  2030. *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
  2031. 2, {-1, -1},
  2032. /* VarArgsArePassed */ true)}));
  2033. }
  2034. }
  2035. break;
  2036. }
  2037. case OMPRTL__kmpc_taskloop: {
  2038. // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
  2039. // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
  2040. // sched, kmp_uint64 grainsize, void *task_dup);
  2041. llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
  2042. CGM.IntTy,
  2043. CGM.VoidPtrTy,
  2044. CGM.IntTy,
  2045. CGM.Int64Ty->getPointerTo(),
  2046. CGM.Int64Ty->getPointerTo(),
  2047. CGM.Int64Ty,
  2048. CGM.IntTy,
  2049. CGM.IntTy,
  2050. CGM.Int64Ty,
  2051. CGM.VoidPtrTy};
  2052. auto *FnTy =
  2053. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2054. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
  2055. break;
  2056. }
  2057. case OMPRTL__kmpc_doacross_init: {
  2058. // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
  2059. // num_dims, struct kmp_dim *dims);
  2060. llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
  2061. CGM.Int32Ty,
  2062. CGM.Int32Ty,
  2063. CGM.VoidPtrTy};
  2064. auto *FnTy =
  2065. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2066. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
  2067. break;
  2068. }
  2069. case OMPRTL__kmpc_doacross_fini: {
  2070. // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
  2071. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  2072. auto *FnTy =
  2073. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2074. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
  2075. break;
  2076. }
  2077. case OMPRTL__kmpc_doacross_post: {
  2078. // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
  2079. // *vec);
  2080. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  2081. CGM.Int64Ty->getPointerTo()};
  2082. auto *FnTy =
  2083. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2084. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
  2085. break;
  2086. }
  2087. case OMPRTL__kmpc_doacross_wait: {
  2088. // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
  2089. // *vec);
  2090. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  2091. CGM.Int64Ty->getPointerTo()};
  2092. auto *FnTy =
  2093. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2094. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
  2095. break;
  2096. }
  2097. case OMPRTL__kmpc_task_reduction_init: {
  2098. // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
  2099. // *data);
  2100. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
  2101. auto *FnTy =
  2102. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  2103. RTLFn =
  2104. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
  2105. break;
  2106. }
  2107. case OMPRTL__kmpc_task_reduction_get_th_data: {
  2108. // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
  2109. // *d);
  2110. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
  2111. auto *FnTy =
  2112. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  2113. RTLFn = CGM.CreateRuntimeFunction(
  2114. FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
  2115. break;
  2116. }
  2117. case OMPRTL__kmpc_alloc: {
  2118. // Build to void *__kmpc_alloc(int gtid, size_t sz, omp_allocator_handle_t
  2119. // al); omp_allocator_handle_t type is void *.
  2120. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.SizeTy, CGM.VoidPtrTy};
  2121. auto *FnTy =
  2122. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  2123. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_alloc");
  2124. break;
  2125. }
  2126. case OMPRTL__kmpc_free: {
  2127. // Build to void __kmpc_free(int gtid, void *ptr, omp_allocator_handle_t
  2128. // al); omp_allocator_handle_t type is void *.
  2129. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
  2130. auto *FnTy =
  2131. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2132. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_free");
  2133. break;
  2134. }
  2135. case OMPRTL__kmpc_push_target_tripcount: {
  2136. // Build void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
  2137. // size);
  2138. llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int64Ty};
  2139. llvm::FunctionType *FnTy =
  2140. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2141. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_target_tripcount");
  2142. break;
  2143. }
  2144. case OMPRTL__tgt_target: {
  2145. // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
  2146. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  2147. // *arg_types);
  2148. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2149. CGM.VoidPtrTy,
  2150. CGM.Int32Ty,
  2151. CGM.VoidPtrPtrTy,
  2152. CGM.VoidPtrPtrTy,
  2153. CGM.SizeTy->getPointerTo(),
  2154. CGM.Int64Ty->getPointerTo()};
  2155. auto *FnTy =
  2156. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2157. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
  2158. break;
  2159. }
  2160. case OMPRTL__tgt_target_nowait: {
  2161. // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
  2162. // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
  2163. // int64_t *arg_types);
  2164. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2165. CGM.VoidPtrTy,
  2166. CGM.Int32Ty,
  2167. CGM.VoidPtrPtrTy,
  2168. CGM.VoidPtrPtrTy,
  2169. CGM.SizeTy->getPointerTo(),
  2170. CGM.Int64Ty->getPointerTo()};
  2171. auto *FnTy =
  2172. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2173. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
  2174. break;
  2175. }
  2176. case OMPRTL__tgt_target_teams: {
  2177. // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
  2178. // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
  2179. // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
  2180. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2181. CGM.VoidPtrTy,
  2182. CGM.Int32Ty,
  2183. CGM.VoidPtrPtrTy,
  2184. CGM.VoidPtrPtrTy,
  2185. CGM.SizeTy->getPointerTo(),
  2186. CGM.Int64Ty->getPointerTo(),
  2187. CGM.Int32Ty,
  2188. CGM.Int32Ty};
  2189. auto *FnTy =
  2190. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2191. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
  2192. break;
  2193. }
  2194. case OMPRTL__tgt_target_teams_nowait: {
  2195. // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
  2196. // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
  2197. // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
  2198. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2199. CGM.VoidPtrTy,
  2200. CGM.Int32Ty,
  2201. CGM.VoidPtrPtrTy,
  2202. CGM.VoidPtrPtrTy,
  2203. CGM.SizeTy->getPointerTo(),
  2204. CGM.Int64Ty->getPointerTo(),
  2205. CGM.Int32Ty,
  2206. CGM.Int32Ty};
  2207. auto *FnTy =
  2208. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2209. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
  2210. break;
  2211. }
  2212. case OMPRTL__tgt_register_requires: {
  2213. // Build void __tgt_register_requires(int64_t flags);
  2214. llvm::Type *TypeParams[] = {CGM.Int64Ty};
  2215. auto *FnTy =
  2216. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2217. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_requires");
  2218. break;
  2219. }
  2220. case OMPRTL__tgt_register_lib: {
  2221. // Build void __tgt_register_lib(__tgt_bin_desc *desc);
  2222. QualType ParamTy =
  2223. CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
  2224. llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
  2225. auto *FnTy =
  2226. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2227. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
  2228. break;
  2229. }
  2230. case OMPRTL__tgt_unregister_lib: {
  2231. // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
  2232. QualType ParamTy =
  2233. CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
  2234. llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
  2235. auto *FnTy =
  2236. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2237. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
  2238. break;
  2239. }
  2240. case OMPRTL__tgt_target_data_begin: {
  2241. // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
  2242. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  2243. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2244. CGM.Int32Ty,
  2245. CGM.VoidPtrPtrTy,
  2246. CGM.VoidPtrPtrTy,
  2247. CGM.SizeTy->getPointerTo(),
  2248. CGM.Int64Ty->getPointerTo()};
  2249. auto *FnTy =
  2250. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2251. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
  2252. break;
  2253. }
  2254. case OMPRTL__tgt_target_data_begin_nowait: {
  2255. // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
  2256. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  2257. // *arg_types);
  2258. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2259. CGM.Int32Ty,
  2260. CGM.VoidPtrPtrTy,
  2261. CGM.VoidPtrPtrTy,
  2262. CGM.SizeTy->getPointerTo(),
  2263. CGM.Int64Ty->getPointerTo()};
  2264. auto *FnTy =
  2265. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2266. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
  2267. break;
  2268. }
  2269. case OMPRTL__tgt_target_data_end: {
  2270. // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
  2271. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  2272. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2273. CGM.Int32Ty,
  2274. CGM.VoidPtrPtrTy,
  2275. CGM.VoidPtrPtrTy,
  2276. CGM.SizeTy->getPointerTo(),
  2277. CGM.Int64Ty->getPointerTo()};
  2278. auto *FnTy =
  2279. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2280. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
  2281. break;
  2282. }
  2283. case OMPRTL__tgt_target_data_end_nowait: {
  2284. // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
  2285. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  2286. // *arg_types);
  2287. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2288. CGM.Int32Ty,
  2289. CGM.VoidPtrPtrTy,
  2290. CGM.VoidPtrPtrTy,
  2291. CGM.SizeTy->getPointerTo(),
  2292. CGM.Int64Ty->getPointerTo()};
  2293. auto *FnTy =
  2294. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2295. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
  2296. break;
  2297. }
  2298. case OMPRTL__tgt_target_data_update: {
  2299. // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
  2300. // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
  2301. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2302. CGM.Int32Ty,
  2303. CGM.VoidPtrPtrTy,
  2304. CGM.VoidPtrPtrTy,
  2305. CGM.SizeTy->getPointerTo(),
  2306. CGM.Int64Ty->getPointerTo()};
  2307. auto *FnTy =
  2308. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2309. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
  2310. break;
  2311. }
  2312. case OMPRTL__tgt_target_data_update_nowait: {
  2313. // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
  2314. // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
  2315. // *arg_types);
  2316. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2317. CGM.Int32Ty,
  2318. CGM.VoidPtrPtrTy,
  2319. CGM.VoidPtrPtrTy,
  2320. CGM.SizeTy->getPointerTo(),
  2321. CGM.Int64Ty->getPointerTo()};
  2322. auto *FnTy =
  2323. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2324. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
  2325. break;
  2326. }
  2327. }
  2328. assert(RTLFn && "Unable to find OpenMP runtime function");
  2329. return RTLFn;
  2330. }
  2331. llvm::FunctionCallee
  2332. CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned) {
  2333. assert((IVSize == 32 || IVSize == 64) &&
  2334. "IV size is not compatible with the omp runtime");
  2335. StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
  2336. : "__kmpc_for_static_init_4u")
  2337. : (IVSigned ? "__kmpc_for_static_init_8"
  2338. : "__kmpc_for_static_init_8u");
  2339. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2340. auto *PtrTy = llvm::PointerType::getUnqual(ITy);
  2341. llvm::Type *TypeParams[] = {
  2342. getIdentTyPointerTy(), // loc
  2343. CGM.Int32Ty, // tid
  2344. CGM.Int32Ty, // schedtype
  2345. llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
  2346. PtrTy, // p_lower
  2347. PtrTy, // p_upper
  2348. PtrTy, // p_stride
  2349. ITy, // incr
  2350. ITy // chunk
  2351. };
  2352. auto *FnTy =
  2353. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2354. return CGM.CreateRuntimeFunction(FnTy, Name);
  2355. }
  2356. llvm::FunctionCallee
  2357. CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) {
  2358. assert((IVSize == 32 || IVSize == 64) &&
  2359. "IV size is not compatible with the omp runtime");
  2360. StringRef Name =
  2361. IVSize == 32
  2362. ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
  2363. : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
  2364. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2365. llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
  2366. CGM.Int32Ty, // tid
  2367. CGM.Int32Ty, // schedtype
  2368. ITy, // lower
  2369. ITy, // upper
  2370. ITy, // stride
  2371. ITy // chunk
  2372. };
  2373. auto *FnTy =
  2374. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2375. return CGM.CreateRuntimeFunction(FnTy, Name);
  2376. }
  2377. llvm::FunctionCallee
  2378. CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) {
  2379. assert((IVSize == 32 || IVSize == 64) &&
  2380. "IV size is not compatible with the omp runtime");
  2381. StringRef Name =
  2382. IVSize == 32
  2383. ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
  2384. : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
  2385. llvm::Type *TypeParams[] = {
  2386. getIdentTyPointerTy(), // loc
  2387. CGM.Int32Ty, // tid
  2388. };
  2389. auto *FnTy =
  2390. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2391. return CGM.CreateRuntimeFunction(FnTy, Name);
  2392. }
  2393. llvm::FunctionCallee
  2394. CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) {
  2395. assert((IVSize == 32 || IVSize == 64) &&
  2396. "IV size is not compatible with the omp runtime");
  2397. StringRef Name =
  2398. IVSize == 32
  2399. ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
  2400. : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
  2401. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2402. auto *PtrTy = llvm::PointerType::getUnqual(ITy);
  2403. llvm::Type *TypeParams[] = {
  2404. getIdentTyPointerTy(), // loc
  2405. CGM.Int32Ty, // tid
  2406. llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
  2407. PtrTy, // p_lower
  2408. PtrTy, // p_upper
  2409. PtrTy // p_stride
  2410. };
  2411. auto *FnTy =
  2412. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2413. return CGM.CreateRuntimeFunction(FnTy, Name);
  2414. }
  2415. Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) {
  2416. if (CGM.getLangOpts().OpenMPSimd)
  2417. return Address::invalid();
  2418. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2419. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2420. if (Res && (*Res == OMPDeclareTargetDeclAttr::MT_Link ||
  2421. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2422. HasRequiresUnifiedSharedMemory))) {
  2423. SmallString<64> PtrName;
  2424. {
  2425. llvm::raw_svector_ostream OS(PtrName);
  2426. OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_ref_ptr";
  2427. }
  2428. llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
  2429. if (!Ptr) {
  2430. QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
  2431. Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
  2432. PtrName);
  2433. if (!CGM.getLangOpts().OpenMPIsDevice) {
  2434. auto *GV = cast<llvm::GlobalVariable>(Ptr);
  2435. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2436. GV->setInitializer(CGM.GetAddrOfGlobal(VD));
  2437. }
  2438. CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
  2439. registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
  2440. }
  2441. return Address(Ptr, CGM.getContext().getDeclAlign(VD));
  2442. }
  2443. return Address::invalid();
  2444. }
  2445. llvm::Constant *
  2446. CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
  2447. assert(!CGM.getLangOpts().OpenMPUseTLS ||
  2448. !CGM.getContext().getTargetInfo().isTLSSupported());
  2449. // Lookup the entry, lazily creating it if necessary.
  2450. std::string Suffix = getName({"cache", ""});
  2451. return getOrCreateInternalVariable(
  2452. CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
  2453. }
  2454. Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
  2455. const VarDecl *VD,
  2456. Address VDAddr,
  2457. SourceLocation Loc) {
  2458. if (CGM.getLangOpts().OpenMPUseTLS &&
  2459. CGM.getContext().getTargetInfo().isTLSSupported())
  2460. return VDAddr;
  2461. llvm::Type *VarTy = VDAddr.getElementType();
  2462. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2463. CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
  2464. CGM.Int8PtrTy),
  2465. CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
  2466. getOrCreateThreadPrivateCache(VD)};
  2467. return Address(CGF.EmitRuntimeCall(
  2468. createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
  2469. VDAddr.getAlignment());
  2470. }
  2471. void CGOpenMPRuntime::emitThreadPrivateVarInit(
  2472. CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
  2473. llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
  2474. // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
  2475. // library.
  2476. llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
  2477. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
  2478. OMPLoc);
  2479. // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
  2480. // to register constructor/destructor for variable.
  2481. llvm::Value *Args[] = {
  2482. OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
  2483. Ctor, CopyCtor, Dtor};
  2484. CGF.EmitRuntimeCall(
  2485. createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
  2486. }
  2487. llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
  2488. const VarDecl *VD, Address VDAddr, SourceLocation Loc,
  2489. bool PerformInit, CodeGenFunction *CGF) {
  2490. if (CGM.getLangOpts().OpenMPUseTLS &&
  2491. CGM.getContext().getTargetInfo().isTLSSupported())
  2492. return nullptr;
  2493. VD = VD->getDefinition(CGM.getContext());
  2494. if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
  2495. QualType ASTTy = VD->getType();
  2496. llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
  2497. const Expr *Init = VD->getAnyInitializer();
  2498. if (CGM.getLangOpts().CPlusPlus && PerformInit) {
  2499. // Generate function that re-emits the declaration's initializer into the
  2500. // threadprivate copy of the variable VD
  2501. CodeGenFunction CtorCGF(CGM);
  2502. FunctionArgList Args;
  2503. ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
  2504. /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
  2505. ImplicitParamDecl::Other);
  2506. Args.push_back(&Dst);
  2507. const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
  2508. CGM.getContext().VoidPtrTy, Args);
  2509. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2510. std::string Name = getName({"__kmpc_global_ctor_", ""});
  2511. llvm::Function *Fn =
  2512. CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
  2513. CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
  2514. Args, Loc, Loc);
  2515. llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
  2516. CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
  2517. CGM.getContext().VoidPtrTy, Dst.getLocation());
  2518. Address Arg = Address(ArgVal, VDAddr.getAlignment());
  2519. Arg = CtorCGF.Builder.CreateElementBitCast(
  2520. Arg, CtorCGF.ConvertTypeForMem(ASTTy));
  2521. CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
  2522. /*IsInitializer=*/true);
  2523. ArgVal = CtorCGF.EmitLoadOfScalar(
  2524. CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
  2525. CGM.getContext().VoidPtrTy, Dst.getLocation());
  2526. CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
  2527. CtorCGF.FinishFunction();
  2528. Ctor = Fn;
  2529. }
  2530. if (VD->getType().isDestructedType() != QualType::DK_none) {
  2531. // Generate function that emits destructor call for the threadprivate copy
  2532. // of the variable VD
  2533. CodeGenFunction DtorCGF(CGM);
  2534. FunctionArgList Args;
  2535. ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
  2536. /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
  2537. ImplicitParamDecl::Other);
  2538. Args.push_back(&Dst);
  2539. const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
  2540. CGM.getContext().VoidTy, Args);
  2541. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2542. std::string Name = getName({"__kmpc_global_dtor_", ""});
  2543. llvm::Function *Fn =
  2544. CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
  2545. auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
  2546. DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
  2547. Loc, Loc);
  2548. // Create a scope with an artificial location for the body of this function.
  2549. auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
  2550. llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
  2551. DtorCGF.GetAddrOfLocalVar(&Dst),
  2552. /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
  2553. DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
  2554. DtorCGF.getDestroyer(ASTTy.isDestructedType()),
  2555. DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
  2556. DtorCGF.FinishFunction();
  2557. Dtor = Fn;
  2558. }
  2559. // Do not emit init function if it is not required.
  2560. if (!Ctor && !Dtor)
  2561. return nullptr;
  2562. llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  2563. auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
  2564. /*isVarArg=*/false)
  2565. ->getPointerTo();
  2566. // Copying constructor for the threadprivate variable.
  2567. // Must be NULL - reserved by runtime, but currently it requires that this
  2568. // parameter is always NULL. Otherwise it fires assertion.
  2569. CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
  2570. if (Ctor == nullptr) {
  2571. auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
  2572. /*isVarArg=*/false)
  2573. ->getPointerTo();
  2574. Ctor = llvm::Constant::getNullValue(CtorTy);
  2575. }
  2576. if (Dtor == nullptr) {
  2577. auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
  2578. /*isVarArg=*/false)
  2579. ->getPointerTo();
  2580. Dtor = llvm::Constant::getNullValue(DtorTy);
  2581. }
  2582. if (!CGF) {
  2583. auto *InitFunctionTy =
  2584. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
  2585. std::string Name = getName({"__omp_threadprivate_init_", ""});
  2586. llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
  2587. InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
  2588. CodeGenFunction InitCGF(CGM);
  2589. FunctionArgList ArgList;
  2590. InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
  2591. CGM.getTypes().arrangeNullaryFunction(), ArgList,
  2592. Loc, Loc);
  2593. emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
  2594. InitCGF.FinishFunction();
  2595. return InitFunction;
  2596. }
  2597. emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
  2598. }
  2599. return nullptr;
  2600. }
  2601. /// Obtain information that uniquely identifies a target entry. This
  2602. /// consists of the file and device IDs as well as line number associated with
  2603. /// the relevant entry source location.
  2604. static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
  2605. unsigned &DeviceID, unsigned &FileID,
  2606. unsigned &LineNum) {
  2607. SourceManager &SM = C.getSourceManager();
  2608. // The loc should be always valid and have a file ID (the user cannot use
  2609. // #pragma directives in macros)
  2610. assert(Loc.isValid() && "Source location is expected to be always valid.");
  2611. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  2612. assert(PLoc.isValid() && "Source location is expected to be always valid.");
  2613. llvm::sys::fs::UniqueID ID;
  2614. if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
  2615. SM.getDiagnostics().Report(diag::err_cannot_open_file)
  2616. << PLoc.getFilename() << EC.message();
  2617. DeviceID = ID.getDevice();
  2618. FileID = ID.getFile();
  2619. LineNum = PLoc.getLine();
  2620. }
  2621. bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
  2622. llvm::GlobalVariable *Addr,
  2623. bool PerformInit) {
  2624. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2625. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2626. if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link ||
  2627. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2628. HasRequiresUnifiedSharedMemory))
  2629. return CGM.getLangOpts().OpenMPIsDevice;
  2630. VD = VD->getDefinition(CGM.getContext());
  2631. if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
  2632. return CGM.getLangOpts().OpenMPIsDevice;
  2633. QualType ASTTy = VD->getType();
  2634. SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
  2635. // Produce the unique prefix to identify the new target regions. We use
  2636. // the source location of the variable declaration which we know to not
  2637. // conflict with any target region.
  2638. unsigned DeviceID;
  2639. unsigned FileID;
  2640. unsigned Line;
  2641. getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
  2642. SmallString<128> Buffer, Out;
  2643. {
  2644. llvm::raw_svector_ostream OS(Buffer);
  2645. OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
  2646. << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
  2647. }
  2648. const Expr *Init = VD->getAnyInitializer();
  2649. if (CGM.getLangOpts().CPlusPlus && PerformInit) {
  2650. llvm::Constant *Ctor;
  2651. llvm::Constant *ID;
  2652. if (CGM.getLangOpts().OpenMPIsDevice) {
  2653. // Generate function that re-emits the declaration's initializer into
  2654. // the threadprivate copy of the variable VD
  2655. CodeGenFunction CtorCGF(CGM);
  2656. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2657. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2658. llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
  2659. FTy, Twine(Buffer, "_ctor"), FI, Loc);
  2660. auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
  2661. CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
  2662. FunctionArgList(), Loc, Loc);
  2663. auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
  2664. CtorCGF.EmitAnyExprToMem(Init,
  2665. Address(Addr, CGM.getContext().getDeclAlign(VD)),
  2666. Init->getType().getQualifiers(),
  2667. /*IsInitializer=*/true);
  2668. CtorCGF.FinishFunction();
  2669. Ctor = Fn;
  2670. ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  2671. CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
  2672. } else {
  2673. Ctor = new llvm::GlobalVariable(
  2674. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  2675. llvm::GlobalValue::PrivateLinkage,
  2676. llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
  2677. ID = Ctor;
  2678. }
  2679. // Register the information for the entry associated with the constructor.
  2680. Out.clear();
  2681. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  2682. DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
  2683. ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
  2684. }
  2685. if (VD->getType().isDestructedType() != QualType::DK_none) {
  2686. llvm::Constant *Dtor;
  2687. llvm::Constant *ID;
  2688. if (CGM.getLangOpts().OpenMPIsDevice) {
  2689. // Generate function that emits destructor call for the threadprivate
  2690. // copy of the variable VD
  2691. CodeGenFunction DtorCGF(CGM);
  2692. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2693. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2694. llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
  2695. FTy, Twine(Buffer, "_dtor"), FI, Loc);
  2696. auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
  2697. DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
  2698. FunctionArgList(), Loc, Loc);
  2699. // Create a scope with an artificial location for the body of this
  2700. // function.
  2701. auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
  2702. DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
  2703. ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
  2704. DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
  2705. DtorCGF.FinishFunction();
  2706. Dtor = Fn;
  2707. ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  2708. CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
  2709. } else {
  2710. Dtor = new llvm::GlobalVariable(
  2711. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  2712. llvm::GlobalValue::PrivateLinkage,
  2713. llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
  2714. ID = Dtor;
  2715. }
  2716. // Register the information for the entry associated with the destructor.
  2717. Out.clear();
  2718. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  2719. DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
  2720. ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
  2721. }
  2722. return CGM.getLangOpts().OpenMPIsDevice;
  2723. }
  2724. Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
  2725. QualType VarType,
  2726. StringRef Name) {
  2727. std::string Suffix = getName({"artificial", ""});
  2728. std::string CacheSuffix = getName({"cache", ""});
  2729. llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
  2730. llvm::Value *GAddr =
  2731. getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
  2732. llvm::Value *Args[] = {
  2733. emitUpdateLocation(CGF, SourceLocation()),
  2734. getThreadID(CGF, SourceLocation()),
  2735. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
  2736. CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
  2737. /*IsSigned=*/false),
  2738. getOrCreateInternalVariable(
  2739. CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
  2740. return Address(
  2741. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2742. CGF.EmitRuntimeCall(
  2743. createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
  2744. VarLVType->getPointerTo(/*AddrSpace=*/0)),
  2745. CGM.getPointerAlign());
  2746. }
  2747. void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
  2748. const RegionCodeGenTy &ThenGen,
  2749. const RegionCodeGenTy &ElseGen) {
  2750. CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
  2751. // If the condition constant folds and can be elided, try to avoid emitting
  2752. // the condition and the dead arm of the if/else.
  2753. bool CondConstant;
  2754. if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
  2755. if (CondConstant)
  2756. ThenGen(CGF);
  2757. else
  2758. ElseGen(CGF);
  2759. return;
  2760. }
  2761. // Otherwise, the condition did not fold, or we couldn't elide it. Just
  2762. // emit the conditional branch.
  2763. llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
  2764. llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
  2765. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
  2766. CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
  2767. // Emit the 'then' code.
  2768. CGF.EmitBlock(ThenBlock);
  2769. ThenGen(CGF);
  2770. CGF.EmitBranch(ContBlock);
  2771. // Emit the 'else' code if present.
  2772. // There is no need to emit line number for unconditional branch.
  2773. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2774. CGF.EmitBlock(ElseBlock);
  2775. ElseGen(CGF);
  2776. // There is no need to emit line number for unconditional branch.
  2777. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2778. CGF.EmitBranch(ContBlock);
  2779. // Emit the continuation block for code after the if.
  2780. CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
  2781. }
  2782. void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  2783. llvm::Function *OutlinedFn,
  2784. ArrayRef<llvm::Value *> CapturedVars,
  2785. const Expr *IfCond) {
  2786. if (!CGF.HaveInsertPoint())
  2787. return;
  2788. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  2789. auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
  2790. PrePostActionTy &) {
  2791. // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
  2792. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  2793. llvm::Value *Args[] = {
  2794. RTLoc,
  2795. CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
  2796. CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
  2797. llvm::SmallVector<llvm::Value *, 16> RealArgs;
  2798. RealArgs.append(std::begin(Args), std::end(Args));
  2799. RealArgs.append(CapturedVars.begin(), CapturedVars.end());
  2800. llvm::FunctionCallee RTLFn =
  2801. RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
  2802. CGF.EmitRuntimeCall(RTLFn, RealArgs);
  2803. };
  2804. auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
  2805. PrePostActionTy &) {
  2806. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  2807. llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
  2808. // Build calls:
  2809. // __kmpc_serialized_parallel(&Loc, GTid);
  2810. llvm::Value *Args[] = {RTLoc, ThreadID};
  2811. CGF.EmitRuntimeCall(
  2812. RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
  2813. // OutlinedFn(&GTid, &zero, CapturedStruct);
  2814. Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2815. /*Name*/ ".zero.addr");
  2816. CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
  2817. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
  2818. // ThreadId for serialized parallels is 0.
  2819. OutlinedFnArgs.push_back(ZeroAddr.getPointer());
  2820. OutlinedFnArgs.push_back(ZeroAddr.getPointer());
  2821. OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
  2822. RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
  2823. // __kmpc_end_serialized_parallel(&Loc, GTid);
  2824. llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
  2825. CGF.EmitRuntimeCall(
  2826. RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
  2827. EndArgs);
  2828. };
  2829. if (IfCond) {
  2830. emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
  2831. } else {
  2832. RegionCodeGenTy ThenRCG(ThenGen);
  2833. ThenRCG(CGF);
  2834. }
  2835. }
  2836. // If we're inside an (outlined) parallel region, use the region info's
  2837. // thread-ID variable (it is passed in a first argument of the outlined function
  2838. // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
  2839. // regular serial code region, get thread ID by calling kmp_int32
  2840. // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
  2841. // return the address of that temp.
  2842. Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
  2843. SourceLocation Loc) {
  2844. if (auto *OMPRegionInfo =
  2845. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  2846. if (OMPRegionInfo->getThreadIDVariable())
  2847. return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
  2848. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  2849. QualType Int32Ty =
  2850. CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
  2851. Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
  2852. CGF.EmitStoreOfScalar(ThreadID,
  2853. CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
  2854. return ThreadIDTemp;
  2855. }
  2856. llvm::Constant *CGOpenMPRuntime::getOrCreateInternalVariable(
  2857. llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
  2858. SmallString<256> Buffer;
  2859. llvm::raw_svector_ostream Out(Buffer);
  2860. Out << Name;
  2861. StringRef RuntimeName = Out.str();
  2862. auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
  2863. if (Elem.second) {
  2864. assert(Elem.second->getType()->getPointerElementType() == Ty &&
  2865. "OMP internal variable has different type than requested");
  2866. return &*Elem.second;
  2867. }
  2868. return Elem.second = new llvm::GlobalVariable(
  2869. CGM.getModule(), Ty, /*IsConstant*/ false,
  2870. llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
  2871. Elem.first(), /*InsertBefore=*/nullptr,
  2872. llvm::GlobalValue::NotThreadLocal, AddressSpace);
  2873. }
  2874. llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
  2875. std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
  2876. std::string Name = getName({Prefix, "var"});
  2877. return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
  2878. }
  2879. namespace {
  2880. /// Common pre(post)-action for different OpenMP constructs.
  2881. class CommonActionTy final : public PrePostActionTy {
  2882. llvm::FunctionCallee EnterCallee;
  2883. ArrayRef<llvm::Value *> EnterArgs;
  2884. llvm::FunctionCallee ExitCallee;
  2885. ArrayRef<llvm::Value *> ExitArgs;
  2886. bool Conditional;
  2887. llvm::BasicBlock *ContBlock = nullptr;
  2888. public:
  2889. CommonActionTy(llvm::FunctionCallee EnterCallee,
  2890. ArrayRef<llvm::Value *> EnterArgs,
  2891. llvm::FunctionCallee ExitCallee,
  2892. ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
  2893. : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
  2894. ExitArgs(ExitArgs), Conditional(Conditional) {}
  2895. void Enter(CodeGenFunction &CGF) override {
  2896. llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
  2897. if (Conditional) {
  2898. llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
  2899. auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
  2900. ContBlock = CGF.createBasicBlock("omp_if.end");
  2901. // Generate the branch (If-stmt)
  2902. CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
  2903. CGF.EmitBlock(ThenBlock);
  2904. }
  2905. }
  2906. void Done(CodeGenFunction &CGF) {
  2907. // Emit the rest of blocks/branches
  2908. CGF.EmitBranch(ContBlock);
  2909. CGF.EmitBlock(ContBlock, true);
  2910. }
  2911. void Exit(CodeGenFunction &CGF) override {
  2912. CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
  2913. }
  2914. };
  2915. } // anonymous namespace
  2916. void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
  2917. StringRef CriticalName,
  2918. const RegionCodeGenTy &CriticalOpGen,
  2919. SourceLocation Loc, const Expr *Hint) {
  2920. // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
  2921. // CriticalOpGen();
  2922. // __kmpc_end_critical(ident_t *, gtid, Lock);
  2923. // Prepare arguments and build a call to __kmpc_critical
  2924. if (!CGF.HaveInsertPoint())
  2925. return;
  2926. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2927. getCriticalRegionLock(CriticalName)};
  2928. llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
  2929. std::end(Args));
  2930. if (Hint) {
  2931. EnterArgs.push_back(CGF.Builder.CreateIntCast(
  2932. CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
  2933. }
  2934. CommonActionTy Action(
  2935. createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
  2936. : OMPRTL__kmpc_critical),
  2937. EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
  2938. CriticalOpGen.setAction(Action);
  2939. emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
  2940. }
  2941. void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
  2942. const RegionCodeGenTy &MasterOpGen,
  2943. SourceLocation Loc) {
  2944. if (!CGF.HaveInsertPoint())
  2945. return;
  2946. // if(__kmpc_master(ident_t *, gtid)) {
  2947. // MasterOpGen();
  2948. // __kmpc_end_master(ident_t *, gtid);
  2949. // }
  2950. // Prepare arguments and build a call to __kmpc_master
  2951. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  2952. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
  2953. createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
  2954. /*Conditional=*/true);
  2955. MasterOpGen.setAction(Action);
  2956. emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
  2957. Action.Done(CGF);
  2958. }
  2959. void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
  2960. SourceLocation Loc) {
  2961. if (!CGF.HaveInsertPoint())
  2962. return;
  2963. // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
  2964. llvm::Value *Args[] = {
  2965. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2966. llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
  2967. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
  2968. if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  2969. Region->emitUntiedSwitch(CGF);
  2970. }
  2971. void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
  2972. const RegionCodeGenTy &TaskgroupOpGen,
  2973. SourceLocation Loc) {
  2974. if (!CGF.HaveInsertPoint())
  2975. return;
  2976. // __kmpc_taskgroup(ident_t *, gtid);
  2977. // TaskgroupOpGen();
  2978. // __kmpc_end_taskgroup(ident_t *, gtid);
  2979. // Prepare arguments and build a call to __kmpc_taskgroup
  2980. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  2981. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
  2982. createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
  2983. Args);
  2984. TaskgroupOpGen.setAction(Action);
  2985. emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
  2986. }
  2987. /// Given an array of pointers to variables, project the address of a
  2988. /// given variable.
  2989. static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
  2990. unsigned Index, const VarDecl *Var) {
  2991. // Pull out the pointer to the variable.
  2992. Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index);
  2993. llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
  2994. Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
  2995. Addr = CGF.Builder.CreateElementBitCast(
  2996. Addr, CGF.ConvertTypeForMem(Var->getType()));
  2997. return Addr;
  2998. }
  2999. static llvm::Value *emitCopyprivateCopyFunction(
  3000. CodeGenModule &CGM, llvm::Type *ArgsType,
  3001. ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
  3002. ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
  3003. SourceLocation Loc) {
  3004. ASTContext &C = CGM.getContext();
  3005. // void copy_func(void *LHSArg, void *RHSArg);
  3006. FunctionArgList Args;
  3007. ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  3008. ImplicitParamDecl::Other);
  3009. ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  3010. ImplicitParamDecl::Other);
  3011. Args.push_back(&LHSArg);
  3012. Args.push_back(&RHSArg);
  3013. const auto &CGFI =
  3014. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3015. std::string Name =
  3016. CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
  3017. auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
  3018. llvm::GlobalValue::InternalLinkage, Name,
  3019. &CGM.getModule());
  3020. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  3021. Fn->setDoesNotRecurse();
  3022. CodeGenFunction CGF(CGM);
  3023. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  3024. // Dest = (void*[n])(LHSArg);
  3025. // Src = (void*[n])(RHSArg);
  3026. Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  3027. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
  3028. ArgsType), CGF.getPointerAlign());
  3029. Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  3030. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
  3031. ArgsType), CGF.getPointerAlign());
  3032. // *(Type0*)Dst[0] = *(Type0*)Src[0];
  3033. // *(Type1*)Dst[1] = *(Type1*)Src[1];
  3034. // ...
  3035. // *(Typen*)Dst[n] = *(Typen*)Src[n];
  3036. for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
  3037. const auto *DestVar =
  3038. cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
  3039. Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
  3040. const auto *SrcVar =
  3041. cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
  3042. Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
  3043. const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
  3044. QualType Type = VD->getType();
  3045. CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
  3046. }
  3047. CGF.FinishFunction();
  3048. return Fn;
  3049. }
  3050. void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
  3051. const RegionCodeGenTy &SingleOpGen,
  3052. SourceLocation Loc,
  3053. ArrayRef<const Expr *> CopyprivateVars,
  3054. ArrayRef<const Expr *> SrcExprs,
  3055. ArrayRef<const Expr *> DstExprs,
  3056. ArrayRef<const Expr *> AssignmentOps) {
  3057. if (!CGF.HaveInsertPoint())
  3058. return;
  3059. assert(CopyprivateVars.size() == SrcExprs.size() &&
  3060. CopyprivateVars.size() == DstExprs.size() &&
  3061. CopyprivateVars.size() == AssignmentOps.size());
  3062. ASTContext &C = CGM.getContext();
  3063. // int32 did_it = 0;
  3064. // if(__kmpc_single(ident_t *, gtid)) {
  3065. // SingleOpGen();
  3066. // __kmpc_end_single(ident_t *, gtid);
  3067. // did_it = 1;
  3068. // }
  3069. // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
  3070. // <copy_func>, did_it);
  3071. Address DidIt = Address::invalid();
  3072. if (!CopyprivateVars.empty()) {
  3073. // int32 did_it = 0;
  3074. QualType KmpInt32Ty =
  3075. C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  3076. DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
  3077. CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
  3078. }
  3079. // Prepare arguments and build a call to __kmpc_single
  3080. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3081. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
  3082. createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
  3083. /*Conditional=*/true);
  3084. SingleOpGen.setAction(Action);
  3085. emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
  3086. if (DidIt.isValid()) {
  3087. // did_it = 1;
  3088. CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
  3089. }
  3090. Action.Done(CGF);
  3091. // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
  3092. // <copy_func>, did_it);
  3093. if (DidIt.isValid()) {
  3094. llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
  3095. QualType CopyprivateArrayTy =
  3096. C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
  3097. /*IndexTypeQuals=*/0);
  3098. // Create a list of all private variables for copyprivate.
  3099. Address CopyprivateList =
  3100. CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
  3101. for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
  3102. Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I);
  3103. CGF.Builder.CreateStore(
  3104. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  3105. CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
  3106. Elem);
  3107. }
  3108. // Build function that copies private values from single region to all other
  3109. // threads in the corresponding parallel region.
  3110. llvm::Value *CpyFn = emitCopyprivateCopyFunction(
  3111. CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
  3112. CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
  3113. llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
  3114. Address CL =
  3115. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
  3116. CGF.VoidPtrTy);
  3117. llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
  3118. llvm::Value *Args[] = {
  3119. emitUpdateLocation(CGF, Loc), // ident_t *<loc>
  3120. getThreadID(CGF, Loc), // i32 <gtid>
  3121. BufSize, // size_t <buf_size>
  3122. CL.getPointer(), // void *<copyprivate list>
  3123. CpyFn, // void (*) (void *, void *) <copy_func>
  3124. DidItVal // i32 did_it
  3125. };
  3126. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
  3127. }
  3128. }
  3129. void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
  3130. const RegionCodeGenTy &OrderedOpGen,
  3131. SourceLocation Loc, bool IsThreads) {
  3132. if (!CGF.HaveInsertPoint())
  3133. return;
  3134. // __kmpc_ordered(ident_t *, gtid);
  3135. // OrderedOpGen();
  3136. // __kmpc_end_ordered(ident_t *, gtid);
  3137. // Prepare arguments and build a call to __kmpc_ordered
  3138. if (IsThreads) {
  3139. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3140. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
  3141. createRuntimeFunction(OMPRTL__kmpc_end_ordered),
  3142. Args);
  3143. OrderedOpGen.setAction(Action);
  3144. emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
  3145. return;
  3146. }
  3147. emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
  3148. }
  3149. unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
  3150. unsigned Flags;
  3151. if (Kind == OMPD_for)
  3152. Flags = OMP_IDENT_BARRIER_IMPL_FOR;
  3153. else if (Kind == OMPD_sections)
  3154. Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
  3155. else if (Kind == OMPD_single)
  3156. Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
  3157. else if (Kind == OMPD_barrier)
  3158. Flags = OMP_IDENT_BARRIER_EXPL;
  3159. else
  3160. Flags = OMP_IDENT_BARRIER_IMPL;
  3161. return Flags;
  3162. }
  3163. void CGOpenMPRuntime::getDefaultScheduleAndChunk(
  3164. CodeGenFunction &CGF, const OMPLoopDirective &S,
  3165. OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const {
  3166. // Check if the loop directive is actually a doacross loop directive. In this
  3167. // case choose static, 1 schedule.
  3168. if (llvm::any_of(
  3169. S.getClausesOfKind<OMPOrderedClause>(),
  3170. [](const OMPOrderedClause *C) { return C->getNumForLoops(); })) {
  3171. ScheduleKind = OMPC_SCHEDULE_static;
  3172. // Chunk size is 1 in this case.
  3173. llvm::APInt ChunkSize(32, 1);
  3174. ChunkExpr = IntegerLiteral::Create(
  3175. CGF.getContext(), ChunkSize,
  3176. CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
  3177. SourceLocation());
  3178. }
  3179. }
  3180. void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
  3181. OpenMPDirectiveKind Kind, bool EmitChecks,
  3182. bool ForceSimpleCall) {
  3183. if (!CGF.HaveInsertPoint())
  3184. return;
  3185. // Build call __kmpc_cancel_barrier(loc, thread_id);
  3186. // Build call __kmpc_barrier(loc, thread_id);
  3187. unsigned Flags = getDefaultFlagsForBarriers(Kind);
  3188. // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
  3189. // thread_id);
  3190. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
  3191. getThreadID(CGF, Loc)};
  3192. if (auto *OMPRegionInfo =
  3193. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  3194. if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
  3195. llvm::Value *Result = CGF.EmitRuntimeCall(
  3196. createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
  3197. if (EmitChecks) {
  3198. // if (__kmpc_cancel_barrier()) {
  3199. // exit from construct;
  3200. // }
  3201. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  3202. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  3203. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  3204. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  3205. CGF.EmitBlock(ExitBB);
  3206. // exit from construct;
  3207. CodeGenFunction::JumpDest CancelDestination =
  3208. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  3209. CGF.EmitBranchThroughCleanup(CancelDestination);
  3210. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  3211. }
  3212. return;
  3213. }
  3214. }
  3215. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
  3216. }
  3217. /// Map the OpenMP loop schedule to the runtime enumeration.
  3218. static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
  3219. bool Chunked, bool Ordered) {
  3220. switch (ScheduleKind) {
  3221. case OMPC_SCHEDULE_static:
  3222. return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
  3223. : (Ordered ? OMP_ord_static : OMP_sch_static);
  3224. case OMPC_SCHEDULE_dynamic:
  3225. return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
  3226. case OMPC_SCHEDULE_guided:
  3227. return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
  3228. case OMPC_SCHEDULE_runtime:
  3229. return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
  3230. case OMPC_SCHEDULE_auto:
  3231. return Ordered ? OMP_ord_auto : OMP_sch_auto;
  3232. case OMPC_SCHEDULE_unknown:
  3233. assert(!Chunked && "chunk was specified but schedule kind not known");
  3234. return Ordered ? OMP_ord_static : OMP_sch_static;
  3235. }
  3236. llvm_unreachable("Unexpected runtime schedule");
  3237. }
  3238. /// Map the OpenMP distribute schedule to the runtime enumeration.
  3239. static OpenMPSchedType
  3240. getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
  3241. // only static is allowed for dist_schedule
  3242. return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
  3243. }
  3244. bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
  3245. bool Chunked) const {
  3246. OpenMPSchedType Schedule =
  3247. getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
  3248. return Schedule == OMP_sch_static;
  3249. }
  3250. bool CGOpenMPRuntime::isStaticNonchunked(
  3251. OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
  3252. OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
  3253. return Schedule == OMP_dist_sch_static;
  3254. }
  3255. bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
  3256. bool Chunked) const {
  3257. OpenMPSchedType Schedule =
  3258. getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
  3259. return Schedule == OMP_sch_static_chunked;
  3260. }
  3261. bool CGOpenMPRuntime::isStaticChunked(
  3262. OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
  3263. OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
  3264. return Schedule == OMP_dist_sch_static_chunked;
  3265. }
  3266. bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
  3267. OpenMPSchedType Schedule =
  3268. getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
  3269. assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
  3270. return Schedule != OMP_sch_static;
  3271. }
  3272. static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
  3273. OpenMPScheduleClauseModifier M1,
  3274. OpenMPScheduleClauseModifier M2) {
  3275. int Modifier = 0;
  3276. switch (M1) {
  3277. case OMPC_SCHEDULE_MODIFIER_monotonic:
  3278. Modifier = OMP_sch_modifier_monotonic;
  3279. break;
  3280. case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
  3281. Modifier = OMP_sch_modifier_nonmonotonic;
  3282. break;
  3283. case OMPC_SCHEDULE_MODIFIER_simd:
  3284. if (Schedule == OMP_sch_static_chunked)
  3285. Schedule = OMP_sch_static_balanced_chunked;
  3286. break;
  3287. case OMPC_SCHEDULE_MODIFIER_last:
  3288. case OMPC_SCHEDULE_MODIFIER_unknown:
  3289. break;
  3290. }
  3291. switch (M2) {
  3292. case OMPC_SCHEDULE_MODIFIER_monotonic:
  3293. Modifier = OMP_sch_modifier_monotonic;
  3294. break;
  3295. case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
  3296. Modifier = OMP_sch_modifier_nonmonotonic;
  3297. break;
  3298. case OMPC_SCHEDULE_MODIFIER_simd:
  3299. if (Schedule == OMP_sch_static_chunked)
  3300. Schedule = OMP_sch_static_balanced_chunked;
  3301. break;
  3302. case OMPC_SCHEDULE_MODIFIER_last:
  3303. case OMPC_SCHEDULE_MODIFIER_unknown:
  3304. break;
  3305. }
  3306. return Schedule | Modifier;
  3307. }
  3308. void CGOpenMPRuntime::emitForDispatchInit(
  3309. CodeGenFunction &CGF, SourceLocation Loc,
  3310. const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
  3311. bool Ordered, const DispatchRTInput &DispatchValues) {
  3312. if (!CGF.HaveInsertPoint())
  3313. return;
  3314. OpenMPSchedType Schedule = getRuntimeSchedule(
  3315. ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
  3316. assert(Ordered ||
  3317. (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
  3318. Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
  3319. Schedule != OMP_sch_static_balanced_chunked));
  3320. // Call __kmpc_dispatch_init(
  3321. // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
  3322. // kmp_int[32|64] lower, kmp_int[32|64] upper,
  3323. // kmp_int[32|64] stride, kmp_int[32|64] chunk);
  3324. // If the Chunk was not specified in the clause - use default value 1.
  3325. llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
  3326. : CGF.Builder.getIntN(IVSize, 1);
  3327. llvm::Value *Args[] = {
  3328. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3329. CGF.Builder.getInt32(addMonoNonMonoModifier(
  3330. Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
  3331. DispatchValues.LB, // Lower
  3332. DispatchValues.UB, // Upper
  3333. CGF.Builder.getIntN(IVSize, 1), // Stride
  3334. Chunk // Chunk
  3335. };
  3336. CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
  3337. }
  3338. static void emitForStaticInitCall(
  3339. CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
  3340. llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule,
  3341. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  3342. const CGOpenMPRuntime::StaticRTInput &Values) {
  3343. if (!CGF.HaveInsertPoint())
  3344. return;
  3345. assert(!Values.Ordered);
  3346. assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
  3347. Schedule == OMP_sch_static_balanced_chunked ||
  3348. Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
  3349. Schedule == OMP_dist_sch_static ||
  3350. Schedule == OMP_dist_sch_static_chunked);
  3351. // Call __kmpc_for_static_init(
  3352. // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
  3353. // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
  3354. // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
  3355. // kmp_int[32|64] incr, kmp_int[32|64] chunk);
  3356. llvm::Value *Chunk = Values.Chunk;
  3357. if (Chunk == nullptr) {
  3358. assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
  3359. Schedule == OMP_dist_sch_static) &&
  3360. "expected static non-chunked schedule");
  3361. // If the Chunk was not specified in the clause - use default value 1.
  3362. Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
  3363. } else {
  3364. assert((Schedule == OMP_sch_static_chunked ||
  3365. Schedule == OMP_sch_static_balanced_chunked ||
  3366. Schedule == OMP_ord_static_chunked ||
  3367. Schedule == OMP_dist_sch_static_chunked) &&
  3368. "expected static chunked schedule");
  3369. }
  3370. llvm::Value *Args[] = {
  3371. UpdateLocation,
  3372. ThreadId,
  3373. CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
  3374. M2)), // Schedule type
  3375. Values.IL.getPointer(), // &isLastIter
  3376. Values.LB.getPointer(), // &LB
  3377. Values.UB.getPointer(), // &UB
  3378. Values.ST.getPointer(), // &Stride
  3379. CGF.Builder.getIntN(Values.IVSize, 1), // Incr
  3380. Chunk // Chunk
  3381. };
  3382. CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
  3383. }
  3384. void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
  3385. SourceLocation Loc,
  3386. OpenMPDirectiveKind DKind,
  3387. const OpenMPScheduleTy &ScheduleKind,
  3388. const StaticRTInput &Values) {
  3389. OpenMPSchedType ScheduleNum = getRuntimeSchedule(
  3390. ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
  3391. assert(isOpenMPWorksharingDirective(DKind) &&
  3392. "Expected loop-based or sections-based directive.");
  3393. llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
  3394. isOpenMPLoopDirective(DKind)
  3395. ? OMP_IDENT_WORK_LOOP
  3396. : OMP_IDENT_WORK_SECTIONS);
  3397. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  3398. llvm::FunctionCallee StaticInitFunction =
  3399. createForStaticInitFunction(Values.IVSize, Values.IVSigned);
  3400. emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
  3401. ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
  3402. }
  3403. void CGOpenMPRuntime::emitDistributeStaticInit(
  3404. CodeGenFunction &CGF, SourceLocation Loc,
  3405. OpenMPDistScheduleClauseKind SchedKind,
  3406. const CGOpenMPRuntime::StaticRTInput &Values) {
  3407. OpenMPSchedType ScheduleNum =
  3408. getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
  3409. llvm::Value *UpdatedLocation =
  3410. emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
  3411. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  3412. llvm::FunctionCallee StaticInitFunction =
  3413. createForStaticInitFunction(Values.IVSize, Values.IVSigned);
  3414. emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
  3415. ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
  3416. OMPC_SCHEDULE_MODIFIER_unknown, Values);
  3417. }
  3418. void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
  3419. SourceLocation Loc,
  3420. OpenMPDirectiveKind DKind) {
  3421. if (!CGF.HaveInsertPoint())
  3422. return;
  3423. // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
  3424. llvm::Value *Args[] = {
  3425. emitUpdateLocation(CGF, Loc,
  3426. isOpenMPDistributeDirective(DKind)
  3427. ? OMP_IDENT_WORK_DISTRIBUTE
  3428. : isOpenMPLoopDirective(DKind)
  3429. ? OMP_IDENT_WORK_LOOP
  3430. : OMP_IDENT_WORK_SECTIONS),
  3431. getThreadID(CGF, Loc)};
  3432. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
  3433. Args);
  3434. }
  3435. void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
  3436. SourceLocation Loc,
  3437. unsigned IVSize,
  3438. bool IVSigned) {
  3439. if (!CGF.HaveInsertPoint())
  3440. return;
  3441. // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
  3442. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3443. CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
  3444. }
  3445. llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
  3446. SourceLocation Loc, unsigned IVSize,
  3447. bool IVSigned, Address IL,
  3448. Address LB, Address UB,
  3449. Address ST) {
  3450. // Call __kmpc_dispatch_next(
  3451. // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
  3452. // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
  3453. // kmp_int[32|64] *p_stride);
  3454. llvm::Value *Args[] = {
  3455. emitUpdateLocation(CGF, Loc),
  3456. getThreadID(CGF, Loc),
  3457. IL.getPointer(), // &isLastIter
  3458. LB.getPointer(), // &Lower
  3459. UB.getPointer(), // &Upper
  3460. ST.getPointer() // &Stride
  3461. };
  3462. llvm::Value *Call =
  3463. CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
  3464. return CGF.EmitScalarConversion(
  3465. Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
  3466. CGF.getContext().BoolTy, Loc);
  3467. }
  3468. void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
  3469. llvm::Value *NumThreads,
  3470. SourceLocation Loc) {
  3471. if (!CGF.HaveInsertPoint())
  3472. return;
  3473. // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
  3474. llvm::Value *Args[] = {
  3475. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3476. CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
  3477. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
  3478. Args);
  3479. }
  3480. void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
  3481. OpenMPProcBindClauseKind ProcBind,
  3482. SourceLocation Loc) {
  3483. if (!CGF.HaveInsertPoint())
  3484. return;
  3485. // Constants for proc bind value accepted by the runtime.
  3486. enum ProcBindTy {
  3487. ProcBindFalse = 0,
  3488. ProcBindTrue,
  3489. ProcBindMaster,
  3490. ProcBindClose,
  3491. ProcBindSpread,
  3492. ProcBindIntel,
  3493. ProcBindDefault
  3494. } RuntimeProcBind;
  3495. switch (ProcBind) {
  3496. case OMPC_PROC_BIND_master:
  3497. RuntimeProcBind = ProcBindMaster;
  3498. break;
  3499. case OMPC_PROC_BIND_close:
  3500. RuntimeProcBind = ProcBindClose;
  3501. break;
  3502. case OMPC_PROC_BIND_spread:
  3503. RuntimeProcBind = ProcBindSpread;
  3504. break;
  3505. case OMPC_PROC_BIND_unknown:
  3506. llvm_unreachable("Unsupported proc_bind value.");
  3507. }
  3508. // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
  3509. llvm::Value *Args[] = {
  3510. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3511. llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
  3512. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
  3513. }
  3514. void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
  3515. SourceLocation Loc) {
  3516. if (!CGF.HaveInsertPoint())
  3517. return;
  3518. // Build call void __kmpc_flush(ident_t *loc)
  3519. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
  3520. emitUpdateLocation(CGF, Loc));
  3521. }
  3522. namespace {
  3523. /// Indexes of fields for type kmp_task_t.
  3524. enum KmpTaskTFields {
  3525. /// List of shared variables.
  3526. KmpTaskTShareds,
  3527. /// Task routine.
  3528. KmpTaskTRoutine,
  3529. /// Partition id for the untied tasks.
  3530. KmpTaskTPartId,
  3531. /// Function with call of destructors for private variables.
  3532. Data1,
  3533. /// Task priority.
  3534. Data2,
  3535. /// (Taskloops only) Lower bound.
  3536. KmpTaskTLowerBound,
  3537. /// (Taskloops only) Upper bound.
  3538. KmpTaskTUpperBound,
  3539. /// (Taskloops only) Stride.
  3540. KmpTaskTStride,
  3541. /// (Taskloops only) Is last iteration flag.
  3542. KmpTaskTLastIter,
  3543. /// (Taskloops only) Reduction data.
  3544. KmpTaskTReductions,
  3545. };
  3546. } // anonymous namespace
  3547. bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
  3548. return OffloadEntriesTargetRegion.empty() &&
  3549. OffloadEntriesDeviceGlobalVar.empty();
  3550. }
  3551. /// Initialize target region entry.
  3552. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3553. initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
  3554. StringRef ParentName, unsigned LineNum,
  3555. unsigned Order) {
  3556. assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
  3557. "only required for the device "
  3558. "code generation.");
  3559. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
  3560. OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
  3561. OMPTargetRegionEntryTargetRegion);
  3562. ++OffloadingEntriesNum;
  3563. }
  3564. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3565. registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
  3566. StringRef ParentName, unsigned LineNum,
  3567. llvm::Constant *Addr, llvm::Constant *ID,
  3568. OMPTargetRegionEntryKind Flags) {
  3569. // If we are emitting code for a target, the entry is already initialized,
  3570. // only has to be registered.
  3571. if (CGM.getLangOpts().OpenMPIsDevice) {
  3572. if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
  3573. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3574. DiagnosticsEngine::Error,
  3575. "Unable to find target region on line '%0' in the device code.");
  3576. CGM.getDiags().Report(DiagID) << LineNum;
  3577. return;
  3578. }
  3579. auto &Entry =
  3580. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
  3581. assert(Entry.isValid() && "Entry not initialized!");
  3582. Entry.setAddress(Addr);
  3583. Entry.setID(ID);
  3584. Entry.setFlags(Flags);
  3585. } else {
  3586. OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
  3587. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
  3588. ++OffloadingEntriesNum;
  3589. }
  3590. }
  3591. bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
  3592. unsigned DeviceID, unsigned FileID, StringRef ParentName,
  3593. unsigned LineNum) const {
  3594. auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
  3595. if (PerDevice == OffloadEntriesTargetRegion.end())
  3596. return false;
  3597. auto PerFile = PerDevice->second.find(FileID);
  3598. if (PerFile == PerDevice->second.end())
  3599. return false;
  3600. auto PerParentName = PerFile->second.find(ParentName);
  3601. if (PerParentName == PerFile->second.end())
  3602. return false;
  3603. auto PerLine = PerParentName->second.find(LineNum);
  3604. if (PerLine == PerParentName->second.end())
  3605. return false;
  3606. // Fail if this entry is already registered.
  3607. if (PerLine->second.getAddress() || PerLine->second.getID())
  3608. return false;
  3609. return true;
  3610. }
  3611. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
  3612. const OffloadTargetRegionEntryInfoActTy &Action) {
  3613. // Scan all target region entries and perform the provided action.
  3614. for (const auto &D : OffloadEntriesTargetRegion)
  3615. for (const auto &F : D.second)
  3616. for (const auto &P : F.second)
  3617. for (const auto &L : P.second)
  3618. Action(D.first, F.first, P.first(), L.first, L.second);
  3619. }
  3620. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3621. initializeDeviceGlobalVarEntryInfo(StringRef Name,
  3622. OMPTargetGlobalVarEntryKind Flags,
  3623. unsigned Order) {
  3624. assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
  3625. "only required for the device "
  3626. "code generation.");
  3627. OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
  3628. ++OffloadingEntriesNum;
  3629. }
  3630. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3631. registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
  3632. CharUnits VarSize,
  3633. OMPTargetGlobalVarEntryKind Flags,
  3634. llvm::GlobalValue::LinkageTypes Linkage) {
  3635. if (CGM.getLangOpts().OpenMPIsDevice) {
  3636. auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
  3637. assert(Entry.isValid() && Entry.getFlags() == Flags &&
  3638. "Entry not initialized!");
  3639. assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
  3640. "Resetting with the new address.");
  3641. if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) {
  3642. if (Entry.getVarSize().isZero()) {
  3643. Entry.setVarSize(VarSize);
  3644. Entry.setLinkage(Linkage);
  3645. }
  3646. return;
  3647. }
  3648. Entry.setVarSize(VarSize);
  3649. Entry.setLinkage(Linkage);
  3650. Entry.setAddress(Addr);
  3651. } else {
  3652. if (hasDeviceGlobalVarEntryInfo(VarName)) {
  3653. auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
  3654. assert(Entry.isValid() && Entry.getFlags() == Flags &&
  3655. "Entry not initialized!");
  3656. assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
  3657. "Resetting with the new address.");
  3658. if (Entry.getVarSize().isZero()) {
  3659. Entry.setVarSize(VarSize);
  3660. Entry.setLinkage(Linkage);
  3661. }
  3662. return;
  3663. }
  3664. OffloadEntriesDeviceGlobalVar.try_emplace(
  3665. VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
  3666. ++OffloadingEntriesNum;
  3667. }
  3668. }
  3669. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3670. actOnDeviceGlobalVarEntriesInfo(
  3671. const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
  3672. // Scan all target region entries and perform the provided action.
  3673. for (const auto &E : OffloadEntriesDeviceGlobalVar)
  3674. Action(E.getKey(), E.getValue());
  3675. }
  3676. llvm::Function *
  3677. CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
  3678. // If we don't have entries or if we are emitting code for the device, we
  3679. // don't need to do anything.
  3680. if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
  3681. return nullptr;
  3682. llvm::Module &M = CGM.getModule();
  3683. ASTContext &C = CGM.getContext();
  3684. // Get list of devices we care about
  3685. const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
  3686. // We should be creating an offloading descriptor only if there are devices
  3687. // specified.
  3688. assert(!Devices.empty() && "No OpenMP offloading devices??");
  3689. // Create the external variables that will point to the begin and end of the
  3690. // host entries section. These will be defined by the linker.
  3691. llvm::Type *OffloadEntryTy =
  3692. CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
  3693. std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
  3694. auto *HostEntriesBegin = new llvm::GlobalVariable(
  3695. M, OffloadEntryTy, /*isConstant=*/true,
  3696. llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
  3697. EntriesBeginName);
  3698. std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
  3699. auto *HostEntriesEnd =
  3700. new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
  3701. llvm::GlobalValue::ExternalLinkage,
  3702. /*Initializer=*/nullptr, EntriesEndName);
  3703. // Create all device images
  3704. auto *DeviceImageTy = cast<llvm::StructType>(
  3705. CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
  3706. ConstantInitBuilder DeviceImagesBuilder(CGM);
  3707. ConstantArrayBuilder DeviceImagesEntries =
  3708. DeviceImagesBuilder.beginArray(DeviceImageTy);
  3709. for (const llvm::Triple &Device : Devices) {
  3710. StringRef T = Device.getTriple();
  3711. std::string BeginName = getName({"omp_offloading", "img_start", ""});
  3712. auto *ImgBegin = new llvm::GlobalVariable(
  3713. M, CGM.Int8Ty, /*isConstant=*/true,
  3714. llvm::GlobalValue::ExternalWeakLinkage,
  3715. /*Initializer=*/nullptr, Twine(BeginName).concat(T));
  3716. std::string EndName = getName({"omp_offloading", "img_end", ""});
  3717. auto *ImgEnd = new llvm::GlobalVariable(
  3718. M, CGM.Int8Ty, /*isConstant=*/true,
  3719. llvm::GlobalValue::ExternalWeakLinkage,
  3720. /*Initializer=*/nullptr, Twine(EndName).concat(T));
  3721. llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
  3722. HostEntriesEnd};
  3723. createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
  3724. DeviceImagesEntries);
  3725. }
  3726. // Create device images global array.
  3727. std::string ImagesName = getName({"omp_offloading", "device_images"});
  3728. llvm::GlobalVariable *DeviceImages =
  3729. DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
  3730. CGM.getPointerAlign(),
  3731. /*isConstant=*/true);
  3732. DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3733. // This is a Zero array to be used in the creation of the constant expressions
  3734. llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
  3735. llvm::Constant::getNullValue(CGM.Int32Ty)};
  3736. // Create the target region descriptor.
  3737. llvm::Constant *Data[] = {
  3738. llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
  3739. llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
  3740. DeviceImages, Index),
  3741. HostEntriesBegin, HostEntriesEnd};
  3742. std::string Descriptor = getName({"omp_offloading", "descriptor"});
  3743. llvm::GlobalVariable *Desc = createGlobalStruct(
  3744. CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
  3745. // Emit code to register or unregister the descriptor at execution
  3746. // startup or closing, respectively.
  3747. llvm::Function *UnRegFn;
  3748. {
  3749. FunctionArgList Args;
  3750. ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
  3751. Args.push_back(&DummyPtr);
  3752. CodeGenFunction CGF(CGM);
  3753. // Disable debug info for global (de-)initializer because they are not part
  3754. // of some particular construct.
  3755. CGF.disableDebugInfo();
  3756. const auto &FI =
  3757. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3758. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  3759. std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
  3760. UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
  3761. CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
  3762. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
  3763. Desc);
  3764. CGF.FinishFunction();
  3765. }
  3766. llvm::Function *RegFn;
  3767. {
  3768. CodeGenFunction CGF(CGM);
  3769. // Disable debug info for global (de-)initializer because they are not part
  3770. // of some particular construct.
  3771. CGF.disableDebugInfo();
  3772. const auto &FI = CGM.getTypes().arrangeNullaryFunction();
  3773. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  3774. // Encode offload target triples into the registration function name. It
  3775. // will serve as a comdat key for the registration/unregistration code for
  3776. // this particular combination of offloading targets.
  3777. SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
  3778. RegFnNameParts[0] = "omp_offloading";
  3779. RegFnNameParts[1] = "descriptor_reg";
  3780. llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
  3781. [](const llvm::Triple &T) -> const std::string& {
  3782. return T.getTriple();
  3783. });
  3784. llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
  3785. std::string Descriptor = getName(RegFnNameParts);
  3786. RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
  3787. CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
  3788. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
  3789. // Create a variable to drive the registration and unregistration of the
  3790. // descriptor, so we can reuse the logic that emits Ctors and Dtors.
  3791. ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
  3792. SourceLocation(), nullptr, C.CharTy,
  3793. ImplicitParamDecl::Other);
  3794. CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
  3795. CGF.FinishFunction();
  3796. }
  3797. if (CGM.supportsCOMDAT()) {
  3798. // It is sufficient to call registration function only once, so create a
  3799. // COMDAT group for registration/unregistration functions and associated
  3800. // data. That would reduce startup time and code size. Registration
  3801. // function serves as a COMDAT group key.
  3802. llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
  3803. RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
  3804. RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
  3805. RegFn->setComdat(ComdatKey);
  3806. UnRegFn->setComdat(ComdatKey);
  3807. DeviceImages->setComdat(ComdatKey);
  3808. Desc->setComdat(ComdatKey);
  3809. }
  3810. return RegFn;
  3811. }
  3812. void CGOpenMPRuntime::createOffloadEntry(
  3813. llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
  3814. llvm::GlobalValue::LinkageTypes Linkage) {
  3815. StringRef Name = Addr->getName();
  3816. llvm::Module &M = CGM.getModule();
  3817. llvm::LLVMContext &C = M.getContext();
  3818. // Create constant string with the name.
  3819. llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
  3820. std::string StringName = getName({"omp_offloading", "entry_name"});
  3821. auto *Str = new llvm::GlobalVariable(
  3822. M, StrPtrInit->getType(), /*isConstant=*/true,
  3823. llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
  3824. Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3825. llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
  3826. llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
  3827. llvm::ConstantInt::get(CGM.SizeTy, Size),
  3828. llvm::ConstantInt::get(CGM.Int32Ty, Flags),
  3829. llvm::ConstantInt::get(CGM.Int32Ty, 0)};
  3830. std::string EntryName = getName({"omp_offloading", "entry", ""});
  3831. llvm::GlobalVariable *Entry = createGlobalStruct(
  3832. CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
  3833. Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
  3834. // The entry has to be created in the section the linker expects it to be.
  3835. std::string Section = getName({"omp_offloading", "entries"});
  3836. Entry->setSection(Section);
  3837. }
  3838. void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
  3839. // Emit the offloading entries and metadata so that the device codegen side
  3840. // can easily figure out what to emit. The produced metadata looks like
  3841. // this:
  3842. //
  3843. // !omp_offload.info = !{!1, ...}
  3844. //
  3845. // Right now we only generate metadata for function that contain target
  3846. // regions.
  3847. // If we do not have entries, we don't need to do anything.
  3848. if (OffloadEntriesInfoManager.empty())
  3849. return;
  3850. llvm::Module &M = CGM.getModule();
  3851. llvm::LLVMContext &C = M.getContext();
  3852. SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
  3853. OrderedEntries(OffloadEntriesInfoManager.size());
  3854. llvm::SmallVector<StringRef, 16> ParentFunctions(
  3855. OffloadEntriesInfoManager.size());
  3856. // Auxiliary methods to create metadata values and strings.
  3857. auto &&GetMDInt = [this](unsigned V) {
  3858. return llvm::ConstantAsMetadata::get(
  3859. llvm::ConstantInt::get(CGM.Int32Ty, V));
  3860. };
  3861. auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
  3862. // Create the offloading info metadata node.
  3863. llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
  3864. // Create function that emits metadata for each target region entry;
  3865. auto &&TargetRegionMetadataEmitter =
  3866. [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
  3867. unsigned DeviceID, unsigned FileID, StringRef ParentName,
  3868. unsigned Line,
  3869. const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
  3870. // Generate metadata for target regions. Each entry of this metadata
  3871. // contains:
  3872. // - Entry 0 -> Kind of this type of metadata (0).
  3873. // - Entry 1 -> Device ID of the file where the entry was identified.
  3874. // - Entry 2 -> File ID of the file where the entry was identified.
  3875. // - Entry 3 -> Mangled name of the function where the entry was
  3876. // identified.
  3877. // - Entry 4 -> Line in the file where the entry was identified.
  3878. // - Entry 5 -> Order the entry was created.
  3879. // The first element of the metadata node is the kind.
  3880. llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
  3881. GetMDInt(FileID), GetMDString(ParentName),
  3882. GetMDInt(Line), GetMDInt(E.getOrder())};
  3883. // Save this entry in the right position of the ordered entries array.
  3884. OrderedEntries[E.getOrder()] = &E;
  3885. ParentFunctions[E.getOrder()] = ParentName;
  3886. // Add metadata to the named metadata node.
  3887. MD->addOperand(llvm::MDNode::get(C, Ops));
  3888. };
  3889. OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
  3890. TargetRegionMetadataEmitter);
  3891. // Create function that emits metadata for each device global variable entry;
  3892. auto &&DeviceGlobalVarMetadataEmitter =
  3893. [&C, &OrderedEntries, &GetMDInt, &GetMDString,
  3894. MD](StringRef MangledName,
  3895. const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
  3896. &E) {
  3897. // Generate metadata for global variables. Each entry of this metadata
  3898. // contains:
  3899. // - Entry 0 -> Kind of this type of metadata (1).
  3900. // - Entry 1 -> Mangled name of the variable.
  3901. // - Entry 2 -> Declare target kind.
  3902. // - Entry 3 -> Order the entry was created.
  3903. // The first element of the metadata node is the kind.
  3904. llvm::Metadata *Ops[] = {
  3905. GetMDInt(E.getKind()), GetMDString(MangledName),
  3906. GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
  3907. // Save this entry in the right position of the ordered entries array.
  3908. OrderedEntries[E.getOrder()] = &E;
  3909. // Add metadata to the named metadata node.
  3910. MD->addOperand(llvm::MDNode::get(C, Ops));
  3911. };
  3912. OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
  3913. DeviceGlobalVarMetadataEmitter);
  3914. for (const auto *E : OrderedEntries) {
  3915. assert(E && "All ordered entries must exist!");
  3916. if (const auto *CE =
  3917. dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
  3918. E)) {
  3919. if (!CE->getID() || !CE->getAddress()) {
  3920. // Do not blame the entry if the parent funtion is not emitted.
  3921. StringRef FnName = ParentFunctions[CE->getOrder()];
  3922. if (!CGM.GetGlobalValue(FnName))
  3923. continue;
  3924. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3925. DiagnosticsEngine::Error,
  3926. "Offloading entry for target region is incorrect: either the "
  3927. "address or the ID is invalid.");
  3928. CGM.getDiags().Report(DiagID);
  3929. continue;
  3930. }
  3931. createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
  3932. CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
  3933. } else if (const auto *CE =
  3934. dyn_cast<OffloadEntriesInfoManagerTy::
  3935. OffloadEntryInfoDeviceGlobalVar>(E)) {
  3936. OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
  3937. static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
  3938. CE->getFlags());
  3939. switch (Flags) {
  3940. case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
  3941. if (CGM.getLangOpts().OpenMPIsDevice &&
  3942. CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())
  3943. continue;
  3944. if (!CE->getAddress()) {
  3945. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3946. DiagnosticsEngine::Error,
  3947. "Offloading entry for declare target variable is incorrect: the "
  3948. "address is invalid.");
  3949. CGM.getDiags().Report(DiagID);
  3950. continue;
  3951. }
  3952. // The vaiable has no definition - no need to add the entry.
  3953. if (CE->getVarSize().isZero())
  3954. continue;
  3955. break;
  3956. }
  3957. case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
  3958. assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
  3959. (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
  3960. "Declaret target link address is set.");
  3961. if (CGM.getLangOpts().OpenMPIsDevice)
  3962. continue;
  3963. if (!CE->getAddress()) {
  3964. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3965. DiagnosticsEngine::Error,
  3966. "Offloading entry for declare target variable is incorrect: the "
  3967. "address is invalid.");
  3968. CGM.getDiags().Report(DiagID);
  3969. continue;
  3970. }
  3971. break;
  3972. }
  3973. createOffloadEntry(CE->getAddress(), CE->getAddress(),
  3974. CE->getVarSize().getQuantity(), Flags,
  3975. CE->getLinkage());
  3976. } else {
  3977. llvm_unreachable("Unsupported entry kind.");
  3978. }
  3979. }
  3980. }
  3981. /// Loads all the offload entries information from the host IR
  3982. /// metadata.
  3983. void CGOpenMPRuntime::loadOffloadInfoMetadata() {
  3984. // If we are in target mode, load the metadata from the host IR. This code has
  3985. // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
  3986. if (!CGM.getLangOpts().OpenMPIsDevice)
  3987. return;
  3988. if (CGM.getLangOpts().OMPHostIRFile.empty())
  3989. return;
  3990. auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
  3991. if (auto EC = Buf.getError()) {
  3992. CGM.getDiags().Report(diag::err_cannot_open_file)
  3993. << CGM.getLangOpts().OMPHostIRFile << EC.message();
  3994. return;
  3995. }
  3996. llvm::LLVMContext C;
  3997. auto ME = expectedToErrorOrAndEmitErrors(
  3998. C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
  3999. if (auto EC = ME.getError()) {
  4000. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  4001. DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
  4002. CGM.getDiags().Report(DiagID)
  4003. << CGM.getLangOpts().OMPHostIRFile << EC.message();
  4004. return;
  4005. }
  4006. llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
  4007. if (!MD)
  4008. return;
  4009. for (llvm::MDNode *MN : MD->operands()) {
  4010. auto &&GetMDInt = [MN](unsigned Idx) {
  4011. auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
  4012. return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
  4013. };
  4014. auto &&GetMDString = [MN](unsigned Idx) {
  4015. auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
  4016. return V->getString();
  4017. };
  4018. switch (GetMDInt(0)) {
  4019. default:
  4020. llvm_unreachable("Unexpected metadata!");
  4021. break;
  4022. case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
  4023. OffloadingEntryInfoTargetRegion:
  4024. OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
  4025. /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
  4026. /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
  4027. /*Order=*/GetMDInt(5));
  4028. break;
  4029. case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
  4030. OffloadingEntryInfoDeviceGlobalVar:
  4031. OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
  4032. /*MangledName=*/GetMDString(1),
  4033. static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
  4034. /*Flags=*/GetMDInt(2)),
  4035. /*Order=*/GetMDInt(3));
  4036. break;
  4037. }
  4038. }
  4039. }
  4040. void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
  4041. if (!KmpRoutineEntryPtrTy) {
  4042. // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
  4043. ASTContext &C = CGM.getContext();
  4044. QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
  4045. FunctionProtoType::ExtProtoInfo EPI;
  4046. KmpRoutineEntryPtrQTy = C.getPointerType(
  4047. C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
  4048. KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
  4049. }
  4050. }
  4051. QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
  4052. // Make sure the type of the entry is already created. This is the type we
  4053. // have to create:
  4054. // struct __tgt_offload_entry{
  4055. // void *addr; // Pointer to the offload entry info.
  4056. // // (function or global)
  4057. // char *name; // Name of the function or global.
  4058. // size_t size; // Size of the entry info (0 if it a function).
  4059. // int32_t flags; // Flags associated with the entry, e.g. 'link'.
  4060. // int32_t reserved; // Reserved, to use by the runtime library.
  4061. // };
  4062. if (TgtOffloadEntryQTy.isNull()) {
  4063. ASTContext &C = CGM.getContext();
  4064. RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
  4065. RD->startDefinition();
  4066. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4067. addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
  4068. addFieldToRecordDecl(C, RD, C.getSizeType());
  4069. addFieldToRecordDecl(
  4070. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  4071. addFieldToRecordDecl(
  4072. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  4073. RD->completeDefinition();
  4074. RD->addAttr(PackedAttr::CreateImplicit(C));
  4075. TgtOffloadEntryQTy = C.getRecordType(RD);
  4076. }
  4077. return TgtOffloadEntryQTy;
  4078. }
  4079. QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
  4080. // These are the types we need to build:
  4081. // struct __tgt_device_image{
  4082. // void *ImageStart; // Pointer to the target code start.
  4083. // void *ImageEnd; // Pointer to the target code end.
  4084. // // We also add the host entries to the device image, as it may be useful
  4085. // // for the target runtime to have access to that information.
  4086. // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
  4087. // // the entries.
  4088. // __tgt_offload_entry *EntriesEnd; // End of the table with all the
  4089. // // entries (non inclusive).
  4090. // };
  4091. if (TgtDeviceImageQTy.isNull()) {
  4092. ASTContext &C = CGM.getContext();
  4093. RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
  4094. RD->startDefinition();
  4095. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4096. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4097. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  4098. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  4099. RD->completeDefinition();
  4100. TgtDeviceImageQTy = C.getRecordType(RD);
  4101. }
  4102. return TgtDeviceImageQTy;
  4103. }
  4104. QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
  4105. // struct __tgt_bin_desc{
  4106. // int32_t NumDevices; // Number of devices supported.
  4107. // __tgt_device_image *DeviceImages; // Arrays of device images
  4108. // // (one per device).
  4109. // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
  4110. // // entries.
  4111. // __tgt_offload_entry *EntriesEnd; // End of the table with all the
  4112. // // entries (non inclusive).
  4113. // };
  4114. if (TgtBinaryDescriptorQTy.isNull()) {
  4115. ASTContext &C = CGM.getContext();
  4116. RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
  4117. RD->startDefinition();
  4118. addFieldToRecordDecl(
  4119. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  4120. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
  4121. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  4122. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  4123. RD->completeDefinition();
  4124. TgtBinaryDescriptorQTy = C.getRecordType(RD);
  4125. }
  4126. return TgtBinaryDescriptorQTy;
  4127. }
  4128. namespace {
  4129. struct PrivateHelpersTy {
  4130. PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
  4131. const VarDecl *PrivateElemInit)
  4132. : Original(Original), PrivateCopy(PrivateCopy),
  4133. PrivateElemInit(PrivateElemInit) {}
  4134. const VarDecl *Original;
  4135. const VarDecl *PrivateCopy;
  4136. const VarDecl *PrivateElemInit;
  4137. };
  4138. typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
  4139. } // anonymous namespace
  4140. static RecordDecl *
  4141. createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
  4142. if (!Privates.empty()) {
  4143. ASTContext &C = CGM.getContext();
  4144. // Build struct .kmp_privates_t. {
  4145. // /* private vars */
  4146. // };
  4147. RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
  4148. RD->startDefinition();
  4149. for (const auto &Pair : Privates) {
  4150. const VarDecl *VD = Pair.second.Original;
  4151. QualType Type = VD->getType().getNonReferenceType();
  4152. FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
  4153. if (VD->hasAttrs()) {
  4154. for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
  4155. E(VD->getAttrs().end());
  4156. I != E; ++I)
  4157. FD->addAttr(*I);
  4158. }
  4159. }
  4160. RD->completeDefinition();
  4161. return RD;
  4162. }
  4163. return nullptr;
  4164. }
  4165. static RecordDecl *
  4166. createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
  4167. QualType KmpInt32Ty,
  4168. QualType KmpRoutineEntryPointerQTy) {
  4169. ASTContext &C = CGM.getContext();
  4170. // Build struct kmp_task_t {
  4171. // void * shareds;
  4172. // kmp_routine_entry_t routine;
  4173. // kmp_int32 part_id;
  4174. // kmp_cmplrdata_t data1;
  4175. // kmp_cmplrdata_t data2;
  4176. // For taskloops additional fields:
  4177. // kmp_uint64 lb;
  4178. // kmp_uint64 ub;
  4179. // kmp_int64 st;
  4180. // kmp_int32 liter;
  4181. // void * reductions;
  4182. // };
  4183. RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
  4184. UD->startDefinition();
  4185. addFieldToRecordDecl(C, UD, KmpInt32Ty);
  4186. addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
  4187. UD->completeDefinition();
  4188. QualType KmpCmplrdataTy = C.getRecordType(UD);
  4189. RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
  4190. RD->startDefinition();
  4191. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4192. addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
  4193. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  4194. addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
  4195. addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
  4196. if (isOpenMPTaskLoopDirective(Kind)) {
  4197. QualType KmpUInt64Ty =
  4198. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4199. QualType KmpInt64Ty =
  4200. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4201. addFieldToRecordDecl(C, RD, KmpUInt64Ty);
  4202. addFieldToRecordDecl(C, RD, KmpUInt64Ty);
  4203. addFieldToRecordDecl(C, RD, KmpInt64Ty);
  4204. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  4205. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4206. }
  4207. RD->completeDefinition();
  4208. return RD;
  4209. }
  4210. static RecordDecl *
  4211. createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
  4212. ArrayRef<PrivateDataTy> Privates) {
  4213. ASTContext &C = CGM.getContext();
  4214. // Build struct kmp_task_t_with_privates {
  4215. // kmp_task_t task_data;
  4216. // .kmp_privates_t. privates;
  4217. // };
  4218. RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
  4219. RD->startDefinition();
  4220. addFieldToRecordDecl(C, RD, KmpTaskTQTy);
  4221. if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
  4222. addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
  4223. RD->completeDefinition();
  4224. return RD;
  4225. }
  4226. /// Emit a proxy function which accepts kmp_task_t as the second
  4227. /// argument.
  4228. /// \code
  4229. /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
  4230. /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
  4231. /// For taskloops:
  4232. /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
  4233. /// tt->reductions, tt->shareds);
  4234. /// return 0;
  4235. /// }
  4236. /// \endcode
  4237. static llvm::Function *
  4238. emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
  4239. OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
  4240. QualType KmpTaskTWithPrivatesPtrQTy,
  4241. QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
  4242. QualType SharedsPtrTy, llvm::Function *TaskFunction,
  4243. llvm::Value *TaskPrivatesMap) {
  4244. ASTContext &C = CGM.getContext();
  4245. FunctionArgList Args;
  4246. ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
  4247. ImplicitParamDecl::Other);
  4248. ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4249. KmpTaskTWithPrivatesPtrQTy.withRestrict(),
  4250. ImplicitParamDecl::Other);
  4251. Args.push_back(&GtidArg);
  4252. Args.push_back(&TaskTypeArg);
  4253. const auto &TaskEntryFnInfo =
  4254. CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
  4255. llvm::FunctionType *TaskEntryTy =
  4256. CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
  4257. std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
  4258. auto *TaskEntry = llvm::Function::Create(
  4259. TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
  4260. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
  4261. TaskEntry->setDoesNotRecurse();
  4262. CodeGenFunction CGF(CGM);
  4263. CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
  4264. Loc, Loc);
  4265. // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
  4266. // tt,
  4267. // For taskloops:
  4268. // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
  4269. // tt->task_data.shareds);
  4270. llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
  4271. CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
  4272. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4273. CGF.GetAddrOfLocalVar(&TaskTypeArg),
  4274. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4275. const auto *KmpTaskTWithPrivatesQTyRD =
  4276. cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
  4277. LValue Base =
  4278. CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4279. const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
  4280. auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
  4281. LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
  4282. llvm::Value *PartidParam = PartIdLVal.getPointer();
  4283. auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
  4284. LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
  4285. llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4286. CGF.EmitLoadOfScalar(SharedsLVal, Loc),
  4287. CGF.ConvertTypeForMem(SharedsPtrTy));
  4288. auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
  4289. llvm::Value *PrivatesParam;
  4290. if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
  4291. LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
  4292. PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4293. PrivatesLVal.getPointer(), CGF.VoidPtrTy);
  4294. } else {
  4295. PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  4296. }
  4297. llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
  4298. TaskPrivatesMap,
  4299. CGF.Builder
  4300. .CreatePointerBitCastOrAddrSpaceCast(
  4301. TDBase.getAddress(), CGF.VoidPtrTy)
  4302. .getPointer()};
  4303. SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
  4304. std::end(CommonArgs));
  4305. if (isOpenMPTaskLoopDirective(Kind)) {
  4306. auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
  4307. LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
  4308. llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
  4309. auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
  4310. LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
  4311. llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
  4312. auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
  4313. LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
  4314. llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
  4315. auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
  4316. LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
  4317. llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
  4318. auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
  4319. LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
  4320. llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
  4321. CallArgs.push_back(LBParam);
  4322. CallArgs.push_back(UBParam);
  4323. CallArgs.push_back(StParam);
  4324. CallArgs.push_back(LIParam);
  4325. CallArgs.push_back(RParam);
  4326. }
  4327. CallArgs.push_back(SharedsParam);
  4328. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
  4329. CallArgs);
  4330. CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
  4331. CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
  4332. CGF.FinishFunction();
  4333. return TaskEntry;
  4334. }
  4335. static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
  4336. SourceLocation Loc,
  4337. QualType KmpInt32Ty,
  4338. QualType KmpTaskTWithPrivatesPtrQTy,
  4339. QualType KmpTaskTWithPrivatesQTy) {
  4340. ASTContext &C = CGM.getContext();
  4341. FunctionArgList Args;
  4342. ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
  4343. ImplicitParamDecl::Other);
  4344. ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4345. KmpTaskTWithPrivatesPtrQTy.withRestrict(),
  4346. ImplicitParamDecl::Other);
  4347. Args.push_back(&GtidArg);
  4348. Args.push_back(&TaskTypeArg);
  4349. const auto &DestructorFnInfo =
  4350. CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
  4351. llvm::FunctionType *DestructorFnTy =
  4352. CGM.getTypes().GetFunctionType(DestructorFnInfo);
  4353. std::string Name =
  4354. CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
  4355. auto *DestructorFn =
  4356. llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
  4357. Name, &CGM.getModule());
  4358. CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
  4359. DestructorFnInfo);
  4360. DestructorFn->setDoesNotRecurse();
  4361. CodeGenFunction CGF(CGM);
  4362. CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
  4363. Args, Loc, Loc);
  4364. LValue Base = CGF.EmitLoadOfPointerLValue(
  4365. CGF.GetAddrOfLocalVar(&TaskTypeArg),
  4366. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4367. const auto *KmpTaskTWithPrivatesQTyRD =
  4368. cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
  4369. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4370. Base = CGF.EmitLValueForField(Base, *FI);
  4371. for (const auto *Field :
  4372. cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
  4373. if (QualType::DestructionKind DtorKind =
  4374. Field->getType().isDestructedType()) {
  4375. LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
  4376. CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
  4377. }
  4378. }
  4379. CGF.FinishFunction();
  4380. return DestructorFn;
  4381. }
  4382. /// Emit a privates mapping function for correct handling of private and
  4383. /// firstprivate variables.
  4384. /// \code
  4385. /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
  4386. /// **noalias priv1,..., <tyn> **noalias privn) {
  4387. /// *priv1 = &.privates.priv1;
  4388. /// ...;
  4389. /// *privn = &.privates.privn;
  4390. /// }
  4391. /// \endcode
  4392. static llvm::Value *
  4393. emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
  4394. ArrayRef<const Expr *> PrivateVars,
  4395. ArrayRef<const Expr *> FirstprivateVars,
  4396. ArrayRef<const Expr *> LastprivateVars,
  4397. QualType PrivatesQTy,
  4398. ArrayRef<PrivateDataTy> Privates) {
  4399. ASTContext &C = CGM.getContext();
  4400. FunctionArgList Args;
  4401. ImplicitParamDecl TaskPrivatesArg(
  4402. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4403. C.getPointerType(PrivatesQTy).withConst().withRestrict(),
  4404. ImplicitParamDecl::Other);
  4405. Args.push_back(&TaskPrivatesArg);
  4406. llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
  4407. unsigned Counter = 1;
  4408. for (const Expr *E : PrivateVars) {
  4409. Args.push_back(ImplicitParamDecl::Create(
  4410. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4411. C.getPointerType(C.getPointerType(E->getType()))
  4412. .withConst()
  4413. .withRestrict(),
  4414. ImplicitParamDecl::Other));
  4415. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4416. PrivateVarsPos[VD] = Counter;
  4417. ++Counter;
  4418. }
  4419. for (const Expr *E : FirstprivateVars) {
  4420. Args.push_back(ImplicitParamDecl::Create(
  4421. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4422. C.getPointerType(C.getPointerType(E->getType()))
  4423. .withConst()
  4424. .withRestrict(),
  4425. ImplicitParamDecl::Other));
  4426. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4427. PrivateVarsPos[VD] = Counter;
  4428. ++Counter;
  4429. }
  4430. for (const Expr *E : LastprivateVars) {
  4431. Args.push_back(ImplicitParamDecl::Create(
  4432. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4433. C.getPointerType(C.getPointerType(E->getType()))
  4434. .withConst()
  4435. .withRestrict(),
  4436. ImplicitParamDecl::Other));
  4437. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4438. PrivateVarsPos[VD] = Counter;
  4439. ++Counter;
  4440. }
  4441. const auto &TaskPrivatesMapFnInfo =
  4442. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  4443. llvm::FunctionType *TaskPrivatesMapTy =
  4444. CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
  4445. std::string Name =
  4446. CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
  4447. auto *TaskPrivatesMap = llvm::Function::Create(
  4448. TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
  4449. &CGM.getModule());
  4450. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
  4451. TaskPrivatesMapFnInfo);
  4452. if (CGM.getLangOpts().Optimize) {
  4453. TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
  4454. TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
  4455. TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
  4456. }
  4457. CodeGenFunction CGF(CGM);
  4458. CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
  4459. TaskPrivatesMapFnInfo, Args, Loc, Loc);
  4460. // *privi = &.privates.privi;
  4461. LValue Base = CGF.EmitLoadOfPointerLValue(
  4462. CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
  4463. TaskPrivatesArg.getType()->castAs<PointerType>());
  4464. const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
  4465. Counter = 0;
  4466. for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
  4467. LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
  4468. const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
  4469. LValue RefLVal =
  4470. CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
  4471. LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
  4472. RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
  4473. CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
  4474. ++Counter;
  4475. }
  4476. CGF.FinishFunction();
  4477. return TaskPrivatesMap;
  4478. }
  4479. /// Emit initialization for private variables in task-based directives.
  4480. static void emitPrivatesInit(CodeGenFunction &CGF,
  4481. const OMPExecutableDirective &D,
  4482. Address KmpTaskSharedsPtr, LValue TDBase,
  4483. const RecordDecl *KmpTaskTWithPrivatesQTyRD,
  4484. QualType SharedsTy, QualType SharedsPtrTy,
  4485. const OMPTaskDataTy &Data,
  4486. ArrayRef<PrivateDataTy> Privates, bool ForDup) {
  4487. ASTContext &C = CGF.getContext();
  4488. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4489. LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
  4490. OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
  4491. ? OMPD_taskloop
  4492. : OMPD_task;
  4493. const CapturedStmt &CS = *D.getCapturedStmt(Kind);
  4494. CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
  4495. LValue SrcBase;
  4496. bool IsTargetTask =
  4497. isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
  4498. isOpenMPTargetExecutionDirective(D.getDirectiveKind());
  4499. // For target-based directives skip 3 firstprivate arrays BasePointersArray,
  4500. // PointersArray and SizesArray. The original variables for these arrays are
  4501. // not captured and we get their addresses explicitly.
  4502. if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
  4503. (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
  4504. SrcBase = CGF.MakeAddrLValue(
  4505. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4506. KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
  4507. SharedsTy);
  4508. }
  4509. FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
  4510. for (const PrivateDataTy &Pair : Privates) {
  4511. const VarDecl *VD = Pair.second.PrivateCopy;
  4512. const Expr *Init = VD->getAnyInitializer();
  4513. if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
  4514. !CGF.isTrivialInitializer(Init)))) {
  4515. LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
  4516. if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
  4517. const VarDecl *OriginalVD = Pair.second.Original;
  4518. // Check if the variable is the target-based BasePointersArray,
  4519. // PointersArray or SizesArray.
  4520. LValue SharedRefLValue;
  4521. QualType Type = PrivateLValue.getType();
  4522. const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
  4523. if (IsTargetTask && !SharedField) {
  4524. assert(isa<ImplicitParamDecl>(OriginalVD) &&
  4525. isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
  4526. cast<CapturedDecl>(OriginalVD->getDeclContext())
  4527. ->getNumParams() == 0 &&
  4528. isa<TranslationUnitDecl>(
  4529. cast<CapturedDecl>(OriginalVD->getDeclContext())
  4530. ->getDeclContext()) &&
  4531. "Expected artificial target data variable.");
  4532. SharedRefLValue =
  4533. CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
  4534. } else {
  4535. SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
  4536. SharedRefLValue = CGF.MakeAddrLValue(
  4537. Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
  4538. SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
  4539. SharedRefLValue.getTBAAInfo());
  4540. }
  4541. if (Type->isArrayType()) {
  4542. // Initialize firstprivate array.
  4543. if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
  4544. // Perform simple memcpy.
  4545. CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
  4546. } else {
  4547. // Initialize firstprivate array using element-by-element
  4548. // initialization.
  4549. CGF.EmitOMPAggregateAssign(
  4550. PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
  4551. [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
  4552. Address SrcElement) {
  4553. // Clean up any temporaries needed by the initialization.
  4554. CodeGenFunction::OMPPrivateScope InitScope(CGF);
  4555. InitScope.addPrivate(
  4556. Elem, [SrcElement]() -> Address { return SrcElement; });
  4557. (void)InitScope.Privatize();
  4558. // Emit initialization for single element.
  4559. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
  4560. CGF, &CapturesInfo);
  4561. CGF.EmitAnyExprToMem(Init, DestElement,
  4562. Init->getType().getQualifiers(),
  4563. /*IsInitializer=*/false);
  4564. });
  4565. }
  4566. } else {
  4567. CodeGenFunction::OMPPrivateScope InitScope(CGF);
  4568. InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
  4569. return SharedRefLValue.getAddress();
  4570. });
  4571. (void)InitScope.Privatize();
  4572. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
  4573. CGF.EmitExprAsInit(Init, VD, PrivateLValue,
  4574. /*capturedByInit=*/false);
  4575. }
  4576. } else {
  4577. CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
  4578. }
  4579. }
  4580. ++FI;
  4581. }
  4582. }
  4583. /// Check if duplication function is required for taskloops.
  4584. static bool checkInitIsRequired(CodeGenFunction &CGF,
  4585. ArrayRef<PrivateDataTy> Privates) {
  4586. bool InitRequired = false;
  4587. for (const PrivateDataTy &Pair : Privates) {
  4588. const VarDecl *VD = Pair.second.PrivateCopy;
  4589. const Expr *Init = VD->getAnyInitializer();
  4590. InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
  4591. !CGF.isTrivialInitializer(Init));
  4592. if (InitRequired)
  4593. break;
  4594. }
  4595. return InitRequired;
  4596. }
  4597. /// Emit task_dup function (for initialization of
  4598. /// private/firstprivate/lastprivate vars and last_iter flag)
  4599. /// \code
  4600. /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
  4601. /// lastpriv) {
  4602. /// // setup lastprivate flag
  4603. /// task_dst->last = lastpriv;
  4604. /// // could be constructor calls here...
  4605. /// }
  4606. /// \endcode
  4607. static llvm::Value *
  4608. emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
  4609. const OMPExecutableDirective &D,
  4610. QualType KmpTaskTWithPrivatesPtrQTy,
  4611. const RecordDecl *KmpTaskTWithPrivatesQTyRD,
  4612. const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
  4613. QualType SharedsPtrTy, const OMPTaskDataTy &Data,
  4614. ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
  4615. ASTContext &C = CGM.getContext();
  4616. FunctionArgList Args;
  4617. ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4618. KmpTaskTWithPrivatesPtrQTy,
  4619. ImplicitParamDecl::Other);
  4620. ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4621. KmpTaskTWithPrivatesPtrQTy,
  4622. ImplicitParamDecl::Other);
  4623. ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  4624. ImplicitParamDecl::Other);
  4625. Args.push_back(&DstArg);
  4626. Args.push_back(&SrcArg);
  4627. Args.push_back(&LastprivArg);
  4628. const auto &TaskDupFnInfo =
  4629. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  4630. llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
  4631. std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
  4632. auto *TaskDup = llvm::Function::Create(
  4633. TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
  4634. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
  4635. TaskDup->setDoesNotRecurse();
  4636. CodeGenFunction CGF(CGM);
  4637. CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
  4638. Loc);
  4639. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4640. CGF.GetAddrOfLocalVar(&DstArg),
  4641. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4642. // task_dst->liter = lastpriv;
  4643. if (WithLastIter) {
  4644. auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
  4645. LValue Base = CGF.EmitLValueForField(
  4646. TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4647. LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
  4648. llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
  4649. CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
  4650. CGF.EmitStoreOfScalar(Lastpriv, LILVal);
  4651. }
  4652. // Emit initial values for private copies (if any).
  4653. assert(!Privates.empty());
  4654. Address KmpTaskSharedsPtr = Address::invalid();
  4655. if (!Data.FirstprivateVars.empty()) {
  4656. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4657. CGF.GetAddrOfLocalVar(&SrcArg),
  4658. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4659. LValue Base = CGF.EmitLValueForField(
  4660. TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4661. KmpTaskSharedsPtr = Address(
  4662. CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
  4663. Base, *std::next(KmpTaskTQTyRD->field_begin(),
  4664. KmpTaskTShareds)),
  4665. Loc),
  4666. CGF.getNaturalTypeAlignment(SharedsTy));
  4667. }
  4668. emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
  4669. SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
  4670. CGF.FinishFunction();
  4671. return TaskDup;
  4672. }
  4673. /// Checks if destructor function is required to be generated.
  4674. /// \return true if cleanups are required, false otherwise.
  4675. static bool
  4676. checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
  4677. bool NeedsCleanup = false;
  4678. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
  4679. const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
  4680. for (const FieldDecl *FD : PrivateRD->fields()) {
  4681. NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
  4682. if (NeedsCleanup)
  4683. break;
  4684. }
  4685. return NeedsCleanup;
  4686. }
  4687. CGOpenMPRuntime::TaskResultTy
  4688. CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
  4689. const OMPExecutableDirective &D,
  4690. llvm::Function *TaskFunction, QualType SharedsTy,
  4691. Address Shareds, const OMPTaskDataTy &Data) {
  4692. ASTContext &C = CGM.getContext();
  4693. llvm::SmallVector<PrivateDataTy, 4> Privates;
  4694. // Aggregate privates and sort them by the alignment.
  4695. auto I = Data.PrivateCopies.begin();
  4696. for (const Expr *E : Data.PrivateVars) {
  4697. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4698. Privates.emplace_back(
  4699. C.getDeclAlign(VD),
  4700. PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4701. /*PrivateElemInit=*/nullptr));
  4702. ++I;
  4703. }
  4704. I = Data.FirstprivateCopies.begin();
  4705. auto IElemInitRef = Data.FirstprivateInits.begin();
  4706. for (const Expr *E : Data.FirstprivateVars) {
  4707. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4708. Privates.emplace_back(
  4709. C.getDeclAlign(VD),
  4710. PrivateHelpersTy(
  4711. VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4712. cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
  4713. ++I;
  4714. ++IElemInitRef;
  4715. }
  4716. I = Data.LastprivateCopies.begin();
  4717. for (const Expr *E : Data.LastprivateVars) {
  4718. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4719. Privates.emplace_back(
  4720. C.getDeclAlign(VD),
  4721. PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4722. /*PrivateElemInit=*/nullptr));
  4723. ++I;
  4724. }
  4725. llvm::stable_sort(Privates, [](PrivateDataTy L, PrivateDataTy R) {
  4726. return L.first > R.first;
  4727. });
  4728. QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  4729. // Build type kmp_routine_entry_t (if not built yet).
  4730. emitKmpRoutineEntryT(KmpInt32Ty);
  4731. // Build type kmp_task_t (if not built yet).
  4732. if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
  4733. if (SavedKmpTaskloopTQTy.isNull()) {
  4734. SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
  4735. CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
  4736. }
  4737. KmpTaskTQTy = SavedKmpTaskloopTQTy;
  4738. } else {
  4739. assert((D.getDirectiveKind() == OMPD_task ||
  4740. isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
  4741. isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
  4742. "Expected taskloop, task or target directive");
  4743. if (SavedKmpTaskTQTy.isNull()) {
  4744. SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
  4745. CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
  4746. }
  4747. KmpTaskTQTy = SavedKmpTaskTQTy;
  4748. }
  4749. const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
  4750. // Build particular struct kmp_task_t for the given task.
  4751. const RecordDecl *KmpTaskTWithPrivatesQTyRD =
  4752. createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
  4753. QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
  4754. QualType KmpTaskTWithPrivatesPtrQTy =
  4755. C.getPointerType(KmpTaskTWithPrivatesQTy);
  4756. llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
  4757. llvm::Type *KmpTaskTWithPrivatesPtrTy =
  4758. KmpTaskTWithPrivatesTy->getPointerTo();
  4759. llvm::Value *KmpTaskTWithPrivatesTySize =
  4760. CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
  4761. QualType SharedsPtrTy = C.getPointerType(SharedsTy);
  4762. // Emit initial values for private copies (if any).
  4763. llvm::Value *TaskPrivatesMap = nullptr;
  4764. llvm::Type *TaskPrivatesMapTy =
  4765. std::next(TaskFunction->arg_begin(), 3)->getType();
  4766. if (!Privates.empty()) {
  4767. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4768. TaskPrivatesMap = emitTaskPrivateMappingFunction(
  4769. CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
  4770. FI->getType(), Privates);
  4771. TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4772. TaskPrivatesMap, TaskPrivatesMapTy);
  4773. } else {
  4774. TaskPrivatesMap = llvm::ConstantPointerNull::get(
  4775. cast<llvm::PointerType>(TaskPrivatesMapTy));
  4776. }
  4777. // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
  4778. // kmp_task_t *tt);
  4779. llvm::Function *TaskEntry = emitProxyTaskFunction(
  4780. CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
  4781. KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
  4782. TaskPrivatesMap);
  4783. // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  4784. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  4785. // kmp_routine_entry_t *task_entry);
  4786. // Task flags. Format is taken from
  4787. // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h,
  4788. // description of kmp_tasking_flags struct.
  4789. enum {
  4790. TiedFlag = 0x1,
  4791. FinalFlag = 0x2,
  4792. DestructorsFlag = 0x8,
  4793. PriorityFlag = 0x20
  4794. };
  4795. unsigned Flags = Data.Tied ? TiedFlag : 0;
  4796. bool NeedsCleanup = false;
  4797. if (!Privates.empty()) {
  4798. NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
  4799. if (NeedsCleanup)
  4800. Flags = Flags | DestructorsFlag;
  4801. }
  4802. if (Data.Priority.getInt())
  4803. Flags = Flags | PriorityFlag;
  4804. llvm::Value *TaskFlags =
  4805. Data.Final.getPointer()
  4806. ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
  4807. CGF.Builder.getInt32(FinalFlag),
  4808. CGF.Builder.getInt32(/*C=*/0))
  4809. : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
  4810. TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
  4811. llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
  4812. SmallVector<llvm::Value *, 8> AllocArgs = {emitUpdateLocation(CGF, Loc),
  4813. getThreadID(CGF, Loc), TaskFlags, KmpTaskTWithPrivatesTySize,
  4814. SharedsSize, CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4815. TaskEntry, KmpRoutineEntryPtrTy)};
  4816. llvm::Value *NewTask;
  4817. if (D.hasClausesOfKind<OMPNowaitClause>()) {
  4818. // Check if we have any device clause associated with the directive.
  4819. const Expr *Device = nullptr;
  4820. if (auto *C = D.getSingleClause<OMPDeviceClause>())
  4821. Device = C->getDevice();
  4822. // Emit device ID if any otherwise use default value.
  4823. llvm::Value *DeviceID;
  4824. if (Device)
  4825. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  4826. CGF.Int64Ty, /*isSigned=*/true);
  4827. else
  4828. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  4829. AllocArgs.push_back(DeviceID);
  4830. NewTask = CGF.EmitRuntimeCall(
  4831. createRuntimeFunction(OMPRTL__kmpc_omp_target_task_alloc), AllocArgs);
  4832. } else {
  4833. NewTask = CGF.EmitRuntimeCall(
  4834. createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
  4835. }
  4836. llvm::Value *NewTaskNewTaskTTy =
  4837. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4838. NewTask, KmpTaskTWithPrivatesPtrTy);
  4839. LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
  4840. KmpTaskTWithPrivatesQTy);
  4841. LValue TDBase =
  4842. CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4843. // Fill the data in the resulting kmp_task_t record.
  4844. // Copy shareds if there are any.
  4845. Address KmpTaskSharedsPtr = Address::invalid();
  4846. if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
  4847. KmpTaskSharedsPtr =
  4848. Address(CGF.EmitLoadOfScalar(
  4849. CGF.EmitLValueForField(
  4850. TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
  4851. KmpTaskTShareds)),
  4852. Loc),
  4853. CGF.getNaturalTypeAlignment(SharedsTy));
  4854. LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
  4855. LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
  4856. CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
  4857. }
  4858. // Emit initial values for private copies (if any).
  4859. TaskResultTy Result;
  4860. if (!Privates.empty()) {
  4861. emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
  4862. SharedsTy, SharedsPtrTy, Data, Privates,
  4863. /*ForDup=*/false);
  4864. if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
  4865. (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
  4866. Result.TaskDupFn = emitTaskDupFunction(
  4867. CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
  4868. KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
  4869. /*WithLastIter=*/!Data.LastprivateVars.empty());
  4870. }
  4871. }
  4872. // Fields of union "kmp_cmplrdata_t" for destructors and priority.
  4873. enum { Priority = 0, Destructors = 1 };
  4874. // Provide pointer to function with destructors for privates.
  4875. auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
  4876. const RecordDecl *KmpCmplrdataUD =
  4877. (*FI)->getType()->getAsUnionType()->getDecl();
  4878. if (NeedsCleanup) {
  4879. llvm::Value *DestructorFn = emitDestructorsFunction(
  4880. CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
  4881. KmpTaskTWithPrivatesQTy);
  4882. LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
  4883. LValue DestructorsLV = CGF.EmitLValueForField(
  4884. Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
  4885. CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4886. DestructorFn, KmpRoutineEntryPtrTy),
  4887. DestructorsLV);
  4888. }
  4889. // Set priority.
  4890. if (Data.Priority.getInt()) {
  4891. LValue Data2LV = CGF.EmitLValueForField(
  4892. TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
  4893. LValue PriorityLV = CGF.EmitLValueForField(
  4894. Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
  4895. CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
  4896. }
  4897. Result.NewTask = NewTask;
  4898. Result.TaskEntry = TaskEntry;
  4899. Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
  4900. Result.TDBase = TDBase;
  4901. Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
  4902. return Result;
  4903. }
  4904. void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
  4905. const OMPExecutableDirective &D,
  4906. llvm::Function *TaskFunction,
  4907. QualType SharedsTy, Address Shareds,
  4908. const Expr *IfCond,
  4909. const OMPTaskDataTy &Data) {
  4910. if (!CGF.HaveInsertPoint())
  4911. return;
  4912. TaskResultTy Result =
  4913. emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
  4914. llvm::Value *NewTask = Result.NewTask;
  4915. llvm::Function *TaskEntry = Result.TaskEntry;
  4916. llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
  4917. LValue TDBase = Result.TDBase;
  4918. const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
  4919. ASTContext &C = CGM.getContext();
  4920. // Process list of dependences.
  4921. Address DependenciesArray = Address::invalid();
  4922. unsigned NumDependencies = Data.Dependences.size();
  4923. if (NumDependencies) {
  4924. // Dependence kind for RTL.
  4925. enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3, DepMutexInOutSet = 0x4 };
  4926. enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
  4927. RecordDecl *KmpDependInfoRD;
  4928. QualType FlagsTy =
  4929. C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
  4930. llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
  4931. if (KmpDependInfoTy.isNull()) {
  4932. KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
  4933. KmpDependInfoRD->startDefinition();
  4934. addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
  4935. addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
  4936. addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
  4937. KmpDependInfoRD->completeDefinition();
  4938. KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
  4939. } else {
  4940. KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
  4941. }
  4942. // Define type kmp_depend_info[<Dependences.size()>];
  4943. QualType KmpDependInfoArrayTy = C.getConstantArrayType(
  4944. KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
  4945. ArrayType::Normal, /*IndexTypeQuals=*/0);
  4946. // kmp_depend_info[<Dependences.size()>] deps;
  4947. DependenciesArray =
  4948. CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
  4949. for (unsigned I = 0; I < NumDependencies; ++I) {
  4950. const Expr *E = Data.Dependences[I].second;
  4951. LValue Addr = CGF.EmitLValue(E);
  4952. llvm::Value *Size;
  4953. QualType Ty = E->getType();
  4954. if (const auto *ASE =
  4955. dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
  4956. LValue UpAddrLVal =
  4957. CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
  4958. llvm::Value *UpAddr =
  4959. CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
  4960. llvm::Value *LowIntPtr =
  4961. CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
  4962. llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
  4963. Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
  4964. } else {
  4965. Size = CGF.getTypeSize(Ty);
  4966. }
  4967. LValue Base = CGF.MakeAddrLValue(
  4968. CGF.Builder.CreateConstArrayGEP(DependenciesArray, I),
  4969. KmpDependInfoTy);
  4970. // deps[i].base_addr = &<Dependences[i].second>;
  4971. LValue BaseAddrLVal = CGF.EmitLValueForField(
  4972. Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
  4973. CGF.EmitStoreOfScalar(
  4974. CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
  4975. BaseAddrLVal);
  4976. // deps[i].len = sizeof(<Dependences[i].second>);
  4977. LValue LenLVal = CGF.EmitLValueForField(
  4978. Base, *std::next(KmpDependInfoRD->field_begin(), Len));
  4979. CGF.EmitStoreOfScalar(Size, LenLVal);
  4980. // deps[i].flags = <Dependences[i].first>;
  4981. RTLDependenceKindTy DepKind;
  4982. switch (Data.Dependences[I].first) {
  4983. case OMPC_DEPEND_in:
  4984. DepKind = DepIn;
  4985. break;
  4986. // Out and InOut dependencies must use the same code.
  4987. case OMPC_DEPEND_out:
  4988. case OMPC_DEPEND_inout:
  4989. DepKind = DepInOut;
  4990. break;
  4991. case OMPC_DEPEND_mutexinoutset:
  4992. DepKind = DepMutexInOutSet;
  4993. break;
  4994. case OMPC_DEPEND_source:
  4995. case OMPC_DEPEND_sink:
  4996. case OMPC_DEPEND_unknown:
  4997. llvm_unreachable("Unknown task dependence type");
  4998. }
  4999. LValue FlagsLVal = CGF.EmitLValueForField(
  5000. Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
  5001. CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
  5002. FlagsLVal);
  5003. }
  5004. DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5005. CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0), CGF.VoidPtrTy);
  5006. }
  5007. // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
  5008. // libcall.
  5009. // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
  5010. // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
  5011. // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
  5012. // list is not empty
  5013. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  5014. llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
  5015. llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
  5016. llvm::Value *DepTaskArgs[7];
  5017. if (NumDependencies) {
  5018. DepTaskArgs[0] = UpLoc;
  5019. DepTaskArgs[1] = ThreadID;
  5020. DepTaskArgs[2] = NewTask;
  5021. DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
  5022. DepTaskArgs[4] = DependenciesArray.getPointer();
  5023. DepTaskArgs[5] = CGF.Builder.getInt32(0);
  5024. DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  5025. }
  5026. auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
  5027. &TaskArgs,
  5028. &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
  5029. if (!Data.Tied) {
  5030. auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
  5031. LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
  5032. CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
  5033. }
  5034. if (NumDependencies) {
  5035. CGF.EmitRuntimeCall(
  5036. createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
  5037. } else {
  5038. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
  5039. TaskArgs);
  5040. }
  5041. // Check if parent region is untied and build return for untied task;
  5042. if (auto *Region =
  5043. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  5044. Region->emitUntiedSwitch(CGF);
  5045. };
  5046. llvm::Value *DepWaitTaskArgs[6];
  5047. if (NumDependencies) {
  5048. DepWaitTaskArgs[0] = UpLoc;
  5049. DepWaitTaskArgs[1] = ThreadID;
  5050. DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
  5051. DepWaitTaskArgs[3] = DependenciesArray.getPointer();
  5052. DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
  5053. DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  5054. }
  5055. auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
  5056. NumDependencies, &DepWaitTaskArgs,
  5057. Loc](CodeGenFunction &CGF, PrePostActionTy &) {
  5058. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5059. CodeGenFunction::RunCleanupsScope LocalScope(CGF);
  5060. // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
  5061. // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
  5062. // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
  5063. // is specified.
  5064. if (NumDependencies)
  5065. CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
  5066. DepWaitTaskArgs);
  5067. // Call proxy_task_entry(gtid, new_task);
  5068. auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
  5069. Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
  5070. Action.Enter(CGF);
  5071. llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
  5072. CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
  5073. OutlinedFnArgs);
  5074. };
  5075. // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
  5076. // kmp_task_t *new_task);
  5077. // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
  5078. // kmp_task_t *new_task);
  5079. RegionCodeGenTy RCG(CodeGen);
  5080. CommonActionTy Action(
  5081. RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
  5082. RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
  5083. RCG.setAction(Action);
  5084. RCG(CGF);
  5085. };
  5086. if (IfCond) {
  5087. emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
  5088. } else {
  5089. RegionCodeGenTy ThenRCG(ThenCodeGen);
  5090. ThenRCG(CGF);
  5091. }
  5092. }
  5093. void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
  5094. const OMPLoopDirective &D,
  5095. llvm::Function *TaskFunction,
  5096. QualType SharedsTy, Address Shareds,
  5097. const Expr *IfCond,
  5098. const OMPTaskDataTy &Data) {
  5099. if (!CGF.HaveInsertPoint())
  5100. return;
  5101. TaskResultTy Result =
  5102. emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
  5103. // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
  5104. // libcall.
  5105. // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
  5106. // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
  5107. // sched, kmp_uint64 grainsize, void *task_dup);
  5108. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  5109. llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
  5110. llvm::Value *IfVal;
  5111. if (IfCond) {
  5112. IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
  5113. /*isSigned=*/true);
  5114. } else {
  5115. IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
  5116. }
  5117. LValue LBLVal = CGF.EmitLValueForField(
  5118. Result.TDBase,
  5119. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
  5120. const auto *LBVar =
  5121. cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
  5122. CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
  5123. /*IsInitializer=*/true);
  5124. LValue UBLVal = CGF.EmitLValueForField(
  5125. Result.TDBase,
  5126. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
  5127. const auto *UBVar =
  5128. cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
  5129. CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
  5130. /*IsInitializer=*/true);
  5131. LValue StLVal = CGF.EmitLValueForField(
  5132. Result.TDBase,
  5133. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
  5134. const auto *StVar =
  5135. cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
  5136. CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
  5137. /*IsInitializer=*/true);
  5138. // Store reductions address.
  5139. LValue RedLVal = CGF.EmitLValueForField(
  5140. Result.TDBase,
  5141. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
  5142. if (Data.Reductions) {
  5143. CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
  5144. } else {
  5145. CGF.EmitNullInitialization(RedLVal.getAddress(),
  5146. CGF.getContext().VoidPtrTy);
  5147. }
  5148. enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
  5149. llvm::Value *TaskArgs[] = {
  5150. UpLoc,
  5151. ThreadID,
  5152. Result.NewTask,
  5153. IfVal,
  5154. LBLVal.getPointer(),
  5155. UBLVal.getPointer(),
  5156. CGF.EmitLoadOfScalar(StLVal, Loc),
  5157. llvm::ConstantInt::getSigned(
  5158. CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
  5159. llvm::ConstantInt::getSigned(
  5160. CGF.IntTy, Data.Schedule.getPointer()
  5161. ? Data.Schedule.getInt() ? NumTasks : Grainsize
  5162. : NoSchedule),
  5163. Data.Schedule.getPointer()
  5164. ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
  5165. /*isSigned=*/false)
  5166. : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
  5167. Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5168. Result.TaskDupFn, CGF.VoidPtrTy)
  5169. : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
  5170. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
  5171. }
  5172. /// Emit reduction operation for each element of array (required for
  5173. /// array sections) LHS op = RHS.
  5174. /// \param Type Type of array.
  5175. /// \param LHSVar Variable on the left side of the reduction operation
  5176. /// (references element of array in original variable).
  5177. /// \param RHSVar Variable on the right side of the reduction operation
  5178. /// (references element of array in original variable).
  5179. /// \param RedOpGen Generator of reduction operation with use of LHSVar and
  5180. /// RHSVar.
  5181. static void EmitOMPAggregateReduction(
  5182. CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
  5183. const VarDecl *RHSVar,
  5184. const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
  5185. const Expr *, const Expr *)> &RedOpGen,
  5186. const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
  5187. const Expr *UpExpr = nullptr) {
  5188. // Perform element-by-element initialization.
  5189. QualType ElementTy;
  5190. Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
  5191. Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
  5192. // Drill down to the base element type on both arrays.
  5193. const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
  5194. llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
  5195. llvm::Value *RHSBegin = RHSAddr.getPointer();
  5196. llvm::Value *LHSBegin = LHSAddr.getPointer();
  5197. // Cast from pointer to array type to pointer to single element.
  5198. llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
  5199. // The basic structure here is a while-do loop.
  5200. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
  5201. llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
  5202. llvm::Value *IsEmpty =
  5203. CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
  5204. CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  5205. // Enter the loop body, making that address the current address.
  5206. llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
  5207. CGF.EmitBlock(BodyBB);
  5208. CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
  5209. llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
  5210. RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
  5211. RHSElementPHI->addIncoming(RHSBegin, EntryBB);
  5212. Address RHSElementCurrent =
  5213. Address(RHSElementPHI,
  5214. RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  5215. llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
  5216. LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
  5217. LHSElementPHI->addIncoming(LHSBegin, EntryBB);
  5218. Address LHSElementCurrent =
  5219. Address(LHSElementPHI,
  5220. LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  5221. // Emit copy.
  5222. CodeGenFunction::OMPPrivateScope Scope(CGF);
  5223. Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
  5224. Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
  5225. Scope.Privatize();
  5226. RedOpGen(CGF, XExpr, EExpr, UpExpr);
  5227. Scope.ForceCleanup();
  5228. // Shift the address forward by one element.
  5229. llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
  5230. LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  5231. llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
  5232. RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
  5233. // Check whether we've reached the end.
  5234. llvm::Value *Done =
  5235. CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
  5236. CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
  5237. LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
  5238. RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
  5239. // Done.
  5240. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  5241. }
  5242. /// Emit reduction combiner. If the combiner is a simple expression emit it as
  5243. /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
  5244. /// UDR combiner function.
  5245. static void emitReductionCombiner(CodeGenFunction &CGF,
  5246. const Expr *ReductionOp) {
  5247. if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
  5248. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
  5249. if (const auto *DRE =
  5250. dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
  5251. if (const auto *DRD =
  5252. dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
  5253. std::pair<llvm::Function *, llvm::Function *> Reduction =
  5254. CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
  5255. RValue Func = RValue::get(Reduction.first);
  5256. CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
  5257. CGF.EmitIgnoredExpr(ReductionOp);
  5258. return;
  5259. }
  5260. CGF.EmitIgnoredExpr(ReductionOp);
  5261. }
  5262. llvm::Function *CGOpenMPRuntime::emitReductionFunction(
  5263. SourceLocation Loc, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
  5264. ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
  5265. ArrayRef<const Expr *> ReductionOps) {
  5266. ASTContext &C = CGM.getContext();
  5267. // void reduction_func(void *LHSArg, void *RHSArg);
  5268. FunctionArgList Args;
  5269. ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5270. ImplicitParamDecl::Other);
  5271. ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5272. ImplicitParamDecl::Other);
  5273. Args.push_back(&LHSArg);
  5274. Args.push_back(&RHSArg);
  5275. const auto &CGFI =
  5276. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5277. std::string Name = getName({"omp", "reduction", "reduction_func"});
  5278. auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
  5279. llvm::GlobalValue::InternalLinkage, Name,
  5280. &CGM.getModule());
  5281. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  5282. Fn->setDoesNotRecurse();
  5283. CodeGenFunction CGF(CGM);
  5284. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  5285. // Dst = (void*[n])(LHSArg);
  5286. // Src = (void*[n])(RHSArg);
  5287. Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5288. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
  5289. ArgsType), CGF.getPointerAlign());
  5290. Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5291. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
  5292. ArgsType), CGF.getPointerAlign());
  5293. // ...
  5294. // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
  5295. // ...
  5296. CodeGenFunction::OMPPrivateScope Scope(CGF);
  5297. auto IPriv = Privates.begin();
  5298. unsigned Idx = 0;
  5299. for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
  5300. const auto *RHSVar =
  5301. cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
  5302. Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
  5303. return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
  5304. });
  5305. const auto *LHSVar =
  5306. cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
  5307. Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
  5308. return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
  5309. });
  5310. QualType PrivTy = (*IPriv)->getType();
  5311. if (PrivTy->isVariablyModifiedType()) {
  5312. // Get array size and emit VLA type.
  5313. ++Idx;
  5314. Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx);
  5315. llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
  5316. const VariableArrayType *VLA =
  5317. CGF.getContext().getAsVariableArrayType(PrivTy);
  5318. const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
  5319. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  5320. CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
  5321. CGF.EmitVariablyModifiedType(PrivTy);
  5322. }
  5323. }
  5324. Scope.Privatize();
  5325. IPriv = Privates.begin();
  5326. auto ILHS = LHSExprs.begin();
  5327. auto IRHS = RHSExprs.begin();
  5328. for (const Expr *E : ReductionOps) {
  5329. if ((*IPriv)->getType()->isArrayType()) {
  5330. // Emit reduction for array section.
  5331. const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5332. const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5333. EmitOMPAggregateReduction(
  5334. CGF, (*IPriv)->getType(), LHSVar, RHSVar,
  5335. [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
  5336. emitReductionCombiner(CGF, E);
  5337. });
  5338. } else {
  5339. // Emit reduction for array subscript or single variable.
  5340. emitReductionCombiner(CGF, E);
  5341. }
  5342. ++IPriv;
  5343. ++ILHS;
  5344. ++IRHS;
  5345. }
  5346. Scope.ForceCleanup();
  5347. CGF.FinishFunction();
  5348. return Fn;
  5349. }
  5350. void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
  5351. const Expr *ReductionOp,
  5352. const Expr *PrivateRef,
  5353. const DeclRefExpr *LHS,
  5354. const DeclRefExpr *RHS) {
  5355. if (PrivateRef->getType()->isArrayType()) {
  5356. // Emit reduction for array section.
  5357. const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
  5358. const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
  5359. EmitOMPAggregateReduction(
  5360. CGF, PrivateRef->getType(), LHSVar, RHSVar,
  5361. [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
  5362. emitReductionCombiner(CGF, ReductionOp);
  5363. });
  5364. } else {
  5365. // Emit reduction for array subscript or single variable.
  5366. emitReductionCombiner(CGF, ReductionOp);
  5367. }
  5368. }
  5369. void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
  5370. ArrayRef<const Expr *> Privates,
  5371. ArrayRef<const Expr *> LHSExprs,
  5372. ArrayRef<const Expr *> RHSExprs,
  5373. ArrayRef<const Expr *> ReductionOps,
  5374. ReductionOptionsTy Options) {
  5375. if (!CGF.HaveInsertPoint())
  5376. return;
  5377. bool WithNowait = Options.WithNowait;
  5378. bool SimpleReduction = Options.SimpleReduction;
  5379. // Next code should be emitted for reduction:
  5380. //
  5381. // static kmp_critical_name lock = { 0 };
  5382. //
  5383. // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
  5384. // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
  5385. // ...
  5386. // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
  5387. // *(Type<n>-1*)rhs[<n>-1]);
  5388. // }
  5389. //
  5390. // ...
  5391. // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
  5392. // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
  5393. // RedList, reduce_func, &<lock>)) {
  5394. // case 1:
  5395. // ...
  5396. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5397. // ...
  5398. // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5399. // break;
  5400. // case 2:
  5401. // ...
  5402. // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
  5403. // ...
  5404. // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
  5405. // break;
  5406. // default:;
  5407. // }
  5408. //
  5409. // if SimpleReduction is true, only the next code is generated:
  5410. // ...
  5411. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5412. // ...
  5413. ASTContext &C = CGM.getContext();
  5414. if (SimpleReduction) {
  5415. CodeGenFunction::RunCleanupsScope Scope(CGF);
  5416. auto IPriv = Privates.begin();
  5417. auto ILHS = LHSExprs.begin();
  5418. auto IRHS = RHSExprs.begin();
  5419. for (const Expr *E : ReductionOps) {
  5420. emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
  5421. cast<DeclRefExpr>(*IRHS));
  5422. ++IPriv;
  5423. ++ILHS;
  5424. ++IRHS;
  5425. }
  5426. return;
  5427. }
  5428. // 1. Build a list of reduction variables.
  5429. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  5430. auto Size = RHSExprs.size();
  5431. for (const Expr *E : Privates) {
  5432. if (E->getType()->isVariablyModifiedType())
  5433. // Reserve place for array size.
  5434. ++Size;
  5435. }
  5436. llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
  5437. QualType ReductionArrayTy =
  5438. C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
  5439. /*IndexTypeQuals=*/0);
  5440. Address ReductionList =
  5441. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  5442. auto IPriv = Privates.begin();
  5443. unsigned Idx = 0;
  5444. for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
  5445. Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  5446. CGF.Builder.CreateStore(
  5447. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5448. CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
  5449. Elem);
  5450. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  5451. // Store array size.
  5452. ++Idx;
  5453. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  5454. llvm::Value *Size = CGF.Builder.CreateIntCast(
  5455. CGF.getVLASize(
  5456. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  5457. .NumElts,
  5458. CGF.SizeTy, /*isSigned=*/false);
  5459. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  5460. Elem);
  5461. }
  5462. }
  5463. // 2. Emit reduce_func().
  5464. llvm::Function *ReductionFn = emitReductionFunction(
  5465. Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
  5466. LHSExprs, RHSExprs, ReductionOps);
  5467. // 3. Create static kmp_critical_name lock = { 0 };
  5468. std::string Name = getName({"reduction"});
  5469. llvm::Value *Lock = getCriticalRegionLock(Name);
  5470. // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
  5471. // RedList, reduce_func, &<lock>);
  5472. llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
  5473. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  5474. llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
  5475. llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5476. ReductionList.getPointer(), CGF.VoidPtrTy);
  5477. llvm::Value *Args[] = {
  5478. IdentTLoc, // ident_t *<loc>
  5479. ThreadId, // i32 <gtid>
  5480. CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
  5481. ReductionArrayTySize, // size_type sizeof(RedList)
  5482. RL, // void *RedList
  5483. ReductionFn, // void (*) (void *, void *) <reduce_func>
  5484. Lock // kmp_critical_name *&<lock>
  5485. };
  5486. llvm::Value *Res = CGF.EmitRuntimeCall(
  5487. createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
  5488. : OMPRTL__kmpc_reduce),
  5489. Args);
  5490. // 5. Build switch(res)
  5491. llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
  5492. llvm::SwitchInst *SwInst =
  5493. CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
  5494. // 6. Build case 1:
  5495. // ...
  5496. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5497. // ...
  5498. // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5499. // break;
  5500. llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
  5501. SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
  5502. CGF.EmitBlock(Case1BB);
  5503. // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5504. llvm::Value *EndArgs[] = {
  5505. IdentTLoc, // ident_t *<loc>
  5506. ThreadId, // i32 <gtid>
  5507. Lock // kmp_critical_name *&<lock>
  5508. };
  5509. auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
  5510. CodeGenFunction &CGF, PrePostActionTy &Action) {
  5511. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5512. auto IPriv = Privates.begin();
  5513. auto ILHS = LHSExprs.begin();
  5514. auto IRHS = RHSExprs.begin();
  5515. for (const Expr *E : ReductionOps) {
  5516. RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
  5517. cast<DeclRefExpr>(*IRHS));
  5518. ++IPriv;
  5519. ++ILHS;
  5520. ++IRHS;
  5521. }
  5522. };
  5523. RegionCodeGenTy RCG(CodeGen);
  5524. CommonActionTy Action(
  5525. nullptr, llvm::None,
  5526. createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
  5527. : OMPRTL__kmpc_end_reduce),
  5528. EndArgs);
  5529. RCG.setAction(Action);
  5530. RCG(CGF);
  5531. CGF.EmitBranch(DefaultBB);
  5532. // 7. Build case 2:
  5533. // ...
  5534. // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
  5535. // ...
  5536. // break;
  5537. llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
  5538. SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
  5539. CGF.EmitBlock(Case2BB);
  5540. auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
  5541. CodeGenFunction &CGF, PrePostActionTy &Action) {
  5542. auto ILHS = LHSExprs.begin();
  5543. auto IRHS = RHSExprs.begin();
  5544. auto IPriv = Privates.begin();
  5545. for (const Expr *E : ReductionOps) {
  5546. const Expr *XExpr = nullptr;
  5547. const Expr *EExpr = nullptr;
  5548. const Expr *UpExpr = nullptr;
  5549. BinaryOperatorKind BO = BO_Comma;
  5550. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  5551. if (BO->getOpcode() == BO_Assign) {
  5552. XExpr = BO->getLHS();
  5553. UpExpr = BO->getRHS();
  5554. }
  5555. }
  5556. // Try to emit update expression as a simple atomic.
  5557. const Expr *RHSExpr = UpExpr;
  5558. if (RHSExpr) {
  5559. // Analyze RHS part of the whole expression.
  5560. if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
  5561. RHSExpr->IgnoreParenImpCasts())) {
  5562. // If this is a conditional operator, analyze its condition for
  5563. // min/max reduction operator.
  5564. RHSExpr = ACO->getCond();
  5565. }
  5566. if (const auto *BORHS =
  5567. dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
  5568. EExpr = BORHS->getRHS();
  5569. BO = BORHS->getOpcode();
  5570. }
  5571. }
  5572. if (XExpr) {
  5573. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5574. auto &&AtomicRedGen = [BO, VD,
  5575. Loc](CodeGenFunction &CGF, const Expr *XExpr,
  5576. const Expr *EExpr, const Expr *UpExpr) {
  5577. LValue X = CGF.EmitLValue(XExpr);
  5578. RValue E;
  5579. if (EExpr)
  5580. E = CGF.EmitAnyExpr(EExpr);
  5581. CGF.EmitOMPAtomicSimpleUpdateExpr(
  5582. X, E, BO, /*IsXLHSInRHSPart=*/true,
  5583. llvm::AtomicOrdering::Monotonic, Loc,
  5584. [&CGF, UpExpr, VD, Loc](RValue XRValue) {
  5585. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  5586. PrivateScope.addPrivate(
  5587. VD, [&CGF, VD, XRValue, Loc]() {
  5588. Address LHSTemp = CGF.CreateMemTemp(VD->getType());
  5589. CGF.emitOMPSimpleStore(
  5590. CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
  5591. VD->getType().getNonReferenceType(), Loc);
  5592. return LHSTemp;
  5593. });
  5594. (void)PrivateScope.Privatize();
  5595. return CGF.EmitAnyExpr(UpExpr);
  5596. });
  5597. };
  5598. if ((*IPriv)->getType()->isArrayType()) {
  5599. // Emit atomic reduction for array section.
  5600. const auto *RHSVar =
  5601. cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5602. EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
  5603. AtomicRedGen, XExpr, EExpr, UpExpr);
  5604. } else {
  5605. // Emit atomic reduction for array subscript or single variable.
  5606. AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
  5607. }
  5608. } else {
  5609. // Emit as a critical region.
  5610. auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
  5611. const Expr *, const Expr *) {
  5612. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5613. std::string Name = RT.getName({"atomic_reduction"});
  5614. RT.emitCriticalRegion(
  5615. CGF, Name,
  5616. [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
  5617. Action.Enter(CGF);
  5618. emitReductionCombiner(CGF, E);
  5619. },
  5620. Loc);
  5621. };
  5622. if ((*IPriv)->getType()->isArrayType()) {
  5623. const auto *LHSVar =
  5624. cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5625. const auto *RHSVar =
  5626. cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5627. EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
  5628. CritRedGen);
  5629. } else {
  5630. CritRedGen(CGF, nullptr, nullptr, nullptr);
  5631. }
  5632. }
  5633. ++ILHS;
  5634. ++IRHS;
  5635. ++IPriv;
  5636. }
  5637. };
  5638. RegionCodeGenTy AtomicRCG(AtomicCodeGen);
  5639. if (!WithNowait) {
  5640. // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
  5641. llvm::Value *EndArgs[] = {
  5642. IdentTLoc, // ident_t *<loc>
  5643. ThreadId, // i32 <gtid>
  5644. Lock // kmp_critical_name *&<lock>
  5645. };
  5646. CommonActionTy Action(nullptr, llvm::None,
  5647. createRuntimeFunction(OMPRTL__kmpc_end_reduce),
  5648. EndArgs);
  5649. AtomicRCG.setAction(Action);
  5650. AtomicRCG(CGF);
  5651. } else {
  5652. AtomicRCG(CGF);
  5653. }
  5654. CGF.EmitBranch(DefaultBB);
  5655. CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
  5656. }
  5657. /// Generates unique name for artificial threadprivate variables.
  5658. /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
  5659. static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
  5660. const Expr *Ref) {
  5661. SmallString<256> Buffer;
  5662. llvm::raw_svector_ostream Out(Buffer);
  5663. const clang::DeclRefExpr *DE;
  5664. const VarDecl *D = ::getBaseDecl(Ref, DE);
  5665. if (!D)
  5666. D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
  5667. D = D->getCanonicalDecl();
  5668. std::string Name = CGM.getOpenMPRuntime().getName(
  5669. {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
  5670. Out << Prefix << Name << "_"
  5671. << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
  5672. return Out.str();
  5673. }
  5674. /// Emits reduction initializer function:
  5675. /// \code
  5676. /// void @.red_init(void* %arg) {
  5677. /// %0 = bitcast void* %arg to <type>*
  5678. /// store <type> <init>, <type>* %0
  5679. /// ret void
  5680. /// }
  5681. /// \endcode
  5682. static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
  5683. SourceLocation Loc,
  5684. ReductionCodeGen &RCG, unsigned N) {
  5685. ASTContext &C = CGM.getContext();
  5686. FunctionArgList Args;
  5687. ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5688. ImplicitParamDecl::Other);
  5689. Args.emplace_back(&Param);
  5690. const auto &FnInfo =
  5691. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5692. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5693. std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
  5694. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5695. Name, &CGM.getModule());
  5696. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5697. Fn->setDoesNotRecurse();
  5698. CodeGenFunction CGF(CGM);
  5699. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5700. Address PrivateAddr = CGF.EmitLoadOfPointer(
  5701. CGF.GetAddrOfLocalVar(&Param),
  5702. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5703. llvm::Value *Size = nullptr;
  5704. // If the size of the reduction item is non-constant, load it from global
  5705. // threadprivate variable.
  5706. if (RCG.getSizes(N).second) {
  5707. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5708. CGF, CGM.getContext().getSizeType(),
  5709. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5710. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5711. CGM.getContext().getSizeType(), Loc);
  5712. }
  5713. RCG.emitAggregateType(CGF, N, Size);
  5714. LValue SharedLVal;
  5715. // If initializer uses initializer from declare reduction construct, emit a
  5716. // pointer to the address of the original reduction item (reuired by reduction
  5717. // initializer)
  5718. if (RCG.usesReductionInitializer(N)) {
  5719. Address SharedAddr =
  5720. CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5721. CGF, CGM.getContext().VoidPtrTy,
  5722. generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
  5723. SharedAddr = CGF.EmitLoadOfPointer(
  5724. SharedAddr,
  5725. CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
  5726. SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
  5727. } else {
  5728. SharedLVal = CGF.MakeNaturalAlignAddrLValue(
  5729. llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
  5730. CGM.getContext().VoidPtrTy);
  5731. }
  5732. // Emit the initializer:
  5733. // %0 = bitcast void* %arg to <type>*
  5734. // store <type> <init>, <type>* %0
  5735. RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
  5736. [](CodeGenFunction &) { return false; });
  5737. CGF.FinishFunction();
  5738. return Fn;
  5739. }
  5740. /// Emits reduction combiner function:
  5741. /// \code
  5742. /// void @.red_comb(void* %arg0, void* %arg1) {
  5743. /// %lhs = bitcast void* %arg0 to <type>*
  5744. /// %rhs = bitcast void* %arg1 to <type>*
  5745. /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
  5746. /// store <type> %2, <type>* %lhs
  5747. /// ret void
  5748. /// }
  5749. /// \endcode
  5750. static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
  5751. SourceLocation Loc,
  5752. ReductionCodeGen &RCG, unsigned N,
  5753. const Expr *ReductionOp,
  5754. const Expr *LHS, const Expr *RHS,
  5755. const Expr *PrivateRef) {
  5756. ASTContext &C = CGM.getContext();
  5757. const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
  5758. const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
  5759. FunctionArgList Args;
  5760. ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  5761. C.VoidPtrTy, ImplicitParamDecl::Other);
  5762. ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5763. ImplicitParamDecl::Other);
  5764. Args.emplace_back(&ParamInOut);
  5765. Args.emplace_back(&ParamIn);
  5766. const auto &FnInfo =
  5767. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5768. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5769. std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
  5770. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5771. Name, &CGM.getModule());
  5772. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5773. Fn->setDoesNotRecurse();
  5774. CodeGenFunction CGF(CGM);
  5775. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5776. llvm::Value *Size = nullptr;
  5777. // If the size of the reduction item is non-constant, load it from global
  5778. // threadprivate variable.
  5779. if (RCG.getSizes(N).second) {
  5780. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5781. CGF, CGM.getContext().getSizeType(),
  5782. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5783. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5784. CGM.getContext().getSizeType(), Loc);
  5785. }
  5786. RCG.emitAggregateType(CGF, N, Size);
  5787. // Remap lhs and rhs variables to the addresses of the function arguments.
  5788. // %lhs = bitcast void* %arg0 to <type>*
  5789. // %rhs = bitcast void* %arg1 to <type>*
  5790. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  5791. PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
  5792. // Pull out the pointer to the variable.
  5793. Address PtrAddr = CGF.EmitLoadOfPointer(
  5794. CGF.GetAddrOfLocalVar(&ParamInOut),
  5795. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5796. return CGF.Builder.CreateElementBitCast(
  5797. PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
  5798. });
  5799. PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
  5800. // Pull out the pointer to the variable.
  5801. Address PtrAddr = CGF.EmitLoadOfPointer(
  5802. CGF.GetAddrOfLocalVar(&ParamIn),
  5803. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5804. return CGF.Builder.CreateElementBitCast(
  5805. PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
  5806. });
  5807. PrivateScope.Privatize();
  5808. // Emit the combiner body:
  5809. // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
  5810. // store <type> %2, <type>* %lhs
  5811. CGM.getOpenMPRuntime().emitSingleReductionCombiner(
  5812. CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
  5813. cast<DeclRefExpr>(RHS));
  5814. CGF.FinishFunction();
  5815. return Fn;
  5816. }
  5817. /// Emits reduction finalizer function:
  5818. /// \code
  5819. /// void @.red_fini(void* %arg) {
  5820. /// %0 = bitcast void* %arg to <type>*
  5821. /// <destroy>(<type>* %0)
  5822. /// ret void
  5823. /// }
  5824. /// \endcode
  5825. static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
  5826. SourceLocation Loc,
  5827. ReductionCodeGen &RCG, unsigned N) {
  5828. if (!RCG.needCleanups(N))
  5829. return nullptr;
  5830. ASTContext &C = CGM.getContext();
  5831. FunctionArgList Args;
  5832. ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5833. ImplicitParamDecl::Other);
  5834. Args.emplace_back(&Param);
  5835. const auto &FnInfo =
  5836. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5837. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5838. std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
  5839. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5840. Name, &CGM.getModule());
  5841. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5842. Fn->setDoesNotRecurse();
  5843. CodeGenFunction CGF(CGM);
  5844. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5845. Address PrivateAddr = CGF.EmitLoadOfPointer(
  5846. CGF.GetAddrOfLocalVar(&Param),
  5847. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5848. llvm::Value *Size = nullptr;
  5849. // If the size of the reduction item is non-constant, load it from global
  5850. // threadprivate variable.
  5851. if (RCG.getSizes(N).second) {
  5852. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5853. CGF, CGM.getContext().getSizeType(),
  5854. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5855. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5856. CGM.getContext().getSizeType(), Loc);
  5857. }
  5858. RCG.emitAggregateType(CGF, N, Size);
  5859. // Emit the finalizer body:
  5860. // <destroy>(<type>* %0)
  5861. RCG.emitCleanups(CGF, N, PrivateAddr);
  5862. CGF.FinishFunction();
  5863. return Fn;
  5864. }
  5865. llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
  5866. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
  5867. ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
  5868. if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
  5869. return nullptr;
  5870. // Build typedef struct:
  5871. // kmp_task_red_input {
  5872. // void *reduce_shar; // shared reduction item
  5873. // size_t reduce_size; // size of data item
  5874. // void *reduce_init; // data initialization routine
  5875. // void *reduce_fini; // data finalization routine
  5876. // void *reduce_comb; // data combiner routine
  5877. // kmp_task_red_flags_t flags; // flags for additional info from compiler
  5878. // } kmp_task_red_input_t;
  5879. ASTContext &C = CGM.getContext();
  5880. RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
  5881. RD->startDefinition();
  5882. const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5883. const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
  5884. const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5885. const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5886. const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5887. const FieldDecl *FlagsFD = addFieldToRecordDecl(
  5888. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
  5889. RD->completeDefinition();
  5890. QualType RDType = C.getRecordType(RD);
  5891. unsigned Size = Data.ReductionVars.size();
  5892. llvm::APInt ArraySize(/*numBits=*/64, Size);
  5893. QualType ArrayRDType = C.getConstantArrayType(
  5894. RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
  5895. // kmp_task_red_input_t .rd_input.[Size];
  5896. Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
  5897. ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
  5898. Data.ReductionOps);
  5899. for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
  5900. // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
  5901. llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
  5902. llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
  5903. llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
  5904. TaskRedInput.getPointer(), Idxs,
  5905. /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
  5906. ".rd_input.gep.");
  5907. LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
  5908. // ElemLVal.reduce_shar = &Shareds[Cnt];
  5909. LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
  5910. RCG.emitSharedLValue(CGF, Cnt);
  5911. llvm::Value *CastedShared =
  5912. CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
  5913. CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
  5914. RCG.emitAggregateType(CGF, Cnt);
  5915. llvm::Value *SizeValInChars;
  5916. llvm::Value *SizeVal;
  5917. std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
  5918. // We use delayed creation/initialization for VLAs, array sections and
  5919. // custom reduction initializations. It is required because runtime does not
  5920. // provide the way to pass the sizes of VLAs/array sections to
  5921. // initializer/combiner/finalizer functions and does not pass the pointer to
  5922. // original reduction item to the initializer. Instead threadprivate global
  5923. // variables are used to store these values and use them in the functions.
  5924. bool DelayedCreation = !!SizeVal;
  5925. SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
  5926. /*isSigned=*/false);
  5927. LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
  5928. CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
  5929. // ElemLVal.reduce_init = init;
  5930. LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
  5931. llvm::Value *InitAddr =
  5932. CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
  5933. CGF.EmitStoreOfScalar(InitAddr, InitLVal);
  5934. DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
  5935. // ElemLVal.reduce_fini = fini;
  5936. LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
  5937. llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
  5938. llvm::Value *FiniAddr = Fini
  5939. ? CGF.EmitCastToVoidPtr(Fini)
  5940. : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
  5941. CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
  5942. // ElemLVal.reduce_comb = comb;
  5943. LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
  5944. llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
  5945. CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
  5946. RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
  5947. CGF.EmitStoreOfScalar(CombAddr, CombLVal);
  5948. // ElemLVal.flags = 0;
  5949. LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
  5950. if (DelayedCreation) {
  5951. CGF.EmitStoreOfScalar(
  5952. llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
  5953. FlagsLVal);
  5954. } else
  5955. CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
  5956. }
  5957. // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
  5958. // *data);
  5959. llvm::Value *Args[] = {
  5960. CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
  5961. /*isSigned=*/true),
  5962. llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
  5963. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
  5964. CGM.VoidPtrTy)};
  5965. return CGF.EmitRuntimeCall(
  5966. createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
  5967. }
  5968. void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
  5969. SourceLocation Loc,
  5970. ReductionCodeGen &RCG,
  5971. unsigned N) {
  5972. auto Sizes = RCG.getSizes(N);
  5973. // Emit threadprivate global variable if the type is non-constant
  5974. // (Sizes.second = nullptr).
  5975. if (Sizes.second) {
  5976. llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
  5977. /*isSigned=*/false);
  5978. Address SizeAddr = getAddrOfArtificialThreadPrivate(
  5979. CGF, CGM.getContext().getSizeType(),
  5980. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5981. CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
  5982. }
  5983. // Store address of the original reduction item if custom initializer is used.
  5984. if (RCG.usesReductionInitializer(N)) {
  5985. Address SharedAddr = getAddrOfArtificialThreadPrivate(
  5986. CGF, CGM.getContext().VoidPtrTy,
  5987. generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
  5988. CGF.Builder.CreateStore(
  5989. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5990. RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
  5991. SharedAddr, /*IsVolatile=*/false);
  5992. }
  5993. }
  5994. Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
  5995. SourceLocation Loc,
  5996. llvm::Value *ReductionsPtr,
  5997. LValue SharedLVal) {
  5998. // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
  5999. // *d);
  6000. llvm::Value *Args[] = {
  6001. CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
  6002. /*isSigned=*/true),
  6003. ReductionsPtr,
  6004. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
  6005. CGM.VoidPtrTy)};
  6006. return Address(
  6007. CGF.EmitRuntimeCall(
  6008. createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
  6009. SharedLVal.getAlignment());
  6010. }
  6011. void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
  6012. SourceLocation Loc) {
  6013. if (!CGF.HaveInsertPoint())
  6014. return;
  6015. // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
  6016. // global_tid);
  6017. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  6018. // Ignore return result until untied tasks are supported.
  6019. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
  6020. if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  6021. Region->emitUntiedSwitch(CGF);
  6022. }
  6023. void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
  6024. OpenMPDirectiveKind InnerKind,
  6025. const RegionCodeGenTy &CodeGen,
  6026. bool HasCancel) {
  6027. if (!CGF.HaveInsertPoint())
  6028. return;
  6029. InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
  6030. CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
  6031. }
  6032. namespace {
  6033. enum RTCancelKind {
  6034. CancelNoreq = 0,
  6035. CancelParallel = 1,
  6036. CancelLoop = 2,
  6037. CancelSections = 3,
  6038. CancelTaskgroup = 4
  6039. };
  6040. } // anonymous namespace
  6041. static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
  6042. RTCancelKind CancelKind = CancelNoreq;
  6043. if (CancelRegion == OMPD_parallel)
  6044. CancelKind = CancelParallel;
  6045. else if (CancelRegion == OMPD_for)
  6046. CancelKind = CancelLoop;
  6047. else if (CancelRegion == OMPD_sections)
  6048. CancelKind = CancelSections;
  6049. else {
  6050. assert(CancelRegion == OMPD_taskgroup);
  6051. CancelKind = CancelTaskgroup;
  6052. }
  6053. return CancelKind;
  6054. }
  6055. void CGOpenMPRuntime::emitCancellationPointCall(
  6056. CodeGenFunction &CGF, SourceLocation Loc,
  6057. OpenMPDirectiveKind CancelRegion) {
  6058. if (!CGF.HaveInsertPoint())
  6059. return;
  6060. // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  6061. // global_tid, kmp_int32 cncl_kind);
  6062. if (auto *OMPRegionInfo =
  6063. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  6064. // For 'cancellation point taskgroup', the task region info may not have a
  6065. // cancel. This may instead happen in another adjacent task.
  6066. if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
  6067. llvm::Value *Args[] = {
  6068. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  6069. CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
  6070. // Ignore return result until untied tasks are supported.
  6071. llvm::Value *Result = CGF.EmitRuntimeCall(
  6072. createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
  6073. // if (__kmpc_cancellationpoint()) {
  6074. // exit from construct;
  6075. // }
  6076. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  6077. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  6078. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  6079. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  6080. CGF.EmitBlock(ExitBB);
  6081. // exit from construct;
  6082. CodeGenFunction::JumpDest CancelDest =
  6083. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  6084. CGF.EmitBranchThroughCleanup(CancelDest);
  6085. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  6086. }
  6087. }
  6088. }
  6089. void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
  6090. const Expr *IfCond,
  6091. OpenMPDirectiveKind CancelRegion) {
  6092. if (!CGF.HaveInsertPoint())
  6093. return;
  6094. // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  6095. // kmp_int32 cncl_kind);
  6096. if (auto *OMPRegionInfo =
  6097. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  6098. auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
  6099. PrePostActionTy &) {
  6100. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  6101. llvm::Value *Args[] = {
  6102. RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
  6103. CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
  6104. // Ignore return result until untied tasks are supported.
  6105. llvm::Value *Result = CGF.EmitRuntimeCall(
  6106. RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
  6107. // if (__kmpc_cancel()) {
  6108. // exit from construct;
  6109. // }
  6110. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  6111. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  6112. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  6113. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  6114. CGF.EmitBlock(ExitBB);
  6115. // exit from construct;
  6116. CodeGenFunction::JumpDest CancelDest =
  6117. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  6118. CGF.EmitBranchThroughCleanup(CancelDest);
  6119. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  6120. };
  6121. if (IfCond) {
  6122. emitOMPIfClause(CGF, IfCond, ThenGen,
  6123. [](CodeGenFunction &, PrePostActionTy &) {});
  6124. } else {
  6125. RegionCodeGenTy ThenRCG(ThenGen);
  6126. ThenRCG(CGF);
  6127. }
  6128. }
  6129. }
  6130. void CGOpenMPRuntime::emitTargetOutlinedFunction(
  6131. const OMPExecutableDirective &D, StringRef ParentName,
  6132. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  6133. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  6134. assert(!ParentName.empty() && "Invalid target region parent name!");
  6135. HasEmittedTargetRegion = true;
  6136. emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
  6137. IsOffloadEntry, CodeGen);
  6138. }
  6139. void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
  6140. const OMPExecutableDirective &D, StringRef ParentName,
  6141. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  6142. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  6143. // Create a unique name for the entry function using the source location
  6144. // information of the current target region. The name will be something like:
  6145. //
  6146. // __omp_offloading_DD_FFFF_PP_lBB
  6147. //
  6148. // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
  6149. // mangled name of the function that encloses the target region and BB is the
  6150. // line number of the target region.
  6151. unsigned DeviceID;
  6152. unsigned FileID;
  6153. unsigned Line;
  6154. getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
  6155. Line);
  6156. SmallString<64> EntryFnName;
  6157. {
  6158. llvm::raw_svector_ostream OS(EntryFnName);
  6159. OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
  6160. << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
  6161. }
  6162. const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
  6163. CodeGenFunction CGF(CGM, true);
  6164. CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
  6165. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6166. OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
  6167. // If this target outline function is not an offload entry, we don't need to
  6168. // register it.
  6169. if (!IsOffloadEntry)
  6170. return;
  6171. // The target region ID is used by the runtime library to identify the current
  6172. // target region, so it only has to be unique and not necessarily point to
  6173. // anything. It could be the pointer to the outlined function that implements
  6174. // the target region, but we aren't using that so that the compiler doesn't
  6175. // need to keep that, and could therefore inline the host function if proven
  6176. // worthwhile during optimization. In the other hand, if emitting code for the
  6177. // device, the ID has to be the function address so that it can retrieved from
  6178. // the offloading entry and launched by the runtime library. We also mark the
  6179. // outlined function to have external linkage in case we are emitting code for
  6180. // the device, because these functions will be entry points to the device.
  6181. if (CGM.getLangOpts().OpenMPIsDevice) {
  6182. OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
  6183. OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
  6184. OutlinedFn->setDSOLocal(false);
  6185. } else {
  6186. std::string Name = getName({EntryFnName, "region_id"});
  6187. OutlinedFnID = new llvm::GlobalVariable(
  6188. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  6189. llvm::GlobalValue::WeakAnyLinkage,
  6190. llvm::Constant::getNullValue(CGM.Int8Ty), Name);
  6191. }
  6192. // Register the information for the entry associated with this target region.
  6193. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  6194. DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
  6195. OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
  6196. }
  6197. /// Checks if the expression is constant or does not have non-trivial function
  6198. /// calls.
  6199. static bool isTrivial(ASTContext &Ctx, const Expr * E) {
  6200. // We can skip constant expressions.
  6201. // We can skip expressions with trivial calls or simple expressions.
  6202. return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
  6203. !E->hasNonTrivialCall(Ctx)) &&
  6204. !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
  6205. }
  6206. const Stmt *CGOpenMPRuntime::getSingleCompoundChild(ASTContext &Ctx,
  6207. const Stmt *Body) {
  6208. const Stmt *Child = Body->IgnoreContainers();
  6209. while (const auto *C = dyn_cast_or_null<CompoundStmt>(Child)) {
  6210. Child = nullptr;
  6211. for (const Stmt *S : C->body()) {
  6212. if (const auto *E = dyn_cast<Expr>(S)) {
  6213. if (isTrivial(Ctx, E))
  6214. continue;
  6215. }
  6216. // Some of the statements can be ignored.
  6217. if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
  6218. isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
  6219. continue;
  6220. // Analyze declarations.
  6221. if (const auto *DS = dyn_cast<DeclStmt>(S)) {
  6222. if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
  6223. if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
  6224. isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
  6225. isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
  6226. isa<UsingDirectiveDecl>(D) ||
  6227. isa<OMPDeclareReductionDecl>(D) ||
  6228. isa<OMPThreadPrivateDecl>(D) || isa<OMPAllocateDecl>(D))
  6229. return true;
  6230. const auto *VD = dyn_cast<VarDecl>(D);
  6231. if (!VD)
  6232. return false;
  6233. return VD->isConstexpr() ||
  6234. ((VD->getType().isTrivialType(Ctx) ||
  6235. VD->getType()->isReferenceType()) &&
  6236. (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
  6237. }))
  6238. continue;
  6239. }
  6240. // Found multiple children - cannot get the one child only.
  6241. if (Child)
  6242. return nullptr;
  6243. Child = S;
  6244. }
  6245. if (Child)
  6246. Child = Child->IgnoreContainers();
  6247. }
  6248. return Child;
  6249. }
  6250. /// Emit the number of teams for a target directive. Inspect the num_teams
  6251. /// clause associated with a teams construct combined or closely nested
  6252. /// with the target directive.
  6253. ///
  6254. /// Emit a team of size one for directives such as 'target parallel' that
  6255. /// have no associated teams construct.
  6256. ///
  6257. /// Otherwise, return nullptr.
  6258. static llvm::Value *
  6259. emitNumTeamsForTargetDirective(CodeGenFunction &CGF,
  6260. const OMPExecutableDirective &D) {
  6261. assert(!CGF.getLangOpts().OpenMPIsDevice &&
  6262. "Clauses associated with the teams directive expected to be emitted "
  6263. "only for the host!");
  6264. OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
  6265. assert(isOpenMPTargetExecutionDirective(DirectiveKind) &&
  6266. "Expected target-based executable directive.");
  6267. CGBuilderTy &Bld = CGF.Builder;
  6268. switch (DirectiveKind) {
  6269. case OMPD_target: {
  6270. const auto *CS = D.getInnermostCapturedStmt();
  6271. const auto *Body =
  6272. CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  6273. const Stmt *ChildStmt =
  6274. CGOpenMPRuntime::getSingleCompoundChild(CGF.getContext(), Body);
  6275. if (const auto *NestedDir =
  6276. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  6277. if (isOpenMPTeamsDirective(NestedDir->getDirectiveKind())) {
  6278. if (NestedDir->hasClausesOfKind<OMPNumTeamsClause>()) {
  6279. CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
  6280. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6281. const Expr *NumTeams =
  6282. NestedDir->getSingleClause<OMPNumTeamsClause>()->getNumTeams();
  6283. llvm::Value *NumTeamsVal =
  6284. CGF.EmitScalarExpr(NumTeams,
  6285. /*IgnoreResultAssign*/ true);
  6286. return Bld.CreateIntCast(NumTeamsVal, CGF.Int32Ty,
  6287. /*IsSigned=*/true);
  6288. }
  6289. return Bld.getInt32(0);
  6290. }
  6291. if (isOpenMPParallelDirective(NestedDir->getDirectiveKind()) ||
  6292. isOpenMPSimdDirective(NestedDir->getDirectiveKind()))
  6293. return Bld.getInt32(1);
  6294. return Bld.getInt32(0);
  6295. }
  6296. return nullptr;
  6297. }
  6298. case OMPD_target_teams:
  6299. case OMPD_target_teams_distribute:
  6300. case OMPD_target_teams_distribute_simd:
  6301. case OMPD_target_teams_distribute_parallel_for:
  6302. case OMPD_target_teams_distribute_parallel_for_simd: {
  6303. if (D.hasClausesOfKind<OMPNumTeamsClause>()) {
  6304. CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
  6305. const Expr *NumTeams =
  6306. D.getSingleClause<OMPNumTeamsClause>()->getNumTeams();
  6307. llvm::Value *NumTeamsVal =
  6308. CGF.EmitScalarExpr(NumTeams,
  6309. /*IgnoreResultAssign*/ true);
  6310. return Bld.CreateIntCast(NumTeamsVal, CGF.Int32Ty,
  6311. /*IsSigned=*/true);
  6312. }
  6313. return Bld.getInt32(0);
  6314. }
  6315. case OMPD_target_parallel:
  6316. case OMPD_target_parallel_for:
  6317. case OMPD_target_parallel_for_simd:
  6318. case OMPD_target_simd:
  6319. return Bld.getInt32(1);
  6320. case OMPD_parallel:
  6321. case OMPD_for:
  6322. case OMPD_parallel_for:
  6323. case OMPD_parallel_sections:
  6324. case OMPD_for_simd:
  6325. case OMPD_parallel_for_simd:
  6326. case OMPD_cancel:
  6327. case OMPD_cancellation_point:
  6328. case OMPD_ordered:
  6329. case OMPD_threadprivate:
  6330. case OMPD_allocate:
  6331. case OMPD_task:
  6332. case OMPD_simd:
  6333. case OMPD_sections:
  6334. case OMPD_section:
  6335. case OMPD_single:
  6336. case OMPD_master:
  6337. case OMPD_critical:
  6338. case OMPD_taskyield:
  6339. case OMPD_barrier:
  6340. case OMPD_taskwait:
  6341. case OMPD_taskgroup:
  6342. case OMPD_atomic:
  6343. case OMPD_flush:
  6344. case OMPD_teams:
  6345. case OMPD_target_data:
  6346. case OMPD_target_exit_data:
  6347. case OMPD_target_enter_data:
  6348. case OMPD_distribute:
  6349. case OMPD_distribute_simd:
  6350. case OMPD_distribute_parallel_for:
  6351. case OMPD_distribute_parallel_for_simd:
  6352. case OMPD_teams_distribute:
  6353. case OMPD_teams_distribute_simd:
  6354. case OMPD_teams_distribute_parallel_for:
  6355. case OMPD_teams_distribute_parallel_for_simd:
  6356. case OMPD_target_update:
  6357. case OMPD_declare_simd:
  6358. case OMPD_declare_target:
  6359. case OMPD_end_declare_target:
  6360. case OMPD_declare_reduction:
  6361. case OMPD_declare_mapper:
  6362. case OMPD_taskloop:
  6363. case OMPD_taskloop_simd:
  6364. case OMPD_requires:
  6365. case OMPD_unknown:
  6366. break;
  6367. }
  6368. llvm_unreachable("Unexpected directive kind.");
  6369. }
  6370. static llvm::Value *getNumThreads(CodeGenFunction &CGF, const CapturedStmt *CS,
  6371. llvm::Value *DefaultThreadLimitVal) {
  6372. const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
  6373. CGF.getContext(), CS->getCapturedStmt());
  6374. if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
  6375. if (isOpenMPParallelDirective(Dir->getDirectiveKind())) {
  6376. llvm::Value *NumThreads = nullptr;
  6377. llvm::Value *CondVal = nullptr;
  6378. // Handle if clause. If if clause present, the number of threads is
  6379. // calculated as <cond> ? (<numthreads> ? <numthreads> : 0 ) : 1.
  6380. if (Dir->hasClausesOfKind<OMPIfClause>()) {
  6381. CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
  6382. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6383. const OMPIfClause *IfClause = nullptr;
  6384. for (const auto *C : Dir->getClausesOfKind<OMPIfClause>()) {
  6385. if (C->getNameModifier() == OMPD_unknown ||
  6386. C->getNameModifier() == OMPD_parallel) {
  6387. IfClause = C;
  6388. break;
  6389. }
  6390. }
  6391. if (IfClause) {
  6392. const Expr *Cond = IfClause->getCondition();
  6393. bool Result;
  6394. if (Cond->EvaluateAsBooleanCondition(Result, CGF.getContext())) {
  6395. if (!Result)
  6396. return CGF.Builder.getInt32(1);
  6397. } else {
  6398. CodeGenFunction::LexicalScope Scope(CGF, Cond->getSourceRange());
  6399. if (const auto *PreInit =
  6400. cast_or_null<DeclStmt>(IfClause->getPreInitStmt())) {
  6401. for (const auto *I : PreInit->decls()) {
  6402. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  6403. CGF.EmitVarDecl(cast<VarDecl>(*I));
  6404. } else {
  6405. CodeGenFunction::AutoVarEmission Emission =
  6406. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  6407. CGF.EmitAutoVarCleanups(Emission);
  6408. }
  6409. }
  6410. }
  6411. CondVal = CGF.EvaluateExprAsBool(Cond);
  6412. }
  6413. }
  6414. }
  6415. // Check the value of num_threads clause iff if clause was not specified
  6416. // or is not evaluated to false.
  6417. if (Dir->hasClausesOfKind<OMPNumThreadsClause>()) {
  6418. CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
  6419. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6420. const auto *NumThreadsClause =
  6421. Dir->getSingleClause<OMPNumThreadsClause>();
  6422. CodeGenFunction::LexicalScope Scope(
  6423. CGF, NumThreadsClause->getNumThreads()->getSourceRange());
  6424. if (const auto *PreInit =
  6425. cast_or_null<DeclStmt>(NumThreadsClause->getPreInitStmt())) {
  6426. for (const auto *I : PreInit->decls()) {
  6427. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  6428. CGF.EmitVarDecl(cast<VarDecl>(*I));
  6429. } else {
  6430. CodeGenFunction::AutoVarEmission Emission =
  6431. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  6432. CGF.EmitAutoVarCleanups(Emission);
  6433. }
  6434. }
  6435. }
  6436. NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads());
  6437. NumThreads = CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty,
  6438. /*IsSigned=*/false);
  6439. if (DefaultThreadLimitVal)
  6440. NumThreads = CGF.Builder.CreateSelect(
  6441. CGF.Builder.CreateICmpULT(DefaultThreadLimitVal, NumThreads),
  6442. DefaultThreadLimitVal, NumThreads);
  6443. } else {
  6444. NumThreads = DefaultThreadLimitVal ? DefaultThreadLimitVal
  6445. : CGF.Builder.getInt32(0);
  6446. }
  6447. // Process condition of the if clause.
  6448. if (CondVal) {
  6449. NumThreads = CGF.Builder.CreateSelect(CondVal, NumThreads,
  6450. CGF.Builder.getInt32(1));
  6451. }
  6452. return NumThreads;
  6453. }
  6454. if (isOpenMPSimdDirective(Dir->getDirectiveKind()))
  6455. return CGF.Builder.getInt32(1);
  6456. return DefaultThreadLimitVal;
  6457. }
  6458. return DefaultThreadLimitVal ? DefaultThreadLimitVal
  6459. : CGF.Builder.getInt32(0);
  6460. }
  6461. /// Emit the number of threads for a target directive. Inspect the
  6462. /// thread_limit clause associated with a teams construct combined or closely
  6463. /// nested with the target directive.
  6464. ///
  6465. /// Emit the num_threads clause for directives such as 'target parallel' that
  6466. /// have no associated teams construct.
  6467. ///
  6468. /// Otherwise, return nullptr.
  6469. static llvm::Value *
  6470. emitNumThreadsForTargetDirective(CodeGenFunction &CGF,
  6471. const OMPExecutableDirective &D) {
  6472. assert(!CGF.getLangOpts().OpenMPIsDevice &&
  6473. "Clauses associated with the teams directive expected to be emitted "
  6474. "only for the host!");
  6475. OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
  6476. assert(isOpenMPTargetExecutionDirective(DirectiveKind) &&
  6477. "Expected target-based executable directive.");
  6478. CGBuilderTy &Bld = CGF.Builder;
  6479. llvm::Value *ThreadLimitVal = nullptr;
  6480. llvm::Value *NumThreadsVal = nullptr;
  6481. switch (DirectiveKind) {
  6482. case OMPD_target: {
  6483. const CapturedStmt *CS = D.getInnermostCapturedStmt();
  6484. if (llvm::Value *NumThreads = getNumThreads(CGF, CS, ThreadLimitVal))
  6485. return NumThreads;
  6486. const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
  6487. CGF.getContext(), CS->getCapturedStmt());
  6488. if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
  6489. if (Dir->hasClausesOfKind<OMPThreadLimitClause>()) {
  6490. CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
  6491. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6492. const auto *ThreadLimitClause =
  6493. Dir->getSingleClause<OMPThreadLimitClause>();
  6494. CodeGenFunction::LexicalScope Scope(
  6495. CGF, ThreadLimitClause->getThreadLimit()->getSourceRange());
  6496. if (const auto *PreInit =
  6497. cast_or_null<DeclStmt>(ThreadLimitClause->getPreInitStmt())) {
  6498. for (const auto *I : PreInit->decls()) {
  6499. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  6500. CGF.EmitVarDecl(cast<VarDecl>(*I));
  6501. } else {
  6502. CodeGenFunction::AutoVarEmission Emission =
  6503. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  6504. CGF.EmitAutoVarCleanups(Emission);
  6505. }
  6506. }
  6507. }
  6508. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(
  6509. ThreadLimitClause->getThreadLimit(), /*IgnoreResultAssign=*/true);
  6510. ThreadLimitVal =
  6511. Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, /*IsSigned=*/false);
  6512. }
  6513. if (isOpenMPTeamsDirective(Dir->getDirectiveKind()) &&
  6514. !isOpenMPDistributeDirective(Dir->getDirectiveKind())) {
  6515. CS = Dir->getInnermostCapturedStmt();
  6516. const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
  6517. CGF.getContext(), CS->getCapturedStmt());
  6518. Dir = dyn_cast_or_null<OMPExecutableDirective>(Child);
  6519. }
  6520. if (Dir && isOpenMPDistributeDirective(Dir->getDirectiveKind()) &&
  6521. !isOpenMPSimdDirective(Dir->getDirectiveKind())) {
  6522. CS = Dir->getInnermostCapturedStmt();
  6523. if (llvm::Value *NumThreads = getNumThreads(CGF, CS, ThreadLimitVal))
  6524. return NumThreads;
  6525. }
  6526. if (Dir && isOpenMPSimdDirective(Dir->getDirectiveKind()))
  6527. return Bld.getInt32(1);
  6528. }
  6529. return ThreadLimitVal ? ThreadLimitVal : Bld.getInt32(0);
  6530. }
  6531. case OMPD_target_teams: {
  6532. if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
  6533. CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
  6534. const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
  6535. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(
  6536. ThreadLimitClause->getThreadLimit(), /*IgnoreResultAssign=*/true);
  6537. ThreadLimitVal =
  6538. Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, /*IsSigned=*/false);
  6539. }
  6540. const CapturedStmt *CS = D.getInnermostCapturedStmt();
  6541. if (llvm::Value *NumThreads = getNumThreads(CGF, CS, ThreadLimitVal))
  6542. return NumThreads;
  6543. const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
  6544. CGF.getContext(), CS->getCapturedStmt());
  6545. if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
  6546. if (Dir->getDirectiveKind() == OMPD_distribute) {
  6547. CS = Dir->getInnermostCapturedStmt();
  6548. if (llvm::Value *NumThreads = getNumThreads(CGF, CS, ThreadLimitVal))
  6549. return NumThreads;
  6550. }
  6551. }
  6552. return ThreadLimitVal ? ThreadLimitVal : Bld.getInt32(0);
  6553. }
  6554. case OMPD_target_teams_distribute:
  6555. if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
  6556. CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
  6557. const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
  6558. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(
  6559. ThreadLimitClause->getThreadLimit(), /*IgnoreResultAssign=*/true);
  6560. ThreadLimitVal =
  6561. Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, /*IsSigned=*/false);
  6562. }
  6563. return getNumThreads(CGF, D.getInnermostCapturedStmt(), ThreadLimitVal);
  6564. case OMPD_target_parallel:
  6565. case OMPD_target_parallel_for:
  6566. case OMPD_target_parallel_for_simd:
  6567. case OMPD_target_teams_distribute_parallel_for:
  6568. case OMPD_target_teams_distribute_parallel_for_simd: {
  6569. llvm::Value *CondVal = nullptr;
  6570. // Handle if clause. If if clause present, the number of threads is
  6571. // calculated as <cond> ? (<numthreads> ? <numthreads> : 0 ) : 1.
  6572. if (D.hasClausesOfKind<OMPIfClause>()) {
  6573. const OMPIfClause *IfClause = nullptr;
  6574. for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
  6575. if (C->getNameModifier() == OMPD_unknown ||
  6576. C->getNameModifier() == OMPD_parallel) {
  6577. IfClause = C;
  6578. break;
  6579. }
  6580. }
  6581. if (IfClause) {
  6582. const Expr *Cond = IfClause->getCondition();
  6583. bool Result;
  6584. if (Cond->EvaluateAsBooleanCondition(Result, CGF.getContext())) {
  6585. if (!Result)
  6586. return Bld.getInt32(1);
  6587. } else {
  6588. CodeGenFunction::RunCleanupsScope Scope(CGF);
  6589. CondVal = CGF.EvaluateExprAsBool(Cond);
  6590. }
  6591. }
  6592. }
  6593. if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
  6594. CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
  6595. const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
  6596. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(
  6597. ThreadLimitClause->getThreadLimit(), /*IgnoreResultAssign=*/true);
  6598. ThreadLimitVal =
  6599. Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, /*IsSigned=*/false);
  6600. }
  6601. if (D.hasClausesOfKind<OMPNumThreadsClause>()) {
  6602. CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
  6603. const auto *NumThreadsClause = D.getSingleClause<OMPNumThreadsClause>();
  6604. llvm::Value *NumThreads = CGF.EmitScalarExpr(
  6605. NumThreadsClause->getNumThreads(), /*IgnoreResultAssign=*/true);
  6606. NumThreadsVal =
  6607. Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/false);
  6608. ThreadLimitVal = ThreadLimitVal
  6609. ? Bld.CreateSelect(Bld.CreateICmpULT(NumThreadsVal,
  6610. ThreadLimitVal),
  6611. NumThreadsVal, ThreadLimitVal)
  6612. : NumThreadsVal;
  6613. }
  6614. if (!ThreadLimitVal)
  6615. ThreadLimitVal = Bld.getInt32(0);
  6616. if (CondVal)
  6617. return Bld.CreateSelect(CondVal, ThreadLimitVal, Bld.getInt32(1));
  6618. return ThreadLimitVal;
  6619. }
  6620. case OMPD_target_teams_distribute_simd:
  6621. case OMPD_target_simd:
  6622. return Bld.getInt32(1);
  6623. case OMPD_parallel:
  6624. case OMPD_for:
  6625. case OMPD_parallel_for:
  6626. case OMPD_parallel_sections:
  6627. case OMPD_for_simd:
  6628. case OMPD_parallel_for_simd:
  6629. case OMPD_cancel:
  6630. case OMPD_cancellation_point:
  6631. case OMPD_ordered:
  6632. case OMPD_threadprivate:
  6633. case OMPD_allocate:
  6634. case OMPD_task:
  6635. case OMPD_simd:
  6636. case OMPD_sections:
  6637. case OMPD_section:
  6638. case OMPD_single:
  6639. case OMPD_master:
  6640. case OMPD_critical:
  6641. case OMPD_taskyield:
  6642. case OMPD_barrier:
  6643. case OMPD_taskwait:
  6644. case OMPD_taskgroup:
  6645. case OMPD_atomic:
  6646. case OMPD_flush:
  6647. case OMPD_teams:
  6648. case OMPD_target_data:
  6649. case OMPD_target_exit_data:
  6650. case OMPD_target_enter_data:
  6651. case OMPD_distribute:
  6652. case OMPD_distribute_simd:
  6653. case OMPD_distribute_parallel_for:
  6654. case OMPD_distribute_parallel_for_simd:
  6655. case OMPD_teams_distribute:
  6656. case OMPD_teams_distribute_simd:
  6657. case OMPD_teams_distribute_parallel_for:
  6658. case OMPD_teams_distribute_parallel_for_simd:
  6659. case OMPD_target_update:
  6660. case OMPD_declare_simd:
  6661. case OMPD_declare_target:
  6662. case OMPD_end_declare_target:
  6663. case OMPD_declare_reduction:
  6664. case OMPD_declare_mapper:
  6665. case OMPD_taskloop:
  6666. case OMPD_taskloop_simd:
  6667. case OMPD_requires:
  6668. case OMPD_unknown:
  6669. break;
  6670. }
  6671. llvm_unreachable("Unsupported directive kind.");
  6672. }
  6673. namespace {
  6674. LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
  6675. // Utility to handle information from clauses associated with a given
  6676. // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
  6677. // It provides a convenient interface to obtain the information and generate
  6678. // code for that information.
  6679. class MappableExprsHandler {
  6680. public:
  6681. /// Values for bit flags used to specify the mapping type for
  6682. /// offloading.
  6683. enum OpenMPOffloadMappingFlags : uint64_t {
  6684. /// No flags
  6685. OMP_MAP_NONE = 0x0,
  6686. /// Allocate memory on the device and move data from host to device.
  6687. OMP_MAP_TO = 0x01,
  6688. /// Allocate memory on the device and move data from device to host.
  6689. OMP_MAP_FROM = 0x02,
  6690. /// Always perform the requested mapping action on the element, even
  6691. /// if it was already mapped before.
  6692. OMP_MAP_ALWAYS = 0x04,
  6693. /// Delete the element from the device environment, ignoring the
  6694. /// current reference count associated with the element.
  6695. OMP_MAP_DELETE = 0x08,
  6696. /// The element being mapped is a pointer-pointee pair; both the
  6697. /// pointer and the pointee should be mapped.
  6698. OMP_MAP_PTR_AND_OBJ = 0x10,
  6699. /// This flags signals that the base address of an entry should be
  6700. /// passed to the target kernel as an argument.
  6701. OMP_MAP_TARGET_PARAM = 0x20,
  6702. /// Signal that the runtime library has to return the device pointer
  6703. /// in the current position for the data being mapped. Used when we have the
  6704. /// use_device_ptr clause.
  6705. OMP_MAP_RETURN_PARAM = 0x40,
  6706. /// This flag signals that the reference being passed is a pointer to
  6707. /// private data.
  6708. OMP_MAP_PRIVATE = 0x80,
  6709. /// Pass the element to the device by value.
  6710. OMP_MAP_LITERAL = 0x100,
  6711. /// Implicit map
  6712. OMP_MAP_IMPLICIT = 0x200,
  6713. /// The 16 MSBs of the flags indicate whether the entry is member of some
  6714. /// struct/class.
  6715. OMP_MAP_MEMBER_OF = 0xffff000000000000,
  6716. LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
  6717. };
  6718. /// Class that associates information with a base pointer to be passed to the
  6719. /// runtime library.
  6720. class BasePointerInfo {
  6721. /// The base pointer.
  6722. llvm::Value *Ptr = nullptr;
  6723. /// The base declaration that refers to this device pointer, or null if
  6724. /// there is none.
  6725. const ValueDecl *DevPtrDecl = nullptr;
  6726. public:
  6727. BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
  6728. : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
  6729. llvm::Value *operator*() const { return Ptr; }
  6730. const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
  6731. void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
  6732. };
  6733. using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
  6734. using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
  6735. using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
  6736. /// Map between a struct and the its lowest & highest elements which have been
  6737. /// mapped.
  6738. /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
  6739. /// HE(FieldIndex, Pointer)}
  6740. struct StructRangeInfoTy {
  6741. std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
  6742. 0, Address::invalid()};
  6743. std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
  6744. 0, Address::invalid()};
  6745. Address Base = Address::invalid();
  6746. };
  6747. private:
  6748. /// Kind that defines how a device pointer has to be returned.
  6749. struct MapInfo {
  6750. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  6751. OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
  6752. ArrayRef<OpenMPMapModifierKind> MapModifiers;
  6753. bool ReturnDevicePointer = false;
  6754. bool IsImplicit = false;
  6755. MapInfo() = default;
  6756. MapInfo(
  6757. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  6758. OpenMPMapClauseKind MapType,
  6759. ArrayRef<OpenMPMapModifierKind> MapModifiers,
  6760. bool ReturnDevicePointer, bool IsImplicit)
  6761. : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
  6762. ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
  6763. };
  6764. /// If use_device_ptr is used on a pointer which is a struct member and there
  6765. /// is no map information about it, then emission of that entry is deferred
  6766. /// until the whole struct has been processed.
  6767. struct DeferredDevicePtrEntryTy {
  6768. const Expr *IE = nullptr;
  6769. const ValueDecl *VD = nullptr;
  6770. DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
  6771. : IE(IE), VD(VD) {}
  6772. };
  6773. /// Directive from where the map clauses were extracted.
  6774. const OMPExecutableDirective &CurDir;
  6775. /// Function the directive is being generated for.
  6776. CodeGenFunction &CGF;
  6777. /// Set of all first private variables in the current directive.
  6778. llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
  6779. /// Map between device pointer declarations and their expression components.
  6780. /// The key value for declarations in 'this' is null.
  6781. llvm::DenseMap<
  6782. const ValueDecl *,
  6783. SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
  6784. DevPointersMap;
  6785. llvm::Value *getExprTypeSize(const Expr *E) const {
  6786. QualType ExprTy = E->getType().getCanonicalType();
  6787. // Reference types are ignored for mapping purposes.
  6788. if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
  6789. ExprTy = RefTy->getPointeeType().getCanonicalType();
  6790. // Given that an array section is considered a built-in type, we need to
  6791. // do the calculation based on the length of the section instead of relying
  6792. // on CGF.getTypeSize(E->getType()).
  6793. if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
  6794. QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
  6795. OAE->getBase()->IgnoreParenImpCasts())
  6796. .getCanonicalType();
  6797. // If there is no length associated with the expression, that means we
  6798. // are using the whole length of the base.
  6799. if (!OAE->getLength() && OAE->getColonLoc().isValid())
  6800. return CGF.getTypeSize(BaseTy);
  6801. llvm::Value *ElemSize;
  6802. if (const auto *PTy = BaseTy->getAs<PointerType>()) {
  6803. ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
  6804. } else {
  6805. const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
  6806. assert(ATy && "Expecting array type if not a pointer type.");
  6807. ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
  6808. }
  6809. // If we don't have a length at this point, that is because we have an
  6810. // array section with a single element.
  6811. if (!OAE->getLength())
  6812. return ElemSize;
  6813. llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
  6814. LengthVal =
  6815. CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
  6816. return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
  6817. }
  6818. return CGF.getTypeSize(ExprTy);
  6819. }
  6820. /// Return the corresponding bits for a given map clause modifier. Add
  6821. /// a flag marking the map as a pointer if requested. Add a flag marking the
  6822. /// map as the first one of a series of maps that relate to the same map
  6823. /// expression.
  6824. OpenMPOffloadMappingFlags getMapTypeBits(
  6825. OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
  6826. bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
  6827. OpenMPOffloadMappingFlags Bits =
  6828. IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
  6829. switch (MapType) {
  6830. case OMPC_MAP_alloc:
  6831. case OMPC_MAP_release:
  6832. // alloc and release is the default behavior in the runtime library, i.e.
  6833. // if we don't pass any bits alloc/release that is what the runtime is
  6834. // going to do. Therefore, we don't need to signal anything for these two
  6835. // type modifiers.
  6836. break;
  6837. case OMPC_MAP_to:
  6838. Bits |= OMP_MAP_TO;
  6839. break;
  6840. case OMPC_MAP_from:
  6841. Bits |= OMP_MAP_FROM;
  6842. break;
  6843. case OMPC_MAP_tofrom:
  6844. Bits |= OMP_MAP_TO | OMP_MAP_FROM;
  6845. break;
  6846. case OMPC_MAP_delete:
  6847. Bits |= OMP_MAP_DELETE;
  6848. break;
  6849. case OMPC_MAP_unknown:
  6850. llvm_unreachable("Unexpected map type!");
  6851. }
  6852. if (AddPtrFlag)
  6853. Bits |= OMP_MAP_PTR_AND_OBJ;
  6854. if (AddIsTargetParamFlag)
  6855. Bits |= OMP_MAP_TARGET_PARAM;
  6856. if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
  6857. != MapModifiers.end())
  6858. Bits |= OMP_MAP_ALWAYS;
  6859. return Bits;
  6860. }
  6861. /// Return true if the provided expression is a final array section. A
  6862. /// final array section, is one whose length can't be proved to be one.
  6863. bool isFinalArraySectionExpression(const Expr *E) const {
  6864. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  6865. // It is not an array section and therefore not a unity-size one.
  6866. if (!OASE)
  6867. return false;
  6868. // An array section with no colon always refer to a single element.
  6869. if (OASE->getColonLoc().isInvalid())
  6870. return false;
  6871. const Expr *Length = OASE->getLength();
  6872. // If we don't have a length we have to check if the array has size 1
  6873. // for this dimension. Also, we should always expect a length if the
  6874. // base type is pointer.
  6875. if (!Length) {
  6876. QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
  6877. OASE->getBase()->IgnoreParenImpCasts())
  6878. .getCanonicalType();
  6879. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  6880. return ATy->getSize().getSExtValue() != 1;
  6881. // If we don't have a constant dimension length, we have to consider
  6882. // the current section as having any size, so it is not necessarily
  6883. // unitary. If it happen to be unity size, that's user fault.
  6884. return true;
  6885. }
  6886. // Check if the length evaluates to 1.
  6887. Expr::EvalResult Result;
  6888. if (!Length->EvaluateAsInt(Result, CGF.getContext()))
  6889. return true; // Can have more that size 1.
  6890. llvm::APSInt ConstLength = Result.Val.getInt();
  6891. return ConstLength.getSExtValue() != 1;
  6892. }
  6893. /// Generate the base pointers, section pointers, sizes and map type
  6894. /// bits for the provided map type, map modifier, and expression components.
  6895. /// \a IsFirstComponent should be set to true if the provided set of
  6896. /// components is the first associated with a capture.
  6897. void generateInfoForComponentList(
  6898. OpenMPMapClauseKind MapType,
  6899. ArrayRef<OpenMPMapModifierKind> MapModifiers,
  6900. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  6901. MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
  6902. MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
  6903. StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
  6904. bool IsImplicit,
  6905. ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
  6906. OverlappedElements = llvm::None) const {
  6907. // The following summarizes what has to be generated for each map and the
  6908. // types below. The generated information is expressed in this order:
  6909. // base pointer, section pointer, size, flags
  6910. // (to add to the ones that come from the map type and modifier).
  6911. //
  6912. // double d;
  6913. // int i[100];
  6914. // float *p;
  6915. //
  6916. // struct S1 {
  6917. // int i;
  6918. // float f[50];
  6919. // }
  6920. // struct S2 {
  6921. // int i;
  6922. // float f[50];
  6923. // S1 s;
  6924. // double *p;
  6925. // struct S2 *ps;
  6926. // }
  6927. // S2 s;
  6928. // S2 *ps;
  6929. //
  6930. // map(d)
  6931. // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
  6932. //
  6933. // map(i)
  6934. // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
  6935. //
  6936. // map(i[1:23])
  6937. // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
  6938. //
  6939. // map(p)
  6940. // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
  6941. //
  6942. // map(p[1:24])
  6943. // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
  6944. //
  6945. // map(s)
  6946. // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
  6947. //
  6948. // map(s.i)
  6949. // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
  6950. //
  6951. // map(s.s.f)
  6952. // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
  6953. //
  6954. // map(s.p)
  6955. // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
  6956. //
  6957. // map(to: s.p[:22])
  6958. // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
  6959. // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
  6960. // &(s.p), &(s.p[0]), 22*sizeof(double),
  6961. // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
  6962. // (*) alloc space for struct members, only this is a target parameter
  6963. // (**) map the pointer (nothing to be mapped in this example) (the compiler
  6964. // optimizes this entry out, same in the examples below)
  6965. // (***) map the pointee (map: to)
  6966. //
  6967. // map(s.ps)
  6968. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
  6969. //
  6970. // map(from: s.ps->s.i)
  6971. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  6972. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  6973. // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  6974. //
  6975. // map(to: s.ps->ps)
  6976. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  6977. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  6978. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
  6979. //
  6980. // map(s.ps->ps->ps)
  6981. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  6982. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  6983. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  6984. // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
  6985. //
  6986. // map(to: s.ps->ps->s.f[:22])
  6987. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  6988. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  6989. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  6990. // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
  6991. //
  6992. // map(ps)
  6993. // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
  6994. //
  6995. // map(ps->i)
  6996. // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
  6997. //
  6998. // map(ps->s.f)
  6999. // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
  7000. //
  7001. // map(from: ps->p)
  7002. // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
  7003. //
  7004. // map(to: ps->p[:22])
  7005. // ps, &(ps->p), sizeof(double*), TARGET_PARAM
  7006. // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
  7007. // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
  7008. //
  7009. // map(ps->ps)
  7010. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
  7011. //
  7012. // map(from: ps->ps->s.i)
  7013. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  7014. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  7015. // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  7016. //
  7017. // map(from: ps->ps->ps)
  7018. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  7019. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  7020. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  7021. //
  7022. // map(ps->ps->ps->ps)
  7023. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  7024. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  7025. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  7026. // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
  7027. //
  7028. // map(to: ps->ps->ps->s.f[:22])
  7029. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  7030. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  7031. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  7032. // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
  7033. //
  7034. // map(to: s.f[:22]) map(from: s.p[:33])
  7035. // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
  7036. // sizeof(double*) (**), TARGET_PARAM
  7037. // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
  7038. // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
  7039. // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  7040. // (*) allocate contiguous space needed to fit all mapped members even if
  7041. // we allocate space for members not mapped (in this example,
  7042. // s.f[22..49] and s.s are not mapped, yet we must allocate space for
  7043. // them as well because they fall between &s.f[0] and &s.p)
  7044. //
  7045. // map(from: s.f[:22]) map(to: ps->p[:33])
  7046. // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
  7047. // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
  7048. // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
  7049. // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
  7050. // (*) the struct this entry pertains to is the 2nd element in the list of
  7051. // arguments, hence MEMBER_OF(2)
  7052. //
  7053. // map(from: s.f[:22], s.s) map(to: ps->p[:33])
  7054. // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
  7055. // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
  7056. // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
  7057. // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
  7058. // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
  7059. // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
  7060. // (*) the struct this entry pertains to is the 4th element in the list
  7061. // of arguments, hence MEMBER_OF(4)
  7062. // Track if the map information being generated is the first for a capture.
  7063. bool IsCaptureFirstInfo = IsFirstComponentList;
  7064. // When the variable is on a declare target link or in a to clause with
  7065. // unified memory, a reference is needed to hold the host/device address
  7066. // of the variable.
  7067. bool RequiresReference = false;
  7068. // Scan the components from the base to the complete expression.
  7069. auto CI = Components.rbegin();
  7070. auto CE = Components.rend();
  7071. auto I = CI;
  7072. // Track if the map information being generated is the first for a list of
  7073. // components.
  7074. bool IsExpressionFirstInfo = true;
  7075. Address BP = Address::invalid();
  7076. const Expr *AssocExpr = I->getAssociatedExpression();
  7077. const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
  7078. const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
  7079. if (isa<MemberExpr>(AssocExpr)) {
  7080. // The base is the 'this' pointer. The content of the pointer is going
  7081. // to be the base of the field being mapped.
  7082. BP = CGF.LoadCXXThisAddress();
  7083. } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
  7084. (OASE &&
  7085. isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
  7086. BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
  7087. } else {
  7088. // The base is the reference to the variable.
  7089. // BP = &Var.
  7090. BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
  7091. if (const auto *VD =
  7092. dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
  7093. if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  7094. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  7095. if ((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  7096. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  7097. CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) {
  7098. RequiresReference = true;
  7099. BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  7100. }
  7101. }
  7102. }
  7103. // If the variable is a pointer and is being dereferenced (i.e. is not
  7104. // the last component), the base has to be the pointer itself, not its
  7105. // reference. References are ignored for mapping purposes.
  7106. QualType Ty =
  7107. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  7108. if (Ty->isAnyPointerType() && std::next(I) != CE) {
  7109. BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
  7110. // We do not need to generate individual map information for the
  7111. // pointer, it can be associated with the combined storage.
  7112. ++I;
  7113. }
  7114. }
  7115. // Track whether a component of the list should be marked as MEMBER_OF some
  7116. // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
  7117. // in a component list should be marked as MEMBER_OF, all subsequent entries
  7118. // do not belong to the base struct. E.g.
  7119. // struct S2 s;
  7120. // s.ps->ps->ps->f[:]
  7121. // (1) (2) (3) (4)
  7122. // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
  7123. // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
  7124. // is the pointee of ps(2) which is not member of struct s, so it should not
  7125. // be marked as such (it is still PTR_AND_OBJ).
  7126. // The variable is initialized to false so that PTR_AND_OBJ entries which
  7127. // are not struct members are not considered (e.g. array of pointers to
  7128. // data).
  7129. bool ShouldBeMemberOf = false;
  7130. // Variable keeping track of whether or not we have encountered a component
  7131. // in the component list which is a member expression. Useful when we have a
  7132. // pointer or a final array section, in which case it is the previous
  7133. // component in the list which tells us whether we have a member expression.
  7134. // E.g. X.f[:]
  7135. // While processing the final array section "[:]" it is "f" which tells us
  7136. // whether we are dealing with a member of a declared struct.
  7137. const MemberExpr *EncounteredME = nullptr;
  7138. for (; I != CE; ++I) {
  7139. // If the current component is member of a struct (parent struct) mark it.
  7140. if (!EncounteredME) {
  7141. EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
  7142. // If we encounter a PTR_AND_OBJ entry from now on it should be marked
  7143. // as MEMBER_OF the parent struct.
  7144. if (EncounteredME)
  7145. ShouldBeMemberOf = true;
  7146. }
  7147. auto Next = std::next(I);
  7148. // We need to generate the addresses and sizes if this is the last
  7149. // component, if the component is a pointer or if it is an array section
  7150. // whose length can't be proved to be one. If this is a pointer, it
  7151. // becomes the base address for the following components.
  7152. // A final array section, is one whose length can't be proved to be one.
  7153. bool IsFinalArraySection =
  7154. isFinalArraySectionExpression(I->getAssociatedExpression());
  7155. // Get information on whether the element is a pointer. Have to do a
  7156. // special treatment for array sections given that they are built-in
  7157. // types.
  7158. const auto *OASE =
  7159. dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
  7160. bool IsPointer =
  7161. (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
  7162. .getCanonicalType()
  7163. ->isAnyPointerType()) ||
  7164. I->getAssociatedExpression()->getType()->isAnyPointerType();
  7165. if (Next == CE || IsPointer || IsFinalArraySection) {
  7166. // If this is not the last component, we expect the pointer to be
  7167. // associated with an array expression or member expression.
  7168. assert((Next == CE ||
  7169. isa<MemberExpr>(Next->getAssociatedExpression()) ||
  7170. isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
  7171. isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
  7172. "Unexpected expression");
  7173. Address LB =
  7174. CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
  7175. // If this component is a pointer inside the base struct then we don't
  7176. // need to create any entry for it - it will be combined with the object
  7177. // it is pointing to into a single PTR_AND_OBJ entry.
  7178. bool IsMemberPointer =
  7179. IsPointer && EncounteredME &&
  7180. (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
  7181. EncounteredME);
  7182. if (!OverlappedElements.empty()) {
  7183. // Handle base element with the info for overlapped elements.
  7184. assert(!PartialStruct.Base.isValid() && "The base element is set.");
  7185. assert(Next == CE &&
  7186. "Expected last element for the overlapped elements.");
  7187. assert(!IsPointer &&
  7188. "Unexpected base element with the pointer type.");
  7189. // Mark the whole struct as the struct that requires allocation on the
  7190. // device.
  7191. PartialStruct.LowestElem = {0, LB};
  7192. CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
  7193. I->getAssociatedExpression()->getType());
  7194. Address HB = CGF.Builder.CreateConstGEP(
  7195. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
  7196. CGF.VoidPtrTy),
  7197. TypeSize.getQuantity() - 1);
  7198. PartialStruct.HighestElem = {
  7199. std::numeric_limits<decltype(
  7200. PartialStruct.HighestElem.first)>::max(),
  7201. HB};
  7202. PartialStruct.Base = BP;
  7203. // Emit data for non-overlapped data.
  7204. OpenMPOffloadMappingFlags Flags =
  7205. OMP_MAP_MEMBER_OF |
  7206. getMapTypeBits(MapType, MapModifiers, IsImplicit,
  7207. /*AddPtrFlag=*/false,
  7208. /*AddIsTargetParamFlag=*/false);
  7209. LB = BP;
  7210. llvm::Value *Size = nullptr;
  7211. // Do bitcopy of all non-overlapped structure elements.
  7212. for (OMPClauseMappableExprCommon::MappableExprComponentListRef
  7213. Component : OverlappedElements) {
  7214. Address ComponentLB = Address::invalid();
  7215. for (const OMPClauseMappableExprCommon::MappableComponent &MC :
  7216. Component) {
  7217. if (MC.getAssociatedDeclaration()) {
  7218. ComponentLB =
  7219. CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
  7220. .getAddress();
  7221. Size = CGF.Builder.CreatePtrDiff(
  7222. CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
  7223. CGF.EmitCastToVoidPtr(LB.getPointer()));
  7224. break;
  7225. }
  7226. }
  7227. BasePointers.push_back(BP.getPointer());
  7228. Pointers.push_back(LB.getPointer());
  7229. Sizes.push_back(Size);
  7230. Types.push_back(Flags);
  7231. LB = CGF.Builder.CreateConstGEP(ComponentLB, 1);
  7232. }
  7233. BasePointers.push_back(BP.getPointer());
  7234. Pointers.push_back(LB.getPointer());
  7235. Size = CGF.Builder.CreatePtrDiff(
  7236. CGF.EmitCastToVoidPtr(
  7237. CGF.Builder.CreateConstGEP(HB, 1).getPointer()),
  7238. CGF.EmitCastToVoidPtr(LB.getPointer()));
  7239. Sizes.push_back(Size);
  7240. Types.push_back(Flags);
  7241. break;
  7242. }
  7243. llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
  7244. if (!IsMemberPointer) {
  7245. BasePointers.push_back(BP.getPointer());
  7246. Pointers.push_back(LB.getPointer());
  7247. Sizes.push_back(Size);
  7248. // We need to add a pointer flag for each map that comes from the
  7249. // same expression except for the first one. We also need to signal
  7250. // this map is the first one that relates with the current capture
  7251. // (there is a set of entries for each capture).
  7252. OpenMPOffloadMappingFlags Flags = getMapTypeBits(
  7253. MapType, MapModifiers, IsImplicit,
  7254. !IsExpressionFirstInfo || RequiresReference,
  7255. IsCaptureFirstInfo && !RequiresReference);
  7256. if (!IsExpressionFirstInfo) {
  7257. // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
  7258. // then we reset the TO/FROM/ALWAYS/DELETE flags.
  7259. if (IsPointer)
  7260. Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
  7261. OMP_MAP_DELETE);
  7262. if (ShouldBeMemberOf) {
  7263. // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
  7264. // should be later updated with the correct value of MEMBER_OF.
  7265. Flags |= OMP_MAP_MEMBER_OF;
  7266. // From now on, all subsequent PTR_AND_OBJ entries should not be
  7267. // marked as MEMBER_OF.
  7268. ShouldBeMemberOf = false;
  7269. }
  7270. }
  7271. Types.push_back(Flags);
  7272. }
  7273. // If we have encountered a member expression so far, keep track of the
  7274. // mapped member. If the parent is "*this", then the value declaration
  7275. // is nullptr.
  7276. if (EncounteredME) {
  7277. const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
  7278. unsigned FieldIndex = FD->getFieldIndex();
  7279. // Update info about the lowest and highest elements for this struct
  7280. if (!PartialStruct.Base.isValid()) {
  7281. PartialStruct.LowestElem = {FieldIndex, LB};
  7282. PartialStruct.HighestElem = {FieldIndex, LB};
  7283. PartialStruct.Base = BP;
  7284. } else if (FieldIndex < PartialStruct.LowestElem.first) {
  7285. PartialStruct.LowestElem = {FieldIndex, LB};
  7286. } else if (FieldIndex > PartialStruct.HighestElem.first) {
  7287. PartialStruct.HighestElem = {FieldIndex, LB};
  7288. }
  7289. }
  7290. // If we have a final array section, we are done with this expression.
  7291. if (IsFinalArraySection)
  7292. break;
  7293. // The pointer becomes the base for the next element.
  7294. if (Next != CE)
  7295. BP = LB;
  7296. IsExpressionFirstInfo = false;
  7297. IsCaptureFirstInfo = false;
  7298. }
  7299. }
  7300. }
  7301. /// Return the adjusted map modifiers if the declaration a capture refers to
  7302. /// appears in a first-private clause. This is expected to be used only with
  7303. /// directives that start with 'target'.
  7304. MappableExprsHandler::OpenMPOffloadMappingFlags
  7305. getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
  7306. assert(Cap.capturesVariable() && "Expected capture by reference only!");
  7307. // A first private variable captured by reference will use only the
  7308. // 'private ptr' and 'map to' flag. Return the right flags if the captured
  7309. // declaration is known as first-private in this handler.
  7310. if (FirstPrivateDecls.count(Cap.getCapturedVar())) {
  7311. if (Cap.getCapturedVar()->getType().isConstant(CGF.getContext()) &&
  7312. Cap.getCaptureKind() == CapturedStmt::VCK_ByRef)
  7313. return MappableExprsHandler::OMP_MAP_ALWAYS |
  7314. MappableExprsHandler::OMP_MAP_TO;
  7315. if (Cap.getCapturedVar()->getType()->isAnyPointerType())
  7316. return MappableExprsHandler::OMP_MAP_TO |
  7317. MappableExprsHandler::OMP_MAP_PTR_AND_OBJ;
  7318. return MappableExprsHandler::OMP_MAP_PRIVATE |
  7319. MappableExprsHandler::OMP_MAP_TO;
  7320. }
  7321. return MappableExprsHandler::OMP_MAP_TO |
  7322. MappableExprsHandler::OMP_MAP_FROM;
  7323. }
  7324. static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
  7325. // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
  7326. return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
  7327. << 48);
  7328. }
  7329. static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
  7330. OpenMPOffloadMappingFlags MemberOfFlag) {
  7331. // If the entry is PTR_AND_OBJ but has not been marked with the special
  7332. // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
  7333. // marked as MEMBER_OF.
  7334. if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
  7335. ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
  7336. return;
  7337. // Reset the placeholder value to prepare the flag for the assignment of the
  7338. // proper MEMBER_OF value.
  7339. Flags &= ~OMP_MAP_MEMBER_OF;
  7340. Flags |= MemberOfFlag;
  7341. }
  7342. void getPlainLayout(const CXXRecordDecl *RD,
  7343. llvm::SmallVectorImpl<const FieldDecl *> &Layout,
  7344. bool AsBase) const {
  7345. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  7346. llvm::StructType *St =
  7347. AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
  7348. unsigned NumElements = St->getNumElements();
  7349. llvm::SmallVector<
  7350. llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
  7351. RecordLayout(NumElements);
  7352. // Fill bases.
  7353. for (const auto &I : RD->bases()) {
  7354. if (I.isVirtual())
  7355. continue;
  7356. const auto *Base = I.getType()->getAsCXXRecordDecl();
  7357. // Ignore empty bases.
  7358. if (Base->isEmpty() || CGF.getContext()
  7359. .getASTRecordLayout(Base)
  7360. .getNonVirtualSize()
  7361. .isZero())
  7362. continue;
  7363. unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
  7364. RecordLayout[FieldIndex] = Base;
  7365. }
  7366. // Fill in virtual bases.
  7367. for (const auto &I : RD->vbases()) {
  7368. const auto *Base = I.getType()->getAsCXXRecordDecl();
  7369. // Ignore empty bases.
  7370. if (Base->isEmpty())
  7371. continue;
  7372. unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
  7373. if (RecordLayout[FieldIndex])
  7374. continue;
  7375. RecordLayout[FieldIndex] = Base;
  7376. }
  7377. // Fill in all the fields.
  7378. assert(!RD->isUnion() && "Unexpected union.");
  7379. for (const auto *Field : RD->fields()) {
  7380. // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
  7381. // will fill in later.)
  7382. if (!Field->isBitField() && !Field->isZeroSize(CGF.getContext())) {
  7383. unsigned FieldIndex = RL.getLLVMFieldNo(Field);
  7384. RecordLayout[FieldIndex] = Field;
  7385. }
  7386. }
  7387. for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
  7388. &Data : RecordLayout) {
  7389. if (Data.isNull())
  7390. continue;
  7391. if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
  7392. getPlainLayout(Base, Layout, /*AsBase=*/true);
  7393. else
  7394. Layout.push_back(Data.get<const FieldDecl *>());
  7395. }
  7396. }
  7397. public:
  7398. MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
  7399. : CurDir(Dir), CGF(CGF) {
  7400. // Extract firstprivate clause information.
  7401. for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
  7402. for (const auto *D : C->varlists())
  7403. FirstPrivateDecls.insert(
  7404. cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
  7405. // Extract device pointer clause information.
  7406. for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
  7407. for (auto L : C->component_lists())
  7408. DevPointersMap[L.first].push_back(L.second);
  7409. }
  7410. /// Generate code for the combined entry if we have a partially mapped struct
  7411. /// and take care of the mapping flags of the arguments corresponding to
  7412. /// individual struct members.
  7413. void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
  7414. MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
  7415. MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
  7416. const StructRangeInfoTy &PartialStruct) const {
  7417. // Base is the base of the struct
  7418. BasePointers.push_back(PartialStruct.Base.getPointer());
  7419. // Pointer is the address of the lowest element
  7420. llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
  7421. Pointers.push_back(LB);
  7422. // Size is (addr of {highest+1} element) - (addr of lowest element)
  7423. llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
  7424. llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
  7425. llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
  7426. llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
  7427. llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
  7428. llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
  7429. /*isSinged=*/false);
  7430. Sizes.push_back(Size);
  7431. // Map type is always TARGET_PARAM
  7432. Types.push_back(OMP_MAP_TARGET_PARAM);
  7433. // Remove TARGET_PARAM flag from the first element
  7434. (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
  7435. // All other current entries will be MEMBER_OF the combined entry
  7436. // (except for PTR_AND_OBJ entries which do not have a placeholder value
  7437. // 0xFFFF in the MEMBER_OF field).
  7438. OpenMPOffloadMappingFlags MemberOfFlag =
  7439. getMemberOfFlag(BasePointers.size() - 1);
  7440. for (auto &M : CurTypes)
  7441. setCorrectMemberOfFlag(M, MemberOfFlag);
  7442. }
  7443. /// Generate all the base pointers, section pointers, sizes and map
  7444. /// types for the extracted mappable expressions. Also, for each item that
  7445. /// relates with a device pointer, a pair of the relevant declaration and
  7446. /// index where it occurs is appended to the device pointers info array.
  7447. void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
  7448. MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
  7449. MapFlagsArrayTy &Types) const {
  7450. // We have to process the component lists that relate with the same
  7451. // declaration in a single chunk so that we can generate the map flags
  7452. // correctly. Therefore, we organize all lists in a map.
  7453. llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
  7454. // Helper function to fill the information map for the different supported
  7455. // clauses.
  7456. auto &&InfoGen = [&Info](
  7457. const ValueDecl *D,
  7458. OMPClauseMappableExprCommon::MappableExprComponentListRef L,
  7459. OpenMPMapClauseKind MapType,
  7460. ArrayRef<OpenMPMapModifierKind> MapModifiers,
  7461. bool ReturnDevicePointer, bool IsImplicit) {
  7462. const ValueDecl *VD =
  7463. D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
  7464. Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
  7465. IsImplicit);
  7466. };
  7467. // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
  7468. for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
  7469. for (const auto &L : C->component_lists()) {
  7470. InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
  7471. /*ReturnDevicePointer=*/false, C->isImplicit());
  7472. }
  7473. for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
  7474. for (const auto &L : C->component_lists()) {
  7475. InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
  7476. /*ReturnDevicePointer=*/false, C->isImplicit());
  7477. }
  7478. for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
  7479. for (const auto &L : C->component_lists()) {
  7480. InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
  7481. /*ReturnDevicePointer=*/false, C->isImplicit());
  7482. }
  7483. // Look at the use_device_ptr clause information and mark the existing map
  7484. // entries as such. If there is no map information for an entry in the
  7485. // use_device_ptr list, we create one with map type 'alloc' and zero size
  7486. // section. It is the user fault if that was not mapped before. If there is
  7487. // no map information and the pointer is a struct member, then we defer the
  7488. // emission of that entry until the whole struct has been processed.
  7489. llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
  7490. DeferredInfo;
  7491. // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
  7492. for (const auto *C :
  7493. this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
  7494. for (const auto &L : C->component_lists()) {
  7495. assert(!L.second.empty() && "Not expecting empty list of components!");
  7496. const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
  7497. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  7498. const Expr *IE = L.second.back().getAssociatedExpression();
  7499. // If the first component is a member expression, we have to look into
  7500. // 'this', which maps to null in the map of map information. Otherwise
  7501. // look directly for the information.
  7502. auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
  7503. // We potentially have map information for this declaration already.
  7504. // Look for the first set of components that refer to it.
  7505. if (It != Info.end()) {
  7506. auto CI = std::find_if(
  7507. It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
  7508. return MI.Components.back().getAssociatedDeclaration() == VD;
  7509. });
  7510. // If we found a map entry, signal that the pointer has to be returned
  7511. // and move on to the next declaration.
  7512. if (CI != It->second.end()) {
  7513. CI->ReturnDevicePointer = true;
  7514. continue;
  7515. }
  7516. }
  7517. // We didn't find any match in our map information - generate a zero
  7518. // size array section - if the pointer is a struct member we defer this
  7519. // action until the whole struct has been processed.
  7520. // FIXME: MSVC 2013 seems to require this-> to find member CGF.
  7521. if (isa<MemberExpr>(IE)) {
  7522. // Insert the pointer into Info to be processed by
  7523. // generateInfoForComponentList. Because it is a member pointer
  7524. // without a pointee, no entry will be generated for it, therefore
  7525. // we need to generate one after the whole struct has been processed.
  7526. // Nonetheless, generateInfoForComponentList must be called to take
  7527. // the pointer into account for the calculation of the range of the
  7528. // partial struct.
  7529. InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
  7530. /*ReturnDevicePointer=*/false, C->isImplicit());
  7531. DeferredInfo[nullptr].emplace_back(IE, VD);
  7532. } else {
  7533. llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
  7534. this->CGF.EmitLValue(IE), IE->getExprLoc());
  7535. BasePointers.emplace_back(Ptr, VD);
  7536. Pointers.push_back(Ptr);
  7537. Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
  7538. Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
  7539. }
  7540. }
  7541. }
  7542. for (const auto &M : Info) {
  7543. // We need to know when we generate information for the first component
  7544. // associated with a capture, because the mapping flags depend on it.
  7545. bool IsFirstComponentList = true;
  7546. // Temporary versions of arrays
  7547. MapBaseValuesArrayTy CurBasePointers;
  7548. MapValuesArrayTy CurPointers;
  7549. MapValuesArrayTy CurSizes;
  7550. MapFlagsArrayTy CurTypes;
  7551. StructRangeInfoTy PartialStruct;
  7552. for (const MapInfo &L : M.second) {
  7553. assert(!L.Components.empty() &&
  7554. "Not expecting declaration with no component lists.");
  7555. // Remember the current base pointer index.
  7556. unsigned CurrentBasePointersIdx = CurBasePointers.size();
  7557. // FIXME: MSVC 2013 seems to require this-> to find the member method.
  7558. this->generateInfoForComponentList(
  7559. L.MapType, L.MapModifiers, L.Components, CurBasePointers,
  7560. CurPointers, CurSizes, CurTypes, PartialStruct,
  7561. IsFirstComponentList, L.IsImplicit);
  7562. // If this entry relates with a device pointer, set the relevant
  7563. // declaration and add the 'return pointer' flag.
  7564. if (L.ReturnDevicePointer) {
  7565. assert(CurBasePointers.size() > CurrentBasePointersIdx &&
  7566. "Unexpected number of mapped base pointers.");
  7567. const ValueDecl *RelevantVD =
  7568. L.Components.back().getAssociatedDeclaration();
  7569. assert(RelevantVD &&
  7570. "No relevant declaration related with device pointer??");
  7571. CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
  7572. CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
  7573. }
  7574. IsFirstComponentList = false;
  7575. }
  7576. // Append any pending zero-length pointers which are struct members and
  7577. // used with use_device_ptr.
  7578. auto CI = DeferredInfo.find(M.first);
  7579. if (CI != DeferredInfo.end()) {
  7580. for (const DeferredDevicePtrEntryTy &L : CI->second) {
  7581. llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
  7582. llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
  7583. this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
  7584. CurBasePointers.emplace_back(BasePtr, L.VD);
  7585. CurPointers.push_back(Ptr);
  7586. CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
  7587. // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
  7588. // value MEMBER_OF=FFFF so that the entry is later updated with the
  7589. // correct value of MEMBER_OF.
  7590. CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
  7591. OMP_MAP_MEMBER_OF);
  7592. }
  7593. }
  7594. // If there is an entry in PartialStruct it means we have a struct with
  7595. // individual members mapped. Emit an extra combined entry.
  7596. if (PartialStruct.Base.isValid())
  7597. emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
  7598. PartialStruct);
  7599. // We need to append the results of this capture to what we already have.
  7600. BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
  7601. Pointers.append(CurPointers.begin(), CurPointers.end());
  7602. Sizes.append(CurSizes.begin(), CurSizes.end());
  7603. Types.append(CurTypes.begin(), CurTypes.end());
  7604. }
  7605. }
  7606. /// Emit capture info for lambdas for variables captured by reference.
  7607. void generateInfoForLambdaCaptures(
  7608. const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
  7609. MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
  7610. MapFlagsArrayTy &Types,
  7611. llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
  7612. const auto *RD = VD->getType()
  7613. .getCanonicalType()
  7614. .getNonReferenceType()
  7615. ->getAsCXXRecordDecl();
  7616. if (!RD || !RD->isLambda())
  7617. return;
  7618. Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
  7619. LValue VDLVal = CGF.MakeAddrLValue(
  7620. VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
  7621. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  7622. FieldDecl *ThisCapture = nullptr;
  7623. RD->getCaptureFields(Captures, ThisCapture);
  7624. if (ThisCapture) {
  7625. LValue ThisLVal =
  7626. CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
  7627. LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
  7628. LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
  7629. BasePointers.push_back(ThisLVal.getPointer());
  7630. Pointers.push_back(ThisLValVal.getPointer());
  7631. Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
  7632. Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
  7633. OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
  7634. }
  7635. for (const LambdaCapture &LC : RD->captures()) {
  7636. if (LC.getCaptureKind() != LCK_ByRef)
  7637. continue;
  7638. const VarDecl *VD = LC.getCapturedVar();
  7639. auto It = Captures.find(VD);
  7640. assert(It != Captures.end() && "Found lambda capture without field.");
  7641. LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
  7642. LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
  7643. LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
  7644. BasePointers.push_back(VarLVal.getPointer());
  7645. Pointers.push_back(VarLValVal.getPointer());
  7646. Sizes.push_back(CGF.getTypeSize(
  7647. VD->getType().getCanonicalType().getNonReferenceType()));
  7648. Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
  7649. OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
  7650. }
  7651. }
  7652. /// Set correct indices for lambdas captures.
  7653. void adjustMemberOfForLambdaCaptures(
  7654. const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
  7655. MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
  7656. MapFlagsArrayTy &Types) const {
  7657. for (unsigned I = 0, E = Types.size(); I < E; ++I) {
  7658. // Set correct member_of idx for all implicit lambda captures.
  7659. if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
  7660. OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
  7661. continue;
  7662. llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
  7663. assert(BasePtr && "Unable to find base lambda address.");
  7664. int TgtIdx = -1;
  7665. for (unsigned J = I; J > 0; --J) {
  7666. unsigned Idx = J - 1;
  7667. if (Pointers[Idx] != BasePtr)
  7668. continue;
  7669. TgtIdx = Idx;
  7670. break;
  7671. }
  7672. assert(TgtIdx != -1 && "Unable to find parent lambda.");
  7673. // All other current entries will be MEMBER_OF the combined entry
  7674. // (except for PTR_AND_OBJ entries which do not have a placeholder value
  7675. // 0xFFFF in the MEMBER_OF field).
  7676. OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
  7677. setCorrectMemberOfFlag(Types[I], MemberOfFlag);
  7678. }
  7679. }
  7680. /// Generate the base pointers, section pointers, sizes and map types
  7681. /// associated to a given capture.
  7682. void generateInfoForCapture(const CapturedStmt::Capture *Cap,
  7683. llvm::Value *Arg,
  7684. MapBaseValuesArrayTy &BasePointers,
  7685. MapValuesArrayTy &Pointers,
  7686. MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
  7687. StructRangeInfoTy &PartialStruct) const {
  7688. assert(!Cap->capturesVariableArrayType() &&
  7689. "Not expecting to generate map info for a variable array type!");
  7690. // We need to know when we generating information for the first component
  7691. const ValueDecl *VD = Cap->capturesThis()
  7692. ? nullptr
  7693. : Cap->getCapturedVar()->getCanonicalDecl();
  7694. // If this declaration appears in a is_device_ptr clause we just have to
  7695. // pass the pointer by value. If it is a reference to a declaration, we just
  7696. // pass its value.
  7697. if (DevPointersMap.count(VD)) {
  7698. BasePointers.emplace_back(Arg, VD);
  7699. Pointers.push_back(Arg);
  7700. Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
  7701. Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
  7702. return;
  7703. }
  7704. using MapData =
  7705. std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
  7706. OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
  7707. SmallVector<MapData, 4> DeclComponentLists;
  7708. // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
  7709. for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
  7710. for (const auto &L : C->decl_component_lists(VD)) {
  7711. assert(L.first == VD &&
  7712. "We got information for the wrong declaration??");
  7713. assert(!L.second.empty() &&
  7714. "Not expecting declaration with no component lists.");
  7715. DeclComponentLists.emplace_back(L.second, C->getMapType(),
  7716. C->getMapTypeModifiers(),
  7717. C->isImplicit());
  7718. }
  7719. }
  7720. // Find overlapping elements (including the offset from the base element).
  7721. llvm::SmallDenseMap<
  7722. const MapData *,
  7723. llvm::SmallVector<
  7724. OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
  7725. 4>
  7726. OverlappedData;
  7727. size_t Count = 0;
  7728. for (const MapData &L : DeclComponentLists) {
  7729. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7730. OpenMPMapClauseKind MapType;
  7731. ArrayRef<OpenMPMapModifierKind> MapModifiers;
  7732. bool IsImplicit;
  7733. std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
  7734. ++Count;
  7735. for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
  7736. OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
  7737. std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
  7738. auto CI = Components.rbegin();
  7739. auto CE = Components.rend();
  7740. auto SI = Components1.rbegin();
  7741. auto SE = Components1.rend();
  7742. for (; CI != CE && SI != SE; ++CI, ++SI) {
  7743. if (CI->getAssociatedExpression()->getStmtClass() !=
  7744. SI->getAssociatedExpression()->getStmtClass())
  7745. break;
  7746. // Are we dealing with different variables/fields?
  7747. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  7748. break;
  7749. }
  7750. // Found overlapping if, at least for one component, reached the head of
  7751. // the components list.
  7752. if (CI == CE || SI == SE) {
  7753. assert((CI != CE || SI != SE) &&
  7754. "Unexpected full match of the mapping components.");
  7755. const MapData &BaseData = CI == CE ? L : L1;
  7756. OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
  7757. SI == SE ? Components : Components1;
  7758. auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
  7759. OverlappedElements.getSecond().push_back(SubData);
  7760. }
  7761. }
  7762. }
  7763. // Sort the overlapped elements for each item.
  7764. llvm::SmallVector<const FieldDecl *, 4> Layout;
  7765. if (!OverlappedData.empty()) {
  7766. if (const auto *CRD =
  7767. VD->getType().getCanonicalType()->getAsCXXRecordDecl())
  7768. getPlainLayout(CRD, Layout, /*AsBase=*/false);
  7769. else {
  7770. const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
  7771. Layout.append(RD->field_begin(), RD->field_end());
  7772. }
  7773. }
  7774. for (auto &Pair : OverlappedData) {
  7775. llvm::sort(
  7776. Pair.getSecond(),
  7777. [&Layout](
  7778. OMPClauseMappableExprCommon::MappableExprComponentListRef First,
  7779. OMPClauseMappableExprCommon::MappableExprComponentListRef
  7780. Second) {
  7781. auto CI = First.rbegin();
  7782. auto CE = First.rend();
  7783. auto SI = Second.rbegin();
  7784. auto SE = Second.rend();
  7785. for (; CI != CE && SI != SE; ++CI, ++SI) {
  7786. if (CI->getAssociatedExpression()->getStmtClass() !=
  7787. SI->getAssociatedExpression()->getStmtClass())
  7788. break;
  7789. // Are we dealing with different variables/fields?
  7790. if (CI->getAssociatedDeclaration() !=
  7791. SI->getAssociatedDeclaration())
  7792. break;
  7793. }
  7794. // Lists contain the same elements.
  7795. if (CI == CE && SI == SE)
  7796. return false;
  7797. // List with less elements is less than list with more elements.
  7798. if (CI == CE || SI == SE)
  7799. return CI == CE;
  7800. const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
  7801. const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
  7802. if (FD1->getParent() == FD2->getParent())
  7803. return FD1->getFieldIndex() < FD2->getFieldIndex();
  7804. const auto It =
  7805. llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
  7806. return FD == FD1 || FD == FD2;
  7807. });
  7808. return *It == FD1;
  7809. });
  7810. }
  7811. // Associated with a capture, because the mapping flags depend on it.
  7812. // Go through all of the elements with the overlapped elements.
  7813. for (const auto &Pair : OverlappedData) {
  7814. const MapData &L = *Pair.getFirst();
  7815. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7816. OpenMPMapClauseKind MapType;
  7817. ArrayRef<OpenMPMapModifierKind> MapModifiers;
  7818. bool IsImplicit;
  7819. std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
  7820. ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
  7821. OverlappedComponents = Pair.getSecond();
  7822. bool IsFirstComponentList = true;
  7823. generateInfoForComponentList(MapType, MapModifiers, Components,
  7824. BasePointers, Pointers, Sizes, Types,
  7825. PartialStruct, IsFirstComponentList,
  7826. IsImplicit, OverlappedComponents);
  7827. }
  7828. // Go through other elements without overlapped elements.
  7829. bool IsFirstComponentList = OverlappedData.empty();
  7830. for (const MapData &L : DeclComponentLists) {
  7831. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7832. OpenMPMapClauseKind MapType;
  7833. ArrayRef<OpenMPMapModifierKind> MapModifiers;
  7834. bool IsImplicit;
  7835. std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
  7836. auto It = OverlappedData.find(&L);
  7837. if (It == OverlappedData.end())
  7838. generateInfoForComponentList(MapType, MapModifiers, Components,
  7839. BasePointers, Pointers, Sizes, Types,
  7840. PartialStruct, IsFirstComponentList,
  7841. IsImplicit);
  7842. IsFirstComponentList = false;
  7843. }
  7844. }
  7845. /// Generate the base pointers, section pointers, sizes and map types
  7846. /// associated with the declare target link variables.
  7847. void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
  7848. MapValuesArrayTy &Pointers,
  7849. MapValuesArrayTy &Sizes,
  7850. MapFlagsArrayTy &Types) const {
  7851. // Map other list items in the map clause which are not captured variables
  7852. // but "declare target link" global variables.
  7853. for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
  7854. for (const auto &L : C->component_lists()) {
  7855. if (!L.first)
  7856. continue;
  7857. const auto *VD = dyn_cast<VarDecl>(L.first);
  7858. if (!VD)
  7859. continue;
  7860. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  7861. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  7862. if (CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory() ||
  7863. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
  7864. continue;
  7865. StructRangeInfoTy PartialStruct;
  7866. generateInfoForComponentList(
  7867. C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
  7868. Pointers, Sizes, Types, PartialStruct,
  7869. /*IsFirstComponentList=*/true, C->isImplicit());
  7870. assert(!PartialStruct.Base.isValid() &&
  7871. "No partial structs for declare target link expected.");
  7872. }
  7873. }
  7874. }
  7875. /// Generate the default map information for a given capture \a CI,
  7876. /// record field declaration \a RI and captured value \a CV.
  7877. void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
  7878. const FieldDecl &RI, llvm::Value *CV,
  7879. MapBaseValuesArrayTy &CurBasePointers,
  7880. MapValuesArrayTy &CurPointers,
  7881. MapValuesArrayTy &CurSizes,
  7882. MapFlagsArrayTy &CurMapTypes) const {
  7883. // Do the default mapping.
  7884. if (CI.capturesThis()) {
  7885. CurBasePointers.push_back(CV);
  7886. CurPointers.push_back(CV);
  7887. const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
  7888. CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
  7889. // Default map type.
  7890. CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
  7891. } else if (CI.capturesVariableByCopy()) {
  7892. CurBasePointers.push_back(CV);
  7893. CurPointers.push_back(CV);
  7894. if (!RI.getType()->isAnyPointerType()) {
  7895. // We have to signal to the runtime captures passed by value that are
  7896. // not pointers.
  7897. CurMapTypes.push_back(OMP_MAP_LITERAL);
  7898. CurSizes.push_back(CGF.getTypeSize(RI.getType()));
  7899. } else {
  7900. // Pointers are implicitly mapped with a zero size and no flags
  7901. // (other than first map that is added for all implicit maps).
  7902. CurMapTypes.push_back(OMP_MAP_NONE);
  7903. CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
  7904. }
  7905. } else {
  7906. assert(CI.capturesVariable() && "Expected captured reference.");
  7907. const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
  7908. QualType ElementType = PtrTy->getPointeeType();
  7909. CurSizes.push_back(CGF.getTypeSize(ElementType));
  7910. // The default map type for a scalar/complex type is 'to' because by
  7911. // default the value doesn't have to be retrieved. For an aggregate
  7912. // type, the default is 'tofrom'.
  7913. CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
  7914. const VarDecl *VD = CI.getCapturedVar();
  7915. if (FirstPrivateDecls.count(VD) &&
  7916. VD->getType().isConstant(CGF.getContext())) {
  7917. llvm::Constant *Addr =
  7918. CGF.CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(CGF, VD);
  7919. // Copy the value of the original variable to the new global copy.
  7920. CGF.Builder.CreateMemCpy(
  7921. CGF.MakeNaturalAlignAddrLValue(Addr, ElementType).getAddress(),
  7922. Address(CV, CGF.getContext().getTypeAlignInChars(ElementType)),
  7923. CurSizes.back(), /*isVolatile=*/false);
  7924. // Use new global variable as the base pointers.
  7925. CurBasePointers.push_back(Addr);
  7926. CurPointers.push_back(Addr);
  7927. } else {
  7928. CurBasePointers.push_back(CV);
  7929. if (FirstPrivateDecls.count(VD) && ElementType->isAnyPointerType()) {
  7930. Address PtrAddr = CGF.EmitLoadOfReference(CGF.MakeAddrLValue(
  7931. CV, ElementType, CGF.getContext().getDeclAlign(VD),
  7932. AlignmentSource::Decl));
  7933. CurPointers.push_back(PtrAddr.getPointer());
  7934. } else {
  7935. CurPointers.push_back(CV);
  7936. }
  7937. }
  7938. }
  7939. // Every default map produces a single argument which is a target parameter.
  7940. CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
  7941. // Add flag stating this is an implicit map.
  7942. CurMapTypes.back() |= OMP_MAP_IMPLICIT;
  7943. }
  7944. };
  7945. } // anonymous namespace
  7946. /// Emit the arrays used to pass the captures and map information to the
  7947. /// offloading runtime library. If there is no map or capture information,
  7948. /// return nullptr by reference.
  7949. static void
  7950. emitOffloadingArrays(CodeGenFunction &CGF,
  7951. MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
  7952. MappableExprsHandler::MapValuesArrayTy &Pointers,
  7953. MappableExprsHandler::MapValuesArrayTy &Sizes,
  7954. MappableExprsHandler::MapFlagsArrayTy &MapTypes,
  7955. CGOpenMPRuntime::TargetDataInfo &Info) {
  7956. CodeGenModule &CGM = CGF.CGM;
  7957. ASTContext &Ctx = CGF.getContext();
  7958. // Reset the array information.
  7959. Info.clearArrayInfo();
  7960. Info.NumberOfPtrs = BasePointers.size();
  7961. if (Info.NumberOfPtrs) {
  7962. // Detect if we have any capture size requiring runtime evaluation of the
  7963. // size so that a constant array could be eventually used.
  7964. bool hasRuntimeEvaluationCaptureSize = false;
  7965. for (llvm::Value *S : Sizes)
  7966. if (!isa<llvm::Constant>(S)) {
  7967. hasRuntimeEvaluationCaptureSize = true;
  7968. break;
  7969. }
  7970. llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
  7971. QualType PointerArrayType =
  7972. Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
  7973. /*IndexTypeQuals=*/0);
  7974. Info.BasePointersArray =
  7975. CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
  7976. Info.PointersArray =
  7977. CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
  7978. // If we don't have any VLA types or other types that require runtime
  7979. // evaluation, we can use a constant array for the map sizes, otherwise we
  7980. // need to fill up the arrays as we do for the pointers.
  7981. if (hasRuntimeEvaluationCaptureSize) {
  7982. QualType SizeArrayType = Ctx.getConstantArrayType(
  7983. Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
  7984. /*IndexTypeQuals=*/0);
  7985. Info.SizesArray =
  7986. CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
  7987. } else {
  7988. // We expect all the sizes to be constant, so we collect them to create
  7989. // a constant array.
  7990. SmallVector<llvm::Constant *, 16> ConstSizes;
  7991. for (llvm::Value *S : Sizes)
  7992. ConstSizes.push_back(cast<llvm::Constant>(S));
  7993. auto *SizesArrayInit = llvm::ConstantArray::get(
  7994. llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
  7995. std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
  7996. auto *SizesArrayGbl = new llvm::GlobalVariable(
  7997. CGM.getModule(), SizesArrayInit->getType(),
  7998. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
  7999. SizesArrayInit, Name);
  8000. SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  8001. Info.SizesArray = SizesArrayGbl;
  8002. }
  8003. // The map types are always constant so we don't need to generate code to
  8004. // fill arrays. Instead, we create an array constant.
  8005. SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
  8006. llvm::copy(MapTypes, Mapping.begin());
  8007. llvm::Constant *MapTypesArrayInit =
  8008. llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
  8009. std::string MaptypesName =
  8010. CGM.getOpenMPRuntime().getName({"offload_maptypes"});
  8011. auto *MapTypesArrayGbl = new llvm::GlobalVariable(
  8012. CGM.getModule(), MapTypesArrayInit->getType(),
  8013. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
  8014. MapTypesArrayInit, MaptypesName);
  8015. MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  8016. Info.MapTypesArray = MapTypesArrayGbl;
  8017. for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
  8018. llvm::Value *BPVal = *BasePointers[I];
  8019. llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
  8020. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  8021. Info.BasePointersArray, 0, I);
  8022. BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  8023. BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
  8024. Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
  8025. CGF.Builder.CreateStore(BPVal, BPAddr);
  8026. if (Info.requiresDevicePointerInfo())
  8027. if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
  8028. Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
  8029. llvm::Value *PVal = Pointers[I];
  8030. llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
  8031. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  8032. Info.PointersArray, 0, I);
  8033. P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  8034. P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
  8035. Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
  8036. CGF.Builder.CreateStore(PVal, PAddr);
  8037. if (hasRuntimeEvaluationCaptureSize) {
  8038. llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
  8039. llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
  8040. Info.SizesArray,
  8041. /*Idx0=*/0,
  8042. /*Idx1=*/I);
  8043. Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
  8044. CGF.Builder.CreateStore(
  8045. CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
  8046. SAddr);
  8047. }
  8048. }
  8049. }
  8050. }
  8051. /// Emit the arguments to be passed to the runtime library based on the
  8052. /// arrays of pointers, sizes and map types.
  8053. static void emitOffloadingArraysArgument(
  8054. CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
  8055. llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
  8056. llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
  8057. CodeGenModule &CGM = CGF.CGM;
  8058. if (Info.NumberOfPtrs) {
  8059. BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  8060. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  8061. Info.BasePointersArray,
  8062. /*Idx0=*/0, /*Idx1=*/0);
  8063. PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  8064. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  8065. Info.PointersArray,
  8066. /*Idx0=*/0,
  8067. /*Idx1=*/0);
  8068. SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  8069. llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
  8070. /*Idx0=*/0, /*Idx1=*/0);
  8071. MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  8072. llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
  8073. Info.MapTypesArray,
  8074. /*Idx0=*/0,
  8075. /*Idx1=*/0);
  8076. } else {
  8077. BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
  8078. PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
  8079. SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
  8080. MapTypesArrayArg =
  8081. llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
  8082. }
  8083. }
  8084. /// Check for inner distribute directive.
  8085. static const OMPExecutableDirective *
  8086. getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
  8087. const auto *CS = D.getInnermostCapturedStmt();
  8088. const auto *Body =
  8089. CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  8090. const Stmt *ChildStmt =
  8091. CGOpenMPSIMDRuntime::getSingleCompoundChild(Ctx, Body);
  8092. if (const auto *NestedDir =
  8093. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  8094. OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
  8095. switch (D.getDirectiveKind()) {
  8096. case OMPD_target:
  8097. if (isOpenMPDistributeDirective(DKind))
  8098. return NestedDir;
  8099. if (DKind == OMPD_teams) {
  8100. Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
  8101. /*IgnoreCaptured=*/true);
  8102. if (!Body)
  8103. return nullptr;
  8104. ChildStmt = CGOpenMPSIMDRuntime::getSingleCompoundChild(Ctx, Body);
  8105. if (const auto *NND =
  8106. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  8107. DKind = NND->getDirectiveKind();
  8108. if (isOpenMPDistributeDirective(DKind))
  8109. return NND;
  8110. }
  8111. }
  8112. return nullptr;
  8113. case OMPD_target_teams:
  8114. if (isOpenMPDistributeDirective(DKind))
  8115. return NestedDir;
  8116. return nullptr;
  8117. case OMPD_target_parallel:
  8118. case OMPD_target_simd:
  8119. case OMPD_target_parallel_for:
  8120. case OMPD_target_parallel_for_simd:
  8121. return nullptr;
  8122. case OMPD_target_teams_distribute:
  8123. case OMPD_target_teams_distribute_simd:
  8124. case OMPD_target_teams_distribute_parallel_for:
  8125. case OMPD_target_teams_distribute_parallel_for_simd:
  8126. case OMPD_parallel:
  8127. case OMPD_for:
  8128. case OMPD_parallel_for:
  8129. case OMPD_parallel_sections:
  8130. case OMPD_for_simd:
  8131. case OMPD_parallel_for_simd:
  8132. case OMPD_cancel:
  8133. case OMPD_cancellation_point:
  8134. case OMPD_ordered:
  8135. case OMPD_threadprivate:
  8136. case OMPD_allocate:
  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_target_exit_data:
  8153. case OMPD_target_enter_data:
  8154. case OMPD_distribute:
  8155. case OMPD_distribute_simd:
  8156. case OMPD_distribute_parallel_for:
  8157. case OMPD_distribute_parallel_for_simd:
  8158. case OMPD_teams_distribute:
  8159. case OMPD_teams_distribute_simd:
  8160. case OMPD_teams_distribute_parallel_for:
  8161. case OMPD_teams_distribute_parallel_for_simd:
  8162. case OMPD_target_update:
  8163. case OMPD_declare_simd:
  8164. case OMPD_declare_target:
  8165. case OMPD_end_declare_target:
  8166. case OMPD_declare_reduction:
  8167. case OMPD_declare_mapper:
  8168. case OMPD_taskloop:
  8169. case OMPD_taskloop_simd:
  8170. case OMPD_requires:
  8171. case OMPD_unknown:
  8172. llvm_unreachable("Unexpected directive.");
  8173. }
  8174. }
  8175. return nullptr;
  8176. }
  8177. void CGOpenMPRuntime::emitTargetNumIterationsCall(
  8178. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *Device,
  8179. const llvm::function_ref<llvm::Value *(
  8180. CodeGenFunction &CGF, const OMPLoopDirective &D)> &SizeEmitter) {
  8181. OpenMPDirectiveKind Kind = D.getDirectiveKind();
  8182. const OMPExecutableDirective *TD = &D;
  8183. // Get nested teams distribute kind directive, if any.
  8184. if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind))
  8185. TD = getNestedDistributeDirective(CGM.getContext(), D);
  8186. if (!TD)
  8187. return;
  8188. const auto *LD = cast<OMPLoopDirective>(TD);
  8189. auto &&CodeGen = [LD, &Device, &SizeEmitter, this](CodeGenFunction &CGF,
  8190. PrePostActionTy &) {
  8191. llvm::Value *NumIterations = SizeEmitter(CGF, *LD);
  8192. // Emit device ID if any.
  8193. llvm::Value *DeviceID;
  8194. if (Device)
  8195. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  8196. CGF.Int64Ty, /*isSigned=*/true);
  8197. else
  8198. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  8199. llvm::Value *Args[] = {DeviceID, NumIterations};
  8200. CGF.EmitRuntimeCall(
  8201. createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args);
  8202. };
  8203. emitInlinedDirective(CGF, OMPD_unknown, CodeGen);
  8204. }
  8205. void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
  8206. const OMPExecutableDirective &D,
  8207. llvm::Function *OutlinedFn,
  8208. llvm::Value *OutlinedFnID,
  8209. const Expr *IfCond, const Expr *Device) {
  8210. if (!CGF.HaveInsertPoint())
  8211. return;
  8212. assert(OutlinedFn && "Invalid outlined function!");
  8213. const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
  8214. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  8215. const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
  8216. auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
  8217. PrePostActionTy &) {
  8218. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  8219. };
  8220. emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
  8221. CodeGenFunction::OMPTargetDataInfo InputInfo;
  8222. llvm::Value *MapTypesArray = nullptr;
  8223. // Fill up the pointer arrays and transfer execution to the device.
  8224. auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
  8225. &MapTypesArray, &CS, RequiresOuterTask,
  8226. &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
  8227. // On top of the arrays that were filled up, the target offloading call
  8228. // takes as arguments the device id as well as the host pointer. The host
  8229. // pointer is used by the runtime library to identify the current target
  8230. // region, so it only has to be unique and not necessarily point to
  8231. // anything. It could be the pointer to the outlined function that
  8232. // implements the target region, but we aren't using that so that the
  8233. // compiler doesn't need to keep that, and could therefore inline the host
  8234. // function if proven worthwhile during optimization.
  8235. // From this point on, we need to have an ID of the target region defined.
  8236. assert(OutlinedFnID && "Invalid outlined function ID!");
  8237. // Emit device ID if any.
  8238. llvm::Value *DeviceID;
  8239. if (Device) {
  8240. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  8241. CGF.Int64Ty, /*isSigned=*/true);
  8242. } else {
  8243. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  8244. }
  8245. // Emit the number of elements in the offloading arrays.
  8246. llvm::Value *PointerNum =
  8247. CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
  8248. // Return value of the runtime offloading call.
  8249. llvm::Value *Return;
  8250. llvm::Value *NumTeams = emitNumTeamsForTargetDirective(CGF, D);
  8251. llvm::Value *NumThreads = emitNumThreadsForTargetDirective(CGF, D);
  8252. bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
  8253. // The target region is an outlined function launched by the runtime
  8254. // via calls __tgt_target() or __tgt_target_teams().
  8255. //
  8256. // __tgt_target() launches a target region with one team and one thread,
  8257. // executing a serial region. This master thread may in turn launch
  8258. // more threads within its team upon encountering a parallel region,
  8259. // however, no additional teams can be launched on the device.
  8260. //
  8261. // __tgt_target_teams() launches a target region with one or more teams,
  8262. // each with one or more threads. This call is required for target
  8263. // constructs such as:
  8264. // 'target teams'
  8265. // 'target' / 'teams'
  8266. // 'target teams distribute parallel for'
  8267. // 'target parallel'
  8268. // and so on.
  8269. //
  8270. // Note that on the host and CPU targets, the runtime implementation of
  8271. // these calls simply call the outlined function without forking threads.
  8272. // The outlined functions themselves have runtime calls to
  8273. // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
  8274. // the compiler in emitTeamsCall() and emitParallelCall().
  8275. //
  8276. // In contrast, on the NVPTX target, the implementation of
  8277. // __tgt_target_teams() launches a GPU kernel with the requested number
  8278. // of teams and threads so no additional calls to the runtime are required.
  8279. if (NumTeams) {
  8280. // If we have NumTeams defined this means that we have an enclosed teams
  8281. // region. Therefore we also expect to have NumThreads defined. These two
  8282. // values should be defined in the presence of a teams directive,
  8283. // regardless of having any clauses associated. If the user is using teams
  8284. // but no clauses, these two values will be the default that should be
  8285. // passed to the runtime library - a 32-bit integer with the value zero.
  8286. assert(NumThreads && "Thread limit expression should be available along "
  8287. "with number of teams.");
  8288. llvm::Value *OffloadingArgs[] = {DeviceID,
  8289. OutlinedFnID,
  8290. PointerNum,
  8291. InputInfo.BasePointersArray.getPointer(),
  8292. InputInfo.PointersArray.getPointer(),
  8293. InputInfo.SizesArray.getPointer(),
  8294. MapTypesArray,
  8295. NumTeams,
  8296. NumThreads};
  8297. Return = CGF.EmitRuntimeCall(
  8298. createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
  8299. : OMPRTL__tgt_target_teams),
  8300. OffloadingArgs);
  8301. } else {
  8302. llvm::Value *OffloadingArgs[] = {DeviceID,
  8303. OutlinedFnID,
  8304. PointerNum,
  8305. InputInfo.BasePointersArray.getPointer(),
  8306. InputInfo.PointersArray.getPointer(),
  8307. InputInfo.SizesArray.getPointer(),
  8308. MapTypesArray};
  8309. Return = CGF.EmitRuntimeCall(
  8310. createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
  8311. : OMPRTL__tgt_target),
  8312. OffloadingArgs);
  8313. }
  8314. // Check the error code and execute the host version if required.
  8315. llvm::BasicBlock *OffloadFailedBlock =
  8316. CGF.createBasicBlock("omp_offload.failed");
  8317. llvm::BasicBlock *OffloadContBlock =
  8318. CGF.createBasicBlock("omp_offload.cont");
  8319. llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
  8320. CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
  8321. CGF.EmitBlock(OffloadFailedBlock);
  8322. if (RequiresOuterTask) {
  8323. CapturedVars.clear();
  8324. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  8325. }
  8326. emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
  8327. CGF.EmitBranch(OffloadContBlock);
  8328. CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
  8329. };
  8330. // Notify that the host version must be executed.
  8331. auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
  8332. RequiresOuterTask](CodeGenFunction &CGF,
  8333. PrePostActionTy &) {
  8334. if (RequiresOuterTask) {
  8335. CapturedVars.clear();
  8336. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  8337. }
  8338. emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
  8339. };
  8340. auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
  8341. &CapturedVars, RequiresOuterTask,
  8342. &CS](CodeGenFunction &CGF, PrePostActionTy &) {
  8343. // Fill up the arrays with all the captured variables.
  8344. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  8345. MappableExprsHandler::MapValuesArrayTy Pointers;
  8346. MappableExprsHandler::MapValuesArrayTy Sizes;
  8347. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  8348. // Get mappable expression information.
  8349. MappableExprsHandler MEHandler(D, CGF);
  8350. llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
  8351. auto RI = CS.getCapturedRecordDecl()->field_begin();
  8352. auto CV = CapturedVars.begin();
  8353. for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
  8354. CE = CS.capture_end();
  8355. CI != CE; ++CI, ++RI, ++CV) {
  8356. MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
  8357. MappableExprsHandler::MapValuesArrayTy CurPointers;
  8358. MappableExprsHandler::MapValuesArrayTy CurSizes;
  8359. MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
  8360. MappableExprsHandler::StructRangeInfoTy PartialStruct;
  8361. // VLA sizes are passed to the outlined region by copy and do not have map
  8362. // information associated.
  8363. if (CI->capturesVariableArrayType()) {
  8364. CurBasePointers.push_back(*CV);
  8365. CurPointers.push_back(*CV);
  8366. CurSizes.push_back(CGF.getTypeSize(RI->getType()));
  8367. // Copy to the device as an argument. No need to retrieve it.
  8368. CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
  8369. MappableExprsHandler::OMP_MAP_TARGET_PARAM);
  8370. } else {
  8371. // If we have any information in the map clause, we use it, otherwise we
  8372. // just do a default mapping.
  8373. MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
  8374. CurSizes, CurMapTypes, PartialStruct);
  8375. if (CurBasePointers.empty())
  8376. MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
  8377. CurPointers, CurSizes, CurMapTypes);
  8378. // Generate correct mapping for variables captured by reference in
  8379. // lambdas.
  8380. if (CI->capturesVariable())
  8381. MEHandler.generateInfoForLambdaCaptures(
  8382. CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
  8383. CurMapTypes, LambdaPointers);
  8384. }
  8385. // We expect to have at least an element of information for this capture.
  8386. assert(!CurBasePointers.empty() &&
  8387. "Non-existing map pointer for capture!");
  8388. assert(CurBasePointers.size() == CurPointers.size() &&
  8389. CurBasePointers.size() == CurSizes.size() &&
  8390. CurBasePointers.size() == CurMapTypes.size() &&
  8391. "Inconsistent map information sizes!");
  8392. // If there is an entry in PartialStruct it means we have a struct with
  8393. // individual members mapped. Emit an extra combined entry.
  8394. if (PartialStruct.Base.isValid())
  8395. MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
  8396. CurMapTypes, PartialStruct);
  8397. // We need to append the results of this capture to what we already have.
  8398. BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
  8399. Pointers.append(CurPointers.begin(), CurPointers.end());
  8400. Sizes.append(CurSizes.begin(), CurSizes.end());
  8401. MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
  8402. }
  8403. // Adjust MEMBER_OF flags for the lambdas captures.
  8404. MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
  8405. Pointers, MapTypes);
  8406. // Map other list items in the map clause which are not captured variables
  8407. // but "declare target link" global variables.
  8408. MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
  8409. MapTypes);
  8410. TargetDataInfo Info;
  8411. // Fill up the arrays and create the arguments.
  8412. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  8413. emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
  8414. Info.PointersArray, Info.SizesArray,
  8415. Info.MapTypesArray, Info);
  8416. InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
  8417. InputInfo.BasePointersArray =
  8418. Address(Info.BasePointersArray, CGM.getPointerAlign());
  8419. InputInfo.PointersArray =
  8420. Address(Info.PointersArray, CGM.getPointerAlign());
  8421. InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
  8422. MapTypesArray = Info.MapTypesArray;
  8423. if (RequiresOuterTask)
  8424. CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
  8425. else
  8426. emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
  8427. };
  8428. auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
  8429. CodeGenFunction &CGF, PrePostActionTy &) {
  8430. if (RequiresOuterTask) {
  8431. CodeGenFunction::OMPTargetDataInfo InputInfo;
  8432. CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
  8433. } else {
  8434. emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
  8435. }
  8436. };
  8437. // If we have a target function ID it means that we need to support
  8438. // offloading, otherwise, just execute on the host. We need to execute on host
  8439. // regardless of the conditional in the if clause if, e.g., the user do not
  8440. // specify target triples.
  8441. if (OutlinedFnID) {
  8442. if (IfCond) {
  8443. emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
  8444. } else {
  8445. RegionCodeGenTy ThenRCG(TargetThenGen);
  8446. ThenRCG(CGF);
  8447. }
  8448. } else {
  8449. RegionCodeGenTy ElseRCG(TargetElseGen);
  8450. ElseRCG(CGF);
  8451. }
  8452. }
  8453. void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
  8454. StringRef ParentName) {
  8455. if (!S)
  8456. return;
  8457. // Codegen OMP target directives that offload compute to the device.
  8458. bool RequiresDeviceCodegen =
  8459. isa<OMPExecutableDirective>(S) &&
  8460. isOpenMPTargetExecutionDirective(
  8461. cast<OMPExecutableDirective>(S)->getDirectiveKind());
  8462. if (RequiresDeviceCodegen) {
  8463. const auto &E = *cast<OMPExecutableDirective>(S);
  8464. unsigned DeviceID;
  8465. unsigned FileID;
  8466. unsigned Line;
  8467. getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
  8468. FileID, Line);
  8469. // Is this a target region that should not be emitted as an entry point? If
  8470. // so just signal we are done with this target region.
  8471. if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
  8472. ParentName, Line))
  8473. return;
  8474. switch (E.getDirectiveKind()) {
  8475. case OMPD_target:
  8476. CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
  8477. cast<OMPTargetDirective>(E));
  8478. break;
  8479. case OMPD_target_parallel:
  8480. CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
  8481. CGM, ParentName, cast<OMPTargetParallelDirective>(E));
  8482. break;
  8483. case OMPD_target_teams:
  8484. CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
  8485. CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
  8486. break;
  8487. case OMPD_target_teams_distribute:
  8488. CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
  8489. CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
  8490. break;
  8491. case OMPD_target_teams_distribute_simd:
  8492. CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  8493. CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
  8494. break;
  8495. case OMPD_target_parallel_for:
  8496. CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
  8497. CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
  8498. break;
  8499. case OMPD_target_parallel_for_simd:
  8500. CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
  8501. CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
  8502. break;
  8503. case OMPD_target_simd:
  8504. CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
  8505. CGM, ParentName, cast<OMPTargetSimdDirective>(E));
  8506. break;
  8507. case OMPD_target_teams_distribute_parallel_for:
  8508. CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
  8509. CGM, ParentName,
  8510. cast<OMPTargetTeamsDistributeParallelForDirective>(E));
  8511. break;
  8512. case OMPD_target_teams_distribute_parallel_for_simd:
  8513. CodeGenFunction::
  8514. EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
  8515. CGM, ParentName,
  8516. cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
  8517. break;
  8518. case OMPD_parallel:
  8519. case OMPD_for:
  8520. case OMPD_parallel_for:
  8521. case OMPD_parallel_sections:
  8522. case OMPD_for_simd:
  8523. case OMPD_parallel_for_simd:
  8524. case OMPD_cancel:
  8525. case OMPD_cancellation_point:
  8526. case OMPD_ordered:
  8527. case OMPD_threadprivate:
  8528. case OMPD_allocate:
  8529. case OMPD_task:
  8530. case OMPD_simd:
  8531. case OMPD_sections:
  8532. case OMPD_section:
  8533. case OMPD_single:
  8534. case OMPD_master:
  8535. case OMPD_critical:
  8536. case OMPD_taskyield:
  8537. case OMPD_barrier:
  8538. case OMPD_taskwait:
  8539. case OMPD_taskgroup:
  8540. case OMPD_atomic:
  8541. case OMPD_flush:
  8542. case OMPD_teams:
  8543. case OMPD_target_data:
  8544. case OMPD_target_exit_data:
  8545. case OMPD_target_enter_data:
  8546. case OMPD_distribute:
  8547. case OMPD_distribute_simd:
  8548. case OMPD_distribute_parallel_for:
  8549. case OMPD_distribute_parallel_for_simd:
  8550. case OMPD_teams_distribute:
  8551. case OMPD_teams_distribute_simd:
  8552. case OMPD_teams_distribute_parallel_for:
  8553. case OMPD_teams_distribute_parallel_for_simd:
  8554. case OMPD_target_update:
  8555. case OMPD_declare_simd:
  8556. case OMPD_declare_target:
  8557. case OMPD_end_declare_target:
  8558. case OMPD_declare_reduction:
  8559. case OMPD_declare_mapper:
  8560. case OMPD_taskloop:
  8561. case OMPD_taskloop_simd:
  8562. case OMPD_requires:
  8563. case OMPD_unknown:
  8564. llvm_unreachable("Unknown target directive for OpenMP device codegen.");
  8565. }
  8566. return;
  8567. }
  8568. if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
  8569. if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
  8570. return;
  8571. scanForTargetRegionsFunctions(
  8572. E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
  8573. return;
  8574. }
  8575. // If this is a lambda function, look into its body.
  8576. if (const auto *L = dyn_cast<LambdaExpr>(S))
  8577. S = L->getBody();
  8578. // Keep looking for target regions recursively.
  8579. for (const Stmt *II : S->children())
  8580. scanForTargetRegionsFunctions(II, ParentName);
  8581. }
  8582. bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
  8583. // If emitting code for the host, we do not process FD here. Instead we do
  8584. // the normal code generation.
  8585. if (!CGM.getLangOpts().OpenMPIsDevice)
  8586. return false;
  8587. const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
  8588. StringRef Name = CGM.getMangledName(GD);
  8589. // Try to detect target regions in the function.
  8590. if (const auto *FD = dyn_cast<FunctionDecl>(VD))
  8591. scanForTargetRegionsFunctions(FD->getBody(), Name);
  8592. // Do not to emit function if it is not marked as declare target.
  8593. return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  8594. AlreadyEmittedTargetFunctions.count(Name) == 0;
  8595. }
  8596. bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
  8597. if (!CGM.getLangOpts().OpenMPIsDevice)
  8598. return false;
  8599. // Check if there are Ctors/Dtors in this declaration and look for target
  8600. // regions in it. We use the complete variant to produce the kernel name
  8601. // mangling.
  8602. QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
  8603. if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
  8604. for (const CXXConstructorDecl *Ctor : RD->ctors()) {
  8605. StringRef ParentName =
  8606. CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
  8607. scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
  8608. }
  8609. if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
  8610. StringRef ParentName =
  8611. CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
  8612. scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
  8613. }
  8614. }
  8615. // Do not to emit variable if it is not marked as declare target.
  8616. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  8617. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  8618. cast<VarDecl>(GD.getDecl()));
  8619. if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link ||
  8620. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  8621. HasRequiresUnifiedSharedMemory)) {
  8622. DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
  8623. return true;
  8624. }
  8625. return false;
  8626. }
  8627. llvm::Constant *
  8628. CGOpenMPRuntime::registerTargetFirstprivateCopy(CodeGenFunction &CGF,
  8629. const VarDecl *VD) {
  8630. assert(VD->getType().isConstant(CGM.getContext()) &&
  8631. "Expected constant variable.");
  8632. StringRef VarName;
  8633. llvm::Constant *Addr;
  8634. llvm::GlobalValue::LinkageTypes Linkage;
  8635. QualType Ty = VD->getType();
  8636. SmallString<128> Buffer;
  8637. {
  8638. unsigned DeviceID;
  8639. unsigned FileID;
  8640. unsigned Line;
  8641. getTargetEntryUniqueInfo(CGM.getContext(), VD->getLocation(), DeviceID,
  8642. FileID, Line);
  8643. llvm::raw_svector_ostream OS(Buffer);
  8644. OS << "__omp_offloading_firstprivate_" << llvm::format("_%x", DeviceID)
  8645. << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
  8646. VarName = OS.str();
  8647. }
  8648. Linkage = llvm::GlobalValue::InternalLinkage;
  8649. Addr =
  8650. getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(Ty), VarName,
  8651. getDefaultFirstprivateAddressSpace());
  8652. cast<llvm::GlobalValue>(Addr)->setLinkage(Linkage);
  8653. CharUnits VarSize = CGM.getContext().getTypeSizeInChars(Ty);
  8654. CGM.addCompilerUsedGlobal(cast<llvm::GlobalValue>(Addr));
  8655. OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
  8656. VarName, Addr, VarSize,
  8657. OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo, Linkage);
  8658. return Addr;
  8659. }
  8660. void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
  8661. llvm::Constant *Addr) {
  8662. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  8663. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  8664. if (!Res) {
  8665. if (CGM.getLangOpts().OpenMPIsDevice) {
  8666. // Register non-target variables being emitted in device code (debug info
  8667. // may cause this).
  8668. StringRef VarName = CGM.getMangledName(VD);
  8669. EmittedNonTargetVariables.try_emplace(VarName, Addr);
  8670. }
  8671. return;
  8672. }
  8673. // Register declare target variables.
  8674. OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
  8675. StringRef VarName;
  8676. CharUnits VarSize;
  8677. llvm::GlobalValue::LinkageTypes Linkage;
  8678. if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  8679. !HasRequiresUnifiedSharedMemory) {
  8680. Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
  8681. VarName = CGM.getMangledName(VD);
  8682. if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
  8683. VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
  8684. assert(!VarSize.isZero() && "Expected non-zero size of the variable");
  8685. } else {
  8686. VarSize = CharUnits::Zero();
  8687. }
  8688. Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
  8689. // Temp solution to prevent optimizations of the internal variables.
  8690. if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
  8691. std::string RefName = getName({VarName, "ref"});
  8692. if (!CGM.GetGlobalValue(RefName)) {
  8693. llvm::Constant *AddrRef =
  8694. getOrCreateInternalVariable(Addr->getType(), RefName);
  8695. auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
  8696. GVAddrRef->setConstant(/*Val=*/true);
  8697. GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
  8698. GVAddrRef->setInitializer(Addr);
  8699. CGM.addCompilerUsedGlobal(GVAddrRef);
  8700. }
  8701. }
  8702. } else {
  8703. assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  8704. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  8705. HasRequiresUnifiedSharedMemory)) &&
  8706. "Declare target attribute must link or to with unified memory.");
  8707. if (*Res == OMPDeclareTargetDeclAttr::MT_Link)
  8708. Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
  8709. else
  8710. Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
  8711. if (CGM.getLangOpts().OpenMPIsDevice) {
  8712. VarName = Addr->getName();
  8713. Addr = nullptr;
  8714. } else {
  8715. VarName = getAddrOfDeclareTargetVar(VD).getName();
  8716. Addr = cast<llvm::Constant>(getAddrOfDeclareTargetVar(VD).getPointer());
  8717. }
  8718. VarSize = CGM.getPointerSize();
  8719. Linkage = llvm::GlobalValue::WeakAnyLinkage;
  8720. }
  8721. OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
  8722. VarName, Addr, VarSize, Flags, Linkage);
  8723. }
  8724. bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
  8725. if (isa<FunctionDecl>(GD.getDecl()) ||
  8726. isa<OMPDeclareReductionDecl>(GD.getDecl()))
  8727. return emitTargetFunctions(GD);
  8728. return emitTargetGlobalVariable(GD);
  8729. }
  8730. void CGOpenMPRuntime::emitDeferredTargetDecls() const {
  8731. for (const VarDecl *VD : DeferredGlobalVariables) {
  8732. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  8733. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  8734. if (!Res)
  8735. continue;
  8736. if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  8737. !HasRequiresUnifiedSharedMemory) {
  8738. CGM.EmitGlobal(VD);
  8739. } else {
  8740. assert((*Res == OMPDeclareTargetDeclAttr::MT_Link ||
  8741. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  8742. HasRequiresUnifiedSharedMemory)) &&
  8743. "Expected link clause or to clause with unified memory.");
  8744. (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  8745. }
  8746. }
  8747. }
  8748. void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
  8749. CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
  8750. assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
  8751. " Expected target-based directive.");
  8752. }
  8753. void CGOpenMPRuntime::checkArchForUnifiedAddressing(
  8754. const OMPRequiresDecl *D) {
  8755. for (const OMPClause *Clause : D->clauselists()) {
  8756. if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
  8757. HasRequiresUnifiedSharedMemory = true;
  8758. break;
  8759. }
  8760. }
  8761. }
  8762. bool CGOpenMPRuntime::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
  8763. LangAS &AS) {
  8764. if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
  8765. return false;
  8766. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  8767. switch(A->getAllocatorType()) {
  8768. case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
  8769. // Not supported, fallback to the default mem space.
  8770. case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
  8771. case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
  8772. case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
  8773. case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
  8774. case OMPAllocateDeclAttr::OMPThreadMemAlloc:
  8775. case OMPAllocateDeclAttr::OMPConstMemAlloc:
  8776. case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
  8777. AS = LangAS::Default;
  8778. return true;
  8779. case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
  8780. llvm_unreachable("Expected predefined allocator for the variables with the "
  8781. "static storage.");
  8782. }
  8783. return false;
  8784. }
  8785. bool CGOpenMPRuntime::hasRequiresUnifiedSharedMemory() const {
  8786. return HasRequiresUnifiedSharedMemory;
  8787. }
  8788. CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
  8789. CodeGenModule &CGM)
  8790. : CGM(CGM) {
  8791. if (CGM.getLangOpts().OpenMPIsDevice) {
  8792. SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
  8793. CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
  8794. }
  8795. }
  8796. CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
  8797. if (CGM.getLangOpts().OpenMPIsDevice)
  8798. CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
  8799. }
  8800. bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
  8801. if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
  8802. return true;
  8803. StringRef Name = CGM.getMangledName(GD);
  8804. const auto *D = cast<FunctionDecl>(GD.getDecl());
  8805. // Do not to emit function if it is marked as declare target as it was already
  8806. // emitted.
  8807. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
  8808. if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
  8809. if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
  8810. return !F->isDeclaration();
  8811. return false;
  8812. }
  8813. return true;
  8814. }
  8815. return !AlreadyEmittedTargetFunctions.insert(Name).second;
  8816. }
  8817. llvm::Function *CGOpenMPRuntime::emitRequiresDirectiveRegFun() {
  8818. // If we don't have entries or if we are emitting code for the device, we
  8819. // don't need to do anything.
  8820. if (CGM.getLangOpts().OMPTargetTriples.empty() ||
  8821. CGM.getLangOpts().OpenMPSimd || CGM.getLangOpts().OpenMPIsDevice ||
  8822. (OffloadEntriesInfoManager.empty() &&
  8823. !HasEmittedDeclareTargetRegion &&
  8824. !HasEmittedTargetRegion))
  8825. return nullptr;
  8826. // Create and register the function that handles the requires directives.
  8827. ASTContext &C = CGM.getContext();
  8828. llvm::Function *RequiresRegFn;
  8829. {
  8830. CodeGenFunction CGF(CGM);
  8831. const auto &FI = CGM.getTypes().arrangeNullaryFunction();
  8832. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  8833. std::string ReqName = getName({"omp_offloading", "requires_reg"});
  8834. RequiresRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, ReqName, FI);
  8835. CGF.StartFunction(GlobalDecl(), C.VoidTy, RequiresRegFn, FI, {});
  8836. OpenMPOffloadingRequiresDirFlags Flags = OMP_REQ_NONE;
  8837. // TODO: check for other requires clauses.
  8838. // The requires directive takes effect only when a target region is
  8839. // present in the compilation unit. Otherwise it is ignored and not
  8840. // passed to the runtime. This avoids the runtime from throwing an error
  8841. // for mismatching requires clauses across compilation units that don't
  8842. // contain at least 1 target region.
  8843. assert((HasEmittedTargetRegion ||
  8844. HasEmittedDeclareTargetRegion ||
  8845. !OffloadEntriesInfoManager.empty()) &&
  8846. "Target or declare target region expected.");
  8847. if (HasRequiresUnifiedSharedMemory)
  8848. Flags = OMP_REQ_UNIFIED_SHARED_MEMORY;
  8849. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_requires),
  8850. llvm::ConstantInt::get(CGM.Int64Ty, Flags));
  8851. CGF.FinishFunction();
  8852. }
  8853. return RequiresRegFn;
  8854. }
  8855. llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
  8856. // If we have offloading in the current module, we need to emit the entries
  8857. // now and register the offloading descriptor.
  8858. createOffloadEntriesAndInfoMetadata();
  8859. // Create and register the offloading binary descriptors. This is the main
  8860. // entity that captures all the information about offloading in the current
  8861. // compilation unit.
  8862. return createOffloadingBinaryDescriptorRegistration();
  8863. }
  8864. void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
  8865. const OMPExecutableDirective &D,
  8866. SourceLocation Loc,
  8867. llvm::Function *OutlinedFn,
  8868. ArrayRef<llvm::Value *> CapturedVars) {
  8869. if (!CGF.HaveInsertPoint())
  8870. return;
  8871. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  8872. CodeGenFunction::RunCleanupsScope Scope(CGF);
  8873. // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
  8874. llvm::Value *Args[] = {
  8875. RTLoc,
  8876. CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
  8877. CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
  8878. llvm::SmallVector<llvm::Value *, 16> RealArgs;
  8879. RealArgs.append(std::begin(Args), std::end(Args));
  8880. RealArgs.append(CapturedVars.begin(), CapturedVars.end());
  8881. llvm::FunctionCallee RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
  8882. CGF.EmitRuntimeCall(RTLFn, RealArgs);
  8883. }
  8884. void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
  8885. const Expr *NumTeams,
  8886. const Expr *ThreadLimit,
  8887. SourceLocation Loc) {
  8888. if (!CGF.HaveInsertPoint())
  8889. return;
  8890. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  8891. llvm::Value *NumTeamsVal =
  8892. NumTeams
  8893. ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
  8894. CGF.CGM.Int32Ty, /* isSigned = */ true)
  8895. : CGF.Builder.getInt32(0);
  8896. llvm::Value *ThreadLimitVal =
  8897. ThreadLimit
  8898. ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
  8899. CGF.CGM.Int32Ty, /* isSigned = */ true)
  8900. : CGF.Builder.getInt32(0);
  8901. // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
  8902. llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
  8903. ThreadLimitVal};
  8904. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
  8905. PushNumTeamsArgs);
  8906. }
  8907. void CGOpenMPRuntime::emitTargetDataCalls(
  8908. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  8909. const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
  8910. if (!CGF.HaveInsertPoint())
  8911. return;
  8912. // Action used to replace the default codegen action and turn privatization
  8913. // off.
  8914. PrePostActionTy NoPrivAction;
  8915. // Generate the code for the opening of the data environment. Capture all the
  8916. // arguments of the runtime call by reference because they are used in the
  8917. // closing of the region.
  8918. auto &&BeginThenGen = [this, &D, Device, &Info,
  8919. &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
  8920. // Fill up the arrays with all the mapped variables.
  8921. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  8922. MappableExprsHandler::MapValuesArrayTy Pointers;
  8923. MappableExprsHandler::MapValuesArrayTy Sizes;
  8924. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  8925. // Get map clause information.
  8926. MappableExprsHandler MCHandler(D, CGF);
  8927. MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
  8928. // Fill up the arrays and create the arguments.
  8929. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  8930. llvm::Value *BasePointersArrayArg = nullptr;
  8931. llvm::Value *PointersArrayArg = nullptr;
  8932. llvm::Value *SizesArrayArg = nullptr;
  8933. llvm::Value *MapTypesArrayArg = nullptr;
  8934. emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
  8935. SizesArrayArg, MapTypesArrayArg, Info);
  8936. // Emit device ID if any.
  8937. llvm::Value *DeviceID = nullptr;
  8938. if (Device) {
  8939. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  8940. CGF.Int64Ty, /*isSigned=*/true);
  8941. } else {
  8942. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  8943. }
  8944. // Emit the number of elements in the offloading arrays.
  8945. llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
  8946. llvm::Value *OffloadingArgs[] = {
  8947. DeviceID, PointerNum, BasePointersArrayArg,
  8948. PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
  8949. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
  8950. OffloadingArgs);
  8951. // If device pointer privatization is required, emit the body of the region
  8952. // here. It will have to be duplicated: with and without privatization.
  8953. if (!Info.CaptureDeviceAddrMap.empty())
  8954. CodeGen(CGF);
  8955. };
  8956. // Generate code for the closing of the data region.
  8957. auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
  8958. PrePostActionTy &) {
  8959. assert(Info.isValid() && "Invalid data environment closing arguments.");
  8960. llvm::Value *BasePointersArrayArg = nullptr;
  8961. llvm::Value *PointersArrayArg = nullptr;
  8962. llvm::Value *SizesArrayArg = nullptr;
  8963. llvm::Value *MapTypesArrayArg = nullptr;
  8964. emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
  8965. SizesArrayArg, MapTypesArrayArg, Info);
  8966. // Emit device ID if any.
  8967. llvm::Value *DeviceID = nullptr;
  8968. if (Device) {
  8969. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  8970. CGF.Int64Ty, /*isSigned=*/true);
  8971. } else {
  8972. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  8973. }
  8974. // Emit the number of elements in the offloading arrays.
  8975. llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
  8976. llvm::Value *OffloadingArgs[] = {
  8977. DeviceID, PointerNum, BasePointersArrayArg,
  8978. PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
  8979. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
  8980. OffloadingArgs);
  8981. };
  8982. // If we need device pointer privatization, we need to emit the body of the
  8983. // region with no privatization in the 'else' branch of the conditional.
  8984. // Otherwise, we don't have to do anything.
  8985. auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
  8986. PrePostActionTy &) {
  8987. if (!Info.CaptureDeviceAddrMap.empty()) {
  8988. CodeGen.setAction(NoPrivAction);
  8989. CodeGen(CGF);
  8990. }
  8991. };
  8992. // We don't have to do anything to close the region if the if clause evaluates
  8993. // to false.
  8994. auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
  8995. if (IfCond) {
  8996. emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
  8997. } else {
  8998. RegionCodeGenTy RCG(BeginThenGen);
  8999. RCG(CGF);
  9000. }
  9001. // If we don't require privatization of device pointers, we emit the body in
  9002. // between the runtime calls. This avoids duplicating the body code.
  9003. if (Info.CaptureDeviceAddrMap.empty()) {
  9004. CodeGen.setAction(NoPrivAction);
  9005. CodeGen(CGF);
  9006. }
  9007. if (IfCond) {
  9008. emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
  9009. } else {
  9010. RegionCodeGenTy RCG(EndThenGen);
  9011. RCG(CGF);
  9012. }
  9013. }
  9014. void CGOpenMPRuntime::emitTargetDataStandAloneCall(
  9015. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  9016. const Expr *Device) {
  9017. if (!CGF.HaveInsertPoint())
  9018. return;
  9019. assert((isa<OMPTargetEnterDataDirective>(D) ||
  9020. isa<OMPTargetExitDataDirective>(D) ||
  9021. isa<OMPTargetUpdateDirective>(D)) &&
  9022. "Expecting either target enter, exit data, or update directives.");
  9023. CodeGenFunction::OMPTargetDataInfo InputInfo;
  9024. llvm::Value *MapTypesArray = nullptr;
  9025. // Generate the code for the opening of the data environment.
  9026. auto &&ThenGen = [this, &D, Device, &InputInfo,
  9027. &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
  9028. // Emit device ID if any.
  9029. llvm::Value *DeviceID = nullptr;
  9030. if (Device) {
  9031. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  9032. CGF.Int64Ty, /*isSigned=*/true);
  9033. } else {
  9034. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  9035. }
  9036. // Emit the number of elements in the offloading arrays.
  9037. llvm::Constant *PointerNum =
  9038. CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
  9039. llvm::Value *OffloadingArgs[] = {DeviceID,
  9040. PointerNum,
  9041. InputInfo.BasePointersArray.getPointer(),
  9042. InputInfo.PointersArray.getPointer(),
  9043. InputInfo.SizesArray.getPointer(),
  9044. MapTypesArray};
  9045. // Select the right runtime function call for each expected standalone
  9046. // directive.
  9047. const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
  9048. OpenMPRTLFunction RTLFn;
  9049. switch (D.getDirectiveKind()) {
  9050. case OMPD_target_enter_data:
  9051. RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
  9052. : OMPRTL__tgt_target_data_begin;
  9053. break;
  9054. case OMPD_target_exit_data:
  9055. RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
  9056. : OMPRTL__tgt_target_data_end;
  9057. break;
  9058. case OMPD_target_update:
  9059. RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
  9060. : OMPRTL__tgt_target_data_update;
  9061. break;
  9062. case OMPD_parallel:
  9063. case OMPD_for:
  9064. case OMPD_parallel_for:
  9065. case OMPD_parallel_sections:
  9066. case OMPD_for_simd:
  9067. case OMPD_parallel_for_simd:
  9068. case OMPD_cancel:
  9069. case OMPD_cancellation_point:
  9070. case OMPD_ordered:
  9071. case OMPD_threadprivate:
  9072. case OMPD_allocate:
  9073. case OMPD_task:
  9074. case OMPD_simd:
  9075. case OMPD_sections:
  9076. case OMPD_section:
  9077. case OMPD_single:
  9078. case OMPD_master:
  9079. case OMPD_critical:
  9080. case OMPD_taskyield:
  9081. case OMPD_barrier:
  9082. case OMPD_taskwait:
  9083. case OMPD_taskgroup:
  9084. case OMPD_atomic:
  9085. case OMPD_flush:
  9086. case OMPD_teams:
  9087. case OMPD_target_data:
  9088. case OMPD_distribute:
  9089. case OMPD_distribute_simd:
  9090. case OMPD_distribute_parallel_for:
  9091. case OMPD_distribute_parallel_for_simd:
  9092. case OMPD_teams_distribute:
  9093. case OMPD_teams_distribute_simd:
  9094. case OMPD_teams_distribute_parallel_for:
  9095. case OMPD_teams_distribute_parallel_for_simd:
  9096. case OMPD_declare_simd:
  9097. case OMPD_declare_target:
  9098. case OMPD_end_declare_target:
  9099. case OMPD_declare_reduction:
  9100. case OMPD_declare_mapper:
  9101. case OMPD_taskloop:
  9102. case OMPD_taskloop_simd:
  9103. case OMPD_target:
  9104. case OMPD_target_simd:
  9105. case OMPD_target_teams_distribute:
  9106. case OMPD_target_teams_distribute_simd:
  9107. case OMPD_target_teams_distribute_parallel_for:
  9108. case OMPD_target_teams_distribute_parallel_for_simd:
  9109. case OMPD_target_teams:
  9110. case OMPD_target_parallel:
  9111. case OMPD_target_parallel_for:
  9112. case OMPD_target_parallel_for_simd:
  9113. case OMPD_requires:
  9114. case OMPD_unknown:
  9115. llvm_unreachable("Unexpected standalone target data directive.");
  9116. break;
  9117. }
  9118. CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
  9119. };
  9120. auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
  9121. CodeGenFunction &CGF, PrePostActionTy &) {
  9122. // Fill up the arrays with all the mapped variables.
  9123. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  9124. MappableExprsHandler::MapValuesArrayTy Pointers;
  9125. MappableExprsHandler::MapValuesArrayTy Sizes;
  9126. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  9127. // Get map clause information.
  9128. MappableExprsHandler MEHandler(D, CGF);
  9129. MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
  9130. TargetDataInfo Info;
  9131. // Fill up the arrays and create the arguments.
  9132. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  9133. emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
  9134. Info.PointersArray, Info.SizesArray,
  9135. Info.MapTypesArray, Info);
  9136. InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
  9137. InputInfo.BasePointersArray =
  9138. Address(Info.BasePointersArray, CGM.getPointerAlign());
  9139. InputInfo.PointersArray =
  9140. Address(Info.PointersArray, CGM.getPointerAlign());
  9141. InputInfo.SizesArray =
  9142. Address(Info.SizesArray, CGM.getPointerAlign());
  9143. MapTypesArray = Info.MapTypesArray;
  9144. if (D.hasClausesOfKind<OMPDependClause>())
  9145. CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
  9146. else
  9147. emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
  9148. };
  9149. if (IfCond) {
  9150. emitOMPIfClause(CGF, IfCond, TargetThenGen,
  9151. [](CodeGenFunction &CGF, PrePostActionTy &) {});
  9152. } else {
  9153. RegionCodeGenTy ThenRCG(TargetThenGen);
  9154. ThenRCG(CGF);
  9155. }
  9156. }
  9157. namespace {
  9158. /// Kind of parameter in a function with 'declare simd' directive.
  9159. enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
  9160. /// Attribute set of the parameter.
  9161. struct ParamAttrTy {
  9162. ParamKindTy Kind = Vector;
  9163. llvm::APSInt StrideOrArg;
  9164. llvm::APSInt Alignment;
  9165. };
  9166. } // namespace
  9167. static unsigned evaluateCDTSize(const FunctionDecl *FD,
  9168. ArrayRef<ParamAttrTy> ParamAttrs) {
  9169. // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
  9170. // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
  9171. // of that clause. The VLEN value must be power of 2.
  9172. // In other case the notion of the function`s "characteristic data type" (CDT)
  9173. // is used to compute the vector length.
  9174. // CDT is defined in the following order:
  9175. // a) For non-void function, the CDT is the return type.
  9176. // b) If the function has any non-uniform, non-linear parameters, then the
  9177. // CDT is the type of the first such parameter.
  9178. // c) If the CDT determined by a) or b) above is struct, union, or class
  9179. // type which is pass-by-value (except for the type that maps to the
  9180. // built-in complex data type), the characteristic data type is int.
  9181. // d) If none of the above three cases is applicable, the CDT is int.
  9182. // The VLEN is then determined based on the CDT and the size of vector
  9183. // register of that ISA for which current vector version is generated. The
  9184. // VLEN is computed using the formula below:
  9185. // VLEN = sizeof(vector_register) / sizeof(CDT),
  9186. // where vector register size specified in section 3.2.1 Registers and the
  9187. // Stack Frame of original AMD64 ABI document.
  9188. QualType RetType = FD->getReturnType();
  9189. if (RetType.isNull())
  9190. return 0;
  9191. ASTContext &C = FD->getASTContext();
  9192. QualType CDT;
  9193. if (!RetType.isNull() && !RetType->isVoidType()) {
  9194. CDT = RetType;
  9195. } else {
  9196. unsigned Offset = 0;
  9197. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  9198. if (ParamAttrs[Offset].Kind == Vector)
  9199. CDT = C.getPointerType(C.getRecordType(MD->getParent()));
  9200. ++Offset;
  9201. }
  9202. if (CDT.isNull()) {
  9203. for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
  9204. if (ParamAttrs[I + Offset].Kind == Vector) {
  9205. CDT = FD->getParamDecl(I)->getType();
  9206. break;
  9207. }
  9208. }
  9209. }
  9210. }
  9211. if (CDT.isNull())
  9212. CDT = C.IntTy;
  9213. CDT = CDT->getCanonicalTypeUnqualified();
  9214. if (CDT->isRecordType() || CDT->isUnionType())
  9215. CDT = C.IntTy;
  9216. return C.getTypeSize(CDT);
  9217. }
  9218. static void
  9219. emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
  9220. const llvm::APSInt &VLENVal,
  9221. ArrayRef<ParamAttrTy> ParamAttrs,
  9222. OMPDeclareSimdDeclAttr::BranchStateTy State) {
  9223. struct ISADataTy {
  9224. char ISA;
  9225. unsigned VecRegSize;
  9226. };
  9227. ISADataTy ISAData[] = {
  9228. {
  9229. 'b', 128
  9230. }, // SSE
  9231. {
  9232. 'c', 256
  9233. }, // AVX
  9234. {
  9235. 'd', 256
  9236. }, // AVX2
  9237. {
  9238. 'e', 512
  9239. }, // AVX512
  9240. };
  9241. llvm::SmallVector<char, 2> Masked;
  9242. switch (State) {
  9243. case OMPDeclareSimdDeclAttr::BS_Undefined:
  9244. Masked.push_back('N');
  9245. Masked.push_back('M');
  9246. break;
  9247. case OMPDeclareSimdDeclAttr::BS_Notinbranch:
  9248. Masked.push_back('N');
  9249. break;
  9250. case OMPDeclareSimdDeclAttr::BS_Inbranch:
  9251. Masked.push_back('M');
  9252. break;
  9253. }
  9254. for (char Mask : Masked) {
  9255. for (const ISADataTy &Data : ISAData) {
  9256. SmallString<256> Buffer;
  9257. llvm::raw_svector_ostream Out(Buffer);
  9258. Out << "_ZGV" << Data.ISA << Mask;
  9259. if (!VLENVal) {
  9260. unsigned NumElts = evaluateCDTSize(FD, ParamAttrs);
  9261. assert(NumElts && "Non-zero simdlen/cdtsize expected");
  9262. Out << llvm::APSInt::getUnsigned(Data.VecRegSize / NumElts);
  9263. } else {
  9264. Out << VLENVal;
  9265. }
  9266. for (const ParamAttrTy &ParamAttr : ParamAttrs) {
  9267. switch (ParamAttr.Kind){
  9268. case LinearWithVarStride:
  9269. Out << 's' << ParamAttr.StrideOrArg;
  9270. break;
  9271. case Linear:
  9272. Out << 'l';
  9273. if (!!ParamAttr.StrideOrArg)
  9274. Out << ParamAttr.StrideOrArg;
  9275. break;
  9276. case Uniform:
  9277. Out << 'u';
  9278. break;
  9279. case Vector:
  9280. Out << 'v';
  9281. break;
  9282. }
  9283. if (!!ParamAttr.Alignment)
  9284. Out << 'a' << ParamAttr.Alignment;
  9285. }
  9286. Out << '_' << Fn->getName();
  9287. Fn->addFnAttr(Out.str());
  9288. }
  9289. }
  9290. }
  9291. // This are the Functions that are needed to mangle the name of the
  9292. // vector functions generated by the compiler, according to the rules
  9293. // defined in the "Vector Function ABI specifications for AArch64",
  9294. // available at
  9295. // https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi.
  9296. /// Maps To Vector (MTV), as defined in 3.1.1 of the AAVFABI.
  9297. ///
  9298. /// TODO: Need to implement the behavior for reference marked with a
  9299. /// var or no linear modifiers (1.b in the section). For this, we
  9300. /// need to extend ParamKindTy to support the linear modifiers.
  9301. static bool getAArch64MTV(QualType QT, ParamKindTy Kind) {
  9302. QT = QT.getCanonicalType();
  9303. if (QT->isVoidType())
  9304. return false;
  9305. if (Kind == ParamKindTy::Uniform)
  9306. return false;
  9307. if (Kind == ParamKindTy::Linear)
  9308. return false;
  9309. // TODO: Handle linear references with modifiers
  9310. if (Kind == ParamKindTy::LinearWithVarStride)
  9311. return false;
  9312. return true;
  9313. }
  9314. /// Pass By Value (PBV), as defined in 3.1.2 of the AAVFABI.
  9315. static bool getAArch64PBV(QualType QT, ASTContext &C) {
  9316. QT = QT.getCanonicalType();
  9317. unsigned Size = C.getTypeSize(QT);
  9318. // Only scalars and complex within 16 bytes wide set PVB to true.
  9319. if (Size != 8 && Size != 16 && Size != 32 && Size != 64 && Size != 128)
  9320. return false;
  9321. if (QT->isFloatingType())
  9322. return true;
  9323. if (QT->isIntegerType())
  9324. return true;
  9325. if (QT->isPointerType())
  9326. return true;
  9327. // TODO: Add support for complex types (section 3.1.2, item 2).
  9328. return false;
  9329. }
  9330. /// Computes the lane size (LS) of a return type or of an input parameter,
  9331. /// as defined by `LS(P)` in 3.2.1 of the AAVFABI.
  9332. /// TODO: Add support for references, section 3.2.1, item 1.
  9333. static unsigned getAArch64LS(QualType QT, ParamKindTy Kind, ASTContext &C) {
  9334. if (getAArch64MTV(QT, Kind) && QT.getCanonicalType()->isPointerType()) {
  9335. QualType PTy = QT.getCanonicalType()->getPointeeType();
  9336. if (getAArch64PBV(PTy, C))
  9337. return C.getTypeSize(PTy);
  9338. }
  9339. if (getAArch64PBV(QT, C))
  9340. return C.getTypeSize(QT);
  9341. return C.getTypeSize(C.getUIntPtrType());
  9342. }
  9343. // Get Narrowest Data Size (NDS) and Widest Data Size (WDS) from the
  9344. // signature of the scalar function, as defined in 3.2.2 of the
  9345. // AAVFABI.
  9346. static std::tuple<unsigned, unsigned, bool>
  9347. getNDSWDS(const FunctionDecl *FD, ArrayRef<ParamAttrTy> ParamAttrs) {
  9348. QualType RetType = FD->getReturnType().getCanonicalType();
  9349. ASTContext &C = FD->getASTContext();
  9350. bool OutputBecomesInput = false;
  9351. llvm::SmallVector<unsigned, 8> Sizes;
  9352. if (!RetType->isVoidType()) {
  9353. Sizes.push_back(getAArch64LS(RetType, ParamKindTy::Vector, C));
  9354. if (!getAArch64PBV(RetType, C) && getAArch64MTV(RetType, {}))
  9355. OutputBecomesInput = true;
  9356. }
  9357. for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
  9358. QualType QT = FD->getParamDecl(I)->getType().getCanonicalType();
  9359. Sizes.push_back(getAArch64LS(QT, ParamAttrs[I].Kind, C));
  9360. }
  9361. assert(!Sizes.empty() && "Unable to determine NDS and WDS.");
  9362. // The LS of a function parameter / return value can only be a power
  9363. // of 2, starting from 8 bits, up to 128.
  9364. assert(std::all_of(Sizes.begin(), Sizes.end(),
  9365. [](unsigned Size) {
  9366. return Size == 8 || Size == 16 || Size == 32 ||
  9367. Size == 64 || Size == 128;
  9368. }) &&
  9369. "Invalid size");
  9370. return std::make_tuple(*std::min_element(std::begin(Sizes), std::end(Sizes)),
  9371. *std::max_element(std::begin(Sizes), std::end(Sizes)),
  9372. OutputBecomesInput);
  9373. }
  9374. /// Mangle the parameter part of the vector function name according to
  9375. /// their OpenMP classification. The mangling function is defined in
  9376. /// section 3.5 of the AAVFABI.
  9377. static std::string mangleVectorParameters(ArrayRef<ParamAttrTy> ParamAttrs) {
  9378. SmallString<256> Buffer;
  9379. llvm::raw_svector_ostream Out(Buffer);
  9380. for (const auto &ParamAttr : ParamAttrs) {
  9381. switch (ParamAttr.Kind) {
  9382. case LinearWithVarStride:
  9383. Out << "ls" << ParamAttr.StrideOrArg;
  9384. break;
  9385. case Linear:
  9386. Out << 'l';
  9387. // Don't print the step value if it is not present or if it is
  9388. // equal to 1.
  9389. if (!!ParamAttr.StrideOrArg && ParamAttr.StrideOrArg != 1)
  9390. Out << ParamAttr.StrideOrArg;
  9391. break;
  9392. case Uniform:
  9393. Out << 'u';
  9394. break;
  9395. case Vector:
  9396. Out << 'v';
  9397. break;
  9398. }
  9399. if (!!ParamAttr.Alignment)
  9400. Out << 'a' << ParamAttr.Alignment;
  9401. }
  9402. return Out.str();
  9403. }
  9404. // Function used to add the attribute. The parameter `VLEN` is
  9405. // templated to allow the use of "x" when targeting scalable functions
  9406. // for SVE.
  9407. template <typename T>
  9408. static void addAArch64VectorName(T VLEN, StringRef LMask, StringRef Prefix,
  9409. char ISA, StringRef ParSeq,
  9410. StringRef MangledName, bool OutputBecomesInput,
  9411. llvm::Function *Fn) {
  9412. SmallString<256> Buffer;
  9413. llvm::raw_svector_ostream Out(Buffer);
  9414. Out << Prefix << ISA << LMask << VLEN;
  9415. if (OutputBecomesInput)
  9416. Out << "v";
  9417. Out << ParSeq << "_" << MangledName;
  9418. Fn->addFnAttr(Out.str());
  9419. }
  9420. // Helper function to generate the Advanced SIMD names depending on
  9421. // the value of the NDS when simdlen is not present.
  9422. static void addAArch64AdvSIMDNDSNames(unsigned NDS, StringRef Mask,
  9423. StringRef Prefix, char ISA,
  9424. StringRef ParSeq, StringRef MangledName,
  9425. bool OutputBecomesInput,
  9426. llvm::Function *Fn) {
  9427. switch (NDS) {
  9428. case 8:
  9429. addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
  9430. OutputBecomesInput, Fn);
  9431. addAArch64VectorName(16, Mask, Prefix, ISA, ParSeq, MangledName,
  9432. OutputBecomesInput, Fn);
  9433. break;
  9434. case 16:
  9435. addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
  9436. OutputBecomesInput, Fn);
  9437. addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
  9438. OutputBecomesInput, Fn);
  9439. break;
  9440. case 32:
  9441. addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
  9442. OutputBecomesInput, Fn);
  9443. addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
  9444. OutputBecomesInput, Fn);
  9445. break;
  9446. case 64:
  9447. case 128:
  9448. addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
  9449. OutputBecomesInput, Fn);
  9450. break;
  9451. default:
  9452. llvm_unreachable("Scalar type is too wide.");
  9453. }
  9454. }
  9455. /// Emit vector function attributes for AArch64, as defined in the AAVFABI.
  9456. static void emitAArch64DeclareSimdFunction(
  9457. CodeGenModule &CGM, const FunctionDecl *FD, unsigned UserVLEN,
  9458. ArrayRef<ParamAttrTy> ParamAttrs,
  9459. OMPDeclareSimdDeclAttr::BranchStateTy State, StringRef MangledName,
  9460. char ISA, unsigned VecRegSize, llvm::Function *Fn, SourceLocation SLoc) {
  9461. // Get basic data for building the vector signature.
  9462. const auto Data = getNDSWDS(FD, ParamAttrs);
  9463. const unsigned NDS = std::get<0>(Data);
  9464. const unsigned WDS = std::get<1>(Data);
  9465. const bool OutputBecomesInput = std::get<2>(Data);
  9466. // Check the values provided via `simdlen` by the user.
  9467. // 1. A `simdlen(1)` doesn't produce vector signatures,
  9468. if (UserVLEN == 1) {
  9469. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  9470. DiagnosticsEngine::Warning,
  9471. "The clause simdlen(1) has no effect when targeting aarch64.");
  9472. CGM.getDiags().Report(SLoc, DiagID);
  9473. return;
  9474. }
  9475. // 2. Section 3.3.1, item 1: user input must be a power of 2 for
  9476. // Advanced SIMD output.
  9477. if (ISA == 'n' && UserVLEN && !llvm::isPowerOf2_32(UserVLEN)) {
  9478. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  9479. DiagnosticsEngine::Warning, "The value specified in simdlen must be a "
  9480. "power of 2 when targeting Advanced SIMD.");
  9481. CGM.getDiags().Report(SLoc, DiagID);
  9482. return;
  9483. }
  9484. // 3. Section 3.4.1. SVE fixed lengh must obey the architectural
  9485. // limits.
  9486. if (ISA == 's' && UserVLEN != 0) {
  9487. if ((UserVLEN * WDS > 2048) || (UserVLEN * WDS % 128 != 0)) {
  9488. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  9489. DiagnosticsEngine::Warning, "The clause simdlen must fit the %0-bit "
  9490. "lanes in the architectural constraints "
  9491. "for SVE (min is 128-bit, max is "
  9492. "2048-bit, by steps of 128-bit)");
  9493. CGM.getDiags().Report(SLoc, DiagID) << WDS;
  9494. return;
  9495. }
  9496. }
  9497. // Sort out parameter sequence.
  9498. const std::string ParSeq = mangleVectorParameters(ParamAttrs);
  9499. StringRef Prefix = "_ZGV";
  9500. // Generate simdlen from user input (if any).
  9501. if (UserVLEN) {
  9502. if (ISA == 's') {
  9503. // SVE generates only a masked function.
  9504. addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
  9505. OutputBecomesInput, Fn);
  9506. } else {
  9507. assert(ISA == 'n' && "Expected ISA either 's' or 'n'.");
  9508. // Advanced SIMD generates one or two functions, depending on
  9509. // the `[not]inbranch` clause.
  9510. switch (State) {
  9511. case OMPDeclareSimdDeclAttr::BS_Undefined:
  9512. addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
  9513. OutputBecomesInput, Fn);
  9514. addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
  9515. OutputBecomesInput, Fn);
  9516. break;
  9517. case OMPDeclareSimdDeclAttr::BS_Notinbranch:
  9518. addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
  9519. OutputBecomesInput, Fn);
  9520. break;
  9521. case OMPDeclareSimdDeclAttr::BS_Inbranch:
  9522. addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
  9523. OutputBecomesInput, Fn);
  9524. break;
  9525. }
  9526. }
  9527. } else {
  9528. // If no user simdlen is provided, follow the AAVFABI rules for
  9529. // generating the vector length.
  9530. if (ISA == 's') {
  9531. // SVE, section 3.4.1, item 1.
  9532. addAArch64VectorName("x", "M", Prefix, ISA, ParSeq, MangledName,
  9533. OutputBecomesInput, Fn);
  9534. } else {
  9535. assert(ISA == 'n' && "Expected ISA either 's' or 'n'.");
  9536. // Advanced SIMD, Section 3.3.1 of the AAVFABI, generates one or
  9537. // two vector names depending on the use of the clause
  9538. // `[not]inbranch`.
  9539. switch (State) {
  9540. case OMPDeclareSimdDeclAttr::BS_Undefined:
  9541. addAArch64AdvSIMDNDSNames(NDS, "N", Prefix, ISA, ParSeq, MangledName,
  9542. OutputBecomesInput, Fn);
  9543. addAArch64AdvSIMDNDSNames(NDS, "M", Prefix, ISA, ParSeq, MangledName,
  9544. OutputBecomesInput, Fn);
  9545. break;
  9546. case OMPDeclareSimdDeclAttr::BS_Notinbranch:
  9547. addAArch64AdvSIMDNDSNames(NDS, "N", Prefix, ISA, ParSeq, MangledName,
  9548. OutputBecomesInput, Fn);
  9549. break;
  9550. case OMPDeclareSimdDeclAttr::BS_Inbranch:
  9551. addAArch64AdvSIMDNDSNames(NDS, "M", Prefix, ISA, ParSeq, MangledName,
  9552. OutputBecomesInput, Fn);
  9553. break;
  9554. }
  9555. }
  9556. }
  9557. }
  9558. void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
  9559. llvm::Function *Fn) {
  9560. ASTContext &C = CGM.getContext();
  9561. FD = FD->getMostRecentDecl();
  9562. // Map params to their positions in function decl.
  9563. llvm::DenseMap<const Decl *, unsigned> ParamPositions;
  9564. if (isa<CXXMethodDecl>(FD))
  9565. ParamPositions.try_emplace(FD, 0);
  9566. unsigned ParamPos = ParamPositions.size();
  9567. for (const ParmVarDecl *P : FD->parameters()) {
  9568. ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
  9569. ++ParamPos;
  9570. }
  9571. while (FD) {
  9572. for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
  9573. llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
  9574. // Mark uniform parameters.
  9575. for (const Expr *E : Attr->uniforms()) {
  9576. E = E->IgnoreParenImpCasts();
  9577. unsigned Pos;
  9578. if (isa<CXXThisExpr>(E)) {
  9579. Pos = ParamPositions[FD];
  9580. } else {
  9581. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  9582. ->getCanonicalDecl();
  9583. Pos = ParamPositions[PVD];
  9584. }
  9585. ParamAttrs[Pos].Kind = Uniform;
  9586. }
  9587. // Get alignment info.
  9588. auto NI = Attr->alignments_begin();
  9589. for (const Expr *E : Attr->aligneds()) {
  9590. E = E->IgnoreParenImpCasts();
  9591. unsigned Pos;
  9592. QualType ParmTy;
  9593. if (isa<CXXThisExpr>(E)) {
  9594. Pos = ParamPositions[FD];
  9595. ParmTy = E->getType();
  9596. } else {
  9597. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  9598. ->getCanonicalDecl();
  9599. Pos = ParamPositions[PVD];
  9600. ParmTy = PVD->getType();
  9601. }
  9602. ParamAttrs[Pos].Alignment =
  9603. (*NI)
  9604. ? (*NI)->EvaluateKnownConstInt(C)
  9605. : llvm::APSInt::getUnsigned(
  9606. C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
  9607. .getQuantity());
  9608. ++NI;
  9609. }
  9610. // Mark linear parameters.
  9611. auto SI = Attr->steps_begin();
  9612. auto MI = Attr->modifiers_begin();
  9613. for (const Expr *E : Attr->linears()) {
  9614. E = E->IgnoreParenImpCasts();
  9615. unsigned Pos;
  9616. if (isa<CXXThisExpr>(E)) {
  9617. Pos = ParamPositions[FD];
  9618. } else {
  9619. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  9620. ->getCanonicalDecl();
  9621. Pos = ParamPositions[PVD];
  9622. }
  9623. ParamAttrTy &ParamAttr = ParamAttrs[Pos];
  9624. ParamAttr.Kind = Linear;
  9625. if (*SI) {
  9626. Expr::EvalResult Result;
  9627. if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
  9628. if (const auto *DRE =
  9629. cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
  9630. if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
  9631. ParamAttr.Kind = LinearWithVarStride;
  9632. ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
  9633. ParamPositions[StridePVD->getCanonicalDecl()]);
  9634. }
  9635. }
  9636. } else {
  9637. ParamAttr.StrideOrArg = Result.Val.getInt();
  9638. }
  9639. }
  9640. ++SI;
  9641. ++MI;
  9642. }
  9643. llvm::APSInt VLENVal;
  9644. SourceLocation ExprLoc;
  9645. const Expr *VLENExpr = Attr->getSimdlen();
  9646. if (VLENExpr) {
  9647. VLENVal = VLENExpr->EvaluateKnownConstInt(C);
  9648. ExprLoc = VLENExpr->getExprLoc();
  9649. }
  9650. OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
  9651. if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
  9652. CGM.getTriple().getArch() == llvm::Triple::x86_64) {
  9653. emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
  9654. } else if (CGM.getTriple().getArch() == llvm::Triple::aarch64) {
  9655. unsigned VLEN = VLENVal.getExtValue();
  9656. StringRef MangledName = Fn->getName();
  9657. if (CGM.getTarget().hasFeature("sve"))
  9658. emitAArch64DeclareSimdFunction(CGM, FD, VLEN, ParamAttrs, State,
  9659. MangledName, 's', 128, Fn, ExprLoc);
  9660. if (CGM.getTarget().hasFeature("neon"))
  9661. emitAArch64DeclareSimdFunction(CGM, FD, VLEN, ParamAttrs, State,
  9662. MangledName, 'n', 128, Fn, ExprLoc);
  9663. }
  9664. }
  9665. FD = FD->getPreviousDecl();
  9666. }
  9667. }
  9668. namespace {
  9669. /// Cleanup action for doacross support.
  9670. class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
  9671. public:
  9672. static const int DoacrossFinArgs = 2;
  9673. private:
  9674. llvm::FunctionCallee RTLFn;
  9675. llvm::Value *Args[DoacrossFinArgs];
  9676. public:
  9677. DoacrossCleanupTy(llvm::FunctionCallee RTLFn,
  9678. ArrayRef<llvm::Value *> CallArgs)
  9679. : RTLFn(RTLFn) {
  9680. assert(CallArgs.size() == DoacrossFinArgs);
  9681. std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
  9682. }
  9683. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  9684. if (!CGF.HaveInsertPoint())
  9685. return;
  9686. CGF.EmitRuntimeCall(RTLFn, Args);
  9687. }
  9688. };
  9689. } // namespace
  9690. void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
  9691. const OMPLoopDirective &D,
  9692. ArrayRef<Expr *> NumIterations) {
  9693. if (!CGF.HaveInsertPoint())
  9694. return;
  9695. ASTContext &C = CGM.getContext();
  9696. QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
  9697. RecordDecl *RD;
  9698. if (KmpDimTy.isNull()) {
  9699. // Build struct kmp_dim { // loop bounds info casted to kmp_int64
  9700. // kmp_int64 lo; // lower
  9701. // kmp_int64 up; // upper
  9702. // kmp_int64 st; // stride
  9703. // };
  9704. RD = C.buildImplicitRecord("kmp_dim");
  9705. RD->startDefinition();
  9706. addFieldToRecordDecl(C, RD, Int64Ty);
  9707. addFieldToRecordDecl(C, RD, Int64Ty);
  9708. addFieldToRecordDecl(C, RD, Int64Ty);
  9709. RD->completeDefinition();
  9710. KmpDimTy = C.getRecordType(RD);
  9711. } else {
  9712. RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
  9713. }
  9714. llvm::APInt Size(/*numBits=*/32, NumIterations.size());
  9715. QualType ArrayTy =
  9716. C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
  9717. Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
  9718. CGF.EmitNullInitialization(DimsAddr, ArrayTy);
  9719. enum { LowerFD = 0, UpperFD, StrideFD };
  9720. // Fill dims with data.
  9721. for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
  9722. LValue DimsLVal = CGF.MakeAddrLValue(
  9723. CGF.Builder.CreateConstArrayGEP(DimsAddr, I), KmpDimTy);
  9724. // dims.upper = num_iterations;
  9725. LValue UpperLVal = CGF.EmitLValueForField(
  9726. DimsLVal, *std::next(RD->field_begin(), UpperFD));
  9727. llvm::Value *NumIterVal =
  9728. CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
  9729. D.getNumIterations()->getType(), Int64Ty,
  9730. D.getNumIterations()->getExprLoc());
  9731. CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
  9732. // dims.stride = 1;
  9733. LValue StrideLVal = CGF.EmitLValueForField(
  9734. DimsLVal, *std::next(RD->field_begin(), StrideFD));
  9735. CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
  9736. StrideLVal);
  9737. }
  9738. // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
  9739. // kmp_int32 num_dims, struct kmp_dim * dims);
  9740. llvm::Value *Args[] = {
  9741. emitUpdateLocation(CGF, D.getBeginLoc()),
  9742. getThreadID(CGF, D.getBeginLoc()),
  9743. llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
  9744. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  9745. CGF.Builder.CreateConstArrayGEP(DimsAddr, 0).getPointer(),
  9746. CGM.VoidPtrTy)};
  9747. llvm::FunctionCallee RTLFn =
  9748. createRuntimeFunction(OMPRTL__kmpc_doacross_init);
  9749. CGF.EmitRuntimeCall(RTLFn, Args);
  9750. llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
  9751. emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
  9752. llvm::FunctionCallee FiniRTLFn =
  9753. createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
  9754. CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
  9755. llvm::makeArrayRef(FiniArgs));
  9756. }
  9757. void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
  9758. const OMPDependClause *C) {
  9759. QualType Int64Ty =
  9760. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  9761. llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
  9762. QualType ArrayTy = CGM.getContext().getConstantArrayType(
  9763. Int64Ty, Size, ArrayType::Normal, 0);
  9764. Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
  9765. for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
  9766. const Expr *CounterVal = C->getLoopData(I);
  9767. assert(CounterVal);
  9768. llvm::Value *CntVal = CGF.EmitScalarConversion(
  9769. CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
  9770. CounterVal->getExprLoc());
  9771. CGF.EmitStoreOfScalar(CntVal, CGF.Builder.CreateConstArrayGEP(CntAddr, I),
  9772. /*Volatile=*/false, Int64Ty);
  9773. }
  9774. llvm::Value *Args[] = {
  9775. emitUpdateLocation(CGF, C->getBeginLoc()),
  9776. getThreadID(CGF, C->getBeginLoc()),
  9777. CGF.Builder.CreateConstArrayGEP(CntAddr, 0).getPointer()};
  9778. llvm::FunctionCallee RTLFn;
  9779. if (C->getDependencyKind() == OMPC_DEPEND_source) {
  9780. RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
  9781. } else {
  9782. assert(C->getDependencyKind() == OMPC_DEPEND_sink);
  9783. RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
  9784. }
  9785. CGF.EmitRuntimeCall(RTLFn, Args);
  9786. }
  9787. void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
  9788. llvm::FunctionCallee Callee,
  9789. ArrayRef<llvm::Value *> Args) const {
  9790. assert(Loc.isValid() && "Outlined function call location must be valid.");
  9791. auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
  9792. if (auto *Fn = dyn_cast<llvm::Function>(Callee.getCallee())) {
  9793. if (Fn->doesNotThrow()) {
  9794. CGF.EmitNounwindRuntimeCall(Fn, Args);
  9795. return;
  9796. }
  9797. }
  9798. CGF.EmitRuntimeCall(Callee, Args);
  9799. }
  9800. void CGOpenMPRuntime::emitOutlinedFunctionCall(
  9801. CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
  9802. ArrayRef<llvm::Value *> Args) const {
  9803. emitCall(CGF, Loc, OutlinedFn, Args);
  9804. }
  9805. void CGOpenMPRuntime::emitFunctionProlog(CodeGenFunction &CGF, const Decl *D) {
  9806. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  9807. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD))
  9808. HasEmittedDeclareTargetRegion = true;
  9809. }
  9810. Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
  9811. const VarDecl *NativeParam,
  9812. const VarDecl *TargetParam) const {
  9813. return CGF.GetAddrOfLocalVar(NativeParam);
  9814. }
  9815. namespace {
  9816. /// Cleanup action for allocate support.
  9817. class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup {
  9818. public:
  9819. static const int CleanupArgs = 3;
  9820. private:
  9821. llvm::FunctionCallee RTLFn;
  9822. llvm::Value *Args[CleanupArgs];
  9823. public:
  9824. OMPAllocateCleanupTy(llvm::FunctionCallee RTLFn,
  9825. ArrayRef<llvm::Value *> CallArgs)
  9826. : RTLFn(RTLFn) {
  9827. assert(CallArgs.size() == CleanupArgs &&
  9828. "Size of arguments does not match.");
  9829. std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
  9830. }
  9831. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  9832. if (!CGF.HaveInsertPoint())
  9833. return;
  9834. CGF.EmitRuntimeCall(RTLFn, Args);
  9835. }
  9836. };
  9837. } // namespace
  9838. Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
  9839. const VarDecl *VD) {
  9840. if (!VD)
  9841. return Address::invalid();
  9842. const VarDecl *CVD = VD->getCanonicalDecl();
  9843. if (!CVD->hasAttr<OMPAllocateDeclAttr>())
  9844. return Address::invalid();
  9845. const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
  9846. // Use the default allocation.
  9847. if (AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc &&
  9848. !AA->getAllocator())
  9849. return Address::invalid();
  9850. llvm::Value *Size;
  9851. CharUnits Align = CGM.getContext().getDeclAlign(CVD);
  9852. if (CVD->getType()->isVariablyModifiedType()) {
  9853. Size = CGF.getTypeSize(CVD->getType());
  9854. // Align the size: ((size + align - 1) / align) * align
  9855. Size = CGF.Builder.CreateNUWAdd(
  9856. Size, CGM.getSize(Align - CharUnits::fromQuantity(1)));
  9857. Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align));
  9858. Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align));
  9859. } else {
  9860. CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType());
  9861. Size = CGM.getSize(Sz.alignTo(Align));
  9862. }
  9863. llvm::Value *ThreadID = getThreadID(CGF, CVD->getBeginLoc());
  9864. assert(AA->getAllocator() &&
  9865. "Expected allocator expression for non-default allocator.");
  9866. llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator());
  9867. // According to the standard, the original allocator type is a enum (integer).
  9868. // Convert to pointer type, if required.
  9869. if (Allocator->getType()->isIntegerTy())
  9870. Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy);
  9871. else if (Allocator->getType()->isPointerTy())
  9872. Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator,
  9873. CGM.VoidPtrTy);
  9874. llvm::Value *Args[] = {ThreadID, Size, Allocator};
  9875. llvm::Value *Addr =
  9876. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_alloc), Args,
  9877. CVD->getName() + ".void.addr");
  9878. llvm::Value *FiniArgs[OMPAllocateCleanupTy::CleanupArgs] = {ThreadID, Addr,
  9879. Allocator};
  9880. llvm::FunctionCallee FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_free);
  9881. CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
  9882. llvm::makeArrayRef(FiniArgs));
  9883. Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  9884. Addr,
  9885. CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())),
  9886. CVD->getName() + ".addr");
  9887. return Address(Addr, Align);
  9888. }
  9889. llvm::Function *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
  9890. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  9891. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  9892. llvm_unreachable("Not supported in SIMD-only mode");
  9893. }
  9894. llvm::Function *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
  9895. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  9896. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  9897. llvm_unreachable("Not supported in SIMD-only mode");
  9898. }
  9899. llvm::Function *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
  9900. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  9901. const VarDecl *PartIDVar, const VarDecl *TaskTVar,
  9902. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  9903. bool Tied, unsigned &NumberOfParts) {
  9904. llvm_unreachable("Not supported in SIMD-only mode");
  9905. }
  9906. void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
  9907. SourceLocation Loc,
  9908. llvm::Function *OutlinedFn,
  9909. ArrayRef<llvm::Value *> CapturedVars,
  9910. const Expr *IfCond) {
  9911. llvm_unreachable("Not supported in SIMD-only mode");
  9912. }
  9913. void CGOpenMPSIMDRuntime::emitCriticalRegion(
  9914. CodeGenFunction &CGF, StringRef CriticalName,
  9915. const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
  9916. const Expr *Hint) {
  9917. llvm_unreachable("Not supported in SIMD-only mode");
  9918. }
  9919. void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
  9920. const RegionCodeGenTy &MasterOpGen,
  9921. SourceLocation Loc) {
  9922. llvm_unreachable("Not supported in SIMD-only mode");
  9923. }
  9924. void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
  9925. SourceLocation Loc) {
  9926. llvm_unreachable("Not supported in SIMD-only mode");
  9927. }
  9928. void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
  9929. CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
  9930. SourceLocation Loc) {
  9931. llvm_unreachable("Not supported in SIMD-only mode");
  9932. }
  9933. void CGOpenMPSIMDRuntime::emitSingleRegion(
  9934. CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
  9935. SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
  9936. ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
  9937. ArrayRef<const Expr *> AssignmentOps) {
  9938. llvm_unreachable("Not supported in SIMD-only mode");
  9939. }
  9940. void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
  9941. const RegionCodeGenTy &OrderedOpGen,
  9942. SourceLocation Loc,
  9943. bool IsThreads) {
  9944. llvm_unreachable("Not supported in SIMD-only mode");
  9945. }
  9946. void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
  9947. SourceLocation Loc,
  9948. OpenMPDirectiveKind Kind,
  9949. bool EmitChecks,
  9950. bool ForceSimpleCall) {
  9951. llvm_unreachable("Not supported in SIMD-only mode");
  9952. }
  9953. void CGOpenMPSIMDRuntime::emitForDispatchInit(
  9954. CodeGenFunction &CGF, SourceLocation Loc,
  9955. const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
  9956. bool Ordered, const DispatchRTInput &DispatchValues) {
  9957. llvm_unreachable("Not supported in SIMD-only mode");
  9958. }
  9959. void CGOpenMPSIMDRuntime::emitForStaticInit(
  9960. CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
  9961. const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
  9962. llvm_unreachable("Not supported in SIMD-only mode");
  9963. }
  9964. void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
  9965. CodeGenFunction &CGF, SourceLocation Loc,
  9966. OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
  9967. llvm_unreachable("Not supported in SIMD-only mode");
  9968. }
  9969. void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
  9970. SourceLocation Loc,
  9971. unsigned IVSize,
  9972. bool IVSigned) {
  9973. llvm_unreachable("Not supported in SIMD-only mode");
  9974. }
  9975. void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
  9976. SourceLocation Loc,
  9977. OpenMPDirectiveKind DKind) {
  9978. llvm_unreachable("Not supported in SIMD-only mode");
  9979. }
  9980. llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
  9981. SourceLocation Loc,
  9982. unsigned IVSize, bool IVSigned,
  9983. Address IL, Address LB,
  9984. Address UB, Address ST) {
  9985. llvm_unreachable("Not supported in SIMD-only mode");
  9986. }
  9987. void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
  9988. llvm::Value *NumThreads,
  9989. SourceLocation Loc) {
  9990. llvm_unreachable("Not supported in SIMD-only mode");
  9991. }
  9992. void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
  9993. OpenMPProcBindClauseKind ProcBind,
  9994. SourceLocation Loc) {
  9995. llvm_unreachable("Not supported in SIMD-only mode");
  9996. }
  9997. Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
  9998. const VarDecl *VD,
  9999. Address VDAddr,
  10000. SourceLocation Loc) {
  10001. llvm_unreachable("Not supported in SIMD-only mode");
  10002. }
  10003. llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
  10004. const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
  10005. CodeGenFunction *CGF) {
  10006. llvm_unreachable("Not supported in SIMD-only mode");
  10007. }
  10008. Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
  10009. CodeGenFunction &CGF, QualType VarType, StringRef Name) {
  10010. llvm_unreachable("Not supported in SIMD-only mode");
  10011. }
  10012. void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
  10013. ArrayRef<const Expr *> Vars,
  10014. SourceLocation Loc) {
  10015. llvm_unreachable("Not supported in SIMD-only mode");
  10016. }
  10017. void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
  10018. const OMPExecutableDirective &D,
  10019. llvm::Function *TaskFunction,
  10020. QualType SharedsTy, Address Shareds,
  10021. const Expr *IfCond,
  10022. const OMPTaskDataTy &Data) {
  10023. llvm_unreachable("Not supported in SIMD-only mode");
  10024. }
  10025. void CGOpenMPSIMDRuntime::emitTaskLoopCall(
  10026. CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
  10027. llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds,
  10028. const Expr *IfCond, const OMPTaskDataTy &Data) {
  10029. llvm_unreachable("Not supported in SIMD-only mode");
  10030. }
  10031. void CGOpenMPSIMDRuntime::emitReduction(
  10032. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
  10033. ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
  10034. ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
  10035. assert(Options.SimpleReduction && "Only simple reduction is expected.");
  10036. CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
  10037. ReductionOps, Options);
  10038. }
  10039. llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
  10040. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
  10041. ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
  10042. llvm_unreachable("Not supported in SIMD-only mode");
  10043. }
  10044. void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
  10045. SourceLocation Loc,
  10046. ReductionCodeGen &RCG,
  10047. unsigned N) {
  10048. llvm_unreachable("Not supported in SIMD-only mode");
  10049. }
  10050. Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
  10051. SourceLocation Loc,
  10052. llvm::Value *ReductionsPtr,
  10053. LValue SharedLVal) {
  10054. llvm_unreachable("Not supported in SIMD-only mode");
  10055. }
  10056. void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
  10057. SourceLocation Loc) {
  10058. llvm_unreachable("Not supported in SIMD-only mode");
  10059. }
  10060. void CGOpenMPSIMDRuntime::emitCancellationPointCall(
  10061. CodeGenFunction &CGF, SourceLocation Loc,
  10062. OpenMPDirectiveKind CancelRegion) {
  10063. llvm_unreachable("Not supported in SIMD-only mode");
  10064. }
  10065. void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
  10066. SourceLocation Loc, const Expr *IfCond,
  10067. OpenMPDirectiveKind CancelRegion) {
  10068. llvm_unreachable("Not supported in SIMD-only mode");
  10069. }
  10070. void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
  10071. const OMPExecutableDirective &D, StringRef ParentName,
  10072. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  10073. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  10074. llvm_unreachable("Not supported in SIMD-only mode");
  10075. }
  10076. void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
  10077. const OMPExecutableDirective &D,
  10078. llvm::Function *OutlinedFn,
  10079. llvm::Value *OutlinedFnID,
  10080. const Expr *IfCond,
  10081. const Expr *Device) {
  10082. llvm_unreachable("Not supported in SIMD-only mode");
  10083. }
  10084. bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
  10085. llvm_unreachable("Not supported in SIMD-only mode");
  10086. }
  10087. bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
  10088. llvm_unreachable("Not supported in SIMD-only mode");
  10089. }
  10090. bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
  10091. return false;
  10092. }
  10093. llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
  10094. return nullptr;
  10095. }
  10096. void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
  10097. const OMPExecutableDirective &D,
  10098. SourceLocation Loc,
  10099. llvm::Function *OutlinedFn,
  10100. ArrayRef<llvm::Value *> CapturedVars) {
  10101. llvm_unreachable("Not supported in SIMD-only mode");
  10102. }
  10103. void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
  10104. const Expr *NumTeams,
  10105. const Expr *ThreadLimit,
  10106. SourceLocation Loc) {
  10107. llvm_unreachable("Not supported in SIMD-only mode");
  10108. }
  10109. void CGOpenMPSIMDRuntime::emitTargetDataCalls(
  10110. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  10111. const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
  10112. llvm_unreachable("Not supported in SIMD-only mode");
  10113. }
  10114. void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
  10115. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  10116. const Expr *Device) {
  10117. llvm_unreachable("Not supported in SIMD-only mode");
  10118. }
  10119. void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
  10120. const OMPLoopDirective &D,
  10121. ArrayRef<Expr *> NumIterations) {
  10122. llvm_unreachable("Not supported in SIMD-only mode");
  10123. }
  10124. void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
  10125. const OMPDependClause *C) {
  10126. llvm_unreachable("Not supported in SIMD-only mode");
  10127. }
  10128. const VarDecl *
  10129. CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
  10130. const VarDecl *NativeParam) const {
  10131. llvm_unreachable("Not supported in SIMD-only mode");
  10132. }
  10133. Address
  10134. CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
  10135. const VarDecl *NativeParam,
  10136. const VarDecl *TargetParam) const {
  10137. llvm_unreachable("Not supported in SIMD-only mode");
  10138. }