CGOpenMPRuntime.cpp 481 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437
  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, int64_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, int64_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, int64_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, int64_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, int64_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, int64_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, int64_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, int64_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, int64_t *arg_sizes, int64_t
  688. // *arg_types);
  689. OMPRTL__tgt_target_data_update_nowait,
  690. // Call to int64_t __tgt_mapper_num_components(void *rt_mapper_handle);
  691. OMPRTL__tgt_mapper_num_components,
  692. // Call to void __tgt_push_mapper_component(void *rt_mapper_handle, void
  693. // *base, void *begin, int64_t size, int64_t type);
  694. OMPRTL__tgt_push_mapper_component,
  695. };
  696. /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
  697. /// region.
  698. class CleanupTy final : public EHScopeStack::Cleanup {
  699. PrePostActionTy *Action;
  700. public:
  701. explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
  702. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  703. if (!CGF.HaveInsertPoint())
  704. return;
  705. Action->Exit(CGF);
  706. }
  707. };
  708. } // anonymous namespace
  709. void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
  710. CodeGenFunction::RunCleanupsScope Scope(CGF);
  711. if (PrePostAction) {
  712. CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
  713. Callback(CodeGen, CGF, *PrePostAction);
  714. } else {
  715. PrePostActionTy Action;
  716. Callback(CodeGen, CGF, Action);
  717. }
  718. }
  719. /// Check if the combiner is a call to UDR combiner and if it is so return the
  720. /// UDR decl used for reduction.
  721. static const OMPDeclareReductionDecl *
  722. getReductionInit(const Expr *ReductionOp) {
  723. if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
  724. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
  725. if (const auto *DRE =
  726. dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
  727. if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
  728. return DRD;
  729. return nullptr;
  730. }
  731. static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
  732. const OMPDeclareReductionDecl *DRD,
  733. const Expr *InitOp,
  734. Address Private, Address Original,
  735. QualType Ty) {
  736. if (DRD->getInitializer()) {
  737. std::pair<llvm::Function *, llvm::Function *> Reduction =
  738. CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
  739. const auto *CE = cast<CallExpr>(InitOp);
  740. const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
  741. const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  742. const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  743. const auto *LHSDRE =
  744. cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
  745. const auto *RHSDRE =
  746. cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
  747. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  748. PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
  749. [=]() { return Private; });
  750. PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
  751. [=]() { return Original; });
  752. (void)PrivateScope.Privatize();
  753. RValue Func = RValue::get(Reduction.second);
  754. CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
  755. CGF.EmitIgnoredExpr(InitOp);
  756. } else {
  757. llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
  758. std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
  759. auto *GV = new llvm::GlobalVariable(
  760. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  761. llvm::GlobalValue::PrivateLinkage, Init, Name);
  762. LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
  763. RValue InitRVal;
  764. switch (CGF.getEvaluationKind(Ty)) {
  765. case TEK_Scalar:
  766. InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
  767. break;
  768. case TEK_Complex:
  769. InitRVal =
  770. RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
  771. break;
  772. case TEK_Aggregate:
  773. InitRVal = RValue::getAggregate(LV.getAddress());
  774. break;
  775. }
  776. OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
  777. CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
  778. CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
  779. /*IsInitializer=*/false);
  780. }
  781. }
  782. /// Emit initialization of arrays of complex types.
  783. /// \param DestAddr Address of the array.
  784. /// \param Type Type of array.
  785. /// \param Init Initial expression of array.
  786. /// \param SrcAddr Address of the original array.
  787. static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
  788. QualType Type, bool EmitDeclareReductionInit,
  789. const Expr *Init,
  790. const OMPDeclareReductionDecl *DRD,
  791. Address SrcAddr = Address::invalid()) {
  792. // Perform element-by-element initialization.
  793. QualType ElementTy;
  794. // Drill down to the base element type on both arrays.
  795. const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
  796. llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
  797. DestAddr =
  798. CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
  799. if (DRD)
  800. SrcAddr =
  801. CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
  802. llvm::Value *SrcBegin = nullptr;
  803. if (DRD)
  804. SrcBegin = SrcAddr.getPointer();
  805. llvm::Value *DestBegin = DestAddr.getPointer();
  806. // Cast from pointer to array type to pointer to single element.
  807. llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
  808. // The basic structure here is a while-do loop.
  809. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
  810. llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
  811. llvm::Value *IsEmpty =
  812. CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
  813. CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  814. // Enter the loop body, making that address the current address.
  815. llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
  816. CGF.EmitBlock(BodyBB);
  817. CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
  818. llvm::PHINode *SrcElementPHI = nullptr;
  819. Address SrcElementCurrent = Address::invalid();
  820. if (DRD) {
  821. SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
  822. "omp.arraycpy.srcElementPast");
  823. SrcElementPHI->addIncoming(SrcBegin, EntryBB);
  824. SrcElementCurrent =
  825. Address(SrcElementPHI,
  826. SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  827. }
  828. llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
  829. DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
  830. DestElementPHI->addIncoming(DestBegin, EntryBB);
  831. Address DestElementCurrent =
  832. Address(DestElementPHI,
  833. DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  834. // Emit copy.
  835. {
  836. CodeGenFunction::RunCleanupsScope InitScope(CGF);
  837. if (EmitDeclareReductionInit) {
  838. emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
  839. SrcElementCurrent, ElementTy);
  840. } else
  841. CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
  842. /*IsInitializer=*/false);
  843. }
  844. if (DRD) {
  845. // Shift the address forward by one element.
  846. llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
  847. SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  848. SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
  849. }
  850. // Shift the address forward by one element.
  851. llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
  852. DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  853. // Check whether we've reached the end.
  854. llvm::Value *Done =
  855. CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
  856. CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
  857. DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
  858. // Done.
  859. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  860. }
  861. LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
  862. return CGF.EmitOMPSharedLValue(E);
  863. }
  864. LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
  865. const Expr *E) {
  866. if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
  867. return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
  868. return LValue();
  869. }
  870. void ReductionCodeGen::emitAggregateInitialization(
  871. CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
  872. const OMPDeclareReductionDecl *DRD) {
  873. // Emit VarDecl with copy init for arrays.
  874. // Get the address of the original variable captured in current
  875. // captured region.
  876. const auto *PrivateVD =
  877. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  878. bool EmitDeclareReductionInit =
  879. DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
  880. EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
  881. EmitDeclareReductionInit,
  882. EmitDeclareReductionInit ? ClausesData[N].ReductionOp
  883. : PrivateVD->getInit(),
  884. DRD, SharedLVal.getAddress());
  885. }
  886. ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
  887. ArrayRef<const Expr *> Privates,
  888. ArrayRef<const Expr *> ReductionOps) {
  889. ClausesData.reserve(Shareds.size());
  890. SharedAddresses.reserve(Shareds.size());
  891. Sizes.reserve(Shareds.size());
  892. BaseDecls.reserve(Shareds.size());
  893. auto IPriv = Privates.begin();
  894. auto IRed = ReductionOps.begin();
  895. for (const Expr *Ref : Shareds) {
  896. ClausesData.emplace_back(Ref, *IPriv, *IRed);
  897. std::advance(IPriv, 1);
  898. std::advance(IRed, 1);
  899. }
  900. }
  901. void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
  902. assert(SharedAddresses.size() == N &&
  903. "Number of generated lvalues must be exactly N.");
  904. LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
  905. LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
  906. SharedAddresses.emplace_back(First, Second);
  907. }
  908. void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
  909. const auto *PrivateVD =
  910. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  911. QualType PrivateType = PrivateVD->getType();
  912. bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
  913. if (!PrivateType->isVariablyModifiedType()) {
  914. Sizes.emplace_back(
  915. CGF.getTypeSize(
  916. SharedAddresses[N].first.getType().getNonReferenceType()),
  917. nullptr);
  918. return;
  919. }
  920. llvm::Value *Size;
  921. llvm::Value *SizeInChars;
  922. auto *ElemType =
  923. cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
  924. ->getElementType();
  925. auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
  926. if (AsArraySection) {
  927. Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
  928. SharedAddresses[N].first.getPointer());
  929. Size = CGF.Builder.CreateNUWAdd(
  930. Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
  931. SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
  932. } else {
  933. SizeInChars = CGF.getTypeSize(
  934. SharedAddresses[N].first.getType().getNonReferenceType());
  935. Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
  936. }
  937. Sizes.emplace_back(SizeInChars, Size);
  938. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  939. CGF,
  940. cast<OpaqueValueExpr>(
  941. CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
  942. RValue::get(Size));
  943. CGF.EmitVariablyModifiedType(PrivateType);
  944. }
  945. void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
  946. llvm::Value *Size) {
  947. const auto *PrivateVD =
  948. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  949. QualType PrivateType = PrivateVD->getType();
  950. if (!PrivateType->isVariablyModifiedType()) {
  951. assert(!Size && !Sizes[N].second &&
  952. "Size should be nullptr for non-variably modified reduction "
  953. "items.");
  954. return;
  955. }
  956. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  957. CGF,
  958. cast<OpaqueValueExpr>(
  959. CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
  960. RValue::get(Size));
  961. CGF.EmitVariablyModifiedType(PrivateType);
  962. }
  963. void ReductionCodeGen::emitInitialization(
  964. CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
  965. llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
  966. assert(SharedAddresses.size() > N && "No variable was generated");
  967. const auto *PrivateVD =
  968. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  969. const OMPDeclareReductionDecl *DRD =
  970. getReductionInit(ClausesData[N].ReductionOp);
  971. QualType PrivateType = PrivateVD->getType();
  972. PrivateAddr = CGF.Builder.CreateElementBitCast(
  973. PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
  974. QualType SharedType = SharedAddresses[N].first.getType();
  975. SharedLVal = CGF.MakeAddrLValue(
  976. CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
  977. CGF.ConvertTypeForMem(SharedType)),
  978. SharedType, SharedAddresses[N].first.getBaseInfo(),
  979. CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
  980. if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
  981. emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
  982. } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
  983. emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
  984. PrivateAddr, SharedLVal.getAddress(),
  985. SharedLVal.getType());
  986. } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
  987. !CGF.isTrivialInitializer(PrivateVD->getInit())) {
  988. CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
  989. PrivateVD->getType().getQualifiers(),
  990. /*IsInitializer=*/false);
  991. }
  992. }
  993. bool ReductionCodeGen::needCleanups(unsigned N) {
  994. const auto *PrivateVD =
  995. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  996. QualType PrivateType = PrivateVD->getType();
  997. QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
  998. return DTorKind != QualType::DK_none;
  999. }
  1000. void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
  1001. Address PrivateAddr) {
  1002. const auto *PrivateVD =
  1003. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
  1004. QualType PrivateType = PrivateVD->getType();
  1005. QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
  1006. if (needCleanups(N)) {
  1007. PrivateAddr = CGF.Builder.CreateElementBitCast(
  1008. PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
  1009. CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
  1010. }
  1011. }
  1012. static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
  1013. LValue BaseLV) {
  1014. BaseTy = BaseTy.getNonReferenceType();
  1015. while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
  1016. !CGF.getContext().hasSameType(BaseTy, ElTy)) {
  1017. if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
  1018. BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
  1019. } else {
  1020. LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
  1021. BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
  1022. }
  1023. BaseTy = BaseTy->getPointeeType();
  1024. }
  1025. return CGF.MakeAddrLValue(
  1026. CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
  1027. CGF.ConvertTypeForMem(ElTy)),
  1028. BaseLV.getType(), BaseLV.getBaseInfo(),
  1029. CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
  1030. }
  1031. static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
  1032. llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
  1033. llvm::Value *Addr) {
  1034. Address Tmp = Address::invalid();
  1035. Address TopTmp = Address::invalid();
  1036. Address MostTopTmp = Address::invalid();
  1037. BaseTy = BaseTy.getNonReferenceType();
  1038. while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
  1039. !CGF.getContext().hasSameType(BaseTy, ElTy)) {
  1040. Tmp = CGF.CreateMemTemp(BaseTy);
  1041. if (TopTmp.isValid())
  1042. CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
  1043. else
  1044. MostTopTmp = Tmp;
  1045. TopTmp = Tmp;
  1046. BaseTy = BaseTy->getPointeeType();
  1047. }
  1048. llvm::Type *Ty = BaseLVType;
  1049. if (Tmp.isValid())
  1050. Ty = Tmp.getElementType();
  1051. Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
  1052. if (Tmp.isValid()) {
  1053. CGF.Builder.CreateStore(Addr, Tmp);
  1054. return MostTopTmp;
  1055. }
  1056. return Address(Addr, BaseLVAlignment);
  1057. }
  1058. static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
  1059. const VarDecl *OrigVD = nullptr;
  1060. if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
  1061. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  1062. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  1063. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  1064. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  1065. Base = TempASE->getBase()->IgnoreParenImpCasts();
  1066. DE = cast<DeclRefExpr>(Base);
  1067. OrigVD = cast<VarDecl>(DE->getDecl());
  1068. } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
  1069. const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  1070. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  1071. Base = TempASE->getBase()->IgnoreParenImpCasts();
  1072. DE = cast<DeclRefExpr>(Base);
  1073. OrigVD = cast<VarDecl>(DE->getDecl());
  1074. }
  1075. return OrigVD;
  1076. }
  1077. Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
  1078. Address PrivateAddr) {
  1079. const DeclRefExpr *DE;
  1080. if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
  1081. BaseDecls.emplace_back(OrigVD);
  1082. LValue OriginalBaseLValue = CGF.EmitLValue(DE);
  1083. LValue BaseLValue =
  1084. loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
  1085. OriginalBaseLValue);
  1086. llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
  1087. BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
  1088. llvm::Value *PrivatePointer =
  1089. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1090. PrivateAddr.getPointer(),
  1091. SharedAddresses[N].first.getAddress().getType());
  1092. llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
  1093. return castToBase(CGF, OrigVD->getType(),
  1094. SharedAddresses[N].first.getType(),
  1095. OriginalBaseLValue.getAddress().getType(),
  1096. OriginalBaseLValue.getAlignment(), Ptr);
  1097. }
  1098. BaseDecls.emplace_back(
  1099. cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
  1100. return PrivateAddr;
  1101. }
  1102. bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
  1103. const OMPDeclareReductionDecl *DRD =
  1104. getReductionInit(ClausesData[N].ReductionOp);
  1105. return DRD && DRD->getInitializer();
  1106. }
  1107. LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
  1108. return CGF.EmitLoadOfPointerLValue(
  1109. CGF.GetAddrOfLocalVar(getThreadIDVariable()),
  1110. getThreadIDVariable()->getType()->castAs<PointerType>());
  1111. }
  1112. void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
  1113. if (!CGF.HaveInsertPoint())
  1114. return;
  1115. // 1.2.2 OpenMP Language Terminology
  1116. // Structured block - An executable statement with a single entry at the
  1117. // top and a single exit at the bottom.
  1118. // The point of exit cannot be a branch out of the structured block.
  1119. // longjmp() and throw() must not violate the entry/exit criteria.
  1120. CGF.EHStack.pushTerminate();
  1121. CodeGen(CGF);
  1122. CGF.EHStack.popTerminate();
  1123. }
  1124. LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
  1125. CodeGenFunction &CGF) {
  1126. return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
  1127. getThreadIDVariable()->getType(),
  1128. AlignmentSource::Decl);
  1129. }
  1130. static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
  1131. QualType FieldTy) {
  1132. auto *Field = FieldDecl::Create(
  1133. C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
  1134. C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
  1135. /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
  1136. Field->setAccess(AS_public);
  1137. DC->addDecl(Field);
  1138. return Field;
  1139. }
  1140. CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
  1141. StringRef Separator)
  1142. : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
  1143. OffloadEntriesInfoManager(CGM) {
  1144. ASTContext &C = CGM.getContext();
  1145. RecordDecl *RD = C.buildImplicitRecord("ident_t");
  1146. QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  1147. RD->startDefinition();
  1148. // reserved_1
  1149. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1150. // flags
  1151. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1152. // reserved_2
  1153. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1154. // reserved_3
  1155. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  1156. // psource
  1157. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  1158. RD->completeDefinition();
  1159. IdentQTy = C.getRecordType(RD);
  1160. IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
  1161. KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
  1162. loadOffloadInfoMetadata();
  1163. }
  1164. bool CGOpenMPRuntime::tryEmitDeclareVariant(const GlobalDecl &NewGD,
  1165. const GlobalDecl &OldGD,
  1166. llvm::GlobalValue *OrigAddr,
  1167. bool IsForDefinition) {
  1168. // Emit at least a definition for the aliasee if the the address of the
  1169. // original function is requested.
  1170. if (IsForDefinition || OrigAddr)
  1171. (void)CGM.GetAddrOfGlobal(NewGD);
  1172. StringRef NewMangledName = CGM.getMangledName(NewGD);
  1173. llvm::GlobalValue *Addr = CGM.GetGlobalValue(NewMangledName);
  1174. if (Addr && !Addr->isDeclaration()) {
  1175. const auto *D = cast<FunctionDecl>(OldGD.getDecl());
  1176. const CGFunctionInfo &FI = CGM.getTypes().arrangeGlobalDeclaration(OldGD);
  1177. llvm::Type *DeclTy = CGM.getTypes().GetFunctionType(FI);
  1178. // Create a reference to the named value. This ensures that it is emitted
  1179. // if a deferred decl.
  1180. llvm::GlobalValue::LinkageTypes LT = CGM.getFunctionLinkage(OldGD);
  1181. // Create the new alias itself, but don't set a name yet.
  1182. auto *GA =
  1183. llvm::GlobalAlias::create(DeclTy, 0, LT, "", Addr, &CGM.getModule());
  1184. if (OrigAddr) {
  1185. assert(OrigAddr->isDeclaration() && "Expected declaration");
  1186. GA->takeName(OrigAddr);
  1187. OrigAddr->replaceAllUsesWith(
  1188. llvm::ConstantExpr::getBitCast(GA, OrigAddr->getType()));
  1189. OrigAddr->eraseFromParent();
  1190. } else {
  1191. GA->setName(CGM.getMangledName(OldGD));
  1192. }
  1193. // Set attributes which are particular to an alias; this is a
  1194. // specialization of the attributes which may be set on a global function.
  1195. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  1196. D->isWeakImported())
  1197. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1198. CGM.SetCommonAttributes(OldGD, GA);
  1199. return true;
  1200. }
  1201. return false;
  1202. }
  1203. void CGOpenMPRuntime::clear() {
  1204. InternalVars.clear();
  1205. // Clean non-target variable declarations possibly used only in debug info.
  1206. for (const auto &Data : EmittedNonTargetVariables) {
  1207. if (!Data.getValue().pointsToAliveValue())
  1208. continue;
  1209. auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
  1210. if (!GV)
  1211. continue;
  1212. if (!GV->isDeclaration() || GV->getNumUses() > 0)
  1213. continue;
  1214. GV->eraseFromParent();
  1215. }
  1216. // Emit aliases for the deferred aliasees.
  1217. for (const auto &Pair : DeferredVariantFunction) {
  1218. StringRef MangledName = CGM.getMangledName(Pair.second.second);
  1219. llvm::GlobalValue *Addr = CGM.GetGlobalValue(MangledName);
  1220. // If not able to emit alias, just emit original declaration.
  1221. (void)tryEmitDeclareVariant(Pair.second.first, Pair.second.second, Addr,
  1222. /*IsForDefinition=*/false);
  1223. }
  1224. }
  1225. std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
  1226. SmallString<128> Buffer;
  1227. llvm::raw_svector_ostream OS(Buffer);
  1228. StringRef Sep = FirstSeparator;
  1229. for (StringRef Part : Parts) {
  1230. OS << Sep << Part;
  1231. Sep = Separator;
  1232. }
  1233. return OS.str();
  1234. }
  1235. static llvm::Function *
  1236. emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
  1237. const Expr *CombinerInitializer, const VarDecl *In,
  1238. const VarDecl *Out, bool IsCombiner) {
  1239. // void .omp_combiner.(Ty *in, Ty *out);
  1240. ASTContext &C = CGM.getContext();
  1241. QualType PtrTy = C.getPointerType(Ty).withRestrict();
  1242. FunctionArgList Args;
  1243. ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
  1244. /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
  1245. ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
  1246. /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
  1247. Args.push_back(&OmpOutParm);
  1248. Args.push_back(&OmpInParm);
  1249. const CGFunctionInfo &FnInfo =
  1250. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  1251. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  1252. std::string Name = CGM.getOpenMPRuntime().getName(
  1253. {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
  1254. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  1255. Name, &CGM.getModule());
  1256. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  1257. if (CGM.getLangOpts().Optimize) {
  1258. Fn->removeFnAttr(llvm::Attribute::NoInline);
  1259. Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
  1260. Fn->addFnAttr(llvm::Attribute::AlwaysInline);
  1261. }
  1262. CodeGenFunction CGF(CGM);
  1263. // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
  1264. // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
  1265. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
  1266. Out->getLocation());
  1267. CodeGenFunction::OMPPrivateScope Scope(CGF);
  1268. Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
  1269. Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
  1270. return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
  1271. .getAddress();
  1272. });
  1273. Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
  1274. Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
  1275. return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
  1276. .getAddress();
  1277. });
  1278. (void)Scope.Privatize();
  1279. if (!IsCombiner && Out->hasInit() &&
  1280. !CGF.isTrivialInitializer(Out->getInit())) {
  1281. CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
  1282. Out->getType().getQualifiers(),
  1283. /*IsInitializer=*/true);
  1284. }
  1285. if (CombinerInitializer)
  1286. CGF.EmitIgnoredExpr(CombinerInitializer);
  1287. Scope.ForceCleanup();
  1288. CGF.FinishFunction();
  1289. return Fn;
  1290. }
  1291. void CGOpenMPRuntime::emitUserDefinedReduction(
  1292. CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
  1293. if (UDRMap.count(D) > 0)
  1294. return;
  1295. llvm::Function *Combiner = emitCombinerOrInitializer(
  1296. CGM, D->getType(), D->getCombiner(),
  1297. cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
  1298. cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
  1299. /*IsCombiner=*/true);
  1300. llvm::Function *Initializer = nullptr;
  1301. if (const Expr *Init = D->getInitializer()) {
  1302. Initializer = emitCombinerOrInitializer(
  1303. CGM, D->getType(),
  1304. D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
  1305. : nullptr,
  1306. cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
  1307. cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
  1308. /*IsCombiner=*/false);
  1309. }
  1310. UDRMap.try_emplace(D, Combiner, Initializer);
  1311. if (CGF) {
  1312. auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
  1313. Decls.second.push_back(D);
  1314. }
  1315. }
  1316. std::pair<llvm::Function *, llvm::Function *>
  1317. CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
  1318. auto I = UDRMap.find(D);
  1319. if (I != UDRMap.end())
  1320. return I->second;
  1321. emitUserDefinedReduction(/*CGF=*/nullptr, D);
  1322. return UDRMap.lookup(D);
  1323. }
  1324. static llvm::Function *emitParallelOrTeamsOutlinedFunction(
  1325. CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
  1326. const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
  1327. const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
  1328. assert(ThreadIDVar->getType()->isPointerType() &&
  1329. "thread id variable must be of type kmp_int32 *");
  1330. CodeGenFunction CGF(CGM, true);
  1331. bool HasCancel = false;
  1332. if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
  1333. HasCancel = OPD->hasCancel();
  1334. else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
  1335. HasCancel = OPSD->hasCancel();
  1336. else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
  1337. HasCancel = OPFD->hasCancel();
  1338. else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
  1339. HasCancel = OPFD->hasCancel();
  1340. else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
  1341. HasCancel = OPFD->hasCancel();
  1342. else if (const auto *OPFD =
  1343. dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
  1344. HasCancel = OPFD->hasCancel();
  1345. else if (const auto *OPFD =
  1346. dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
  1347. HasCancel = OPFD->hasCancel();
  1348. CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
  1349. HasCancel, OutlinedHelperName);
  1350. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  1351. return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
  1352. }
  1353. llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction(
  1354. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1355. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  1356. const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
  1357. return emitParallelOrTeamsOutlinedFunction(
  1358. CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
  1359. }
  1360. llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction(
  1361. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1362. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  1363. const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
  1364. return emitParallelOrTeamsOutlinedFunction(
  1365. CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
  1366. }
  1367. llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction(
  1368. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  1369. const VarDecl *PartIDVar, const VarDecl *TaskTVar,
  1370. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  1371. bool Tied, unsigned &NumberOfParts) {
  1372. auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
  1373. PrePostActionTy &) {
  1374. llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
  1375. llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
  1376. llvm::Value *TaskArgs[] = {
  1377. UpLoc, ThreadID,
  1378. CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
  1379. TaskTVar->getType()->castAs<PointerType>())
  1380. .getPointer()};
  1381. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
  1382. };
  1383. CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
  1384. UntiedCodeGen);
  1385. CodeGen.setAction(Action);
  1386. assert(!ThreadIDVar->getType()->isPointerType() &&
  1387. "thread id variable must be of type kmp_int32 for tasks");
  1388. const OpenMPDirectiveKind Region =
  1389. isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
  1390. : OMPD_task;
  1391. const CapturedStmt *CS = D.getCapturedStmt(Region);
  1392. const auto *TD = dyn_cast<OMPTaskDirective>(&D);
  1393. CodeGenFunction CGF(CGM, true);
  1394. CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
  1395. InnermostKind,
  1396. TD ? TD->hasCancel() : false, Action);
  1397. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  1398. llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS);
  1399. if (!Tied)
  1400. NumberOfParts = Action.getNumberOfParts();
  1401. return Res;
  1402. }
  1403. static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
  1404. const RecordDecl *RD, const CGRecordLayout &RL,
  1405. ArrayRef<llvm::Constant *> Data) {
  1406. llvm::StructType *StructTy = RL.getLLVMType();
  1407. unsigned PrevIdx = 0;
  1408. ConstantInitBuilder CIBuilder(CGM);
  1409. auto DI = Data.begin();
  1410. for (const FieldDecl *FD : RD->fields()) {
  1411. unsigned Idx = RL.getLLVMFieldNo(FD);
  1412. // Fill the alignment.
  1413. for (unsigned I = PrevIdx; I < Idx; ++I)
  1414. Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
  1415. PrevIdx = Idx + 1;
  1416. Fields.add(*DI);
  1417. ++DI;
  1418. }
  1419. }
  1420. template <class... As>
  1421. static llvm::GlobalVariable *
  1422. createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
  1423. ArrayRef<llvm::Constant *> Data, const Twine &Name,
  1424. As &&... Args) {
  1425. const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
  1426. const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
  1427. ConstantInitBuilder CIBuilder(CGM);
  1428. ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
  1429. buildStructValue(Fields, CGM, RD, RL, Data);
  1430. return Fields.finishAndCreateGlobal(
  1431. Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
  1432. std::forward<As>(Args)...);
  1433. }
  1434. template <typename T>
  1435. static void
  1436. createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
  1437. ArrayRef<llvm::Constant *> Data,
  1438. T &Parent) {
  1439. const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
  1440. const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
  1441. ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
  1442. buildStructValue(Fields, CGM, RD, RL, Data);
  1443. Fields.finishAndAddTo(Parent);
  1444. }
  1445. Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
  1446. CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
  1447. unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
  1448. FlagsTy FlagsKey(Flags, Reserved2Flags);
  1449. llvm::Value *Entry = OpenMPDefaultLocMap.lookup(FlagsKey);
  1450. if (!Entry) {
  1451. if (!DefaultOpenMPPSource) {
  1452. // Initialize default location for psource field of ident_t structure of
  1453. // all ident_t objects. Format is ";file;function;line;column;;".
  1454. // Taken from
  1455. // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp_str.cpp
  1456. DefaultOpenMPPSource =
  1457. CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
  1458. DefaultOpenMPPSource =
  1459. llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
  1460. }
  1461. llvm::Constant *Data[] = {
  1462. llvm::ConstantInt::getNullValue(CGM.Int32Ty),
  1463. llvm::ConstantInt::get(CGM.Int32Ty, Flags),
  1464. llvm::ConstantInt::get(CGM.Int32Ty, Reserved2Flags),
  1465. llvm::ConstantInt::getNullValue(CGM.Int32Ty), DefaultOpenMPPSource};
  1466. llvm::GlobalValue *DefaultOpenMPLocation =
  1467. createGlobalStruct(CGM, IdentQTy, isDefaultLocationConstant(), Data, "",
  1468. llvm::GlobalValue::PrivateLinkage);
  1469. DefaultOpenMPLocation->setUnnamedAddr(
  1470. llvm::GlobalValue::UnnamedAddr::Global);
  1471. OpenMPDefaultLocMap[FlagsKey] = Entry = DefaultOpenMPLocation;
  1472. }
  1473. return Address(Entry, Align);
  1474. }
  1475. void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
  1476. bool AtCurrentPoint) {
  1477. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1478. assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
  1479. llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
  1480. if (AtCurrentPoint) {
  1481. Elem.second.ServiceInsertPt = new llvm::BitCastInst(
  1482. Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
  1483. } else {
  1484. Elem.second.ServiceInsertPt =
  1485. new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
  1486. Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
  1487. }
  1488. }
  1489. void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
  1490. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1491. if (Elem.second.ServiceInsertPt) {
  1492. llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
  1493. Elem.second.ServiceInsertPt = nullptr;
  1494. Ptr->eraseFromParent();
  1495. }
  1496. }
  1497. llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
  1498. SourceLocation Loc,
  1499. unsigned Flags) {
  1500. Flags |= OMP_IDENT_KMPC;
  1501. // If no debug info is generated - return global default location.
  1502. if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
  1503. Loc.isInvalid())
  1504. return getOrCreateDefaultLocation(Flags).getPointer();
  1505. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1506. CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
  1507. Address LocValue = Address::invalid();
  1508. auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
  1509. if (I != OpenMPLocThreadIDMap.end())
  1510. LocValue = Address(I->second.DebugLoc, Align);
  1511. // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
  1512. // GetOpenMPThreadID was called before this routine.
  1513. if (!LocValue.isValid()) {
  1514. // Generate "ident_t .kmpc_loc.addr;"
  1515. Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
  1516. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1517. Elem.second.DebugLoc = AI.getPointer();
  1518. LocValue = AI;
  1519. if (!Elem.second.ServiceInsertPt)
  1520. setLocThreadIdInsertPt(CGF);
  1521. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  1522. CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
  1523. CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
  1524. CGF.getTypeSize(IdentQTy));
  1525. }
  1526. // char **psource = &.kmpc_loc_<flags>.addr.psource;
  1527. LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
  1528. auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
  1529. LValue PSource =
  1530. CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
  1531. llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
  1532. if (OMPDebugLoc == nullptr) {
  1533. SmallString<128> Buffer2;
  1534. llvm::raw_svector_ostream OS2(Buffer2);
  1535. // Build debug location
  1536. PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
  1537. OS2 << ";" << PLoc.getFilename() << ";";
  1538. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
  1539. OS2 << FD->getQualifiedNameAsString();
  1540. OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
  1541. OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
  1542. OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
  1543. }
  1544. // *psource = ";<File>;<Function>;<Line>;<Column>;;";
  1545. CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
  1546. // Our callers always pass this to a runtime function, so for
  1547. // convenience, go ahead and return a naked pointer.
  1548. return LocValue.getPointer();
  1549. }
  1550. llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
  1551. SourceLocation Loc) {
  1552. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1553. llvm::Value *ThreadID = nullptr;
  1554. // Check whether we've already cached a load of the thread id in this
  1555. // function.
  1556. auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
  1557. if (I != OpenMPLocThreadIDMap.end()) {
  1558. ThreadID = I->second.ThreadID;
  1559. if (ThreadID != nullptr)
  1560. return ThreadID;
  1561. }
  1562. // If exceptions are enabled, do not use parameter to avoid possible crash.
  1563. if (auto *OMPRegionInfo =
  1564. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  1565. if (OMPRegionInfo->getThreadIDVariable()) {
  1566. // Check if this an outlined function with thread id passed as argument.
  1567. LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
  1568. llvm::BasicBlock *TopBlock = CGF.AllocaInsertPt->getParent();
  1569. if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
  1570. !CGF.getLangOpts().CXXExceptions ||
  1571. CGF.Builder.GetInsertBlock() == TopBlock ||
  1572. !isa<llvm::Instruction>(LVal.getPointer()) ||
  1573. cast<llvm::Instruction>(LVal.getPointer())->getParent() == TopBlock ||
  1574. cast<llvm::Instruction>(LVal.getPointer())->getParent() ==
  1575. CGF.Builder.GetInsertBlock()) {
  1576. ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
  1577. // If value loaded in entry block, cache it and use it everywhere in
  1578. // function.
  1579. if (CGF.Builder.GetInsertBlock() == TopBlock) {
  1580. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1581. Elem.second.ThreadID = ThreadID;
  1582. }
  1583. return ThreadID;
  1584. }
  1585. }
  1586. }
  1587. // This is not an outlined function region - need to call __kmpc_int32
  1588. // kmpc_global_thread_num(ident_t *loc).
  1589. // Generate thread id value and cache this value for use across the
  1590. // function.
  1591. auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
  1592. if (!Elem.second.ServiceInsertPt)
  1593. setLocThreadIdInsertPt(CGF);
  1594. CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
  1595. CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
  1596. llvm::CallInst *Call = CGF.Builder.CreateCall(
  1597. createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
  1598. emitUpdateLocation(CGF, Loc));
  1599. Call->setCallingConv(CGF.getRuntimeCC());
  1600. Elem.second.ThreadID = Call;
  1601. return Call;
  1602. }
  1603. void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
  1604. assert(CGF.CurFn && "No function in current CodeGenFunction.");
  1605. if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
  1606. clearLocThreadIdInsertPt(CGF);
  1607. OpenMPLocThreadIDMap.erase(CGF.CurFn);
  1608. }
  1609. if (FunctionUDRMap.count(CGF.CurFn) > 0) {
  1610. for(auto *D : FunctionUDRMap[CGF.CurFn])
  1611. UDRMap.erase(D);
  1612. FunctionUDRMap.erase(CGF.CurFn);
  1613. }
  1614. auto I = FunctionUDMMap.find(CGF.CurFn);
  1615. if (I != FunctionUDMMap.end()) {
  1616. for(auto *D : I->second)
  1617. UDMMap.erase(D);
  1618. FunctionUDMMap.erase(I);
  1619. }
  1620. }
  1621. llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
  1622. return IdentTy->getPointerTo();
  1623. }
  1624. llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
  1625. if (!Kmpc_MicroTy) {
  1626. // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
  1627. llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
  1628. llvm::PointerType::getUnqual(CGM.Int32Ty)};
  1629. Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
  1630. }
  1631. return llvm::PointerType::getUnqual(Kmpc_MicroTy);
  1632. }
  1633. llvm::FunctionCallee CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
  1634. llvm::FunctionCallee RTLFn = nullptr;
  1635. switch (static_cast<OpenMPRTLFunction>(Function)) {
  1636. case OMPRTL__kmpc_fork_call: {
  1637. // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
  1638. // microtask, ...);
  1639. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1640. getKmpc_MicroPointerTy()};
  1641. auto *FnTy =
  1642. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
  1643. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
  1644. if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
  1645. if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
  1646. llvm::LLVMContext &Ctx = F->getContext();
  1647. llvm::MDBuilder MDB(Ctx);
  1648. // Annotate the callback behavior of the __kmpc_fork_call:
  1649. // - The callback callee is argument number 2 (microtask).
  1650. // - The first two arguments of the callback callee are unknown (-1).
  1651. // - All variadic arguments to the __kmpc_fork_call are passed to the
  1652. // callback callee.
  1653. F->addMetadata(
  1654. llvm::LLVMContext::MD_callback,
  1655. *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
  1656. 2, {-1, -1},
  1657. /* VarArgsArePassed */ true)}));
  1658. }
  1659. }
  1660. break;
  1661. }
  1662. case OMPRTL__kmpc_global_thread_num: {
  1663. // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
  1664. llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
  1665. auto *FnTy =
  1666. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1667. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
  1668. break;
  1669. }
  1670. case OMPRTL__kmpc_threadprivate_cached: {
  1671. // Build void *__kmpc_threadprivate_cached(ident_t *loc,
  1672. // kmp_int32 global_tid, void *data, size_t size, void ***cache);
  1673. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1674. CGM.VoidPtrTy, CGM.SizeTy,
  1675. CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
  1676. auto *FnTy =
  1677. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
  1678. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
  1679. break;
  1680. }
  1681. case OMPRTL__kmpc_critical: {
  1682. // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
  1683. // kmp_critical_name *crit);
  1684. llvm::Type *TypeParams[] = {
  1685. getIdentTyPointerTy(), CGM.Int32Ty,
  1686. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1687. auto *FnTy =
  1688. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1689. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
  1690. break;
  1691. }
  1692. case OMPRTL__kmpc_critical_with_hint: {
  1693. // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
  1694. // kmp_critical_name *crit, uintptr_t hint);
  1695. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1696. llvm::PointerType::getUnqual(KmpCriticalNameTy),
  1697. CGM.IntPtrTy};
  1698. auto *FnTy =
  1699. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1700. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
  1701. break;
  1702. }
  1703. case OMPRTL__kmpc_threadprivate_register: {
  1704. // Build void __kmpc_threadprivate_register(ident_t *, void *data,
  1705. // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
  1706. // typedef void *(*kmpc_ctor)(void *);
  1707. auto *KmpcCtorTy =
  1708. llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
  1709. /*isVarArg*/ false)->getPointerTo();
  1710. // typedef void *(*kmpc_cctor)(void *, void *);
  1711. llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1712. auto *KmpcCopyCtorTy =
  1713. llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
  1714. /*isVarArg*/ false)
  1715. ->getPointerTo();
  1716. // typedef void (*kmpc_dtor)(void *);
  1717. auto *KmpcDtorTy =
  1718. llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
  1719. ->getPointerTo();
  1720. llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
  1721. KmpcCopyCtorTy, KmpcDtorTy};
  1722. auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
  1723. /*isVarArg*/ false);
  1724. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
  1725. break;
  1726. }
  1727. case OMPRTL__kmpc_end_critical: {
  1728. // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
  1729. // kmp_critical_name *crit);
  1730. llvm::Type *TypeParams[] = {
  1731. getIdentTyPointerTy(), CGM.Int32Ty,
  1732. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1733. auto *FnTy =
  1734. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1735. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
  1736. break;
  1737. }
  1738. case OMPRTL__kmpc_cancel_barrier: {
  1739. // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
  1740. // global_tid);
  1741. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1742. auto *FnTy =
  1743. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  1744. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
  1745. break;
  1746. }
  1747. case OMPRTL__kmpc_barrier: {
  1748. // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
  1749. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1750. auto *FnTy =
  1751. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1752. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
  1753. break;
  1754. }
  1755. case OMPRTL__kmpc_for_static_fini: {
  1756. // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
  1757. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1758. auto *FnTy =
  1759. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1760. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
  1761. break;
  1762. }
  1763. case OMPRTL__kmpc_push_num_threads: {
  1764. // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
  1765. // kmp_int32 num_threads)
  1766. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1767. CGM.Int32Ty};
  1768. auto *FnTy =
  1769. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1770. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
  1771. break;
  1772. }
  1773. case OMPRTL__kmpc_serialized_parallel: {
  1774. // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
  1775. // global_tid);
  1776. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1777. auto *FnTy =
  1778. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1779. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
  1780. break;
  1781. }
  1782. case OMPRTL__kmpc_end_serialized_parallel: {
  1783. // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
  1784. // global_tid);
  1785. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1786. auto *FnTy =
  1787. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1788. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
  1789. break;
  1790. }
  1791. case OMPRTL__kmpc_flush: {
  1792. // Build void __kmpc_flush(ident_t *loc);
  1793. llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
  1794. auto *FnTy =
  1795. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  1796. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
  1797. break;
  1798. }
  1799. case OMPRTL__kmpc_master: {
  1800. // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
  1801. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1802. auto *FnTy =
  1803. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1804. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
  1805. break;
  1806. }
  1807. case OMPRTL__kmpc_end_master: {
  1808. // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
  1809. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1810. auto *FnTy =
  1811. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1812. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
  1813. break;
  1814. }
  1815. case OMPRTL__kmpc_omp_taskyield: {
  1816. // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
  1817. // int end_part);
  1818. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  1819. auto *FnTy =
  1820. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1821. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
  1822. break;
  1823. }
  1824. case OMPRTL__kmpc_single: {
  1825. // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
  1826. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1827. auto *FnTy =
  1828. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1829. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
  1830. break;
  1831. }
  1832. case OMPRTL__kmpc_end_single: {
  1833. // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
  1834. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1835. auto *FnTy =
  1836. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1837. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
  1838. break;
  1839. }
  1840. case OMPRTL__kmpc_omp_task_alloc: {
  1841. // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  1842. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  1843. // kmp_routine_entry_t *task_entry);
  1844. assert(KmpRoutineEntryPtrTy != nullptr &&
  1845. "Type kmp_routine_entry_t must be created.");
  1846. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  1847. CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
  1848. // Return void * and then cast to particular kmp_task_t type.
  1849. auto *FnTy =
  1850. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  1851. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
  1852. break;
  1853. }
  1854. case OMPRTL__kmpc_omp_target_task_alloc: {
  1855. // Build kmp_task_t *__kmpc_omp_target_task_alloc(ident_t *, kmp_int32 gtid,
  1856. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  1857. // kmp_routine_entry_t *task_entry, kmp_int64 device_id);
  1858. assert(KmpRoutineEntryPtrTy != nullptr &&
  1859. "Type kmp_routine_entry_t must be created.");
  1860. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  1861. CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy,
  1862. CGM.Int64Ty};
  1863. // Return void * and then cast to particular kmp_task_t type.
  1864. auto *FnTy =
  1865. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  1866. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_target_task_alloc");
  1867. break;
  1868. }
  1869. case OMPRTL__kmpc_omp_task: {
  1870. // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1871. // *new_task);
  1872. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1873. CGM.VoidPtrTy};
  1874. auto *FnTy =
  1875. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1876. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
  1877. break;
  1878. }
  1879. case OMPRTL__kmpc_copyprivate: {
  1880. // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
  1881. // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
  1882. // kmp_int32 didit);
  1883. llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1884. auto *CpyFnTy =
  1885. llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
  1886. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
  1887. CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
  1888. CGM.Int32Ty};
  1889. auto *FnTy =
  1890. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1891. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
  1892. break;
  1893. }
  1894. case OMPRTL__kmpc_reduce: {
  1895. // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
  1896. // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
  1897. // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
  1898. llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1899. auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
  1900. /*isVarArg=*/false);
  1901. llvm::Type *TypeParams[] = {
  1902. getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
  1903. CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
  1904. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1905. auto *FnTy =
  1906. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1907. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
  1908. break;
  1909. }
  1910. case OMPRTL__kmpc_reduce_nowait: {
  1911. // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
  1912. // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
  1913. // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
  1914. // *lck);
  1915. llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  1916. auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
  1917. /*isVarArg=*/false);
  1918. llvm::Type *TypeParams[] = {
  1919. getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
  1920. CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
  1921. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1922. auto *FnTy =
  1923. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1924. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
  1925. break;
  1926. }
  1927. case OMPRTL__kmpc_end_reduce: {
  1928. // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
  1929. // kmp_critical_name *lck);
  1930. llvm::Type *TypeParams[] = {
  1931. getIdentTyPointerTy(), CGM.Int32Ty,
  1932. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1933. auto *FnTy =
  1934. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1935. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
  1936. break;
  1937. }
  1938. case OMPRTL__kmpc_end_reduce_nowait: {
  1939. // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
  1940. // kmp_critical_name *lck);
  1941. llvm::Type *TypeParams[] = {
  1942. getIdentTyPointerTy(), CGM.Int32Ty,
  1943. llvm::PointerType::getUnqual(KmpCriticalNameTy)};
  1944. auto *FnTy =
  1945. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1946. RTLFn =
  1947. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
  1948. break;
  1949. }
  1950. case OMPRTL__kmpc_omp_task_begin_if0: {
  1951. // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1952. // *new_task);
  1953. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1954. CGM.VoidPtrTy};
  1955. auto *FnTy =
  1956. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1957. RTLFn =
  1958. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
  1959. break;
  1960. }
  1961. case OMPRTL__kmpc_omp_task_complete_if0: {
  1962. // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
  1963. // *new_task);
  1964. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  1965. CGM.VoidPtrTy};
  1966. auto *FnTy =
  1967. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1968. RTLFn = CGM.CreateRuntimeFunction(FnTy,
  1969. /*Name=*/"__kmpc_omp_task_complete_if0");
  1970. break;
  1971. }
  1972. case OMPRTL__kmpc_ordered: {
  1973. // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
  1974. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1975. auto *FnTy =
  1976. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1977. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
  1978. break;
  1979. }
  1980. case OMPRTL__kmpc_end_ordered: {
  1981. // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
  1982. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1983. auto *FnTy =
  1984. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  1985. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
  1986. break;
  1987. }
  1988. case OMPRTL__kmpc_omp_taskwait: {
  1989. // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
  1990. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1991. auto *FnTy =
  1992. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  1993. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
  1994. break;
  1995. }
  1996. case OMPRTL__kmpc_taskgroup: {
  1997. // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
  1998. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  1999. auto *FnTy =
  2000. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2001. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
  2002. break;
  2003. }
  2004. case OMPRTL__kmpc_end_taskgroup: {
  2005. // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
  2006. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  2007. auto *FnTy =
  2008. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2009. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
  2010. break;
  2011. }
  2012. case OMPRTL__kmpc_push_proc_bind: {
  2013. // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
  2014. // int proc_bind)
  2015. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  2016. auto *FnTy =
  2017. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2018. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
  2019. break;
  2020. }
  2021. case OMPRTL__kmpc_omp_task_with_deps: {
  2022. // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
  2023. // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
  2024. // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
  2025. llvm::Type *TypeParams[] = {
  2026. getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
  2027. CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
  2028. auto *FnTy =
  2029. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
  2030. RTLFn =
  2031. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
  2032. break;
  2033. }
  2034. case OMPRTL__kmpc_omp_wait_deps: {
  2035. // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
  2036. // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
  2037. // kmp_depend_info_t *noalias_dep_list);
  2038. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  2039. CGM.Int32Ty, CGM.VoidPtrTy,
  2040. CGM.Int32Ty, CGM.VoidPtrTy};
  2041. auto *FnTy =
  2042. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2043. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
  2044. break;
  2045. }
  2046. case OMPRTL__kmpc_cancellationpoint: {
  2047. // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  2048. // global_tid, kmp_int32 cncl_kind)
  2049. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  2050. auto *FnTy =
  2051. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2052. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
  2053. break;
  2054. }
  2055. case OMPRTL__kmpc_cancel: {
  2056. // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  2057. // kmp_int32 cncl_kind)
  2058. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
  2059. auto *FnTy =
  2060. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2061. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
  2062. break;
  2063. }
  2064. case OMPRTL__kmpc_push_num_teams: {
  2065. // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
  2066. // kmp_int32 num_teams, kmp_int32 num_threads)
  2067. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
  2068. CGM.Int32Ty};
  2069. auto *FnTy =
  2070. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2071. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
  2072. break;
  2073. }
  2074. case OMPRTL__kmpc_fork_teams: {
  2075. // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
  2076. // microtask, ...);
  2077. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  2078. getKmpc_MicroPointerTy()};
  2079. auto *FnTy =
  2080. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
  2081. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
  2082. if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
  2083. if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
  2084. llvm::LLVMContext &Ctx = F->getContext();
  2085. llvm::MDBuilder MDB(Ctx);
  2086. // Annotate the callback behavior of the __kmpc_fork_teams:
  2087. // - The callback callee is argument number 2 (microtask).
  2088. // - The first two arguments of the callback callee are unknown (-1).
  2089. // - All variadic arguments to the __kmpc_fork_teams are passed to the
  2090. // callback callee.
  2091. F->addMetadata(
  2092. llvm::LLVMContext::MD_callback,
  2093. *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
  2094. 2, {-1, -1},
  2095. /* VarArgsArePassed */ true)}));
  2096. }
  2097. }
  2098. break;
  2099. }
  2100. case OMPRTL__kmpc_taskloop: {
  2101. // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
  2102. // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
  2103. // sched, kmp_uint64 grainsize, void *task_dup);
  2104. llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
  2105. CGM.IntTy,
  2106. CGM.VoidPtrTy,
  2107. CGM.IntTy,
  2108. CGM.Int64Ty->getPointerTo(),
  2109. CGM.Int64Ty->getPointerTo(),
  2110. CGM.Int64Ty,
  2111. CGM.IntTy,
  2112. CGM.IntTy,
  2113. CGM.Int64Ty,
  2114. CGM.VoidPtrTy};
  2115. auto *FnTy =
  2116. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2117. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
  2118. break;
  2119. }
  2120. case OMPRTL__kmpc_doacross_init: {
  2121. // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
  2122. // num_dims, struct kmp_dim *dims);
  2123. llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
  2124. CGM.Int32Ty,
  2125. CGM.Int32Ty,
  2126. CGM.VoidPtrTy};
  2127. auto *FnTy =
  2128. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2129. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
  2130. break;
  2131. }
  2132. case OMPRTL__kmpc_doacross_fini: {
  2133. // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
  2134. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
  2135. auto *FnTy =
  2136. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2137. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
  2138. break;
  2139. }
  2140. case OMPRTL__kmpc_doacross_post: {
  2141. // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
  2142. // *vec);
  2143. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  2144. CGM.Int64Ty->getPointerTo()};
  2145. auto *FnTy =
  2146. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2147. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
  2148. break;
  2149. }
  2150. case OMPRTL__kmpc_doacross_wait: {
  2151. // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
  2152. // *vec);
  2153. llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
  2154. CGM.Int64Ty->getPointerTo()};
  2155. auto *FnTy =
  2156. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2157. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
  2158. break;
  2159. }
  2160. case OMPRTL__kmpc_task_reduction_init: {
  2161. // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
  2162. // *data);
  2163. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
  2164. auto *FnTy =
  2165. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  2166. RTLFn =
  2167. CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
  2168. break;
  2169. }
  2170. case OMPRTL__kmpc_task_reduction_get_th_data: {
  2171. // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
  2172. // *d);
  2173. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
  2174. auto *FnTy =
  2175. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  2176. RTLFn = CGM.CreateRuntimeFunction(
  2177. FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
  2178. break;
  2179. }
  2180. case OMPRTL__kmpc_alloc: {
  2181. // Build to void *__kmpc_alloc(int gtid, size_t sz, omp_allocator_handle_t
  2182. // al); omp_allocator_handle_t type is void *.
  2183. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.SizeTy, CGM.VoidPtrTy};
  2184. auto *FnTy =
  2185. llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
  2186. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_alloc");
  2187. break;
  2188. }
  2189. case OMPRTL__kmpc_free: {
  2190. // Build to void __kmpc_free(int gtid, void *ptr, omp_allocator_handle_t
  2191. // al); omp_allocator_handle_t type is void *.
  2192. llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
  2193. auto *FnTy =
  2194. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2195. RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_free");
  2196. break;
  2197. }
  2198. case OMPRTL__kmpc_push_target_tripcount: {
  2199. // Build void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
  2200. // size);
  2201. llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int64Ty};
  2202. llvm::FunctionType *FnTy =
  2203. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2204. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_target_tripcount");
  2205. break;
  2206. }
  2207. case OMPRTL__tgt_target: {
  2208. // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
  2209. // arg_num, void** args_base, void **args, int64_t *arg_sizes, int64_t
  2210. // *arg_types);
  2211. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2212. CGM.VoidPtrTy,
  2213. CGM.Int32Ty,
  2214. CGM.VoidPtrPtrTy,
  2215. CGM.VoidPtrPtrTy,
  2216. CGM.Int64Ty->getPointerTo(),
  2217. CGM.Int64Ty->getPointerTo()};
  2218. auto *FnTy =
  2219. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2220. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
  2221. break;
  2222. }
  2223. case OMPRTL__tgt_target_nowait: {
  2224. // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
  2225. // int32_t arg_num, void** args_base, void **args, int64_t *arg_sizes,
  2226. // int64_t *arg_types);
  2227. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2228. CGM.VoidPtrTy,
  2229. CGM.Int32Ty,
  2230. CGM.VoidPtrPtrTy,
  2231. CGM.VoidPtrPtrTy,
  2232. CGM.Int64Ty->getPointerTo(),
  2233. CGM.Int64Ty->getPointerTo()};
  2234. auto *FnTy =
  2235. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2236. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
  2237. break;
  2238. }
  2239. case OMPRTL__tgt_target_teams: {
  2240. // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
  2241. // int32_t arg_num, void** args_base, void **args, int64_t *arg_sizes,
  2242. // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
  2243. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2244. CGM.VoidPtrTy,
  2245. CGM.Int32Ty,
  2246. CGM.VoidPtrPtrTy,
  2247. CGM.VoidPtrPtrTy,
  2248. CGM.Int64Ty->getPointerTo(),
  2249. CGM.Int64Ty->getPointerTo(),
  2250. CGM.Int32Ty,
  2251. CGM.Int32Ty};
  2252. auto *FnTy =
  2253. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2254. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
  2255. break;
  2256. }
  2257. case OMPRTL__tgt_target_teams_nowait: {
  2258. // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
  2259. // *host_ptr, int32_t arg_num, void** args_base, void **args, int64_t
  2260. // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
  2261. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2262. CGM.VoidPtrTy,
  2263. CGM.Int32Ty,
  2264. CGM.VoidPtrPtrTy,
  2265. CGM.VoidPtrPtrTy,
  2266. CGM.Int64Ty->getPointerTo(),
  2267. CGM.Int64Ty->getPointerTo(),
  2268. CGM.Int32Ty,
  2269. CGM.Int32Ty};
  2270. auto *FnTy =
  2271. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2272. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
  2273. break;
  2274. }
  2275. case OMPRTL__tgt_register_requires: {
  2276. // Build void __tgt_register_requires(int64_t flags);
  2277. llvm::Type *TypeParams[] = {CGM.Int64Ty};
  2278. auto *FnTy =
  2279. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2280. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_requires");
  2281. break;
  2282. }
  2283. case OMPRTL__tgt_register_lib: {
  2284. // Build void __tgt_register_lib(__tgt_bin_desc *desc);
  2285. QualType ParamTy =
  2286. CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
  2287. llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
  2288. auto *FnTy =
  2289. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2290. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
  2291. break;
  2292. }
  2293. case OMPRTL__tgt_unregister_lib: {
  2294. // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
  2295. QualType ParamTy =
  2296. CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
  2297. llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
  2298. auto *FnTy =
  2299. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2300. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
  2301. break;
  2302. }
  2303. case OMPRTL__tgt_target_data_begin: {
  2304. // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
  2305. // void** args_base, void **args, int64_t *arg_sizes, int64_t *arg_types);
  2306. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2307. CGM.Int32Ty,
  2308. CGM.VoidPtrPtrTy,
  2309. CGM.VoidPtrPtrTy,
  2310. CGM.Int64Ty->getPointerTo(),
  2311. CGM.Int64Ty->getPointerTo()};
  2312. auto *FnTy =
  2313. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2314. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
  2315. break;
  2316. }
  2317. case OMPRTL__tgt_target_data_begin_nowait: {
  2318. // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
  2319. // arg_num, void** args_base, void **args, int64_t *arg_sizes, int64_t
  2320. // *arg_types);
  2321. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2322. CGM.Int32Ty,
  2323. CGM.VoidPtrPtrTy,
  2324. CGM.VoidPtrPtrTy,
  2325. CGM.Int64Ty->getPointerTo(),
  2326. CGM.Int64Ty->getPointerTo()};
  2327. auto *FnTy =
  2328. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2329. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
  2330. break;
  2331. }
  2332. case OMPRTL__tgt_target_data_end: {
  2333. // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
  2334. // void** args_base, void **args, int64_t *arg_sizes, int64_t *arg_types);
  2335. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2336. CGM.Int32Ty,
  2337. CGM.VoidPtrPtrTy,
  2338. CGM.VoidPtrPtrTy,
  2339. CGM.Int64Ty->getPointerTo(),
  2340. CGM.Int64Ty->getPointerTo()};
  2341. auto *FnTy =
  2342. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2343. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
  2344. break;
  2345. }
  2346. case OMPRTL__tgt_target_data_end_nowait: {
  2347. // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
  2348. // arg_num, void** args_base, void **args, int64_t *arg_sizes, int64_t
  2349. // *arg_types);
  2350. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2351. CGM.Int32Ty,
  2352. CGM.VoidPtrPtrTy,
  2353. CGM.VoidPtrPtrTy,
  2354. CGM.Int64Ty->getPointerTo(),
  2355. CGM.Int64Ty->getPointerTo()};
  2356. auto *FnTy =
  2357. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2358. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
  2359. break;
  2360. }
  2361. case OMPRTL__tgt_target_data_update: {
  2362. // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
  2363. // void** args_base, void **args, int64_t *arg_sizes, int64_t *arg_types);
  2364. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2365. CGM.Int32Ty,
  2366. CGM.VoidPtrPtrTy,
  2367. CGM.VoidPtrPtrTy,
  2368. CGM.Int64Ty->getPointerTo(),
  2369. CGM.Int64Ty->getPointerTo()};
  2370. auto *FnTy =
  2371. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2372. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
  2373. break;
  2374. }
  2375. case OMPRTL__tgt_target_data_update_nowait: {
  2376. // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
  2377. // arg_num, void** args_base, void **args, int64_t *arg_sizes, int64_t
  2378. // *arg_types);
  2379. llvm::Type *TypeParams[] = {CGM.Int64Ty,
  2380. CGM.Int32Ty,
  2381. CGM.VoidPtrPtrTy,
  2382. CGM.VoidPtrPtrTy,
  2383. CGM.Int64Ty->getPointerTo(),
  2384. CGM.Int64Ty->getPointerTo()};
  2385. auto *FnTy =
  2386. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2387. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
  2388. break;
  2389. }
  2390. case OMPRTL__tgt_mapper_num_components: {
  2391. // Build int64_t __tgt_mapper_num_components(void *rt_mapper_handle);
  2392. llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
  2393. auto *FnTy =
  2394. llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
  2395. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_mapper_num_components");
  2396. break;
  2397. }
  2398. case OMPRTL__tgt_push_mapper_component: {
  2399. // Build void __tgt_push_mapper_component(void *rt_mapper_handle, void
  2400. // *base, void *begin, int64_t size, int64_t type);
  2401. llvm::Type *TypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy, CGM.VoidPtrTy,
  2402. CGM.Int64Ty, CGM.Int64Ty};
  2403. auto *FnTy =
  2404. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2405. RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_push_mapper_component");
  2406. break;
  2407. }
  2408. }
  2409. assert(RTLFn && "Unable to find OpenMP runtime function");
  2410. return RTLFn;
  2411. }
  2412. llvm::FunctionCallee
  2413. CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned) {
  2414. assert((IVSize == 32 || IVSize == 64) &&
  2415. "IV size is not compatible with the omp runtime");
  2416. StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
  2417. : "__kmpc_for_static_init_4u")
  2418. : (IVSigned ? "__kmpc_for_static_init_8"
  2419. : "__kmpc_for_static_init_8u");
  2420. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2421. auto *PtrTy = llvm::PointerType::getUnqual(ITy);
  2422. llvm::Type *TypeParams[] = {
  2423. getIdentTyPointerTy(), // loc
  2424. CGM.Int32Ty, // tid
  2425. CGM.Int32Ty, // schedtype
  2426. llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
  2427. PtrTy, // p_lower
  2428. PtrTy, // p_upper
  2429. PtrTy, // p_stride
  2430. ITy, // incr
  2431. ITy // chunk
  2432. };
  2433. auto *FnTy =
  2434. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2435. return CGM.CreateRuntimeFunction(FnTy, Name);
  2436. }
  2437. llvm::FunctionCallee
  2438. CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) {
  2439. assert((IVSize == 32 || IVSize == 64) &&
  2440. "IV size is not compatible with the omp runtime");
  2441. StringRef Name =
  2442. IVSize == 32
  2443. ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
  2444. : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
  2445. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2446. llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
  2447. CGM.Int32Ty, // tid
  2448. CGM.Int32Ty, // schedtype
  2449. ITy, // lower
  2450. ITy, // upper
  2451. ITy, // stride
  2452. ITy // chunk
  2453. };
  2454. auto *FnTy =
  2455. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
  2456. return CGM.CreateRuntimeFunction(FnTy, Name);
  2457. }
  2458. llvm::FunctionCallee
  2459. CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) {
  2460. assert((IVSize == 32 || IVSize == 64) &&
  2461. "IV size is not compatible with the omp runtime");
  2462. StringRef Name =
  2463. IVSize == 32
  2464. ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
  2465. : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
  2466. llvm::Type *TypeParams[] = {
  2467. getIdentTyPointerTy(), // loc
  2468. CGM.Int32Ty, // tid
  2469. };
  2470. auto *FnTy =
  2471. llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
  2472. return CGM.CreateRuntimeFunction(FnTy, Name);
  2473. }
  2474. llvm::FunctionCallee
  2475. CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) {
  2476. assert((IVSize == 32 || IVSize == 64) &&
  2477. "IV size is not compatible with the omp runtime");
  2478. StringRef Name =
  2479. IVSize == 32
  2480. ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
  2481. : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
  2482. llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
  2483. auto *PtrTy = llvm::PointerType::getUnqual(ITy);
  2484. llvm::Type *TypeParams[] = {
  2485. getIdentTyPointerTy(), // loc
  2486. CGM.Int32Ty, // tid
  2487. llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
  2488. PtrTy, // p_lower
  2489. PtrTy, // p_upper
  2490. PtrTy // p_stride
  2491. };
  2492. auto *FnTy =
  2493. llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
  2494. return CGM.CreateRuntimeFunction(FnTy, Name);
  2495. }
  2496. /// Obtain information that uniquely identifies a target entry. This
  2497. /// consists of the file and device IDs as well as line number associated with
  2498. /// the relevant entry source location.
  2499. static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
  2500. unsigned &DeviceID, unsigned &FileID,
  2501. unsigned &LineNum) {
  2502. SourceManager &SM = C.getSourceManager();
  2503. // The loc should be always valid and have a file ID (the user cannot use
  2504. // #pragma directives in macros)
  2505. assert(Loc.isValid() && "Source location is expected to be always valid.");
  2506. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  2507. assert(PLoc.isValid() && "Source location is expected to be always valid.");
  2508. llvm::sys::fs::UniqueID ID;
  2509. if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
  2510. SM.getDiagnostics().Report(diag::err_cannot_open_file)
  2511. << PLoc.getFilename() << EC.message();
  2512. DeviceID = ID.getDevice();
  2513. FileID = ID.getFile();
  2514. LineNum = PLoc.getLine();
  2515. }
  2516. Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) {
  2517. if (CGM.getLangOpts().OpenMPSimd)
  2518. return Address::invalid();
  2519. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2520. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2521. if (Res && (*Res == OMPDeclareTargetDeclAttr::MT_Link ||
  2522. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2523. HasRequiresUnifiedSharedMemory))) {
  2524. SmallString<64> PtrName;
  2525. {
  2526. llvm::raw_svector_ostream OS(PtrName);
  2527. OS << CGM.getMangledName(GlobalDecl(VD));
  2528. if (!VD->isExternallyVisible()) {
  2529. unsigned DeviceID, FileID, Line;
  2530. getTargetEntryUniqueInfo(CGM.getContext(),
  2531. VD->getCanonicalDecl()->getBeginLoc(),
  2532. DeviceID, FileID, Line);
  2533. OS << llvm::format("_%x", FileID);
  2534. }
  2535. OS << "_decl_tgt_ref_ptr";
  2536. }
  2537. llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
  2538. if (!Ptr) {
  2539. QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
  2540. Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
  2541. PtrName);
  2542. auto *GV = cast<llvm::GlobalVariable>(Ptr);
  2543. GV->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
  2544. if (!CGM.getLangOpts().OpenMPIsDevice)
  2545. GV->setInitializer(CGM.GetAddrOfGlobal(VD));
  2546. registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
  2547. }
  2548. return Address(Ptr, CGM.getContext().getDeclAlign(VD));
  2549. }
  2550. return Address::invalid();
  2551. }
  2552. llvm::Constant *
  2553. CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
  2554. assert(!CGM.getLangOpts().OpenMPUseTLS ||
  2555. !CGM.getContext().getTargetInfo().isTLSSupported());
  2556. // Lookup the entry, lazily creating it if necessary.
  2557. std::string Suffix = getName({"cache", ""});
  2558. return getOrCreateInternalVariable(
  2559. CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
  2560. }
  2561. Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
  2562. const VarDecl *VD,
  2563. Address VDAddr,
  2564. SourceLocation Loc) {
  2565. if (CGM.getLangOpts().OpenMPUseTLS &&
  2566. CGM.getContext().getTargetInfo().isTLSSupported())
  2567. return VDAddr;
  2568. llvm::Type *VarTy = VDAddr.getElementType();
  2569. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  2570. CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
  2571. CGM.Int8PtrTy),
  2572. CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
  2573. getOrCreateThreadPrivateCache(VD)};
  2574. return Address(CGF.EmitRuntimeCall(
  2575. createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
  2576. VDAddr.getAlignment());
  2577. }
  2578. void CGOpenMPRuntime::emitThreadPrivateVarInit(
  2579. CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
  2580. llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
  2581. // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
  2582. // library.
  2583. llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
  2584. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
  2585. OMPLoc);
  2586. // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
  2587. // to register constructor/destructor for variable.
  2588. llvm::Value *Args[] = {
  2589. OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
  2590. Ctor, CopyCtor, Dtor};
  2591. CGF.EmitRuntimeCall(
  2592. createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
  2593. }
  2594. llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
  2595. const VarDecl *VD, Address VDAddr, SourceLocation Loc,
  2596. bool PerformInit, CodeGenFunction *CGF) {
  2597. if (CGM.getLangOpts().OpenMPUseTLS &&
  2598. CGM.getContext().getTargetInfo().isTLSSupported())
  2599. return nullptr;
  2600. VD = VD->getDefinition(CGM.getContext());
  2601. if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
  2602. QualType ASTTy = VD->getType();
  2603. llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
  2604. const Expr *Init = VD->getAnyInitializer();
  2605. if (CGM.getLangOpts().CPlusPlus && PerformInit) {
  2606. // Generate function that re-emits the declaration's initializer into the
  2607. // threadprivate copy of the variable VD
  2608. CodeGenFunction CtorCGF(CGM);
  2609. FunctionArgList Args;
  2610. ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
  2611. /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
  2612. ImplicitParamDecl::Other);
  2613. Args.push_back(&Dst);
  2614. const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
  2615. CGM.getContext().VoidPtrTy, Args);
  2616. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2617. std::string Name = getName({"__kmpc_global_ctor_", ""});
  2618. llvm::Function *Fn =
  2619. CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
  2620. CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
  2621. Args, Loc, Loc);
  2622. llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
  2623. CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
  2624. CGM.getContext().VoidPtrTy, Dst.getLocation());
  2625. Address Arg = Address(ArgVal, VDAddr.getAlignment());
  2626. Arg = CtorCGF.Builder.CreateElementBitCast(
  2627. Arg, CtorCGF.ConvertTypeForMem(ASTTy));
  2628. CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
  2629. /*IsInitializer=*/true);
  2630. ArgVal = CtorCGF.EmitLoadOfScalar(
  2631. CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
  2632. CGM.getContext().VoidPtrTy, Dst.getLocation());
  2633. CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
  2634. CtorCGF.FinishFunction();
  2635. Ctor = Fn;
  2636. }
  2637. if (VD->getType().isDestructedType() != QualType::DK_none) {
  2638. // Generate function that emits destructor call for the threadprivate copy
  2639. // of the variable VD
  2640. CodeGenFunction DtorCGF(CGM);
  2641. FunctionArgList Args;
  2642. ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
  2643. /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
  2644. ImplicitParamDecl::Other);
  2645. Args.push_back(&Dst);
  2646. const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
  2647. CGM.getContext().VoidTy, Args);
  2648. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2649. std::string Name = getName({"__kmpc_global_dtor_", ""});
  2650. llvm::Function *Fn =
  2651. CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
  2652. auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
  2653. DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
  2654. Loc, Loc);
  2655. // Create a scope with an artificial location for the body of this function.
  2656. auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
  2657. llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
  2658. DtorCGF.GetAddrOfLocalVar(&Dst),
  2659. /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
  2660. DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
  2661. DtorCGF.getDestroyer(ASTTy.isDestructedType()),
  2662. DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
  2663. DtorCGF.FinishFunction();
  2664. Dtor = Fn;
  2665. }
  2666. // Do not emit init function if it is not required.
  2667. if (!Ctor && !Dtor)
  2668. return nullptr;
  2669. llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
  2670. auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
  2671. /*isVarArg=*/false)
  2672. ->getPointerTo();
  2673. // Copying constructor for the threadprivate variable.
  2674. // Must be NULL - reserved by runtime, but currently it requires that this
  2675. // parameter is always NULL. Otherwise it fires assertion.
  2676. CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
  2677. if (Ctor == nullptr) {
  2678. auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
  2679. /*isVarArg=*/false)
  2680. ->getPointerTo();
  2681. Ctor = llvm::Constant::getNullValue(CtorTy);
  2682. }
  2683. if (Dtor == nullptr) {
  2684. auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
  2685. /*isVarArg=*/false)
  2686. ->getPointerTo();
  2687. Dtor = llvm::Constant::getNullValue(DtorTy);
  2688. }
  2689. if (!CGF) {
  2690. auto *InitFunctionTy =
  2691. llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
  2692. std::string Name = getName({"__omp_threadprivate_init_", ""});
  2693. llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
  2694. InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
  2695. CodeGenFunction InitCGF(CGM);
  2696. FunctionArgList ArgList;
  2697. InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
  2698. CGM.getTypes().arrangeNullaryFunction(), ArgList,
  2699. Loc, Loc);
  2700. emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
  2701. InitCGF.FinishFunction();
  2702. return InitFunction;
  2703. }
  2704. emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
  2705. }
  2706. return nullptr;
  2707. }
  2708. bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
  2709. llvm::GlobalVariable *Addr,
  2710. bool PerformInit) {
  2711. if (CGM.getLangOpts().OMPTargetTriples.empty() &&
  2712. !CGM.getLangOpts().OpenMPIsDevice)
  2713. return false;
  2714. Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2715. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2716. if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link ||
  2717. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2718. HasRequiresUnifiedSharedMemory))
  2719. return CGM.getLangOpts().OpenMPIsDevice;
  2720. VD = VD->getDefinition(CGM.getContext());
  2721. if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
  2722. return CGM.getLangOpts().OpenMPIsDevice;
  2723. QualType ASTTy = VD->getType();
  2724. SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
  2725. // Produce the unique prefix to identify the new target regions. We use
  2726. // the source location of the variable declaration which we know to not
  2727. // conflict with any target region.
  2728. unsigned DeviceID;
  2729. unsigned FileID;
  2730. unsigned Line;
  2731. getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
  2732. SmallString<128> Buffer, Out;
  2733. {
  2734. llvm::raw_svector_ostream OS(Buffer);
  2735. OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
  2736. << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
  2737. }
  2738. const Expr *Init = VD->getAnyInitializer();
  2739. if (CGM.getLangOpts().CPlusPlus && PerformInit) {
  2740. llvm::Constant *Ctor;
  2741. llvm::Constant *ID;
  2742. if (CGM.getLangOpts().OpenMPIsDevice) {
  2743. // Generate function that re-emits the declaration's initializer into
  2744. // the threadprivate copy of the variable VD
  2745. CodeGenFunction CtorCGF(CGM);
  2746. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2747. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2748. llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
  2749. FTy, Twine(Buffer, "_ctor"), FI, Loc);
  2750. auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
  2751. CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
  2752. FunctionArgList(), Loc, Loc);
  2753. auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
  2754. CtorCGF.EmitAnyExprToMem(Init,
  2755. Address(Addr, CGM.getContext().getDeclAlign(VD)),
  2756. Init->getType().getQualifiers(),
  2757. /*IsInitializer=*/true);
  2758. CtorCGF.FinishFunction();
  2759. Ctor = Fn;
  2760. ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  2761. CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
  2762. } else {
  2763. Ctor = new llvm::GlobalVariable(
  2764. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  2765. llvm::GlobalValue::PrivateLinkage,
  2766. llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
  2767. ID = Ctor;
  2768. }
  2769. // Register the information for the entry associated with the constructor.
  2770. Out.clear();
  2771. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  2772. DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
  2773. ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
  2774. }
  2775. if (VD->getType().isDestructedType() != QualType::DK_none) {
  2776. llvm::Constant *Dtor;
  2777. llvm::Constant *ID;
  2778. if (CGM.getLangOpts().OpenMPIsDevice) {
  2779. // Generate function that emits destructor call for the threadprivate
  2780. // copy of the variable VD
  2781. CodeGenFunction DtorCGF(CGM);
  2782. const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
  2783. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  2784. llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
  2785. FTy, Twine(Buffer, "_dtor"), FI, Loc);
  2786. auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
  2787. DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
  2788. FunctionArgList(), Loc, Loc);
  2789. // Create a scope with an artificial location for the body of this
  2790. // function.
  2791. auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
  2792. DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
  2793. ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
  2794. DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
  2795. DtorCGF.FinishFunction();
  2796. Dtor = Fn;
  2797. ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
  2798. CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
  2799. } else {
  2800. Dtor = new llvm::GlobalVariable(
  2801. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  2802. llvm::GlobalValue::PrivateLinkage,
  2803. llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
  2804. ID = Dtor;
  2805. }
  2806. // Register the information for the entry associated with the destructor.
  2807. Out.clear();
  2808. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  2809. DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
  2810. ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
  2811. }
  2812. return CGM.getLangOpts().OpenMPIsDevice;
  2813. }
  2814. Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
  2815. QualType VarType,
  2816. StringRef Name) {
  2817. std::string Suffix = getName({"artificial", ""});
  2818. std::string CacheSuffix = getName({"cache", ""});
  2819. llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
  2820. llvm::Value *GAddr =
  2821. getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
  2822. llvm::Value *Args[] = {
  2823. emitUpdateLocation(CGF, SourceLocation()),
  2824. getThreadID(CGF, SourceLocation()),
  2825. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
  2826. CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
  2827. /*isSigned=*/false),
  2828. getOrCreateInternalVariable(
  2829. CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
  2830. return Address(
  2831. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2832. CGF.EmitRuntimeCall(
  2833. createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
  2834. VarLVType->getPointerTo(/*AddrSpace=*/0)),
  2835. CGM.getPointerAlign());
  2836. }
  2837. void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
  2838. const RegionCodeGenTy &ThenGen,
  2839. const RegionCodeGenTy &ElseGen) {
  2840. CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
  2841. // If the condition constant folds and can be elided, try to avoid emitting
  2842. // the condition and the dead arm of the if/else.
  2843. bool CondConstant;
  2844. if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
  2845. if (CondConstant)
  2846. ThenGen(CGF);
  2847. else
  2848. ElseGen(CGF);
  2849. return;
  2850. }
  2851. // Otherwise, the condition did not fold, or we couldn't elide it. Just
  2852. // emit the conditional branch.
  2853. llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
  2854. llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
  2855. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
  2856. CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
  2857. // Emit the 'then' code.
  2858. CGF.EmitBlock(ThenBlock);
  2859. ThenGen(CGF);
  2860. CGF.EmitBranch(ContBlock);
  2861. // Emit the 'else' code if present.
  2862. // There is no need to emit line number for unconditional branch.
  2863. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2864. CGF.EmitBlock(ElseBlock);
  2865. ElseGen(CGF);
  2866. // There is no need to emit line number for unconditional branch.
  2867. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2868. CGF.EmitBranch(ContBlock);
  2869. // Emit the continuation block for code after the if.
  2870. CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
  2871. }
  2872. void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  2873. llvm::Function *OutlinedFn,
  2874. ArrayRef<llvm::Value *> CapturedVars,
  2875. const Expr *IfCond) {
  2876. if (!CGF.HaveInsertPoint())
  2877. return;
  2878. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  2879. auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
  2880. PrePostActionTy &) {
  2881. // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
  2882. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  2883. llvm::Value *Args[] = {
  2884. RTLoc,
  2885. CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
  2886. CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
  2887. llvm::SmallVector<llvm::Value *, 16> RealArgs;
  2888. RealArgs.append(std::begin(Args), std::end(Args));
  2889. RealArgs.append(CapturedVars.begin(), CapturedVars.end());
  2890. llvm::FunctionCallee RTLFn =
  2891. RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
  2892. CGF.EmitRuntimeCall(RTLFn, RealArgs);
  2893. };
  2894. auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
  2895. PrePostActionTy &) {
  2896. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  2897. llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
  2898. // Build calls:
  2899. // __kmpc_serialized_parallel(&Loc, GTid);
  2900. llvm::Value *Args[] = {RTLoc, ThreadID};
  2901. CGF.EmitRuntimeCall(
  2902. RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
  2903. // OutlinedFn(&GTid, &zero_bound, CapturedStruct);
  2904. Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
  2905. Address ZeroAddrBound =
  2906. CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2907. /*Name=*/".bound.zero.addr");
  2908. CGF.InitTempAlloca(ZeroAddrBound, CGF.Builder.getInt32(/*C*/ 0));
  2909. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
  2910. // ThreadId for serialized parallels is 0.
  2911. OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
  2912. OutlinedFnArgs.push_back(ZeroAddrBound.getPointer());
  2913. OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
  2914. RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
  2915. // __kmpc_end_serialized_parallel(&Loc, GTid);
  2916. llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
  2917. CGF.EmitRuntimeCall(
  2918. RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
  2919. EndArgs);
  2920. };
  2921. if (IfCond) {
  2922. emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
  2923. } else {
  2924. RegionCodeGenTy ThenRCG(ThenGen);
  2925. ThenRCG(CGF);
  2926. }
  2927. }
  2928. // If we're inside an (outlined) parallel region, use the region info's
  2929. // thread-ID variable (it is passed in a first argument of the outlined function
  2930. // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
  2931. // regular serial code region, get thread ID by calling kmp_int32
  2932. // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
  2933. // return the address of that temp.
  2934. Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
  2935. SourceLocation Loc) {
  2936. if (auto *OMPRegionInfo =
  2937. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  2938. if (OMPRegionInfo->getThreadIDVariable())
  2939. return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
  2940. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  2941. QualType Int32Ty =
  2942. CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
  2943. Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
  2944. CGF.EmitStoreOfScalar(ThreadID,
  2945. CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
  2946. return ThreadIDTemp;
  2947. }
  2948. llvm::Constant *CGOpenMPRuntime::getOrCreateInternalVariable(
  2949. llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
  2950. SmallString<256> Buffer;
  2951. llvm::raw_svector_ostream Out(Buffer);
  2952. Out << Name;
  2953. StringRef RuntimeName = Out.str();
  2954. auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
  2955. if (Elem.second) {
  2956. assert(Elem.second->getType()->getPointerElementType() == Ty &&
  2957. "OMP internal variable has different type than requested");
  2958. return &*Elem.second;
  2959. }
  2960. return Elem.second = new llvm::GlobalVariable(
  2961. CGM.getModule(), Ty, /*IsConstant*/ false,
  2962. llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
  2963. Elem.first(), /*InsertBefore=*/nullptr,
  2964. llvm::GlobalValue::NotThreadLocal, AddressSpace);
  2965. }
  2966. llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
  2967. std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
  2968. std::string Name = getName({Prefix, "var"});
  2969. return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
  2970. }
  2971. namespace {
  2972. /// Common pre(post)-action for different OpenMP constructs.
  2973. class CommonActionTy final : public PrePostActionTy {
  2974. llvm::FunctionCallee EnterCallee;
  2975. ArrayRef<llvm::Value *> EnterArgs;
  2976. llvm::FunctionCallee ExitCallee;
  2977. ArrayRef<llvm::Value *> ExitArgs;
  2978. bool Conditional;
  2979. llvm::BasicBlock *ContBlock = nullptr;
  2980. public:
  2981. CommonActionTy(llvm::FunctionCallee EnterCallee,
  2982. ArrayRef<llvm::Value *> EnterArgs,
  2983. llvm::FunctionCallee ExitCallee,
  2984. ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
  2985. : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
  2986. ExitArgs(ExitArgs), Conditional(Conditional) {}
  2987. void Enter(CodeGenFunction &CGF) override {
  2988. llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
  2989. if (Conditional) {
  2990. llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
  2991. auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
  2992. ContBlock = CGF.createBasicBlock("omp_if.end");
  2993. // Generate the branch (If-stmt)
  2994. CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
  2995. CGF.EmitBlock(ThenBlock);
  2996. }
  2997. }
  2998. void Done(CodeGenFunction &CGF) {
  2999. // Emit the rest of blocks/branches
  3000. CGF.EmitBranch(ContBlock);
  3001. CGF.EmitBlock(ContBlock, true);
  3002. }
  3003. void Exit(CodeGenFunction &CGF) override {
  3004. CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
  3005. }
  3006. };
  3007. } // anonymous namespace
  3008. void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
  3009. StringRef CriticalName,
  3010. const RegionCodeGenTy &CriticalOpGen,
  3011. SourceLocation Loc, const Expr *Hint) {
  3012. // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
  3013. // CriticalOpGen();
  3014. // __kmpc_end_critical(ident_t *, gtid, Lock);
  3015. // Prepare arguments and build a call to __kmpc_critical
  3016. if (!CGF.HaveInsertPoint())
  3017. return;
  3018. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3019. getCriticalRegionLock(CriticalName)};
  3020. llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
  3021. std::end(Args));
  3022. if (Hint) {
  3023. EnterArgs.push_back(CGF.Builder.CreateIntCast(
  3024. CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
  3025. }
  3026. CommonActionTy Action(
  3027. createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
  3028. : OMPRTL__kmpc_critical),
  3029. EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
  3030. CriticalOpGen.setAction(Action);
  3031. emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
  3032. }
  3033. void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
  3034. const RegionCodeGenTy &MasterOpGen,
  3035. SourceLocation Loc) {
  3036. if (!CGF.HaveInsertPoint())
  3037. return;
  3038. // if(__kmpc_master(ident_t *, gtid)) {
  3039. // MasterOpGen();
  3040. // __kmpc_end_master(ident_t *, gtid);
  3041. // }
  3042. // Prepare arguments and build a call to __kmpc_master
  3043. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3044. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
  3045. createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
  3046. /*Conditional=*/true);
  3047. MasterOpGen.setAction(Action);
  3048. emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
  3049. Action.Done(CGF);
  3050. }
  3051. void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
  3052. SourceLocation Loc) {
  3053. if (!CGF.HaveInsertPoint())
  3054. return;
  3055. // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
  3056. llvm::Value *Args[] = {
  3057. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3058. llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
  3059. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
  3060. if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  3061. Region->emitUntiedSwitch(CGF);
  3062. }
  3063. void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
  3064. const RegionCodeGenTy &TaskgroupOpGen,
  3065. SourceLocation Loc) {
  3066. if (!CGF.HaveInsertPoint())
  3067. return;
  3068. // __kmpc_taskgroup(ident_t *, gtid);
  3069. // TaskgroupOpGen();
  3070. // __kmpc_end_taskgroup(ident_t *, gtid);
  3071. // Prepare arguments and build a call to __kmpc_taskgroup
  3072. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3073. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
  3074. createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
  3075. Args);
  3076. TaskgroupOpGen.setAction(Action);
  3077. emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
  3078. }
  3079. /// Given an array of pointers to variables, project the address of a
  3080. /// given variable.
  3081. static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
  3082. unsigned Index, const VarDecl *Var) {
  3083. // Pull out the pointer to the variable.
  3084. Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index);
  3085. llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
  3086. Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
  3087. Addr = CGF.Builder.CreateElementBitCast(
  3088. Addr, CGF.ConvertTypeForMem(Var->getType()));
  3089. return Addr;
  3090. }
  3091. static llvm::Value *emitCopyprivateCopyFunction(
  3092. CodeGenModule &CGM, llvm::Type *ArgsType,
  3093. ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
  3094. ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
  3095. SourceLocation Loc) {
  3096. ASTContext &C = CGM.getContext();
  3097. // void copy_func(void *LHSArg, void *RHSArg);
  3098. FunctionArgList Args;
  3099. ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  3100. ImplicitParamDecl::Other);
  3101. ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  3102. ImplicitParamDecl::Other);
  3103. Args.push_back(&LHSArg);
  3104. Args.push_back(&RHSArg);
  3105. const auto &CGFI =
  3106. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  3107. std::string Name =
  3108. CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
  3109. auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
  3110. llvm::GlobalValue::InternalLinkage, Name,
  3111. &CGM.getModule());
  3112. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  3113. Fn->setDoesNotRecurse();
  3114. CodeGenFunction CGF(CGM);
  3115. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  3116. // Dest = (void*[n])(LHSArg);
  3117. // Src = (void*[n])(RHSArg);
  3118. Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  3119. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
  3120. ArgsType), CGF.getPointerAlign());
  3121. Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  3122. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
  3123. ArgsType), CGF.getPointerAlign());
  3124. // *(Type0*)Dst[0] = *(Type0*)Src[0];
  3125. // *(Type1*)Dst[1] = *(Type1*)Src[1];
  3126. // ...
  3127. // *(Typen*)Dst[n] = *(Typen*)Src[n];
  3128. for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
  3129. const auto *DestVar =
  3130. cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
  3131. Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
  3132. const auto *SrcVar =
  3133. cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
  3134. Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
  3135. const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
  3136. QualType Type = VD->getType();
  3137. CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
  3138. }
  3139. CGF.FinishFunction();
  3140. return Fn;
  3141. }
  3142. void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
  3143. const RegionCodeGenTy &SingleOpGen,
  3144. SourceLocation Loc,
  3145. ArrayRef<const Expr *> CopyprivateVars,
  3146. ArrayRef<const Expr *> SrcExprs,
  3147. ArrayRef<const Expr *> DstExprs,
  3148. ArrayRef<const Expr *> AssignmentOps) {
  3149. if (!CGF.HaveInsertPoint())
  3150. return;
  3151. assert(CopyprivateVars.size() == SrcExprs.size() &&
  3152. CopyprivateVars.size() == DstExprs.size() &&
  3153. CopyprivateVars.size() == AssignmentOps.size());
  3154. ASTContext &C = CGM.getContext();
  3155. // int32 did_it = 0;
  3156. // if(__kmpc_single(ident_t *, gtid)) {
  3157. // SingleOpGen();
  3158. // __kmpc_end_single(ident_t *, gtid);
  3159. // did_it = 1;
  3160. // }
  3161. // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
  3162. // <copy_func>, did_it);
  3163. Address DidIt = Address::invalid();
  3164. if (!CopyprivateVars.empty()) {
  3165. // int32 did_it = 0;
  3166. QualType KmpInt32Ty =
  3167. C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  3168. DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
  3169. CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
  3170. }
  3171. // Prepare arguments and build a call to __kmpc_single
  3172. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3173. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
  3174. createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
  3175. /*Conditional=*/true);
  3176. SingleOpGen.setAction(Action);
  3177. emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
  3178. if (DidIt.isValid()) {
  3179. // did_it = 1;
  3180. CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
  3181. }
  3182. Action.Done(CGF);
  3183. // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
  3184. // <copy_func>, did_it);
  3185. if (DidIt.isValid()) {
  3186. llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
  3187. QualType CopyprivateArrayTy = C.getConstantArrayType(
  3188. C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
  3189. /*IndexTypeQuals=*/0);
  3190. // Create a list of all private variables for copyprivate.
  3191. Address CopyprivateList =
  3192. CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
  3193. for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
  3194. Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I);
  3195. CGF.Builder.CreateStore(
  3196. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  3197. CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
  3198. Elem);
  3199. }
  3200. // Build function that copies private values from single region to all other
  3201. // threads in the corresponding parallel region.
  3202. llvm::Value *CpyFn = emitCopyprivateCopyFunction(
  3203. CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
  3204. CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
  3205. llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
  3206. Address CL =
  3207. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
  3208. CGF.VoidPtrTy);
  3209. llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
  3210. llvm::Value *Args[] = {
  3211. emitUpdateLocation(CGF, Loc), // ident_t *<loc>
  3212. getThreadID(CGF, Loc), // i32 <gtid>
  3213. BufSize, // size_t <buf_size>
  3214. CL.getPointer(), // void *<copyprivate list>
  3215. CpyFn, // void (*) (void *, void *) <copy_func>
  3216. DidItVal // i32 did_it
  3217. };
  3218. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
  3219. }
  3220. }
  3221. void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
  3222. const RegionCodeGenTy &OrderedOpGen,
  3223. SourceLocation Loc, bool IsThreads) {
  3224. if (!CGF.HaveInsertPoint())
  3225. return;
  3226. // __kmpc_ordered(ident_t *, gtid);
  3227. // OrderedOpGen();
  3228. // __kmpc_end_ordered(ident_t *, gtid);
  3229. // Prepare arguments and build a call to __kmpc_ordered
  3230. if (IsThreads) {
  3231. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3232. CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
  3233. createRuntimeFunction(OMPRTL__kmpc_end_ordered),
  3234. Args);
  3235. OrderedOpGen.setAction(Action);
  3236. emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
  3237. return;
  3238. }
  3239. emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
  3240. }
  3241. unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
  3242. unsigned Flags;
  3243. if (Kind == OMPD_for)
  3244. Flags = OMP_IDENT_BARRIER_IMPL_FOR;
  3245. else if (Kind == OMPD_sections)
  3246. Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
  3247. else if (Kind == OMPD_single)
  3248. Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
  3249. else if (Kind == OMPD_barrier)
  3250. Flags = OMP_IDENT_BARRIER_EXPL;
  3251. else
  3252. Flags = OMP_IDENT_BARRIER_IMPL;
  3253. return Flags;
  3254. }
  3255. void CGOpenMPRuntime::getDefaultScheduleAndChunk(
  3256. CodeGenFunction &CGF, const OMPLoopDirective &S,
  3257. OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const {
  3258. // Check if the loop directive is actually a doacross loop directive. In this
  3259. // case choose static, 1 schedule.
  3260. if (llvm::any_of(
  3261. S.getClausesOfKind<OMPOrderedClause>(),
  3262. [](const OMPOrderedClause *C) { return C->getNumForLoops(); })) {
  3263. ScheduleKind = OMPC_SCHEDULE_static;
  3264. // Chunk size is 1 in this case.
  3265. llvm::APInt ChunkSize(32, 1);
  3266. ChunkExpr = IntegerLiteral::Create(
  3267. CGF.getContext(), ChunkSize,
  3268. CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
  3269. SourceLocation());
  3270. }
  3271. }
  3272. void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
  3273. OpenMPDirectiveKind Kind, bool EmitChecks,
  3274. bool ForceSimpleCall) {
  3275. if (!CGF.HaveInsertPoint())
  3276. return;
  3277. // Build call __kmpc_cancel_barrier(loc, thread_id);
  3278. // Build call __kmpc_barrier(loc, thread_id);
  3279. unsigned Flags = getDefaultFlagsForBarriers(Kind);
  3280. // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
  3281. // thread_id);
  3282. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
  3283. getThreadID(CGF, Loc)};
  3284. if (auto *OMPRegionInfo =
  3285. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  3286. if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
  3287. llvm::Value *Result = CGF.EmitRuntimeCall(
  3288. createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
  3289. if (EmitChecks) {
  3290. // if (__kmpc_cancel_barrier()) {
  3291. // exit from construct;
  3292. // }
  3293. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  3294. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  3295. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  3296. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  3297. CGF.EmitBlock(ExitBB);
  3298. // exit from construct;
  3299. CodeGenFunction::JumpDest CancelDestination =
  3300. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  3301. CGF.EmitBranchThroughCleanup(CancelDestination);
  3302. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  3303. }
  3304. return;
  3305. }
  3306. }
  3307. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
  3308. }
  3309. /// Map the OpenMP loop schedule to the runtime enumeration.
  3310. static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
  3311. bool Chunked, bool Ordered) {
  3312. switch (ScheduleKind) {
  3313. case OMPC_SCHEDULE_static:
  3314. return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
  3315. : (Ordered ? OMP_ord_static : OMP_sch_static);
  3316. case OMPC_SCHEDULE_dynamic:
  3317. return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
  3318. case OMPC_SCHEDULE_guided:
  3319. return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
  3320. case OMPC_SCHEDULE_runtime:
  3321. return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
  3322. case OMPC_SCHEDULE_auto:
  3323. return Ordered ? OMP_ord_auto : OMP_sch_auto;
  3324. case OMPC_SCHEDULE_unknown:
  3325. assert(!Chunked && "chunk was specified but schedule kind not known");
  3326. return Ordered ? OMP_ord_static : OMP_sch_static;
  3327. }
  3328. llvm_unreachable("Unexpected runtime schedule");
  3329. }
  3330. /// Map the OpenMP distribute schedule to the runtime enumeration.
  3331. static OpenMPSchedType
  3332. getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
  3333. // only static is allowed for dist_schedule
  3334. return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
  3335. }
  3336. bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
  3337. bool Chunked) const {
  3338. OpenMPSchedType Schedule =
  3339. getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
  3340. return Schedule == OMP_sch_static;
  3341. }
  3342. bool CGOpenMPRuntime::isStaticNonchunked(
  3343. OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
  3344. OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
  3345. return Schedule == OMP_dist_sch_static;
  3346. }
  3347. bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
  3348. bool Chunked) const {
  3349. OpenMPSchedType Schedule =
  3350. getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
  3351. return Schedule == OMP_sch_static_chunked;
  3352. }
  3353. bool CGOpenMPRuntime::isStaticChunked(
  3354. OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
  3355. OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
  3356. return Schedule == OMP_dist_sch_static_chunked;
  3357. }
  3358. bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
  3359. OpenMPSchedType Schedule =
  3360. getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
  3361. assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
  3362. return Schedule != OMP_sch_static;
  3363. }
  3364. static int addMonoNonMonoModifier(CodeGenModule &CGM, OpenMPSchedType Schedule,
  3365. OpenMPScheduleClauseModifier M1,
  3366. OpenMPScheduleClauseModifier M2) {
  3367. int Modifier = 0;
  3368. switch (M1) {
  3369. case OMPC_SCHEDULE_MODIFIER_monotonic:
  3370. Modifier = OMP_sch_modifier_monotonic;
  3371. break;
  3372. case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
  3373. Modifier = OMP_sch_modifier_nonmonotonic;
  3374. break;
  3375. case OMPC_SCHEDULE_MODIFIER_simd:
  3376. if (Schedule == OMP_sch_static_chunked)
  3377. Schedule = OMP_sch_static_balanced_chunked;
  3378. break;
  3379. case OMPC_SCHEDULE_MODIFIER_last:
  3380. case OMPC_SCHEDULE_MODIFIER_unknown:
  3381. break;
  3382. }
  3383. switch (M2) {
  3384. case OMPC_SCHEDULE_MODIFIER_monotonic:
  3385. Modifier = OMP_sch_modifier_monotonic;
  3386. break;
  3387. case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
  3388. Modifier = OMP_sch_modifier_nonmonotonic;
  3389. break;
  3390. case OMPC_SCHEDULE_MODIFIER_simd:
  3391. if (Schedule == OMP_sch_static_chunked)
  3392. Schedule = OMP_sch_static_balanced_chunked;
  3393. break;
  3394. case OMPC_SCHEDULE_MODIFIER_last:
  3395. case OMPC_SCHEDULE_MODIFIER_unknown:
  3396. break;
  3397. }
  3398. // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Desription.
  3399. // If the static schedule kind is specified or if the ordered clause is
  3400. // specified, and if the nonmonotonic modifier is not specified, the effect is
  3401. // as if the monotonic modifier is specified. Otherwise, unless the monotonic
  3402. // modifier is specified, the effect is as if the nonmonotonic modifier is
  3403. // specified.
  3404. if (CGM.getLangOpts().OpenMP >= 50 && Modifier == 0) {
  3405. if (!(Schedule == OMP_sch_static_chunked || Schedule == OMP_sch_static ||
  3406. Schedule == OMP_sch_static_balanced_chunked ||
  3407. Schedule == OMP_ord_static_chunked || Schedule == OMP_ord_static))
  3408. Modifier = OMP_sch_modifier_nonmonotonic;
  3409. }
  3410. return Schedule | Modifier;
  3411. }
  3412. void CGOpenMPRuntime::emitForDispatchInit(
  3413. CodeGenFunction &CGF, SourceLocation Loc,
  3414. const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
  3415. bool Ordered, const DispatchRTInput &DispatchValues) {
  3416. if (!CGF.HaveInsertPoint())
  3417. return;
  3418. OpenMPSchedType Schedule = getRuntimeSchedule(
  3419. ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
  3420. assert(Ordered ||
  3421. (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
  3422. Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
  3423. Schedule != OMP_sch_static_balanced_chunked));
  3424. // Call __kmpc_dispatch_init(
  3425. // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
  3426. // kmp_int[32|64] lower, kmp_int[32|64] upper,
  3427. // kmp_int[32|64] stride, kmp_int[32|64] chunk);
  3428. // If the Chunk was not specified in the clause - use default value 1.
  3429. llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
  3430. : CGF.Builder.getIntN(IVSize, 1);
  3431. llvm::Value *Args[] = {
  3432. emitUpdateLocation(CGF, Loc),
  3433. getThreadID(CGF, Loc),
  3434. CGF.Builder.getInt32(addMonoNonMonoModifier(
  3435. CGM, Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
  3436. DispatchValues.LB, // Lower
  3437. DispatchValues.UB, // Upper
  3438. CGF.Builder.getIntN(IVSize, 1), // Stride
  3439. Chunk // Chunk
  3440. };
  3441. CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
  3442. }
  3443. static void emitForStaticInitCall(
  3444. CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
  3445. llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule,
  3446. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  3447. const CGOpenMPRuntime::StaticRTInput &Values) {
  3448. if (!CGF.HaveInsertPoint())
  3449. return;
  3450. assert(!Values.Ordered);
  3451. assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
  3452. Schedule == OMP_sch_static_balanced_chunked ||
  3453. Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
  3454. Schedule == OMP_dist_sch_static ||
  3455. Schedule == OMP_dist_sch_static_chunked);
  3456. // Call __kmpc_for_static_init(
  3457. // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
  3458. // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
  3459. // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
  3460. // kmp_int[32|64] incr, kmp_int[32|64] chunk);
  3461. llvm::Value *Chunk = Values.Chunk;
  3462. if (Chunk == nullptr) {
  3463. assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
  3464. Schedule == OMP_dist_sch_static) &&
  3465. "expected static non-chunked schedule");
  3466. // If the Chunk was not specified in the clause - use default value 1.
  3467. Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
  3468. } else {
  3469. assert((Schedule == OMP_sch_static_chunked ||
  3470. Schedule == OMP_sch_static_balanced_chunked ||
  3471. Schedule == OMP_ord_static_chunked ||
  3472. Schedule == OMP_dist_sch_static_chunked) &&
  3473. "expected static chunked schedule");
  3474. }
  3475. llvm::Value *Args[] = {
  3476. UpdateLocation,
  3477. ThreadId,
  3478. CGF.Builder.getInt32(addMonoNonMonoModifier(CGF.CGM, Schedule, M1,
  3479. M2)), // Schedule type
  3480. Values.IL.getPointer(), // &isLastIter
  3481. Values.LB.getPointer(), // &LB
  3482. Values.UB.getPointer(), // &UB
  3483. Values.ST.getPointer(), // &Stride
  3484. CGF.Builder.getIntN(Values.IVSize, 1), // Incr
  3485. Chunk // Chunk
  3486. };
  3487. CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
  3488. }
  3489. void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
  3490. SourceLocation Loc,
  3491. OpenMPDirectiveKind DKind,
  3492. const OpenMPScheduleTy &ScheduleKind,
  3493. const StaticRTInput &Values) {
  3494. OpenMPSchedType ScheduleNum = getRuntimeSchedule(
  3495. ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
  3496. assert(isOpenMPWorksharingDirective(DKind) &&
  3497. "Expected loop-based or sections-based directive.");
  3498. llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
  3499. isOpenMPLoopDirective(DKind)
  3500. ? OMP_IDENT_WORK_LOOP
  3501. : OMP_IDENT_WORK_SECTIONS);
  3502. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  3503. llvm::FunctionCallee StaticInitFunction =
  3504. createForStaticInitFunction(Values.IVSize, Values.IVSigned);
  3505. emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
  3506. ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
  3507. }
  3508. void CGOpenMPRuntime::emitDistributeStaticInit(
  3509. CodeGenFunction &CGF, SourceLocation Loc,
  3510. OpenMPDistScheduleClauseKind SchedKind,
  3511. const CGOpenMPRuntime::StaticRTInput &Values) {
  3512. OpenMPSchedType ScheduleNum =
  3513. getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
  3514. llvm::Value *UpdatedLocation =
  3515. emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
  3516. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  3517. llvm::FunctionCallee StaticInitFunction =
  3518. createForStaticInitFunction(Values.IVSize, Values.IVSigned);
  3519. emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
  3520. ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
  3521. OMPC_SCHEDULE_MODIFIER_unknown, Values);
  3522. }
  3523. void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
  3524. SourceLocation Loc,
  3525. OpenMPDirectiveKind DKind) {
  3526. if (!CGF.HaveInsertPoint())
  3527. return;
  3528. // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
  3529. llvm::Value *Args[] = {
  3530. emitUpdateLocation(CGF, Loc,
  3531. isOpenMPDistributeDirective(DKind)
  3532. ? OMP_IDENT_WORK_DISTRIBUTE
  3533. : isOpenMPLoopDirective(DKind)
  3534. ? OMP_IDENT_WORK_LOOP
  3535. : OMP_IDENT_WORK_SECTIONS),
  3536. getThreadID(CGF, Loc)};
  3537. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
  3538. Args);
  3539. }
  3540. void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
  3541. SourceLocation Loc,
  3542. unsigned IVSize,
  3543. bool IVSigned) {
  3544. if (!CGF.HaveInsertPoint())
  3545. return;
  3546. // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
  3547. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  3548. CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
  3549. }
  3550. llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
  3551. SourceLocation Loc, unsigned IVSize,
  3552. bool IVSigned, Address IL,
  3553. Address LB, Address UB,
  3554. Address ST) {
  3555. // Call __kmpc_dispatch_next(
  3556. // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
  3557. // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
  3558. // kmp_int[32|64] *p_stride);
  3559. llvm::Value *Args[] = {
  3560. emitUpdateLocation(CGF, Loc),
  3561. getThreadID(CGF, Loc),
  3562. IL.getPointer(), // &isLastIter
  3563. LB.getPointer(), // &Lower
  3564. UB.getPointer(), // &Upper
  3565. ST.getPointer() // &Stride
  3566. };
  3567. llvm::Value *Call =
  3568. CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
  3569. return CGF.EmitScalarConversion(
  3570. Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
  3571. CGF.getContext().BoolTy, Loc);
  3572. }
  3573. void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
  3574. llvm::Value *NumThreads,
  3575. SourceLocation Loc) {
  3576. if (!CGF.HaveInsertPoint())
  3577. return;
  3578. // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
  3579. llvm::Value *Args[] = {
  3580. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3581. CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
  3582. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
  3583. Args);
  3584. }
  3585. void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
  3586. OpenMPProcBindClauseKind ProcBind,
  3587. SourceLocation Loc) {
  3588. if (!CGF.HaveInsertPoint())
  3589. return;
  3590. // Constants for proc bind value accepted by the runtime.
  3591. enum ProcBindTy {
  3592. ProcBindFalse = 0,
  3593. ProcBindTrue,
  3594. ProcBindMaster,
  3595. ProcBindClose,
  3596. ProcBindSpread,
  3597. ProcBindIntel,
  3598. ProcBindDefault
  3599. } RuntimeProcBind;
  3600. switch (ProcBind) {
  3601. case OMPC_PROC_BIND_master:
  3602. RuntimeProcBind = ProcBindMaster;
  3603. break;
  3604. case OMPC_PROC_BIND_close:
  3605. RuntimeProcBind = ProcBindClose;
  3606. break;
  3607. case OMPC_PROC_BIND_spread:
  3608. RuntimeProcBind = ProcBindSpread;
  3609. break;
  3610. case OMPC_PROC_BIND_unknown:
  3611. llvm_unreachable("Unsupported proc_bind value.");
  3612. }
  3613. // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
  3614. llvm::Value *Args[] = {
  3615. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  3616. llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
  3617. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
  3618. }
  3619. void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
  3620. SourceLocation Loc) {
  3621. if (!CGF.HaveInsertPoint())
  3622. return;
  3623. // Build call void __kmpc_flush(ident_t *loc)
  3624. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
  3625. emitUpdateLocation(CGF, Loc));
  3626. }
  3627. namespace {
  3628. /// Indexes of fields for type kmp_task_t.
  3629. enum KmpTaskTFields {
  3630. /// List of shared variables.
  3631. KmpTaskTShareds,
  3632. /// Task routine.
  3633. KmpTaskTRoutine,
  3634. /// Partition id for the untied tasks.
  3635. KmpTaskTPartId,
  3636. /// Function with call of destructors for private variables.
  3637. Data1,
  3638. /// Task priority.
  3639. Data2,
  3640. /// (Taskloops only) Lower bound.
  3641. KmpTaskTLowerBound,
  3642. /// (Taskloops only) Upper bound.
  3643. KmpTaskTUpperBound,
  3644. /// (Taskloops only) Stride.
  3645. KmpTaskTStride,
  3646. /// (Taskloops only) Is last iteration flag.
  3647. KmpTaskTLastIter,
  3648. /// (Taskloops only) Reduction data.
  3649. KmpTaskTReductions,
  3650. };
  3651. } // anonymous namespace
  3652. bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
  3653. return OffloadEntriesTargetRegion.empty() &&
  3654. OffloadEntriesDeviceGlobalVar.empty();
  3655. }
  3656. /// Initialize target region entry.
  3657. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3658. initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
  3659. StringRef ParentName, unsigned LineNum,
  3660. unsigned Order) {
  3661. assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
  3662. "only required for the device "
  3663. "code generation.");
  3664. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
  3665. OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
  3666. OMPTargetRegionEntryTargetRegion);
  3667. ++OffloadingEntriesNum;
  3668. }
  3669. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3670. registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
  3671. StringRef ParentName, unsigned LineNum,
  3672. llvm::Constant *Addr, llvm::Constant *ID,
  3673. OMPTargetRegionEntryKind Flags) {
  3674. // If we are emitting code for a target, the entry is already initialized,
  3675. // only has to be registered.
  3676. if (CGM.getLangOpts().OpenMPIsDevice) {
  3677. if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
  3678. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3679. DiagnosticsEngine::Error,
  3680. "Unable to find target region on line '%0' in the device code.");
  3681. CGM.getDiags().Report(DiagID) << LineNum;
  3682. return;
  3683. }
  3684. auto &Entry =
  3685. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
  3686. assert(Entry.isValid() && "Entry not initialized!");
  3687. Entry.setAddress(Addr);
  3688. Entry.setID(ID);
  3689. Entry.setFlags(Flags);
  3690. } else {
  3691. OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
  3692. OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
  3693. ++OffloadingEntriesNum;
  3694. }
  3695. }
  3696. bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
  3697. unsigned DeviceID, unsigned FileID, StringRef ParentName,
  3698. unsigned LineNum) const {
  3699. auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
  3700. if (PerDevice == OffloadEntriesTargetRegion.end())
  3701. return false;
  3702. auto PerFile = PerDevice->second.find(FileID);
  3703. if (PerFile == PerDevice->second.end())
  3704. return false;
  3705. auto PerParentName = PerFile->second.find(ParentName);
  3706. if (PerParentName == PerFile->second.end())
  3707. return false;
  3708. auto PerLine = PerParentName->second.find(LineNum);
  3709. if (PerLine == PerParentName->second.end())
  3710. return false;
  3711. // Fail if this entry is already registered.
  3712. if (PerLine->second.getAddress() || PerLine->second.getID())
  3713. return false;
  3714. return true;
  3715. }
  3716. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
  3717. const OffloadTargetRegionEntryInfoActTy &Action) {
  3718. // Scan all target region entries and perform the provided action.
  3719. for (const auto &D : OffloadEntriesTargetRegion)
  3720. for (const auto &F : D.second)
  3721. for (const auto &P : F.second)
  3722. for (const auto &L : P.second)
  3723. Action(D.first, F.first, P.first(), L.first, L.second);
  3724. }
  3725. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3726. initializeDeviceGlobalVarEntryInfo(StringRef Name,
  3727. OMPTargetGlobalVarEntryKind Flags,
  3728. unsigned Order) {
  3729. assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
  3730. "only required for the device "
  3731. "code generation.");
  3732. OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
  3733. ++OffloadingEntriesNum;
  3734. }
  3735. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3736. registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
  3737. CharUnits VarSize,
  3738. OMPTargetGlobalVarEntryKind Flags,
  3739. llvm::GlobalValue::LinkageTypes Linkage) {
  3740. if (CGM.getLangOpts().OpenMPIsDevice) {
  3741. auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
  3742. assert(Entry.isValid() && Entry.getFlags() == Flags &&
  3743. "Entry not initialized!");
  3744. assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
  3745. "Resetting with the new address.");
  3746. if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) {
  3747. if (Entry.getVarSize().isZero()) {
  3748. Entry.setVarSize(VarSize);
  3749. Entry.setLinkage(Linkage);
  3750. }
  3751. return;
  3752. }
  3753. Entry.setVarSize(VarSize);
  3754. Entry.setLinkage(Linkage);
  3755. Entry.setAddress(Addr);
  3756. } else {
  3757. if (hasDeviceGlobalVarEntryInfo(VarName)) {
  3758. auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
  3759. assert(Entry.isValid() && Entry.getFlags() == Flags &&
  3760. "Entry not initialized!");
  3761. assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
  3762. "Resetting with the new address.");
  3763. if (Entry.getVarSize().isZero()) {
  3764. Entry.setVarSize(VarSize);
  3765. Entry.setLinkage(Linkage);
  3766. }
  3767. return;
  3768. }
  3769. OffloadEntriesDeviceGlobalVar.try_emplace(
  3770. VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
  3771. ++OffloadingEntriesNum;
  3772. }
  3773. }
  3774. void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
  3775. actOnDeviceGlobalVarEntriesInfo(
  3776. const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
  3777. // Scan all target region entries and perform the provided action.
  3778. for (const auto &E : OffloadEntriesDeviceGlobalVar)
  3779. Action(E.getKey(), E.getValue());
  3780. }
  3781. void CGOpenMPRuntime::createOffloadEntry(
  3782. llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
  3783. llvm::GlobalValue::LinkageTypes Linkage) {
  3784. StringRef Name = Addr->getName();
  3785. llvm::Module &M = CGM.getModule();
  3786. llvm::LLVMContext &C = M.getContext();
  3787. // Create constant string with the name.
  3788. llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
  3789. std::string StringName = getName({"omp_offloading", "entry_name"});
  3790. auto *Str = new llvm::GlobalVariable(
  3791. M, StrPtrInit->getType(), /*isConstant=*/true,
  3792. llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
  3793. Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3794. llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
  3795. llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
  3796. llvm::ConstantInt::get(CGM.SizeTy, Size),
  3797. llvm::ConstantInt::get(CGM.Int32Ty, Flags),
  3798. llvm::ConstantInt::get(CGM.Int32Ty, 0)};
  3799. std::string EntryName = getName({"omp_offloading", "entry", ""});
  3800. llvm::GlobalVariable *Entry = createGlobalStruct(
  3801. CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
  3802. Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
  3803. // The entry has to be created in the section the linker expects it to be.
  3804. Entry->setSection("omp_offloading_entries");
  3805. }
  3806. void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
  3807. // Emit the offloading entries and metadata so that the device codegen side
  3808. // can easily figure out what to emit. The produced metadata looks like
  3809. // this:
  3810. //
  3811. // !omp_offload.info = !{!1, ...}
  3812. //
  3813. // Right now we only generate metadata for function that contain target
  3814. // regions.
  3815. // If we are in simd mode or there are no entries, we don't need to do
  3816. // anything.
  3817. if (CGM.getLangOpts().OpenMPSimd || OffloadEntriesInfoManager.empty())
  3818. return;
  3819. llvm::Module &M = CGM.getModule();
  3820. llvm::LLVMContext &C = M.getContext();
  3821. SmallVector<std::tuple<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *,
  3822. SourceLocation, StringRef>,
  3823. 16>
  3824. OrderedEntries(OffloadEntriesInfoManager.size());
  3825. llvm::SmallVector<StringRef, 16> ParentFunctions(
  3826. OffloadEntriesInfoManager.size());
  3827. // Auxiliary methods to create metadata values and strings.
  3828. auto &&GetMDInt = [this](unsigned V) {
  3829. return llvm::ConstantAsMetadata::get(
  3830. llvm::ConstantInt::get(CGM.Int32Ty, V));
  3831. };
  3832. auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
  3833. // Create the offloading info metadata node.
  3834. llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
  3835. // Create function that emits metadata for each target region entry;
  3836. auto &&TargetRegionMetadataEmitter =
  3837. [this, &C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt,
  3838. &GetMDString](
  3839. unsigned DeviceID, unsigned FileID, StringRef ParentName,
  3840. unsigned Line,
  3841. const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
  3842. // Generate metadata for target regions. Each entry of this metadata
  3843. // contains:
  3844. // - Entry 0 -> Kind of this type of metadata (0).
  3845. // - Entry 1 -> Device ID of the file where the entry was identified.
  3846. // - Entry 2 -> File ID of the file where the entry was identified.
  3847. // - Entry 3 -> Mangled name of the function where the entry was
  3848. // identified.
  3849. // - Entry 4 -> Line in the file where the entry was identified.
  3850. // - Entry 5 -> Order the entry was created.
  3851. // The first element of the metadata node is the kind.
  3852. llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
  3853. GetMDInt(FileID), GetMDString(ParentName),
  3854. GetMDInt(Line), GetMDInt(E.getOrder())};
  3855. SourceLocation Loc;
  3856. for (auto I = CGM.getContext().getSourceManager().fileinfo_begin(),
  3857. E = CGM.getContext().getSourceManager().fileinfo_end();
  3858. I != E; ++I) {
  3859. if (I->getFirst()->getUniqueID().getDevice() == DeviceID &&
  3860. I->getFirst()->getUniqueID().getFile() == FileID) {
  3861. Loc = CGM.getContext().getSourceManager().translateFileLineCol(
  3862. I->getFirst(), Line, 1);
  3863. break;
  3864. }
  3865. }
  3866. // Save this entry in the right position of the ordered entries array.
  3867. OrderedEntries[E.getOrder()] = std::make_tuple(&E, Loc, ParentName);
  3868. ParentFunctions[E.getOrder()] = ParentName;
  3869. // Add metadata to the named metadata node.
  3870. MD->addOperand(llvm::MDNode::get(C, Ops));
  3871. };
  3872. OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
  3873. TargetRegionMetadataEmitter);
  3874. // Create function that emits metadata for each device global variable entry;
  3875. auto &&DeviceGlobalVarMetadataEmitter =
  3876. [&C, &OrderedEntries, &GetMDInt, &GetMDString,
  3877. MD](StringRef MangledName,
  3878. const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
  3879. &E) {
  3880. // Generate metadata for global variables. Each entry of this metadata
  3881. // contains:
  3882. // - Entry 0 -> Kind of this type of metadata (1).
  3883. // - Entry 1 -> Mangled name of the variable.
  3884. // - Entry 2 -> Declare target kind.
  3885. // - Entry 3 -> Order the entry was created.
  3886. // The first element of the metadata node is the kind.
  3887. llvm::Metadata *Ops[] = {
  3888. GetMDInt(E.getKind()), GetMDString(MangledName),
  3889. GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
  3890. // Save this entry in the right position of the ordered entries array.
  3891. OrderedEntries[E.getOrder()] =
  3892. std::make_tuple(&E, SourceLocation(), MangledName);
  3893. // Add metadata to the named metadata node.
  3894. MD->addOperand(llvm::MDNode::get(C, Ops));
  3895. };
  3896. OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
  3897. DeviceGlobalVarMetadataEmitter);
  3898. for (const auto &E : OrderedEntries) {
  3899. assert(std::get<0>(E) && "All ordered entries must exist!");
  3900. if (const auto *CE =
  3901. dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
  3902. std::get<0>(E))) {
  3903. if (!CE->getID() || !CE->getAddress()) {
  3904. // Do not blame the entry if the parent funtion is not emitted.
  3905. StringRef FnName = ParentFunctions[CE->getOrder()];
  3906. if (!CGM.GetGlobalValue(FnName))
  3907. continue;
  3908. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3909. DiagnosticsEngine::Error,
  3910. "Offloading entry for target region in %0 is incorrect: either the "
  3911. "address or the ID is invalid.");
  3912. CGM.getDiags().Report(std::get<1>(E), DiagID) << FnName;
  3913. continue;
  3914. }
  3915. createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
  3916. CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
  3917. } else if (const auto *CE = dyn_cast<OffloadEntriesInfoManagerTy::
  3918. OffloadEntryInfoDeviceGlobalVar>(
  3919. std::get<0>(E))) {
  3920. OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
  3921. static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
  3922. CE->getFlags());
  3923. switch (Flags) {
  3924. case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
  3925. if (CGM.getLangOpts().OpenMPIsDevice &&
  3926. CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())
  3927. continue;
  3928. if (!CE->getAddress()) {
  3929. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3930. DiagnosticsEngine::Error, "Offloading entry for declare target "
  3931. "variable %0 is incorrect: the "
  3932. "address is invalid.");
  3933. CGM.getDiags().Report(std::get<1>(E), DiagID) << std::get<2>(E);
  3934. continue;
  3935. }
  3936. // The vaiable has no definition - no need to add the entry.
  3937. if (CE->getVarSize().isZero())
  3938. continue;
  3939. break;
  3940. }
  3941. case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
  3942. assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
  3943. (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
  3944. "Declaret target link address is set.");
  3945. if (CGM.getLangOpts().OpenMPIsDevice)
  3946. continue;
  3947. if (!CE->getAddress()) {
  3948. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3949. DiagnosticsEngine::Error,
  3950. "Offloading entry for declare target variable is incorrect: the "
  3951. "address is invalid.");
  3952. CGM.getDiags().Report(DiagID);
  3953. continue;
  3954. }
  3955. break;
  3956. }
  3957. createOffloadEntry(CE->getAddress(), CE->getAddress(),
  3958. CE->getVarSize().getQuantity(), Flags,
  3959. CE->getLinkage());
  3960. } else {
  3961. llvm_unreachable("Unsupported entry kind.");
  3962. }
  3963. }
  3964. }
  3965. /// Loads all the offload entries information from the host IR
  3966. /// metadata.
  3967. void CGOpenMPRuntime::loadOffloadInfoMetadata() {
  3968. // If we are in target mode, load the metadata from the host IR. This code has
  3969. // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
  3970. if (!CGM.getLangOpts().OpenMPIsDevice)
  3971. return;
  3972. if (CGM.getLangOpts().OMPHostIRFile.empty())
  3973. return;
  3974. auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
  3975. if (auto EC = Buf.getError()) {
  3976. CGM.getDiags().Report(diag::err_cannot_open_file)
  3977. << CGM.getLangOpts().OMPHostIRFile << EC.message();
  3978. return;
  3979. }
  3980. llvm::LLVMContext C;
  3981. auto ME = expectedToErrorOrAndEmitErrors(
  3982. C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
  3983. if (auto EC = ME.getError()) {
  3984. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  3985. DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
  3986. CGM.getDiags().Report(DiagID)
  3987. << CGM.getLangOpts().OMPHostIRFile << EC.message();
  3988. return;
  3989. }
  3990. llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
  3991. if (!MD)
  3992. return;
  3993. for (llvm::MDNode *MN : MD->operands()) {
  3994. auto &&GetMDInt = [MN](unsigned Idx) {
  3995. auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
  3996. return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
  3997. };
  3998. auto &&GetMDString = [MN](unsigned Idx) {
  3999. auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
  4000. return V->getString();
  4001. };
  4002. switch (GetMDInt(0)) {
  4003. default:
  4004. llvm_unreachable("Unexpected metadata!");
  4005. break;
  4006. case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
  4007. OffloadingEntryInfoTargetRegion:
  4008. OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
  4009. /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
  4010. /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
  4011. /*Order=*/GetMDInt(5));
  4012. break;
  4013. case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
  4014. OffloadingEntryInfoDeviceGlobalVar:
  4015. OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
  4016. /*MangledName=*/GetMDString(1),
  4017. static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
  4018. /*Flags=*/GetMDInt(2)),
  4019. /*Order=*/GetMDInt(3));
  4020. break;
  4021. }
  4022. }
  4023. }
  4024. void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
  4025. if (!KmpRoutineEntryPtrTy) {
  4026. // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
  4027. ASTContext &C = CGM.getContext();
  4028. QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
  4029. FunctionProtoType::ExtProtoInfo EPI;
  4030. KmpRoutineEntryPtrQTy = C.getPointerType(
  4031. C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
  4032. KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
  4033. }
  4034. }
  4035. QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
  4036. // Make sure the type of the entry is already created. This is the type we
  4037. // have to create:
  4038. // struct __tgt_offload_entry{
  4039. // void *addr; // Pointer to the offload entry info.
  4040. // // (function or global)
  4041. // char *name; // Name of the function or global.
  4042. // size_t size; // Size of the entry info (0 if it a function).
  4043. // int32_t flags; // Flags associated with the entry, e.g. 'link'.
  4044. // int32_t reserved; // Reserved, to use by the runtime library.
  4045. // };
  4046. if (TgtOffloadEntryQTy.isNull()) {
  4047. ASTContext &C = CGM.getContext();
  4048. RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
  4049. RD->startDefinition();
  4050. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4051. addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
  4052. addFieldToRecordDecl(C, RD, C.getSizeType());
  4053. addFieldToRecordDecl(
  4054. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  4055. addFieldToRecordDecl(
  4056. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  4057. RD->completeDefinition();
  4058. RD->addAttr(PackedAttr::CreateImplicit(C));
  4059. TgtOffloadEntryQTy = C.getRecordType(RD);
  4060. }
  4061. return TgtOffloadEntryQTy;
  4062. }
  4063. QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
  4064. // These are the types we need to build:
  4065. // struct __tgt_device_image{
  4066. // void *ImageStart; // Pointer to the target code start.
  4067. // void *ImageEnd; // Pointer to the target code end.
  4068. // // We also add the host entries to the device image, as it may be useful
  4069. // // for the target runtime to have access to that information.
  4070. // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
  4071. // // the entries.
  4072. // __tgt_offload_entry *EntriesEnd; // End of the table with all the
  4073. // // entries (non inclusive).
  4074. // };
  4075. if (TgtDeviceImageQTy.isNull()) {
  4076. ASTContext &C = CGM.getContext();
  4077. RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
  4078. RD->startDefinition();
  4079. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4080. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4081. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  4082. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  4083. RD->completeDefinition();
  4084. TgtDeviceImageQTy = C.getRecordType(RD);
  4085. }
  4086. return TgtDeviceImageQTy;
  4087. }
  4088. QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
  4089. // struct __tgt_bin_desc{
  4090. // int32_t NumDevices; // Number of devices supported.
  4091. // __tgt_device_image *DeviceImages; // Arrays of device images
  4092. // // (one per device).
  4093. // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
  4094. // // entries.
  4095. // __tgt_offload_entry *EntriesEnd; // End of the table with all the
  4096. // // entries (non inclusive).
  4097. // };
  4098. if (TgtBinaryDescriptorQTy.isNull()) {
  4099. ASTContext &C = CGM.getContext();
  4100. RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
  4101. RD->startDefinition();
  4102. addFieldToRecordDecl(
  4103. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
  4104. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
  4105. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  4106. addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
  4107. RD->completeDefinition();
  4108. TgtBinaryDescriptorQTy = C.getRecordType(RD);
  4109. }
  4110. return TgtBinaryDescriptorQTy;
  4111. }
  4112. namespace {
  4113. struct PrivateHelpersTy {
  4114. PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
  4115. const VarDecl *PrivateElemInit)
  4116. : Original(Original), PrivateCopy(PrivateCopy),
  4117. PrivateElemInit(PrivateElemInit) {}
  4118. const VarDecl *Original;
  4119. const VarDecl *PrivateCopy;
  4120. const VarDecl *PrivateElemInit;
  4121. };
  4122. typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
  4123. } // anonymous namespace
  4124. static RecordDecl *
  4125. createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
  4126. if (!Privates.empty()) {
  4127. ASTContext &C = CGM.getContext();
  4128. // Build struct .kmp_privates_t. {
  4129. // /* private vars */
  4130. // };
  4131. RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
  4132. RD->startDefinition();
  4133. for (const auto &Pair : Privates) {
  4134. const VarDecl *VD = Pair.second.Original;
  4135. QualType Type = VD->getType().getNonReferenceType();
  4136. FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
  4137. if (VD->hasAttrs()) {
  4138. for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
  4139. E(VD->getAttrs().end());
  4140. I != E; ++I)
  4141. FD->addAttr(*I);
  4142. }
  4143. }
  4144. RD->completeDefinition();
  4145. return RD;
  4146. }
  4147. return nullptr;
  4148. }
  4149. static RecordDecl *
  4150. createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
  4151. QualType KmpInt32Ty,
  4152. QualType KmpRoutineEntryPointerQTy) {
  4153. ASTContext &C = CGM.getContext();
  4154. // Build struct kmp_task_t {
  4155. // void * shareds;
  4156. // kmp_routine_entry_t routine;
  4157. // kmp_int32 part_id;
  4158. // kmp_cmplrdata_t data1;
  4159. // kmp_cmplrdata_t data2;
  4160. // For taskloops additional fields:
  4161. // kmp_uint64 lb;
  4162. // kmp_uint64 ub;
  4163. // kmp_int64 st;
  4164. // kmp_int32 liter;
  4165. // void * reductions;
  4166. // };
  4167. RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
  4168. UD->startDefinition();
  4169. addFieldToRecordDecl(C, UD, KmpInt32Ty);
  4170. addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
  4171. UD->completeDefinition();
  4172. QualType KmpCmplrdataTy = C.getRecordType(UD);
  4173. RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
  4174. RD->startDefinition();
  4175. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4176. addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
  4177. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  4178. addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
  4179. addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
  4180. if (isOpenMPTaskLoopDirective(Kind)) {
  4181. QualType KmpUInt64Ty =
  4182. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  4183. QualType KmpInt64Ty =
  4184. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  4185. addFieldToRecordDecl(C, RD, KmpUInt64Ty);
  4186. addFieldToRecordDecl(C, RD, KmpUInt64Ty);
  4187. addFieldToRecordDecl(C, RD, KmpInt64Ty);
  4188. addFieldToRecordDecl(C, RD, KmpInt32Ty);
  4189. addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  4190. }
  4191. RD->completeDefinition();
  4192. return RD;
  4193. }
  4194. static RecordDecl *
  4195. createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
  4196. ArrayRef<PrivateDataTy> Privates) {
  4197. ASTContext &C = CGM.getContext();
  4198. // Build struct kmp_task_t_with_privates {
  4199. // kmp_task_t task_data;
  4200. // .kmp_privates_t. privates;
  4201. // };
  4202. RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
  4203. RD->startDefinition();
  4204. addFieldToRecordDecl(C, RD, KmpTaskTQTy);
  4205. if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
  4206. addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
  4207. RD->completeDefinition();
  4208. return RD;
  4209. }
  4210. /// Emit a proxy function which accepts kmp_task_t as the second
  4211. /// argument.
  4212. /// \code
  4213. /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
  4214. /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
  4215. /// For taskloops:
  4216. /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
  4217. /// tt->reductions, tt->shareds);
  4218. /// return 0;
  4219. /// }
  4220. /// \endcode
  4221. static llvm::Function *
  4222. emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
  4223. OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
  4224. QualType KmpTaskTWithPrivatesPtrQTy,
  4225. QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
  4226. QualType SharedsPtrTy, llvm::Function *TaskFunction,
  4227. llvm::Value *TaskPrivatesMap) {
  4228. ASTContext &C = CGM.getContext();
  4229. FunctionArgList Args;
  4230. ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
  4231. ImplicitParamDecl::Other);
  4232. ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4233. KmpTaskTWithPrivatesPtrQTy.withRestrict(),
  4234. ImplicitParamDecl::Other);
  4235. Args.push_back(&GtidArg);
  4236. Args.push_back(&TaskTypeArg);
  4237. const auto &TaskEntryFnInfo =
  4238. CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
  4239. llvm::FunctionType *TaskEntryTy =
  4240. CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
  4241. std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
  4242. auto *TaskEntry = llvm::Function::Create(
  4243. TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
  4244. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
  4245. TaskEntry->setDoesNotRecurse();
  4246. CodeGenFunction CGF(CGM);
  4247. CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
  4248. Loc, Loc);
  4249. // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
  4250. // tt,
  4251. // For taskloops:
  4252. // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
  4253. // tt->task_data.shareds);
  4254. llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
  4255. CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
  4256. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4257. CGF.GetAddrOfLocalVar(&TaskTypeArg),
  4258. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4259. const auto *KmpTaskTWithPrivatesQTyRD =
  4260. cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
  4261. LValue Base =
  4262. CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4263. const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
  4264. auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
  4265. LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
  4266. llvm::Value *PartidParam = PartIdLVal.getPointer();
  4267. auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
  4268. LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
  4269. llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4270. CGF.EmitLoadOfScalar(SharedsLVal, Loc),
  4271. CGF.ConvertTypeForMem(SharedsPtrTy));
  4272. auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
  4273. llvm::Value *PrivatesParam;
  4274. if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
  4275. LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
  4276. PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4277. PrivatesLVal.getPointer(), CGF.VoidPtrTy);
  4278. } else {
  4279. PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  4280. }
  4281. llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
  4282. TaskPrivatesMap,
  4283. CGF.Builder
  4284. .CreatePointerBitCastOrAddrSpaceCast(
  4285. TDBase.getAddress(), CGF.VoidPtrTy)
  4286. .getPointer()};
  4287. SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
  4288. std::end(CommonArgs));
  4289. if (isOpenMPTaskLoopDirective(Kind)) {
  4290. auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
  4291. LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
  4292. llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
  4293. auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
  4294. LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
  4295. llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
  4296. auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
  4297. LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
  4298. llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
  4299. auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
  4300. LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
  4301. llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
  4302. auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
  4303. LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
  4304. llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
  4305. CallArgs.push_back(LBParam);
  4306. CallArgs.push_back(UBParam);
  4307. CallArgs.push_back(StParam);
  4308. CallArgs.push_back(LIParam);
  4309. CallArgs.push_back(RParam);
  4310. }
  4311. CallArgs.push_back(SharedsParam);
  4312. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
  4313. CallArgs);
  4314. CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
  4315. CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
  4316. CGF.FinishFunction();
  4317. return TaskEntry;
  4318. }
  4319. static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
  4320. SourceLocation Loc,
  4321. QualType KmpInt32Ty,
  4322. QualType KmpTaskTWithPrivatesPtrQTy,
  4323. QualType KmpTaskTWithPrivatesQTy) {
  4324. ASTContext &C = CGM.getContext();
  4325. FunctionArgList Args;
  4326. ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
  4327. ImplicitParamDecl::Other);
  4328. ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4329. KmpTaskTWithPrivatesPtrQTy.withRestrict(),
  4330. ImplicitParamDecl::Other);
  4331. Args.push_back(&GtidArg);
  4332. Args.push_back(&TaskTypeArg);
  4333. const auto &DestructorFnInfo =
  4334. CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
  4335. llvm::FunctionType *DestructorFnTy =
  4336. CGM.getTypes().GetFunctionType(DestructorFnInfo);
  4337. std::string Name =
  4338. CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
  4339. auto *DestructorFn =
  4340. llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
  4341. Name, &CGM.getModule());
  4342. CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
  4343. DestructorFnInfo);
  4344. DestructorFn->setDoesNotRecurse();
  4345. CodeGenFunction CGF(CGM);
  4346. CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
  4347. Args, Loc, Loc);
  4348. LValue Base = CGF.EmitLoadOfPointerLValue(
  4349. CGF.GetAddrOfLocalVar(&TaskTypeArg),
  4350. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4351. const auto *KmpTaskTWithPrivatesQTyRD =
  4352. cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
  4353. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4354. Base = CGF.EmitLValueForField(Base, *FI);
  4355. for (const auto *Field :
  4356. cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
  4357. if (QualType::DestructionKind DtorKind =
  4358. Field->getType().isDestructedType()) {
  4359. LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
  4360. CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
  4361. }
  4362. }
  4363. CGF.FinishFunction();
  4364. return DestructorFn;
  4365. }
  4366. /// Emit a privates mapping function for correct handling of private and
  4367. /// firstprivate variables.
  4368. /// \code
  4369. /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
  4370. /// **noalias priv1,..., <tyn> **noalias privn) {
  4371. /// *priv1 = &.privates.priv1;
  4372. /// ...;
  4373. /// *privn = &.privates.privn;
  4374. /// }
  4375. /// \endcode
  4376. static llvm::Value *
  4377. emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
  4378. ArrayRef<const Expr *> PrivateVars,
  4379. ArrayRef<const Expr *> FirstprivateVars,
  4380. ArrayRef<const Expr *> LastprivateVars,
  4381. QualType PrivatesQTy,
  4382. ArrayRef<PrivateDataTy> Privates) {
  4383. ASTContext &C = CGM.getContext();
  4384. FunctionArgList Args;
  4385. ImplicitParamDecl TaskPrivatesArg(
  4386. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4387. C.getPointerType(PrivatesQTy).withConst().withRestrict(),
  4388. ImplicitParamDecl::Other);
  4389. Args.push_back(&TaskPrivatesArg);
  4390. llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
  4391. unsigned Counter = 1;
  4392. for (const Expr *E : PrivateVars) {
  4393. Args.push_back(ImplicitParamDecl::Create(
  4394. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4395. C.getPointerType(C.getPointerType(E->getType()))
  4396. .withConst()
  4397. .withRestrict(),
  4398. ImplicitParamDecl::Other));
  4399. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4400. PrivateVarsPos[VD] = Counter;
  4401. ++Counter;
  4402. }
  4403. for (const Expr *E : FirstprivateVars) {
  4404. Args.push_back(ImplicitParamDecl::Create(
  4405. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4406. C.getPointerType(C.getPointerType(E->getType()))
  4407. .withConst()
  4408. .withRestrict(),
  4409. ImplicitParamDecl::Other));
  4410. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4411. PrivateVarsPos[VD] = Counter;
  4412. ++Counter;
  4413. }
  4414. for (const Expr *E : LastprivateVars) {
  4415. Args.push_back(ImplicitParamDecl::Create(
  4416. C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4417. C.getPointerType(C.getPointerType(E->getType()))
  4418. .withConst()
  4419. .withRestrict(),
  4420. ImplicitParamDecl::Other));
  4421. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4422. PrivateVarsPos[VD] = Counter;
  4423. ++Counter;
  4424. }
  4425. const auto &TaskPrivatesMapFnInfo =
  4426. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  4427. llvm::FunctionType *TaskPrivatesMapTy =
  4428. CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
  4429. std::string Name =
  4430. CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
  4431. auto *TaskPrivatesMap = llvm::Function::Create(
  4432. TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
  4433. &CGM.getModule());
  4434. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
  4435. TaskPrivatesMapFnInfo);
  4436. if (CGM.getLangOpts().Optimize) {
  4437. TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
  4438. TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
  4439. TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
  4440. }
  4441. CodeGenFunction CGF(CGM);
  4442. CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
  4443. TaskPrivatesMapFnInfo, Args, Loc, Loc);
  4444. // *privi = &.privates.privi;
  4445. LValue Base = CGF.EmitLoadOfPointerLValue(
  4446. CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
  4447. TaskPrivatesArg.getType()->castAs<PointerType>());
  4448. const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
  4449. Counter = 0;
  4450. for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
  4451. LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
  4452. const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
  4453. LValue RefLVal =
  4454. CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
  4455. LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
  4456. RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
  4457. CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
  4458. ++Counter;
  4459. }
  4460. CGF.FinishFunction();
  4461. return TaskPrivatesMap;
  4462. }
  4463. /// Emit initialization for private variables in task-based directives.
  4464. static void emitPrivatesInit(CodeGenFunction &CGF,
  4465. const OMPExecutableDirective &D,
  4466. Address KmpTaskSharedsPtr, LValue TDBase,
  4467. const RecordDecl *KmpTaskTWithPrivatesQTyRD,
  4468. QualType SharedsTy, QualType SharedsPtrTy,
  4469. const OMPTaskDataTy &Data,
  4470. ArrayRef<PrivateDataTy> Privates, bool ForDup) {
  4471. ASTContext &C = CGF.getContext();
  4472. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4473. LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
  4474. OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
  4475. ? OMPD_taskloop
  4476. : OMPD_task;
  4477. const CapturedStmt &CS = *D.getCapturedStmt(Kind);
  4478. CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
  4479. LValue SrcBase;
  4480. bool IsTargetTask =
  4481. isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
  4482. isOpenMPTargetExecutionDirective(D.getDirectiveKind());
  4483. // For target-based directives skip 3 firstprivate arrays BasePointersArray,
  4484. // PointersArray and SizesArray. The original variables for these arrays are
  4485. // not captured and we get their addresses explicitly.
  4486. if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
  4487. (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
  4488. SrcBase = CGF.MakeAddrLValue(
  4489. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4490. KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
  4491. SharedsTy);
  4492. }
  4493. FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
  4494. for (const PrivateDataTy &Pair : Privates) {
  4495. const VarDecl *VD = Pair.second.PrivateCopy;
  4496. const Expr *Init = VD->getAnyInitializer();
  4497. if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
  4498. !CGF.isTrivialInitializer(Init)))) {
  4499. LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
  4500. if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
  4501. const VarDecl *OriginalVD = Pair.second.Original;
  4502. // Check if the variable is the target-based BasePointersArray,
  4503. // PointersArray or SizesArray.
  4504. LValue SharedRefLValue;
  4505. QualType Type = PrivateLValue.getType();
  4506. const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
  4507. if (IsTargetTask && !SharedField) {
  4508. assert(isa<ImplicitParamDecl>(OriginalVD) &&
  4509. isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
  4510. cast<CapturedDecl>(OriginalVD->getDeclContext())
  4511. ->getNumParams() == 0 &&
  4512. isa<TranslationUnitDecl>(
  4513. cast<CapturedDecl>(OriginalVD->getDeclContext())
  4514. ->getDeclContext()) &&
  4515. "Expected artificial target data variable.");
  4516. SharedRefLValue =
  4517. CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
  4518. } else {
  4519. SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
  4520. SharedRefLValue = CGF.MakeAddrLValue(
  4521. Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
  4522. SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
  4523. SharedRefLValue.getTBAAInfo());
  4524. }
  4525. if (Type->isArrayType()) {
  4526. // Initialize firstprivate array.
  4527. if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
  4528. // Perform simple memcpy.
  4529. CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
  4530. } else {
  4531. // Initialize firstprivate array using element-by-element
  4532. // initialization.
  4533. CGF.EmitOMPAggregateAssign(
  4534. PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
  4535. [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
  4536. Address SrcElement) {
  4537. // Clean up any temporaries needed by the initialization.
  4538. CodeGenFunction::OMPPrivateScope InitScope(CGF);
  4539. InitScope.addPrivate(
  4540. Elem, [SrcElement]() -> Address { return SrcElement; });
  4541. (void)InitScope.Privatize();
  4542. // Emit initialization for single element.
  4543. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
  4544. CGF, &CapturesInfo);
  4545. CGF.EmitAnyExprToMem(Init, DestElement,
  4546. Init->getType().getQualifiers(),
  4547. /*IsInitializer=*/false);
  4548. });
  4549. }
  4550. } else {
  4551. CodeGenFunction::OMPPrivateScope InitScope(CGF);
  4552. InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
  4553. return SharedRefLValue.getAddress();
  4554. });
  4555. (void)InitScope.Privatize();
  4556. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
  4557. CGF.EmitExprAsInit(Init, VD, PrivateLValue,
  4558. /*capturedByInit=*/false);
  4559. }
  4560. } else {
  4561. CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
  4562. }
  4563. }
  4564. ++FI;
  4565. }
  4566. }
  4567. /// Check if duplication function is required for taskloops.
  4568. static bool checkInitIsRequired(CodeGenFunction &CGF,
  4569. ArrayRef<PrivateDataTy> Privates) {
  4570. bool InitRequired = false;
  4571. for (const PrivateDataTy &Pair : Privates) {
  4572. const VarDecl *VD = Pair.second.PrivateCopy;
  4573. const Expr *Init = VD->getAnyInitializer();
  4574. InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
  4575. !CGF.isTrivialInitializer(Init));
  4576. if (InitRequired)
  4577. break;
  4578. }
  4579. return InitRequired;
  4580. }
  4581. /// Emit task_dup function (for initialization of
  4582. /// private/firstprivate/lastprivate vars and last_iter flag)
  4583. /// \code
  4584. /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
  4585. /// lastpriv) {
  4586. /// // setup lastprivate flag
  4587. /// task_dst->last = lastpriv;
  4588. /// // could be constructor calls here...
  4589. /// }
  4590. /// \endcode
  4591. static llvm::Value *
  4592. emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
  4593. const OMPExecutableDirective &D,
  4594. QualType KmpTaskTWithPrivatesPtrQTy,
  4595. const RecordDecl *KmpTaskTWithPrivatesQTyRD,
  4596. const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
  4597. QualType SharedsPtrTy, const OMPTaskDataTy &Data,
  4598. ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
  4599. ASTContext &C = CGM.getContext();
  4600. FunctionArgList Args;
  4601. ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4602. KmpTaskTWithPrivatesPtrQTy,
  4603. ImplicitParamDecl::Other);
  4604. ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  4605. KmpTaskTWithPrivatesPtrQTy,
  4606. ImplicitParamDecl::Other);
  4607. ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  4608. ImplicitParamDecl::Other);
  4609. Args.push_back(&DstArg);
  4610. Args.push_back(&SrcArg);
  4611. Args.push_back(&LastprivArg);
  4612. const auto &TaskDupFnInfo =
  4613. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  4614. llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
  4615. std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
  4616. auto *TaskDup = llvm::Function::Create(
  4617. TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
  4618. CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
  4619. TaskDup->setDoesNotRecurse();
  4620. CodeGenFunction CGF(CGM);
  4621. CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
  4622. Loc);
  4623. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4624. CGF.GetAddrOfLocalVar(&DstArg),
  4625. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4626. // task_dst->liter = lastpriv;
  4627. if (WithLastIter) {
  4628. auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
  4629. LValue Base = CGF.EmitLValueForField(
  4630. TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4631. LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
  4632. llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
  4633. CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
  4634. CGF.EmitStoreOfScalar(Lastpriv, LILVal);
  4635. }
  4636. // Emit initial values for private copies (if any).
  4637. assert(!Privates.empty());
  4638. Address KmpTaskSharedsPtr = Address::invalid();
  4639. if (!Data.FirstprivateVars.empty()) {
  4640. LValue TDBase = CGF.EmitLoadOfPointerLValue(
  4641. CGF.GetAddrOfLocalVar(&SrcArg),
  4642. KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
  4643. LValue Base = CGF.EmitLValueForField(
  4644. TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4645. KmpTaskSharedsPtr = Address(
  4646. CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
  4647. Base, *std::next(KmpTaskTQTyRD->field_begin(),
  4648. KmpTaskTShareds)),
  4649. Loc),
  4650. CGF.getNaturalTypeAlignment(SharedsTy));
  4651. }
  4652. emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
  4653. SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
  4654. CGF.FinishFunction();
  4655. return TaskDup;
  4656. }
  4657. /// Checks if destructor function is required to be generated.
  4658. /// \return true if cleanups are required, false otherwise.
  4659. static bool
  4660. checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
  4661. bool NeedsCleanup = false;
  4662. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
  4663. const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
  4664. for (const FieldDecl *FD : PrivateRD->fields()) {
  4665. NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
  4666. if (NeedsCleanup)
  4667. break;
  4668. }
  4669. return NeedsCleanup;
  4670. }
  4671. CGOpenMPRuntime::TaskResultTy
  4672. CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
  4673. const OMPExecutableDirective &D,
  4674. llvm::Function *TaskFunction, QualType SharedsTy,
  4675. Address Shareds, const OMPTaskDataTy &Data) {
  4676. ASTContext &C = CGM.getContext();
  4677. llvm::SmallVector<PrivateDataTy, 4> Privates;
  4678. // Aggregate privates and sort them by the alignment.
  4679. auto I = Data.PrivateCopies.begin();
  4680. for (const Expr *E : Data.PrivateVars) {
  4681. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4682. Privates.emplace_back(
  4683. C.getDeclAlign(VD),
  4684. PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4685. /*PrivateElemInit=*/nullptr));
  4686. ++I;
  4687. }
  4688. I = Data.FirstprivateCopies.begin();
  4689. auto IElemInitRef = Data.FirstprivateInits.begin();
  4690. for (const Expr *E : Data.FirstprivateVars) {
  4691. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4692. Privates.emplace_back(
  4693. C.getDeclAlign(VD),
  4694. PrivateHelpersTy(
  4695. VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4696. cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
  4697. ++I;
  4698. ++IElemInitRef;
  4699. }
  4700. I = Data.LastprivateCopies.begin();
  4701. for (const Expr *E : Data.LastprivateVars) {
  4702. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  4703. Privates.emplace_back(
  4704. C.getDeclAlign(VD),
  4705. PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
  4706. /*PrivateElemInit=*/nullptr));
  4707. ++I;
  4708. }
  4709. llvm::stable_sort(Privates, [](PrivateDataTy L, PrivateDataTy R) {
  4710. return L.first > R.first;
  4711. });
  4712. QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  4713. // Build type kmp_routine_entry_t (if not built yet).
  4714. emitKmpRoutineEntryT(KmpInt32Ty);
  4715. // Build type kmp_task_t (if not built yet).
  4716. if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
  4717. if (SavedKmpTaskloopTQTy.isNull()) {
  4718. SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
  4719. CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
  4720. }
  4721. KmpTaskTQTy = SavedKmpTaskloopTQTy;
  4722. } else {
  4723. assert((D.getDirectiveKind() == OMPD_task ||
  4724. isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
  4725. isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
  4726. "Expected taskloop, task or target directive");
  4727. if (SavedKmpTaskTQTy.isNull()) {
  4728. SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
  4729. CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
  4730. }
  4731. KmpTaskTQTy = SavedKmpTaskTQTy;
  4732. }
  4733. const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
  4734. // Build particular struct kmp_task_t for the given task.
  4735. const RecordDecl *KmpTaskTWithPrivatesQTyRD =
  4736. createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
  4737. QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
  4738. QualType KmpTaskTWithPrivatesPtrQTy =
  4739. C.getPointerType(KmpTaskTWithPrivatesQTy);
  4740. llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
  4741. llvm::Type *KmpTaskTWithPrivatesPtrTy =
  4742. KmpTaskTWithPrivatesTy->getPointerTo();
  4743. llvm::Value *KmpTaskTWithPrivatesTySize =
  4744. CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
  4745. QualType SharedsPtrTy = C.getPointerType(SharedsTy);
  4746. // Emit initial values for private copies (if any).
  4747. llvm::Value *TaskPrivatesMap = nullptr;
  4748. llvm::Type *TaskPrivatesMapTy =
  4749. std::next(TaskFunction->arg_begin(), 3)->getType();
  4750. if (!Privates.empty()) {
  4751. auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
  4752. TaskPrivatesMap = emitTaskPrivateMappingFunction(
  4753. CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
  4754. FI->getType(), Privates);
  4755. TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4756. TaskPrivatesMap, TaskPrivatesMapTy);
  4757. } else {
  4758. TaskPrivatesMap = llvm::ConstantPointerNull::get(
  4759. cast<llvm::PointerType>(TaskPrivatesMapTy));
  4760. }
  4761. // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
  4762. // kmp_task_t *tt);
  4763. llvm::Function *TaskEntry = emitProxyTaskFunction(
  4764. CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
  4765. KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
  4766. TaskPrivatesMap);
  4767. // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
  4768. // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
  4769. // kmp_routine_entry_t *task_entry);
  4770. // Task flags. Format is taken from
  4771. // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h,
  4772. // description of kmp_tasking_flags struct.
  4773. enum {
  4774. TiedFlag = 0x1,
  4775. FinalFlag = 0x2,
  4776. DestructorsFlag = 0x8,
  4777. PriorityFlag = 0x20
  4778. };
  4779. unsigned Flags = Data.Tied ? TiedFlag : 0;
  4780. bool NeedsCleanup = false;
  4781. if (!Privates.empty()) {
  4782. NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
  4783. if (NeedsCleanup)
  4784. Flags = Flags | DestructorsFlag;
  4785. }
  4786. if (Data.Priority.getInt())
  4787. Flags = Flags | PriorityFlag;
  4788. llvm::Value *TaskFlags =
  4789. Data.Final.getPointer()
  4790. ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
  4791. CGF.Builder.getInt32(FinalFlag),
  4792. CGF.Builder.getInt32(/*C=*/0))
  4793. : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
  4794. TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
  4795. llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
  4796. SmallVector<llvm::Value *, 8> AllocArgs = {emitUpdateLocation(CGF, Loc),
  4797. getThreadID(CGF, Loc), TaskFlags, KmpTaskTWithPrivatesTySize,
  4798. SharedsSize, CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4799. TaskEntry, KmpRoutineEntryPtrTy)};
  4800. llvm::Value *NewTask;
  4801. if (D.hasClausesOfKind<OMPNowaitClause>()) {
  4802. // Check if we have any device clause associated with the directive.
  4803. const Expr *Device = nullptr;
  4804. if (auto *C = D.getSingleClause<OMPDeviceClause>())
  4805. Device = C->getDevice();
  4806. // Emit device ID if any otherwise use default value.
  4807. llvm::Value *DeviceID;
  4808. if (Device)
  4809. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  4810. CGF.Int64Ty, /*isSigned=*/true);
  4811. else
  4812. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  4813. AllocArgs.push_back(DeviceID);
  4814. NewTask = CGF.EmitRuntimeCall(
  4815. createRuntimeFunction(OMPRTL__kmpc_omp_target_task_alloc), AllocArgs);
  4816. } else {
  4817. NewTask = CGF.EmitRuntimeCall(
  4818. createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
  4819. }
  4820. llvm::Value *NewTaskNewTaskTTy =
  4821. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4822. NewTask, KmpTaskTWithPrivatesPtrTy);
  4823. LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
  4824. KmpTaskTWithPrivatesQTy);
  4825. LValue TDBase =
  4826. CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
  4827. // Fill the data in the resulting kmp_task_t record.
  4828. // Copy shareds if there are any.
  4829. Address KmpTaskSharedsPtr = Address::invalid();
  4830. if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
  4831. KmpTaskSharedsPtr =
  4832. Address(CGF.EmitLoadOfScalar(
  4833. CGF.EmitLValueForField(
  4834. TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
  4835. KmpTaskTShareds)),
  4836. Loc),
  4837. CGF.getNaturalTypeAlignment(SharedsTy));
  4838. LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
  4839. LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
  4840. CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
  4841. }
  4842. // Emit initial values for private copies (if any).
  4843. TaskResultTy Result;
  4844. if (!Privates.empty()) {
  4845. emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
  4846. SharedsTy, SharedsPtrTy, Data, Privates,
  4847. /*ForDup=*/false);
  4848. if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
  4849. (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
  4850. Result.TaskDupFn = emitTaskDupFunction(
  4851. CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
  4852. KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
  4853. /*WithLastIter=*/!Data.LastprivateVars.empty());
  4854. }
  4855. }
  4856. // Fields of union "kmp_cmplrdata_t" for destructors and priority.
  4857. enum { Priority = 0, Destructors = 1 };
  4858. // Provide pointer to function with destructors for privates.
  4859. auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
  4860. const RecordDecl *KmpCmplrdataUD =
  4861. (*FI)->getType()->getAsUnionType()->getDecl();
  4862. if (NeedsCleanup) {
  4863. llvm::Value *DestructorFn = emitDestructorsFunction(
  4864. CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
  4865. KmpTaskTWithPrivatesQTy);
  4866. LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
  4867. LValue DestructorsLV = CGF.EmitLValueForField(
  4868. Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
  4869. CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4870. DestructorFn, KmpRoutineEntryPtrTy),
  4871. DestructorsLV);
  4872. }
  4873. // Set priority.
  4874. if (Data.Priority.getInt()) {
  4875. LValue Data2LV = CGF.EmitLValueForField(
  4876. TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
  4877. LValue PriorityLV = CGF.EmitLValueForField(
  4878. Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
  4879. CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
  4880. }
  4881. Result.NewTask = NewTask;
  4882. Result.TaskEntry = TaskEntry;
  4883. Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
  4884. Result.TDBase = TDBase;
  4885. Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
  4886. return Result;
  4887. }
  4888. void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
  4889. const OMPExecutableDirective &D,
  4890. llvm::Function *TaskFunction,
  4891. QualType SharedsTy, Address Shareds,
  4892. const Expr *IfCond,
  4893. const OMPTaskDataTy &Data) {
  4894. if (!CGF.HaveInsertPoint())
  4895. return;
  4896. TaskResultTy Result =
  4897. emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
  4898. llvm::Value *NewTask = Result.NewTask;
  4899. llvm::Function *TaskEntry = Result.TaskEntry;
  4900. llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
  4901. LValue TDBase = Result.TDBase;
  4902. const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
  4903. ASTContext &C = CGM.getContext();
  4904. // Process list of dependences.
  4905. Address DependenciesArray = Address::invalid();
  4906. unsigned NumDependencies = Data.Dependences.size();
  4907. if (NumDependencies) {
  4908. // Dependence kind for RTL.
  4909. enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3, DepMutexInOutSet = 0x4 };
  4910. enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
  4911. RecordDecl *KmpDependInfoRD;
  4912. QualType FlagsTy =
  4913. C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
  4914. llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
  4915. if (KmpDependInfoTy.isNull()) {
  4916. KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
  4917. KmpDependInfoRD->startDefinition();
  4918. addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
  4919. addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
  4920. addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
  4921. KmpDependInfoRD->completeDefinition();
  4922. KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
  4923. } else {
  4924. KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
  4925. }
  4926. // Define type kmp_depend_info[<Dependences.size()>];
  4927. QualType KmpDependInfoArrayTy = C.getConstantArrayType(
  4928. KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
  4929. nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
  4930. // kmp_depend_info[<Dependences.size()>] deps;
  4931. DependenciesArray =
  4932. CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
  4933. for (unsigned I = 0; I < NumDependencies; ++I) {
  4934. const Expr *E = Data.Dependences[I].second;
  4935. LValue Addr = CGF.EmitLValue(E);
  4936. llvm::Value *Size;
  4937. QualType Ty = E->getType();
  4938. if (const auto *ASE =
  4939. dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
  4940. LValue UpAddrLVal =
  4941. CGF.EmitOMPArraySectionExpr(ASE, /*IsLowerBound=*/false);
  4942. llvm::Value *UpAddr =
  4943. CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
  4944. llvm::Value *LowIntPtr =
  4945. CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
  4946. llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
  4947. Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
  4948. } else {
  4949. Size = CGF.getTypeSize(Ty);
  4950. }
  4951. LValue Base = CGF.MakeAddrLValue(
  4952. CGF.Builder.CreateConstArrayGEP(DependenciesArray, I),
  4953. KmpDependInfoTy);
  4954. // deps[i].base_addr = &<Dependences[i].second>;
  4955. LValue BaseAddrLVal = CGF.EmitLValueForField(
  4956. Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
  4957. CGF.EmitStoreOfScalar(
  4958. CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
  4959. BaseAddrLVal);
  4960. // deps[i].len = sizeof(<Dependences[i].second>);
  4961. LValue LenLVal = CGF.EmitLValueForField(
  4962. Base, *std::next(KmpDependInfoRD->field_begin(), Len));
  4963. CGF.EmitStoreOfScalar(Size, LenLVal);
  4964. // deps[i].flags = <Dependences[i].first>;
  4965. RTLDependenceKindTy DepKind;
  4966. switch (Data.Dependences[I].first) {
  4967. case OMPC_DEPEND_in:
  4968. DepKind = DepIn;
  4969. break;
  4970. // Out and InOut dependencies must use the same code.
  4971. case OMPC_DEPEND_out:
  4972. case OMPC_DEPEND_inout:
  4973. DepKind = DepInOut;
  4974. break;
  4975. case OMPC_DEPEND_mutexinoutset:
  4976. DepKind = DepMutexInOutSet;
  4977. break;
  4978. case OMPC_DEPEND_source:
  4979. case OMPC_DEPEND_sink:
  4980. case OMPC_DEPEND_unknown:
  4981. llvm_unreachable("Unknown task dependence type");
  4982. }
  4983. LValue FlagsLVal = CGF.EmitLValueForField(
  4984. Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
  4985. CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
  4986. FlagsLVal);
  4987. }
  4988. DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  4989. CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0), CGF.VoidPtrTy);
  4990. }
  4991. // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
  4992. // libcall.
  4993. // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
  4994. // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
  4995. // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
  4996. // list is not empty
  4997. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  4998. llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
  4999. llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
  5000. llvm::Value *DepTaskArgs[7];
  5001. if (NumDependencies) {
  5002. DepTaskArgs[0] = UpLoc;
  5003. DepTaskArgs[1] = ThreadID;
  5004. DepTaskArgs[2] = NewTask;
  5005. DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
  5006. DepTaskArgs[4] = DependenciesArray.getPointer();
  5007. DepTaskArgs[5] = CGF.Builder.getInt32(0);
  5008. DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  5009. }
  5010. auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
  5011. &TaskArgs,
  5012. &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
  5013. if (!Data.Tied) {
  5014. auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
  5015. LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
  5016. CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
  5017. }
  5018. if (NumDependencies) {
  5019. CGF.EmitRuntimeCall(
  5020. createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
  5021. } else {
  5022. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
  5023. TaskArgs);
  5024. }
  5025. // Check if parent region is untied and build return for untied task;
  5026. if (auto *Region =
  5027. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  5028. Region->emitUntiedSwitch(CGF);
  5029. };
  5030. llvm::Value *DepWaitTaskArgs[6];
  5031. if (NumDependencies) {
  5032. DepWaitTaskArgs[0] = UpLoc;
  5033. DepWaitTaskArgs[1] = ThreadID;
  5034. DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
  5035. DepWaitTaskArgs[3] = DependenciesArray.getPointer();
  5036. DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
  5037. DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
  5038. }
  5039. auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
  5040. NumDependencies, &DepWaitTaskArgs,
  5041. Loc](CodeGenFunction &CGF, PrePostActionTy &) {
  5042. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5043. CodeGenFunction::RunCleanupsScope LocalScope(CGF);
  5044. // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
  5045. // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
  5046. // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
  5047. // is specified.
  5048. if (NumDependencies)
  5049. CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
  5050. DepWaitTaskArgs);
  5051. // Call proxy_task_entry(gtid, new_task);
  5052. auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
  5053. Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
  5054. Action.Enter(CGF);
  5055. llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
  5056. CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
  5057. OutlinedFnArgs);
  5058. };
  5059. // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
  5060. // kmp_task_t *new_task);
  5061. // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
  5062. // kmp_task_t *new_task);
  5063. RegionCodeGenTy RCG(CodeGen);
  5064. CommonActionTy Action(
  5065. RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
  5066. RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
  5067. RCG.setAction(Action);
  5068. RCG(CGF);
  5069. };
  5070. if (IfCond) {
  5071. emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
  5072. } else {
  5073. RegionCodeGenTy ThenRCG(ThenCodeGen);
  5074. ThenRCG(CGF);
  5075. }
  5076. }
  5077. void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
  5078. const OMPLoopDirective &D,
  5079. llvm::Function *TaskFunction,
  5080. QualType SharedsTy, Address Shareds,
  5081. const Expr *IfCond,
  5082. const OMPTaskDataTy &Data) {
  5083. if (!CGF.HaveInsertPoint())
  5084. return;
  5085. TaskResultTy Result =
  5086. emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
  5087. // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
  5088. // libcall.
  5089. // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
  5090. // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
  5091. // sched, kmp_uint64 grainsize, void *task_dup);
  5092. llvm::Value *ThreadID = getThreadID(CGF, Loc);
  5093. llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
  5094. llvm::Value *IfVal;
  5095. if (IfCond) {
  5096. IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
  5097. /*isSigned=*/true);
  5098. } else {
  5099. IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
  5100. }
  5101. LValue LBLVal = CGF.EmitLValueForField(
  5102. Result.TDBase,
  5103. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
  5104. const auto *LBVar =
  5105. cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
  5106. CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
  5107. /*IsInitializer=*/true);
  5108. LValue UBLVal = CGF.EmitLValueForField(
  5109. Result.TDBase,
  5110. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
  5111. const auto *UBVar =
  5112. cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
  5113. CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
  5114. /*IsInitializer=*/true);
  5115. LValue StLVal = CGF.EmitLValueForField(
  5116. Result.TDBase,
  5117. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
  5118. const auto *StVar =
  5119. cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
  5120. CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
  5121. /*IsInitializer=*/true);
  5122. // Store reductions address.
  5123. LValue RedLVal = CGF.EmitLValueForField(
  5124. Result.TDBase,
  5125. *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
  5126. if (Data.Reductions) {
  5127. CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
  5128. } else {
  5129. CGF.EmitNullInitialization(RedLVal.getAddress(),
  5130. CGF.getContext().VoidPtrTy);
  5131. }
  5132. enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
  5133. llvm::Value *TaskArgs[] = {
  5134. UpLoc,
  5135. ThreadID,
  5136. Result.NewTask,
  5137. IfVal,
  5138. LBLVal.getPointer(),
  5139. UBLVal.getPointer(),
  5140. CGF.EmitLoadOfScalar(StLVal, Loc),
  5141. llvm::ConstantInt::getSigned(
  5142. CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
  5143. llvm::ConstantInt::getSigned(
  5144. CGF.IntTy, Data.Schedule.getPointer()
  5145. ? Data.Schedule.getInt() ? NumTasks : Grainsize
  5146. : NoSchedule),
  5147. Data.Schedule.getPointer()
  5148. ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
  5149. /*isSigned=*/false)
  5150. : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
  5151. Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5152. Result.TaskDupFn, CGF.VoidPtrTy)
  5153. : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
  5154. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
  5155. }
  5156. /// Emit reduction operation for each element of array (required for
  5157. /// array sections) LHS op = RHS.
  5158. /// \param Type Type of array.
  5159. /// \param LHSVar Variable on the left side of the reduction operation
  5160. /// (references element of array in original variable).
  5161. /// \param RHSVar Variable on the right side of the reduction operation
  5162. /// (references element of array in original variable).
  5163. /// \param RedOpGen Generator of reduction operation with use of LHSVar and
  5164. /// RHSVar.
  5165. static void EmitOMPAggregateReduction(
  5166. CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
  5167. const VarDecl *RHSVar,
  5168. const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
  5169. const Expr *, const Expr *)> &RedOpGen,
  5170. const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
  5171. const Expr *UpExpr = nullptr) {
  5172. // Perform element-by-element initialization.
  5173. QualType ElementTy;
  5174. Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
  5175. Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
  5176. // Drill down to the base element type on both arrays.
  5177. const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
  5178. llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
  5179. llvm::Value *RHSBegin = RHSAddr.getPointer();
  5180. llvm::Value *LHSBegin = LHSAddr.getPointer();
  5181. // Cast from pointer to array type to pointer to single element.
  5182. llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
  5183. // The basic structure here is a while-do loop.
  5184. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
  5185. llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
  5186. llvm::Value *IsEmpty =
  5187. CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
  5188. CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  5189. // Enter the loop body, making that address the current address.
  5190. llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
  5191. CGF.EmitBlock(BodyBB);
  5192. CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
  5193. llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
  5194. RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
  5195. RHSElementPHI->addIncoming(RHSBegin, EntryBB);
  5196. Address RHSElementCurrent =
  5197. Address(RHSElementPHI,
  5198. RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  5199. llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
  5200. LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
  5201. LHSElementPHI->addIncoming(LHSBegin, EntryBB);
  5202. Address LHSElementCurrent =
  5203. Address(LHSElementPHI,
  5204. LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  5205. // Emit copy.
  5206. CodeGenFunction::OMPPrivateScope Scope(CGF);
  5207. Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
  5208. Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
  5209. Scope.Privatize();
  5210. RedOpGen(CGF, XExpr, EExpr, UpExpr);
  5211. Scope.ForceCleanup();
  5212. // Shift the address forward by one element.
  5213. llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
  5214. LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  5215. llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
  5216. RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
  5217. // Check whether we've reached the end.
  5218. llvm::Value *Done =
  5219. CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
  5220. CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
  5221. LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
  5222. RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
  5223. // Done.
  5224. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  5225. }
  5226. /// Emit reduction combiner. If the combiner is a simple expression emit it as
  5227. /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
  5228. /// UDR combiner function.
  5229. static void emitReductionCombiner(CodeGenFunction &CGF,
  5230. const Expr *ReductionOp) {
  5231. if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
  5232. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
  5233. if (const auto *DRE =
  5234. dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
  5235. if (const auto *DRD =
  5236. dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
  5237. std::pair<llvm::Function *, llvm::Function *> Reduction =
  5238. CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
  5239. RValue Func = RValue::get(Reduction.first);
  5240. CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
  5241. CGF.EmitIgnoredExpr(ReductionOp);
  5242. return;
  5243. }
  5244. CGF.EmitIgnoredExpr(ReductionOp);
  5245. }
  5246. llvm::Function *CGOpenMPRuntime::emitReductionFunction(
  5247. SourceLocation Loc, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
  5248. ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
  5249. ArrayRef<const Expr *> ReductionOps) {
  5250. ASTContext &C = CGM.getContext();
  5251. // void reduction_func(void *LHSArg, void *RHSArg);
  5252. FunctionArgList Args;
  5253. ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5254. ImplicitParamDecl::Other);
  5255. ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5256. ImplicitParamDecl::Other);
  5257. Args.push_back(&LHSArg);
  5258. Args.push_back(&RHSArg);
  5259. const auto &CGFI =
  5260. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5261. std::string Name = getName({"omp", "reduction", "reduction_func"});
  5262. auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
  5263. llvm::GlobalValue::InternalLinkage, Name,
  5264. &CGM.getModule());
  5265. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  5266. Fn->setDoesNotRecurse();
  5267. CodeGenFunction CGF(CGM);
  5268. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  5269. // Dst = (void*[n])(LHSArg);
  5270. // Src = (void*[n])(RHSArg);
  5271. Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5272. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
  5273. ArgsType), CGF.getPointerAlign());
  5274. Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5275. CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
  5276. ArgsType), CGF.getPointerAlign());
  5277. // ...
  5278. // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
  5279. // ...
  5280. CodeGenFunction::OMPPrivateScope Scope(CGF);
  5281. auto IPriv = Privates.begin();
  5282. unsigned Idx = 0;
  5283. for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
  5284. const auto *RHSVar =
  5285. cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
  5286. Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
  5287. return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
  5288. });
  5289. const auto *LHSVar =
  5290. cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
  5291. Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
  5292. return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
  5293. });
  5294. QualType PrivTy = (*IPriv)->getType();
  5295. if (PrivTy->isVariablyModifiedType()) {
  5296. // Get array size and emit VLA type.
  5297. ++Idx;
  5298. Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx);
  5299. llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
  5300. const VariableArrayType *VLA =
  5301. CGF.getContext().getAsVariableArrayType(PrivTy);
  5302. const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
  5303. CodeGenFunction::OpaqueValueMapping OpaqueMap(
  5304. CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
  5305. CGF.EmitVariablyModifiedType(PrivTy);
  5306. }
  5307. }
  5308. Scope.Privatize();
  5309. IPriv = Privates.begin();
  5310. auto ILHS = LHSExprs.begin();
  5311. auto IRHS = RHSExprs.begin();
  5312. for (const Expr *E : ReductionOps) {
  5313. if ((*IPriv)->getType()->isArrayType()) {
  5314. // Emit reduction for array section.
  5315. const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5316. const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5317. EmitOMPAggregateReduction(
  5318. CGF, (*IPriv)->getType(), LHSVar, RHSVar,
  5319. [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
  5320. emitReductionCombiner(CGF, E);
  5321. });
  5322. } else {
  5323. // Emit reduction for array subscript or single variable.
  5324. emitReductionCombiner(CGF, E);
  5325. }
  5326. ++IPriv;
  5327. ++ILHS;
  5328. ++IRHS;
  5329. }
  5330. Scope.ForceCleanup();
  5331. CGF.FinishFunction();
  5332. return Fn;
  5333. }
  5334. void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
  5335. const Expr *ReductionOp,
  5336. const Expr *PrivateRef,
  5337. const DeclRefExpr *LHS,
  5338. const DeclRefExpr *RHS) {
  5339. if (PrivateRef->getType()->isArrayType()) {
  5340. // Emit reduction for array section.
  5341. const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
  5342. const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
  5343. EmitOMPAggregateReduction(
  5344. CGF, PrivateRef->getType(), LHSVar, RHSVar,
  5345. [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
  5346. emitReductionCombiner(CGF, ReductionOp);
  5347. });
  5348. } else {
  5349. // Emit reduction for array subscript or single variable.
  5350. emitReductionCombiner(CGF, ReductionOp);
  5351. }
  5352. }
  5353. void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
  5354. ArrayRef<const Expr *> Privates,
  5355. ArrayRef<const Expr *> LHSExprs,
  5356. ArrayRef<const Expr *> RHSExprs,
  5357. ArrayRef<const Expr *> ReductionOps,
  5358. ReductionOptionsTy Options) {
  5359. if (!CGF.HaveInsertPoint())
  5360. return;
  5361. bool WithNowait = Options.WithNowait;
  5362. bool SimpleReduction = Options.SimpleReduction;
  5363. // Next code should be emitted for reduction:
  5364. //
  5365. // static kmp_critical_name lock = { 0 };
  5366. //
  5367. // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
  5368. // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
  5369. // ...
  5370. // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
  5371. // *(Type<n>-1*)rhs[<n>-1]);
  5372. // }
  5373. //
  5374. // ...
  5375. // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
  5376. // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
  5377. // RedList, reduce_func, &<lock>)) {
  5378. // case 1:
  5379. // ...
  5380. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5381. // ...
  5382. // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5383. // break;
  5384. // case 2:
  5385. // ...
  5386. // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
  5387. // ...
  5388. // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
  5389. // break;
  5390. // default:;
  5391. // }
  5392. //
  5393. // if SimpleReduction is true, only the next code is generated:
  5394. // ...
  5395. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5396. // ...
  5397. ASTContext &C = CGM.getContext();
  5398. if (SimpleReduction) {
  5399. CodeGenFunction::RunCleanupsScope Scope(CGF);
  5400. auto IPriv = Privates.begin();
  5401. auto ILHS = LHSExprs.begin();
  5402. auto IRHS = RHSExprs.begin();
  5403. for (const Expr *E : ReductionOps) {
  5404. emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
  5405. cast<DeclRefExpr>(*IRHS));
  5406. ++IPriv;
  5407. ++ILHS;
  5408. ++IRHS;
  5409. }
  5410. return;
  5411. }
  5412. // 1. Build a list of reduction variables.
  5413. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  5414. auto Size = RHSExprs.size();
  5415. for (const Expr *E : Privates) {
  5416. if (E->getType()->isVariablyModifiedType())
  5417. // Reserve place for array size.
  5418. ++Size;
  5419. }
  5420. llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
  5421. QualType ReductionArrayTy =
  5422. C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
  5423. /*IndexTypeQuals=*/0);
  5424. Address ReductionList =
  5425. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  5426. auto IPriv = Privates.begin();
  5427. unsigned Idx = 0;
  5428. for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
  5429. Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  5430. CGF.Builder.CreateStore(
  5431. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5432. CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
  5433. Elem);
  5434. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  5435. // Store array size.
  5436. ++Idx;
  5437. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  5438. llvm::Value *Size = CGF.Builder.CreateIntCast(
  5439. CGF.getVLASize(
  5440. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  5441. .NumElts,
  5442. CGF.SizeTy, /*isSigned=*/false);
  5443. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  5444. Elem);
  5445. }
  5446. }
  5447. // 2. Emit reduce_func().
  5448. llvm::Function *ReductionFn = emitReductionFunction(
  5449. Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
  5450. LHSExprs, RHSExprs, ReductionOps);
  5451. // 3. Create static kmp_critical_name lock = { 0 };
  5452. std::string Name = getName({"reduction"});
  5453. llvm::Value *Lock = getCriticalRegionLock(Name);
  5454. // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
  5455. // RedList, reduce_func, &<lock>);
  5456. llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
  5457. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  5458. llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
  5459. llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5460. ReductionList.getPointer(), CGF.VoidPtrTy);
  5461. llvm::Value *Args[] = {
  5462. IdentTLoc, // ident_t *<loc>
  5463. ThreadId, // i32 <gtid>
  5464. CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
  5465. ReductionArrayTySize, // size_type sizeof(RedList)
  5466. RL, // void *RedList
  5467. ReductionFn, // void (*) (void *, void *) <reduce_func>
  5468. Lock // kmp_critical_name *&<lock>
  5469. };
  5470. llvm::Value *Res = CGF.EmitRuntimeCall(
  5471. createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
  5472. : OMPRTL__kmpc_reduce),
  5473. Args);
  5474. // 5. Build switch(res)
  5475. llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
  5476. llvm::SwitchInst *SwInst =
  5477. CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
  5478. // 6. Build case 1:
  5479. // ...
  5480. // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
  5481. // ...
  5482. // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5483. // break;
  5484. llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
  5485. SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
  5486. CGF.EmitBlock(Case1BB);
  5487. // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
  5488. llvm::Value *EndArgs[] = {
  5489. IdentTLoc, // ident_t *<loc>
  5490. ThreadId, // i32 <gtid>
  5491. Lock // kmp_critical_name *&<lock>
  5492. };
  5493. auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
  5494. CodeGenFunction &CGF, PrePostActionTy &Action) {
  5495. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5496. auto IPriv = Privates.begin();
  5497. auto ILHS = LHSExprs.begin();
  5498. auto IRHS = RHSExprs.begin();
  5499. for (const Expr *E : ReductionOps) {
  5500. RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
  5501. cast<DeclRefExpr>(*IRHS));
  5502. ++IPriv;
  5503. ++ILHS;
  5504. ++IRHS;
  5505. }
  5506. };
  5507. RegionCodeGenTy RCG(CodeGen);
  5508. CommonActionTy Action(
  5509. nullptr, llvm::None,
  5510. createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
  5511. : OMPRTL__kmpc_end_reduce),
  5512. EndArgs);
  5513. RCG.setAction(Action);
  5514. RCG(CGF);
  5515. CGF.EmitBranch(DefaultBB);
  5516. // 7. Build case 2:
  5517. // ...
  5518. // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
  5519. // ...
  5520. // break;
  5521. llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
  5522. SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
  5523. CGF.EmitBlock(Case2BB);
  5524. auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
  5525. CodeGenFunction &CGF, PrePostActionTy &Action) {
  5526. auto ILHS = LHSExprs.begin();
  5527. auto IRHS = RHSExprs.begin();
  5528. auto IPriv = Privates.begin();
  5529. for (const Expr *E : ReductionOps) {
  5530. const Expr *XExpr = nullptr;
  5531. const Expr *EExpr = nullptr;
  5532. const Expr *UpExpr = nullptr;
  5533. BinaryOperatorKind BO = BO_Comma;
  5534. if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
  5535. if (BO->getOpcode() == BO_Assign) {
  5536. XExpr = BO->getLHS();
  5537. UpExpr = BO->getRHS();
  5538. }
  5539. }
  5540. // Try to emit update expression as a simple atomic.
  5541. const Expr *RHSExpr = UpExpr;
  5542. if (RHSExpr) {
  5543. // Analyze RHS part of the whole expression.
  5544. if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
  5545. RHSExpr->IgnoreParenImpCasts())) {
  5546. // If this is a conditional operator, analyze its condition for
  5547. // min/max reduction operator.
  5548. RHSExpr = ACO->getCond();
  5549. }
  5550. if (const auto *BORHS =
  5551. dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
  5552. EExpr = BORHS->getRHS();
  5553. BO = BORHS->getOpcode();
  5554. }
  5555. }
  5556. if (XExpr) {
  5557. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5558. auto &&AtomicRedGen = [BO, VD,
  5559. Loc](CodeGenFunction &CGF, const Expr *XExpr,
  5560. const Expr *EExpr, const Expr *UpExpr) {
  5561. LValue X = CGF.EmitLValue(XExpr);
  5562. RValue E;
  5563. if (EExpr)
  5564. E = CGF.EmitAnyExpr(EExpr);
  5565. CGF.EmitOMPAtomicSimpleUpdateExpr(
  5566. X, E, BO, /*IsXLHSInRHSPart=*/true,
  5567. llvm::AtomicOrdering::Monotonic, Loc,
  5568. [&CGF, UpExpr, VD, Loc](RValue XRValue) {
  5569. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  5570. PrivateScope.addPrivate(
  5571. VD, [&CGF, VD, XRValue, Loc]() {
  5572. Address LHSTemp = CGF.CreateMemTemp(VD->getType());
  5573. CGF.emitOMPSimpleStore(
  5574. CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
  5575. VD->getType().getNonReferenceType(), Loc);
  5576. return LHSTemp;
  5577. });
  5578. (void)PrivateScope.Privatize();
  5579. return CGF.EmitAnyExpr(UpExpr);
  5580. });
  5581. };
  5582. if ((*IPriv)->getType()->isArrayType()) {
  5583. // Emit atomic reduction for array section.
  5584. const auto *RHSVar =
  5585. cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5586. EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
  5587. AtomicRedGen, XExpr, EExpr, UpExpr);
  5588. } else {
  5589. // Emit atomic reduction for array subscript or single variable.
  5590. AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
  5591. }
  5592. } else {
  5593. // Emit as a critical region.
  5594. auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
  5595. const Expr *, const Expr *) {
  5596. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  5597. std::string Name = RT.getName({"atomic_reduction"});
  5598. RT.emitCriticalRegion(
  5599. CGF, Name,
  5600. [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
  5601. Action.Enter(CGF);
  5602. emitReductionCombiner(CGF, E);
  5603. },
  5604. Loc);
  5605. };
  5606. if ((*IPriv)->getType()->isArrayType()) {
  5607. const auto *LHSVar =
  5608. cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  5609. const auto *RHSVar =
  5610. cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  5611. EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
  5612. CritRedGen);
  5613. } else {
  5614. CritRedGen(CGF, nullptr, nullptr, nullptr);
  5615. }
  5616. }
  5617. ++ILHS;
  5618. ++IRHS;
  5619. ++IPriv;
  5620. }
  5621. };
  5622. RegionCodeGenTy AtomicRCG(AtomicCodeGen);
  5623. if (!WithNowait) {
  5624. // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
  5625. llvm::Value *EndArgs[] = {
  5626. IdentTLoc, // ident_t *<loc>
  5627. ThreadId, // i32 <gtid>
  5628. Lock // kmp_critical_name *&<lock>
  5629. };
  5630. CommonActionTy Action(nullptr, llvm::None,
  5631. createRuntimeFunction(OMPRTL__kmpc_end_reduce),
  5632. EndArgs);
  5633. AtomicRCG.setAction(Action);
  5634. AtomicRCG(CGF);
  5635. } else {
  5636. AtomicRCG(CGF);
  5637. }
  5638. CGF.EmitBranch(DefaultBB);
  5639. CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
  5640. }
  5641. /// Generates unique name for artificial threadprivate variables.
  5642. /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
  5643. static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
  5644. const Expr *Ref) {
  5645. SmallString<256> Buffer;
  5646. llvm::raw_svector_ostream Out(Buffer);
  5647. const clang::DeclRefExpr *DE;
  5648. const VarDecl *D = ::getBaseDecl(Ref, DE);
  5649. if (!D)
  5650. D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
  5651. D = D->getCanonicalDecl();
  5652. std::string Name = CGM.getOpenMPRuntime().getName(
  5653. {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
  5654. Out << Prefix << Name << "_"
  5655. << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
  5656. return Out.str();
  5657. }
  5658. /// Emits reduction initializer function:
  5659. /// \code
  5660. /// void @.red_init(void* %arg) {
  5661. /// %0 = bitcast void* %arg to <type>*
  5662. /// store <type> <init>, <type>* %0
  5663. /// ret void
  5664. /// }
  5665. /// \endcode
  5666. static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
  5667. SourceLocation Loc,
  5668. ReductionCodeGen &RCG, unsigned N) {
  5669. ASTContext &C = CGM.getContext();
  5670. FunctionArgList Args;
  5671. ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5672. ImplicitParamDecl::Other);
  5673. Args.emplace_back(&Param);
  5674. const auto &FnInfo =
  5675. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5676. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5677. std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
  5678. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5679. Name, &CGM.getModule());
  5680. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5681. Fn->setDoesNotRecurse();
  5682. CodeGenFunction CGF(CGM);
  5683. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5684. Address PrivateAddr = CGF.EmitLoadOfPointer(
  5685. CGF.GetAddrOfLocalVar(&Param),
  5686. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5687. llvm::Value *Size = nullptr;
  5688. // If the size of the reduction item is non-constant, load it from global
  5689. // threadprivate variable.
  5690. if (RCG.getSizes(N).second) {
  5691. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5692. CGF, CGM.getContext().getSizeType(),
  5693. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5694. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5695. CGM.getContext().getSizeType(), Loc);
  5696. }
  5697. RCG.emitAggregateType(CGF, N, Size);
  5698. LValue SharedLVal;
  5699. // If initializer uses initializer from declare reduction construct, emit a
  5700. // pointer to the address of the original reduction item (reuired by reduction
  5701. // initializer)
  5702. if (RCG.usesReductionInitializer(N)) {
  5703. Address SharedAddr =
  5704. CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5705. CGF, CGM.getContext().VoidPtrTy,
  5706. generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
  5707. SharedAddr = CGF.EmitLoadOfPointer(
  5708. SharedAddr,
  5709. CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
  5710. SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
  5711. } else {
  5712. SharedLVal = CGF.MakeNaturalAlignAddrLValue(
  5713. llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
  5714. CGM.getContext().VoidPtrTy);
  5715. }
  5716. // Emit the initializer:
  5717. // %0 = bitcast void* %arg to <type>*
  5718. // store <type> <init>, <type>* %0
  5719. RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
  5720. [](CodeGenFunction &) { return false; });
  5721. CGF.FinishFunction();
  5722. return Fn;
  5723. }
  5724. /// Emits reduction combiner function:
  5725. /// \code
  5726. /// void @.red_comb(void* %arg0, void* %arg1) {
  5727. /// %lhs = bitcast void* %arg0 to <type>*
  5728. /// %rhs = bitcast void* %arg1 to <type>*
  5729. /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
  5730. /// store <type> %2, <type>* %lhs
  5731. /// ret void
  5732. /// }
  5733. /// \endcode
  5734. static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
  5735. SourceLocation Loc,
  5736. ReductionCodeGen &RCG, unsigned N,
  5737. const Expr *ReductionOp,
  5738. const Expr *LHS, const Expr *RHS,
  5739. const Expr *PrivateRef) {
  5740. ASTContext &C = CGM.getContext();
  5741. const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
  5742. const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
  5743. FunctionArgList Args;
  5744. ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  5745. C.VoidPtrTy, ImplicitParamDecl::Other);
  5746. ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5747. ImplicitParamDecl::Other);
  5748. Args.emplace_back(&ParamInOut);
  5749. Args.emplace_back(&ParamIn);
  5750. const auto &FnInfo =
  5751. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5752. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5753. std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
  5754. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5755. Name, &CGM.getModule());
  5756. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5757. Fn->setDoesNotRecurse();
  5758. CodeGenFunction CGF(CGM);
  5759. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5760. llvm::Value *Size = nullptr;
  5761. // If the size of the reduction item is non-constant, load it from global
  5762. // threadprivate variable.
  5763. if (RCG.getSizes(N).second) {
  5764. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5765. CGF, CGM.getContext().getSizeType(),
  5766. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5767. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5768. CGM.getContext().getSizeType(), Loc);
  5769. }
  5770. RCG.emitAggregateType(CGF, N, Size);
  5771. // Remap lhs and rhs variables to the addresses of the function arguments.
  5772. // %lhs = bitcast void* %arg0 to <type>*
  5773. // %rhs = bitcast void* %arg1 to <type>*
  5774. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  5775. PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
  5776. // Pull out the pointer to the variable.
  5777. Address PtrAddr = CGF.EmitLoadOfPointer(
  5778. CGF.GetAddrOfLocalVar(&ParamInOut),
  5779. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5780. return CGF.Builder.CreateElementBitCast(
  5781. PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
  5782. });
  5783. PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
  5784. // Pull out the pointer to the variable.
  5785. Address PtrAddr = CGF.EmitLoadOfPointer(
  5786. CGF.GetAddrOfLocalVar(&ParamIn),
  5787. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5788. return CGF.Builder.CreateElementBitCast(
  5789. PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
  5790. });
  5791. PrivateScope.Privatize();
  5792. // Emit the combiner body:
  5793. // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
  5794. // store <type> %2, <type>* %lhs
  5795. CGM.getOpenMPRuntime().emitSingleReductionCombiner(
  5796. CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
  5797. cast<DeclRefExpr>(RHS));
  5798. CGF.FinishFunction();
  5799. return Fn;
  5800. }
  5801. /// Emits reduction finalizer function:
  5802. /// \code
  5803. /// void @.red_fini(void* %arg) {
  5804. /// %0 = bitcast void* %arg to <type>*
  5805. /// <destroy>(<type>* %0)
  5806. /// ret void
  5807. /// }
  5808. /// \endcode
  5809. static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
  5810. SourceLocation Loc,
  5811. ReductionCodeGen &RCG, unsigned N) {
  5812. if (!RCG.needCleanups(N))
  5813. return nullptr;
  5814. ASTContext &C = CGM.getContext();
  5815. FunctionArgList Args;
  5816. ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  5817. ImplicitParamDecl::Other);
  5818. Args.emplace_back(&Param);
  5819. const auto &FnInfo =
  5820. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  5821. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  5822. std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
  5823. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  5824. Name, &CGM.getModule());
  5825. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  5826. Fn->setDoesNotRecurse();
  5827. CodeGenFunction CGF(CGM);
  5828. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  5829. Address PrivateAddr = CGF.EmitLoadOfPointer(
  5830. CGF.GetAddrOfLocalVar(&Param),
  5831. C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
  5832. llvm::Value *Size = nullptr;
  5833. // If the size of the reduction item is non-constant, load it from global
  5834. // threadprivate variable.
  5835. if (RCG.getSizes(N).second) {
  5836. Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
  5837. CGF, CGM.getContext().getSizeType(),
  5838. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5839. Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
  5840. CGM.getContext().getSizeType(), Loc);
  5841. }
  5842. RCG.emitAggregateType(CGF, N, Size);
  5843. // Emit the finalizer body:
  5844. // <destroy>(<type>* %0)
  5845. RCG.emitCleanups(CGF, N, PrivateAddr);
  5846. CGF.FinishFunction();
  5847. return Fn;
  5848. }
  5849. llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
  5850. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
  5851. ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
  5852. if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
  5853. return nullptr;
  5854. // Build typedef struct:
  5855. // kmp_task_red_input {
  5856. // void *reduce_shar; // shared reduction item
  5857. // size_t reduce_size; // size of data item
  5858. // void *reduce_init; // data initialization routine
  5859. // void *reduce_fini; // data finalization routine
  5860. // void *reduce_comb; // data combiner routine
  5861. // kmp_task_red_flags_t flags; // flags for additional info from compiler
  5862. // } kmp_task_red_input_t;
  5863. ASTContext &C = CGM.getContext();
  5864. RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
  5865. RD->startDefinition();
  5866. const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5867. const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
  5868. const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5869. const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5870. const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
  5871. const FieldDecl *FlagsFD = addFieldToRecordDecl(
  5872. C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
  5873. RD->completeDefinition();
  5874. QualType RDType = C.getRecordType(RD);
  5875. unsigned Size = Data.ReductionVars.size();
  5876. llvm::APInt ArraySize(/*numBits=*/64, Size);
  5877. QualType ArrayRDType = C.getConstantArrayType(
  5878. RDType, ArraySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
  5879. // kmp_task_red_input_t .rd_input.[Size];
  5880. Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
  5881. ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
  5882. Data.ReductionOps);
  5883. for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
  5884. // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
  5885. llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
  5886. llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
  5887. llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
  5888. TaskRedInput.getPointer(), Idxs,
  5889. /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
  5890. ".rd_input.gep.");
  5891. LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
  5892. // ElemLVal.reduce_shar = &Shareds[Cnt];
  5893. LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
  5894. RCG.emitSharedLValue(CGF, Cnt);
  5895. llvm::Value *CastedShared =
  5896. CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
  5897. CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
  5898. RCG.emitAggregateType(CGF, Cnt);
  5899. llvm::Value *SizeValInChars;
  5900. llvm::Value *SizeVal;
  5901. std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
  5902. // We use delayed creation/initialization for VLAs, array sections and
  5903. // custom reduction initializations. It is required because runtime does not
  5904. // provide the way to pass the sizes of VLAs/array sections to
  5905. // initializer/combiner/finalizer functions and does not pass the pointer to
  5906. // original reduction item to the initializer. Instead threadprivate global
  5907. // variables are used to store these values and use them in the functions.
  5908. bool DelayedCreation = !!SizeVal;
  5909. SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
  5910. /*isSigned=*/false);
  5911. LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
  5912. CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
  5913. // ElemLVal.reduce_init = init;
  5914. LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
  5915. llvm::Value *InitAddr =
  5916. CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
  5917. CGF.EmitStoreOfScalar(InitAddr, InitLVal);
  5918. DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
  5919. // ElemLVal.reduce_fini = fini;
  5920. LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
  5921. llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
  5922. llvm::Value *FiniAddr = Fini
  5923. ? CGF.EmitCastToVoidPtr(Fini)
  5924. : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
  5925. CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
  5926. // ElemLVal.reduce_comb = comb;
  5927. LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
  5928. llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
  5929. CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
  5930. RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
  5931. CGF.EmitStoreOfScalar(CombAddr, CombLVal);
  5932. // ElemLVal.flags = 0;
  5933. LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
  5934. if (DelayedCreation) {
  5935. CGF.EmitStoreOfScalar(
  5936. llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*isSigned=*/true),
  5937. FlagsLVal);
  5938. } else
  5939. CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
  5940. }
  5941. // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
  5942. // *data);
  5943. llvm::Value *Args[] = {
  5944. CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
  5945. /*isSigned=*/true),
  5946. llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
  5947. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
  5948. CGM.VoidPtrTy)};
  5949. return CGF.EmitRuntimeCall(
  5950. createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
  5951. }
  5952. void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
  5953. SourceLocation Loc,
  5954. ReductionCodeGen &RCG,
  5955. unsigned N) {
  5956. auto Sizes = RCG.getSizes(N);
  5957. // Emit threadprivate global variable if the type is non-constant
  5958. // (Sizes.second = nullptr).
  5959. if (Sizes.second) {
  5960. llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
  5961. /*isSigned=*/false);
  5962. Address SizeAddr = getAddrOfArtificialThreadPrivate(
  5963. CGF, CGM.getContext().getSizeType(),
  5964. generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
  5965. CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
  5966. }
  5967. // Store address of the original reduction item if custom initializer is used.
  5968. if (RCG.usesReductionInitializer(N)) {
  5969. Address SharedAddr = getAddrOfArtificialThreadPrivate(
  5970. CGF, CGM.getContext().VoidPtrTy,
  5971. generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
  5972. CGF.Builder.CreateStore(
  5973. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  5974. RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
  5975. SharedAddr, /*IsVolatile=*/false);
  5976. }
  5977. }
  5978. Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
  5979. SourceLocation Loc,
  5980. llvm::Value *ReductionsPtr,
  5981. LValue SharedLVal) {
  5982. // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
  5983. // *d);
  5984. llvm::Value *Args[] = {
  5985. CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
  5986. /*isSigned=*/true),
  5987. ReductionsPtr,
  5988. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
  5989. CGM.VoidPtrTy)};
  5990. return Address(
  5991. CGF.EmitRuntimeCall(
  5992. createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
  5993. SharedLVal.getAlignment());
  5994. }
  5995. void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
  5996. SourceLocation Loc) {
  5997. if (!CGF.HaveInsertPoint())
  5998. return;
  5999. // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
  6000. // global_tid);
  6001. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
  6002. // Ignore return result until untied tasks are supported.
  6003. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
  6004. if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
  6005. Region->emitUntiedSwitch(CGF);
  6006. }
  6007. void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
  6008. OpenMPDirectiveKind InnerKind,
  6009. const RegionCodeGenTy &CodeGen,
  6010. bool HasCancel) {
  6011. if (!CGF.HaveInsertPoint())
  6012. return;
  6013. InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
  6014. CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
  6015. }
  6016. namespace {
  6017. enum RTCancelKind {
  6018. CancelNoreq = 0,
  6019. CancelParallel = 1,
  6020. CancelLoop = 2,
  6021. CancelSections = 3,
  6022. CancelTaskgroup = 4
  6023. };
  6024. } // anonymous namespace
  6025. static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
  6026. RTCancelKind CancelKind = CancelNoreq;
  6027. if (CancelRegion == OMPD_parallel)
  6028. CancelKind = CancelParallel;
  6029. else if (CancelRegion == OMPD_for)
  6030. CancelKind = CancelLoop;
  6031. else if (CancelRegion == OMPD_sections)
  6032. CancelKind = CancelSections;
  6033. else {
  6034. assert(CancelRegion == OMPD_taskgroup);
  6035. CancelKind = CancelTaskgroup;
  6036. }
  6037. return CancelKind;
  6038. }
  6039. void CGOpenMPRuntime::emitCancellationPointCall(
  6040. CodeGenFunction &CGF, SourceLocation Loc,
  6041. OpenMPDirectiveKind CancelRegion) {
  6042. if (!CGF.HaveInsertPoint())
  6043. return;
  6044. // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
  6045. // global_tid, kmp_int32 cncl_kind);
  6046. if (auto *OMPRegionInfo =
  6047. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  6048. // For 'cancellation point taskgroup', the task region info may not have a
  6049. // cancel. This may instead happen in another adjacent task.
  6050. if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
  6051. llvm::Value *Args[] = {
  6052. emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
  6053. CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
  6054. // Ignore return result until untied tasks are supported.
  6055. llvm::Value *Result = CGF.EmitRuntimeCall(
  6056. createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
  6057. // if (__kmpc_cancellationpoint()) {
  6058. // exit from construct;
  6059. // }
  6060. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  6061. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  6062. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  6063. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  6064. CGF.EmitBlock(ExitBB);
  6065. // exit from construct;
  6066. CodeGenFunction::JumpDest CancelDest =
  6067. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  6068. CGF.EmitBranchThroughCleanup(CancelDest);
  6069. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  6070. }
  6071. }
  6072. }
  6073. void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
  6074. const Expr *IfCond,
  6075. OpenMPDirectiveKind CancelRegion) {
  6076. if (!CGF.HaveInsertPoint())
  6077. return;
  6078. // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
  6079. // kmp_int32 cncl_kind);
  6080. if (auto *OMPRegionInfo =
  6081. dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
  6082. auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
  6083. PrePostActionTy &) {
  6084. CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
  6085. llvm::Value *Args[] = {
  6086. RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
  6087. CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
  6088. // Ignore return result until untied tasks are supported.
  6089. llvm::Value *Result = CGF.EmitRuntimeCall(
  6090. RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
  6091. // if (__kmpc_cancel()) {
  6092. // exit from construct;
  6093. // }
  6094. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
  6095. llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
  6096. llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
  6097. CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
  6098. CGF.EmitBlock(ExitBB);
  6099. // exit from construct;
  6100. CodeGenFunction::JumpDest CancelDest =
  6101. CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
  6102. CGF.EmitBranchThroughCleanup(CancelDest);
  6103. CGF.EmitBlock(ContBB, /*IsFinished=*/true);
  6104. };
  6105. if (IfCond) {
  6106. emitOMPIfClause(CGF, IfCond, ThenGen,
  6107. [](CodeGenFunction &, PrePostActionTy &) {});
  6108. } else {
  6109. RegionCodeGenTy ThenRCG(ThenGen);
  6110. ThenRCG(CGF);
  6111. }
  6112. }
  6113. }
  6114. void CGOpenMPRuntime::emitTargetOutlinedFunction(
  6115. const OMPExecutableDirective &D, StringRef ParentName,
  6116. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  6117. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  6118. assert(!ParentName.empty() && "Invalid target region parent name!");
  6119. HasEmittedTargetRegion = true;
  6120. emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
  6121. IsOffloadEntry, CodeGen);
  6122. }
  6123. void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
  6124. const OMPExecutableDirective &D, StringRef ParentName,
  6125. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  6126. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  6127. // Create a unique name for the entry function using the source location
  6128. // information of the current target region. The name will be something like:
  6129. //
  6130. // __omp_offloading_DD_FFFF_PP_lBB
  6131. //
  6132. // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
  6133. // mangled name of the function that encloses the target region and BB is the
  6134. // line number of the target region.
  6135. unsigned DeviceID;
  6136. unsigned FileID;
  6137. unsigned Line;
  6138. getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
  6139. Line);
  6140. SmallString<64> EntryFnName;
  6141. {
  6142. llvm::raw_svector_ostream OS(EntryFnName);
  6143. OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
  6144. << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
  6145. }
  6146. const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
  6147. CodeGenFunction CGF(CGM, true);
  6148. CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
  6149. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6150. OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
  6151. // If this target outline function is not an offload entry, we don't need to
  6152. // register it.
  6153. if (!IsOffloadEntry)
  6154. return;
  6155. // The target region ID is used by the runtime library to identify the current
  6156. // target region, so it only has to be unique and not necessarily point to
  6157. // anything. It could be the pointer to the outlined function that implements
  6158. // the target region, but we aren't using that so that the compiler doesn't
  6159. // need to keep that, and could therefore inline the host function if proven
  6160. // worthwhile during optimization. In the other hand, if emitting code for the
  6161. // device, the ID has to be the function address so that it can retrieved from
  6162. // the offloading entry and launched by the runtime library. We also mark the
  6163. // outlined function to have external linkage in case we are emitting code for
  6164. // the device, because these functions will be entry points to the device.
  6165. if (CGM.getLangOpts().OpenMPIsDevice) {
  6166. OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
  6167. OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
  6168. OutlinedFn->setDSOLocal(false);
  6169. } else {
  6170. std::string Name = getName({EntryFnName, "region_id"});
  6171. OutlinedFnID = new llvm::GlobalVariable(
  6172. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  6173. llvm::GlobalValue::WeakAnyLinkage,
  6174. llvm::Constant::getNullValue(CGM.Int8Ty), Name);
  6175. }
  6176. // Register the information for the entry associated with this target region.
  6177. OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
  6178. DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
  6179. OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
  6180. }
  6181. /// Checks if the expression is constant or does not have non-trivial function
  6182. /// calls.
  6183. static bool isTrivial(ASTContext &Ctx, const Expr * E) {
  6184. // We can skip constant expressions.
  6185. // We can skip expressions with trivial calls or simple expressions.
  6186. return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
  6187. !E->hasNonTrivialCall(Ctx)) &&
  6188. !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
  6189. }
  6190. const Stmt *CGOpenMPRuntime::getSingleCompoundChild(ASTContext &Ctx,
  6191. const Stmt *Body) {
  6192. const Stmt *Child = Body->IgnoreContainers();
  6193. while (const auto *C = dyn_cast_or_null<CompoundStmt>(Child)) {
  6194. Child = nullptr;
  6195. for (const Stmt *S : C->body()) {
  6196. if (const auto *E = dyn_cast<Expr>(S)) {
  6197. if (isTrivial(Ctx, E))
  6198. continue;
  6199. }
  6200. // Some of the statements can be ignored.
  6201. if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
  6202. isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
  6203. continue;
  6204. // Analyze declarations.
  6205. if (const auto *DS = dyn_cast<DeclStmt>(S)) {
  6206. if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
  6207. if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
  6208. isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
  6209. isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
  6210. isa<UsingDirectiveDecl>(D) ||
  6211. isa<OMPDeclareReductionDecl>(D) ||
  6212. isa<OMPThreadPrivateDecl>(D) || isa<OMPAllocateDecl>(D))
  6213. return true;
  6214. const auto *VD = dyn_cast<VarDecl>(D);
  6215. if (!VD)
  6216. return false;
  6217. return VD->isConstexpr() ||
  6218. ((VD->getType().isTrivialType(Ctx) ||
  6219. VD->getType()->isReferenceType()) &&
  6220. (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
  6221. }))
  6222. continue;
  6223. }
  6224. // Found multiple children - cannot get the one child only.
  6225. if (Child)
  6226. return nullptr;
  6227. Child = S;
  6228. }
  6229. if (Child)
  6230. Child = Child->IgnoreContainers();
  6231. }
  6232. return Child;
  6233. }
  6234. /// Emit the number of teams for a target directive. Inspect the num_teams
  6235. /// clause associated with a teams construct combined or closely nested
  6236. /// with the target directive.
  6237. ///
  6238. /// Emit a team of size one for directives such as 'target parallel' that
  6239. /// have no associated teams construct.
  6240. ///
  6241. /// Otherwise, return nullptr.
  6242. static llvm::Value *
  6243. emitNumTeamsForTargetDirective(CodeGenFunction &CGF,
  6244. const OMPExecutableDirective &D) {
  6245. assert(!CGF.getLangOpts().OpenMPIsDevice &&
  6246. "Clauses associated with the teams directive expected to be emitted "
  6247. "only for the host!");
  6248. OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
  6249. assert(isOpenMPTargetExecutionDirective(DirectiveKind) &&
  6250. "Expected target-based executable directive.");
  6251. CGBuilderTy &Bld = CGF.Builder;
  6252. switch (DirectiveKind) {
  6253. case OMPD_target: {
  6254. const auto *CS = D.getInnermostCapturedStmt();
  6255. const auto *Body =
  6256. CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  6257. const Stmt *ChildStmt =
  6258. CGOpenMPRuntime::getSingleCompoundChild(CGF.getContext(), Body);
  6259. if (const auto *NestedDir =
  6260. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  6261. if (isOpenMPTeamsDirective(NestedDir->getDirectiveKind())) {
  6262. if (NestedDir->hasClausesOfKind<OMPNumTeamsClause>()) {
  6263. CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
  6264. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6265. const Expr *NumTeams =
  6266. NestedDir->getSingleClause<OMPNumTeamsClause>()->getNumTeams();
  6267. llvm::Value *NumTeamsVal =
  6268. CGF.EmitScalarExpr(NumTeams,
  6269. /*IgnoreResultAssign*/ true);
  6270. return Bld.CreateIntCast(NumTeamsVal, CGF.Int32Ty,
  6271. /*isSigned=*/true);
  6272. }
  6273. return Bld.getInt32(0);
  6274. }
  6275. if (isOpenMPParallelDirective(NestedDir->getDirectiveKind()) ||
  6276. isOpenMPSimdDirective(NestedDir->getDirectiveKind()))
  6277. return Bld.getInt32(1);
  6278. return Bld.getInt32(0);
  6279. }
  6280. return nullptr;
  6281. }
  6282. case OMPD_target_teams:
  6283. case OMPD_target_teams_distribute:
  6284. case OMPD_target_teams_distribute_simd:
  6285. case OMPD_target_teams_distribute_parallel_for:
  6286. case OMPD_target_teams_distribute_parallel_for_simd: {
  6287. if (D.hasClausesOfKind<OMPNumTeamsClause>()) {
  6288. CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
  6289. const Expr *NumTeams =
  6290. D.getSingleClause<OMPNumTeamsClause>()->getNumTeams();
  6291. llvm::Value *NumTeamsVal =
  6292. CGF.EmitScalarExpr(NumTeams,
  6293. /*IgnoreResultAssign*/ true);
  6294. return Bld.CreateIntCast(NumTeamsVal, CGF.Int32Ty,
  6295. /*isSigned=*/true);
  6296. }
  6297. return Bld.getInt32(0);
  6298. }
  6299. case OMPD_target_parallel:
  6300. case OMPD_target_parallel_for:
  6301. case OMPD_target_parallel_for_simd:
  6302. case OMPD_target_simd:
  6303. return Bld.getInt32(1);
  6304. case OMPD_parallel:
  6305. case OMPD_for:
  6306. case OMPD_parallel_for:
  6307. case OMPD_parallel_sections:
  6308. case OMPD_for_simd:
  6309. case OMPD_parallel_for_simd:
  6310. case OMPD_cancel:
  6311. case OMPD_cancellation_point:
  6312. case OMPD_ordered:
  6313. case OMPD_threadprivate:
  6314. case OMPD_allocate:
  6315. case OMPD_task:
  6316. case OMPD_simd:
  6317. case OMPD_sections:
  6318. case OMPD_section:
  6319. case OMPD_single:
  6320. case OMPD_master:
  6321. case OMPD_critical:
  6322. case OMPD_taskyield:
  6323. case OMPD_barrier:
  6324. case OMPD_taskwait:
  6325. case OMPD_taskgroup:
  6326. case OMPD_atomic:
  6327. case OMPD_flush:
  6328. case OMPD_teams:
  6329. case OMPD_target_data:
  6330. case OMPD_target_exit_data:
  6331. case OMPD_target_enter_data:
  6332. case OMPD_distribute:
  6333. case OMPD_distribute_simd:
  6334. case OMPD_distribute_parallel_for:
  6335. case OMPD_distribute_parallel_for_simd:
  6336. case OMPD_teams_distribute:
  6337. case OMPD_teams_distribute_simd:
  6338. case OMPD_teams_distribute_parallel_for:
  6339. case OMPD_teams_distribute_parallel_for_simd:
  6340. case OMPD_target_update:
  6341. case OMPD_declare_simd:
  6342. case OMPD_declare_variant:
  6343. case OMPD_declare_target:
  6344. case OMPD_end_declare_target:
  6345. case OMPD_declare_reduction:
  6346. case OMPD_declare_mapper:
  6347. case OMPD_taskloop:
  6348. case OMPD_taskloop_simd:
  6349. case OMPD_master_taskloop:
  6350. case OMPD_master_taskloop_simd:
  6351. case OMPD_parallel_master_taskloop:
  6352. case OMPD_requires:
  6353. case OMPD_unknown:
  6354. break;
  6355. }
  6356. llvm_unreachable("Unexpected directive kind.");
  6357. }
  6358. static llvm::Value *getNumThreads(CodeGenFunction &CGF, const CapturedStmt *CS,
  6359. llvm::Value *DefaultThreadLimitVal) {
  6360. const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
  6361. CGF.getContext(), CS->getCapturedStmt());
  6362. if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
  6363. if (isOpenMPParallelDirective(Dir->getDirectiveKind())) {
  6364. llvm::Value *NumThreads = nullptr;
  6365. llvm::Value *CondVal = nullptr;
  6366. // Handle if clause. If if clause present, the number of threads is
  6367. // calculated as <cond> ? (<numthreads> ? <numthreads> : 0 ) : 1.
  6368. if (Dir->hasClausesOfKind<OMPIfClause>()) {
  6369. CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
  6370. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6371. const OMPIfClause *IfClause = nullptr;
  6372. for (const auto *C : Dir->getClausesOfKind<OMPIfClause>()) {
  6373. if (C->getNameModifier() == OMPD_unknown ||
  6374. C->getNameModifier() == OMPD_parallel) {
  6375. IfClause = C;
  6376. break;
  6377. }
  6378. }
  6379. if (IfClause) {
  6380. const Expr *Cond = IfClause->getCondition();
  6381. bool Result;
  6382. if (Cond->EvaluateAsBooleanCondition(Result, CGF.getContext())) {
  6383. if (!Result)
  6384. return CGF.Builder.getInt32(1);
  6385. } else {
  6386. CodeGenFunction::LexicalScope Scope(CGF, Cond->getSourceRange());
  6387. if (const auto *PreInit =
  6388. cast_or_null<DeclStmt>(IfClause->getPreInitStmt())) {
  6389. for (const auto *I : PreInit->decls()) {
  6390. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  6391. CGF.EmitVarDecl(cast<VarDecl>(*I));
  6392. } else {
  6393. CodeGenFunction::AutoVarEmission Emission =
  6394. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  6395. CGF.EmitAutoVarCleanups(Emission);
  6396. }
  6397. }
  6398. }
  6399. CondVal = CGF.EvaluateExprAsBool(Cond);
  6400. }
  6401. }
  6402. }
  6403. // Check the value of num_threads clause iff if clause was not specified
  6404. // or is not evaluated to false.
  6405. if (Dir->hasClausesOfKind<OMPNumThreadsClause>()) {
  6406. CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
  6407. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6408. const auto *NumThreadsClause =
  6409. Dir->getSingleClause<OMPNumThreadsClause>();
  6410. CodeGenFunction::LexicalScope Scope(
  6411. CGF, NumThreadsClause->getNumThreads()->getSourceRange());
  6412. if (const auto *PreInit =
  6413. cast_or_null<DeclStmt>(NumThreadsClause->getPreInitStmt())) {
  6414. for (const auto *I : PreInit->decls()) {
  6415. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  6416. CGF.EmitVarDecl(cast<VarDecl>(*I));
  6417. } else {
  6418. CodeGenFunction::AutoVarEmission Emission =
  6419. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  6420. CGF.EmitAutoVarCleanups(Emission);
  6421. }
  6422. }
  6423. }
  6424. NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads());
  6425. NumThreads = CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty,
  6426. /*isSigned=*/false);
  6427. if (DefaultThreadLimitVal)
  6428. NumThreads = CGF.Builder.CreateSelect(
  6429. CGF.Builder.CreateICmpULT(DefaultThreadLimitVal, NumThreads),
  6430. DefaultThreadLimitVal, NumThreads);
  6431. } else {
  6432. NumThreads = DefaultThreadLimitVal ? DefaultThreadLimitVal
  6433. : CGF.Builder.getInt32(0);
  6434. }
  6435. // Process condition of the if clause.
  6436. if (CondVal) {
  6437. NumThreads = CGF.Builder.CreateSelect(CondVal, NumThreads,
  6438. CGF.Builder.getInt32(1));
  6439. }
  6440. return NumThreads;
  6441. }
  6442. if (isOpenMPSimdDirective(Dir->getDirectiveKind()))
  6443. return CGF.Builder.getInt32(1);
  6444. return DefaultThreadLimitVal;
  6445. }
  6446. return DefaultThreadLimitVal ? DefaultThreadLimitVal
  6447. : CGF.Builder.getInt32(0);
  6448. }
  6449. /// Emit the number of threads for a target directive. Inspect the
  6450. /// thread_limit clause associated with a teams construct combined or closely
  6451. /// nested with the target directive.
  6452. ///
  6453. /// Emit the num_threads clause for directives such as 'target parallel' that
  6454. /// have no associated teams construct.
  6455. ///
  6456. /// Otherwise, return nullptr.
  6457. static llvm::Value *
  6458. emitNumThreadsForTargetDirective(CodeGenFunction &CGF,
  6459. const OMPExecutableDirective &D) {
  6460. assert(!CGF.getLangOpts().OpenMPIsDevice &&
  6461. "Clauses associated with the teams directive expected to be emitted "
  6462. "only for the host!");
  6463. OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
  6464. assert(isOpenMPTargetExecutionDirective(DirectiveKind) &&
  6465. "Expected target-based executable directive.");
  6466. CGBuilderTy &Bld = CGF.Builder;
  6467. llvm::Value *ThreadLimitVal = nullptr;
  6468. llvm::Value *NumThreadsVal = nullptr;
  6469. switch (DirectiveKind) {
  6470. case OMPD_target: {
  6471. const CapturedStmt *CS = D.getInnermostCapturedStmt();
  6472. if (llvm::Value *NumThreads = getNumThreads(CGF, CS, ThreadLimitVal))
  6473. return NumThreads;
  6474. const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
  6475. CGF.getContext(), CS->getCapturedStmt());
  6476. if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
  6477. if (Dir->hasClausesOfKind<OMPThreadLimitClause>()) {
  6478. CGOpenMPInnerExprInfo CGInfo(CGF, *CS);
  6479. CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
  6480. const auto *ThreadLimitClause =
  6481. Dir->getSingleClause<OMPThreadLimitClause>();
  6482. CodeGenFunction::LexicalScope Scope(
  6483. CGF, ThreadLimitClause->getThreadLimit()->getSourceRange());
  6484. if (const auto *PreInit =
  6485. cast_or_null<DeclStmt>(ThreadLimitClause->getPreInitStmt())) {
  6486. for (const auto *I : PreInit->decls()) {
  6487. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  6488. CGF.EmitVarDecl(cast<VarDecl>(*I));
  6489. } else {
  6490. CodeGenFunction::AutoVarEmission Emission =
  6491. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  6492. CGF.EmitAutoVarCleanups(Emission);
  6493. }
  6494. }
  6495. }
  6496. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(
  6497. ThreadLimitClause->getThreadLimit(), /*IgnoreResultAssign=*/true);
  6498. ThreadLimitVal =
  6499. Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, /*isSigned=*/false);
  6500. }
  6501. if (isOpenMPTeamsDirective(Dir->getDirectiveKind()) &&
  6502. !isOpenMPDistributeDirective(Dir->getDirectiveKind())) {
  6503. CS = Dir->getInnermostCapturedStmt();
  6504. const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
  6505. CGF.getContext(), CS->getCapturedStmt());
  6506. Dir = dyn_cast_or_null<OMPExecutableDirective>(Child);
  6507. }
  6508. if (Dir && isOpenMPDistributeDirective(Dir->getDirectiveKind()) &&
  6509. !isOpenMPSimdDirective(Dir->getDirectiveKind())) {
  6510. CS = Dir->getInnermostCapturedStmt();
  6511. if (llvm::Value *NumThreads = getNumThreads(CGF, CS, ThreadLimitVal))
  6512. return NumThreads;
  6513. }
  6514. if (Dir && isOpenMPSimdDirective(Dir->getDirectiveKind()))
  6515. return Bld.getInt32(1);
  6516. }
  6517. return ThreadLimitVal ? ThreadLimitVal : Bld.getInt32(0);
  6518. }
  6519. case OMPD_target_teams: {
  6520. if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
  6521. CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
  6522. const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
  6523. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(
  6524. ThreadLimitClause->getThreadLimit(), /*IgnoreResultAssign=*/true);
  6525. ThreadLimitVal =
  6526. Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, /*isSigned=*/false);
  6527. }
  6528. const CapturedStmt *CS = D.getInnermostCapturedStmt();
  6529. if (llvm::Value *NumThreads = getNumThreads(CGF, CS, ThreadLimitVal))
  6530. return NumThreads;
  6531. const Stmt *Child = CGOpenMPRuntime::getSingleCompoundChild(
  6532. CGF.getContext(), CS->getCapturedStmt());
  6533. if (const auto *Dir = dyn_cast_or_null<OMPExecutableDirective>(Child)) {
  6534. if (Dir->getDirectiveKind() == OMPD_distribute) {
  6535. CS = Dir->getInnermostCapturedStmt();
  6536. if (llvm::Value *NumThreads = getNumThreads(CGF, CS, ThreadLimitVal))
  6537. return NumThreads;
  6538. }
  6539. }
  6540. return ThreadLimitVal ? ThreadLimitVal : Bld.getInt32(0);
  6541. }
  6542. case OMPD_target_teams_distribute:
  6543. if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
  6544. CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
  6545. const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
  6546. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(
  6547. ThreadLimitClause->getThreadLimit(), /*IgnoreResultAssign=*/true);
  6548. ThreadLimitVal =
  6549. Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, /*isSigned=*/false);
  6550. }
  6551. return getNumThreads(CGF, D.getInnermostCapturedStmt(), ThreadLimitVal);
  6552. case OMPD_target_parallel:
  6553. case OMPD_target_parallel_for:
  6554. case OMPD_target_parallel_for_simd:
  6555. case OMPD_target_teams_distribute_parallel_for:
  6556. case OMPD_target_teams_distribute_parallel_for_simd: {
  6557. llvm::Value *CondVal = nullptr;
  6558. // Handle if clause. If if clause present, the number of threads is
  6559. // calculated as <cond> ? (<numthreads> ? <numthreads> : 0 ) : 1.
  6560. if (D.hasClausesOfKind<OMPIfClause>()) {
  6561. const OMPIfClause *IfClause = nullptr;
  6562. for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
  6563. if (C->getNameModifier() == OMPD_unknown ||
  6564. C->getNameModifier() == OMPD_parallel) {
  6565. IfClause = C;
  6566. break;
  6567. }
  6568. }
  6569. if (IfClause) {
  6570. const Expr *Cond = IfClause->getCondition();
  6571. bool Result;
  6572. if (Cond->EvaluateAsBooleanCondition(Result, CGF.getContext())) {
  6573. if (!Result)
  6574. return Bld.getInt32(1);
  6575. } else {
  6576. CodeGenFunction::RunCleanupsScope Scope(CGF);
  6577. CondVal = CGF.EvaluateExprAsBool(Cond);
  6578. }
  6579. }
  6580. }
  6581. if (D.hasClausesOfKind<OMPThreadLimitClause>()) {
  6582. CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
  6583. const auto *ThreadLimitClause = D.getSingleClause<OMPThreadLimitClause>();
  6584. llvm::Value *ThreadLimit = CGF.EmitScalarExpr(
  6585. ThreadLimitClause->getThreadLimit(), /*IgnoreResultAssign=*/true);
  6586. ThreadLimitVal =
  6587. Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, /*isSigned=*/false);
  6588. }
  6589. if (D.hasClausesOfKind<OMPNumThreadsClause>()) {
  6590. CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
  6591. const auto *NumThreadsClause = D.getSingleClause<OMPNumThreadsClause>();
  6592. llvm::Value *NumThreads = CGF.EmitScalarExpr(
  6593. NumThreadsClause->getNumThreads(), /*IgnoreResultAssign=*/true);
  6594. NumThreadsVal =
  6595. Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned=*/false);
  6596. ThreadLimitVal = ThreadLimitVal
  6597. ? Bld.CreateSelect(Bld.CreateICmpULT(NumThreadsVal,
  6598. ThreadLimitVal),
  6599. NumThreadsVal, ThreadLimitVal)
  6600. : NumThreadsVal;
  6601. }
  6602. if (!ThreadLimitVal)
  6603. ThreadLimitVal = Bld.getInt32(0);
  6604. if (CondVal)
  6605. return Bld.CreateSelect(CondVal, ThreadLimitVal, Bld.getInt32(1));
  6606. return ThreadLimitVal;
  6607. }
  6608. case OMPD_target_teams_distribute_simd:
  6609. case OMPD_target_simd:
  6610. return Bld.getInt32(1);
  6611. case OMPD_parallel:
  6612. case OMPD_for:
  6613. case OMPD_parallel_for:
  6614. case OMPD_parallel_sections:
  6615. case OMPD_for_simd:
  6616. case OMPD_parallel_for_simd:
  6617. case OMPD_cancel:
  6618. case OMPD_cancellation_point:
  6619. case OMPD_ordered:
  6620. case OMPD_threadprivate:
  6621. case OMPD_allocate:
  6622. case OMPD_task:
  6623. case OMPD_simd:
  6624. case OMPD_sections:
  6625. case OMPD_section:
  6626. case OMPD_single:
  6627. case OMPD_master:
  6628. case OMPD_critical:
  6629. case OMPD_taskyield:
  6630. case OMPD_barrier:
  6631. case OMPD_taskwait:
  6632. case OMPD_taskgroup:
  6633. case OMPD_atomic:
  6634. case OMPD_flush:
  6635. case OMPD_teams:
  6636. case OMPD_target_data:
  6637. case OMPD_target_exit_data:
  6638. case OMPD_target_enter_data:
  6639. case OMPD_distribute:
  6640. case OMPD_distribute_simd:
  6641. case OMPD_distribute_parallel_for:
  6642. case OMPD_distribute_parallel_for_simd:
  6643. case OMPD_teams_distribute:
  6644. case OMPD_teams_distribute_simd:
  6645. case OMPD_teams_distribute_parallel_for:
  6646. case OMPD_teams_distribute_parallel_for_simd:
  6647. case OMPD_target_update:
  6648. case OMPD_declare_simd:
  6649. case OMPD_declare_variant:
  6650. case OMPD_declare_target:
  6651. case OMPD_end_declare_target:
  6652. case OMPD_declare_reduction:
  6653. case OMPD_declare_mapper:
  6654. case OMPD_taskloop:
  6655. case OMPD_taskloop_simd:
  6656. case OMPD_master_taskloop:
  6657. case OMPD_master_taskloop_simd:
  6658. case OMPD_parallel_master_taskloop:
  6659. case OMPD_requires:
  6660. case OMPD_unknown:
  6661. break;
  6662. }
  6663. llvm_unreachable("Unsupported directive kind.");
  6664. }
  6665. namespace {
  6666. LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
  6667. // Utility to handle information from clauses associated with a given
  6668. // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
  6669. // It provides a convenient interface to obtain the information and generate
  6670. // code for that information.
  6671. class MappableExprsHandler {
  6672. public:
  6673. /// Values for bit flags used to specify the mapping type for
  6674. /// offloading.
  6675. enum OpenMPOffloadMappingFlags : uint64_t {
  6676. /// No flags
  6677. OMP_MAP_NONE = 0x0,
  6678. /// Allocate memory on the device and move data from host to device.
  6679. OMP_MAP_TO = 0x01,
  6680. /// Allocate memory on the device and move data from device to host.
  6681. OMP_MAP_FROM = 0x02,
  6682. /// Always perform the requested mapping action on the element, even
  6683. /// if it was already mapped before.
  6684. OMP_MAP_ALWAYS = 0x04,
  6685. /// Delete the element from the device environment, ignoring the
  6686. /// current reference count associated with the element.
  6687. OMP_MAP_DELETE = 0x08,
  6688. /// The element being mapped is a pointer-pointee pair; both the
  6689. /// pointer and the pointee should be mapped.
  6690. OMP_MAP_PTR_AND_OBJ = 0x10,
  6691. /// This flags signals that the base address of an entry should be
  6692. /// passed to the target kernel as an argument.
  6693. OMP_MAP_TARGET_PARAM = 0x20,
  6694. /// Signal that the runtime library has to return the device pointer
  6695. /// in the current position for the data being mapped. Used when we have the
  6696. /// use_device_ptr clause.
  6697. OMP_MAP_RETURN_PARAM = 0x40,
  6698. /// This flag signals that the reference being passed is a pointer to
  6699. /// private data.
  6700. OMP_MAP_PRIVATE = 0x80,
  6701. /// Pass the element to the device by value.
  6702. OMP_MAP_LITERAL = 0x100,
  6703. /// Implicit map
  6704. OMP_MAP_IMPLICIT = 0x200,
  6705. /// Close is a hint to the runtime to allocate memory close to
  6706. /// the target device.
  6707. OMP_MAP_CLOSE = 0x400,
  6708. /// The 16 MSBs of the flags indicate whether the entry is member of some
  6709. /// struct/class.
  6710. OMP_MAP_MEMBER_OF = 0xffff000000000000,
  6711. LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
  6712. };
  6713. /// Get the offset of the OMP_MAP_MEMBER_OF field.
  6714. static unsigned getFlagMemberOffset() {
  6715. unsigned Offset = 0;
  6716. for (uint64_t Remain = OMP_MAP_MEMBER_OF; !(Remain & 1);
  6717. Remain = Remain >> 1)
  6718. Offset++;
  6719. return Offset;
  6720. }
  6721. /// Class that associates information with a base pointer to be passed to the
  6722. /// runtime library.
  6723. class BasePointerInfo {
  6724. /// The base pointer.
  6725. llvm::Value *Ptr = nullptr;
  6726. /// The base declaration that refers to this device pointer, or null if
  6727. /// there is none.
  6728. const ValueDecl *DevPtrDecl = nullptr;
  6729. public:
  6730. BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
  6731. : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
  6732. llvm::Value *operator*() const { return Ptr; }
  6733. const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
  6734. void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
  6735. };
  6736. using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
  6737. using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
  6738. using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
  6739. /// Map between a struct and the its lowest & highest elements which have been
  6740. /// mapped.
  6741. /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
  6742. /// HE(FieldIndex, Pointer)}
  6743. struct StructRangeInfoTy {
  6744. std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
  6745. 0, Address::invalid()};
  6746. std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
  6747. 0, Address::invalid()};
  6748. Address Base = Address::invalid();
  6749. };
  6750. private:
  6751. /// Kind that defines how a device pointer has to be returned.
  6752. struct MapInfo {
  6753. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  6754. OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
  6755. ArrayRef<OpenMPMapModifierKind> MapModifiers;
  6756. bool ReturnDevicePointer = false;
  6757. bool IsImplicit = false;
  6758. MapInfo() = default;
  6759. MapInfo(
  6760. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  6761. OpenMPMapClauseKind MapType,
  6762. ArrayRef<OpenMPMapModifierKind> MapModifiers,
  6763. bool ReturnDevicePointer, bool IsImplicit)
  6764. : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
  6765. ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
  6766. };
  6767. /// If use_device_ptr is used on a pointer which is a struct member and there
  6768. /// is no map information about it, then emission of that entry is deferred
  6769. /// until the whole struct has been processed.
  6770. struct DeferredDevicePtrEntryTy {
  6771. const Expr *IE = nullptr;
  6772. const ValueDecl *VD = nullptr;
  6773. DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
  6774. : IE(IE), VD(VD) {}
  6775. };
  6776. /// The target directive from where the mappable clauses were extracted. It
  6777. /// is either a executable directive or a user-defined mapper directive.
  6778. llvm::PointerUnion<const OMPExecutableDirective *,
  6779. const OMPDeclareMapperDecl *>
  6780. CurDir;
  6781. /// Function the directive is being generated for.
  6782. CodeGenFunction &CGF;
  6783. /// Set of all first private variables in the current directive.
  6784. /// bool data is set to true if the variable is implicitly marked as
  6785. /// firstprivate, false otherwise.
  6786. llvm::DenseMap<CanonicalDeclPtr<const VarDecl>, bool> FirstPrivateDecls;
  6787. /// Map between device pointer declarations and their expression components.
  6788. /// The key value for declarations in 'this' is null.
  6789. llvm::DenseMap<
  6790. const ValueDecl *,
  6791. SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
  6792. DevPointersMap;
  6793. llvm::Value *getExprTypeSize(const Expr *E) const {
  6794. QualType ExprTy = E->getType().getCanonicalType();
  6795. // Reference types are ignored for mapping purposes.
  6796. if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
  6797. ExprTy = RefTy->getPointeeType().getCanonicalType();
  6798. // Given that an array section is considered a built-in type, we need to
  6799. // do the calculation based on the length of the section instead of relying
  6800. // on CGF.getTypeSize(E->getType()).
  6801. if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
  6802. QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
  6803. OAE->getBase()->IgnoreParenImpCasts())
  6804. .getCanonicalType();
  6805. // If there is no length associated with the expression and lower bound is
  6806. // not specified too, that means we are using the whole length of the
  6807. // base.
  6808. if (!OAE->getLength() && OAE->getColonLoc().isValid() &&
  6809. !OAE->getLowerBound())
  6810. return CGF.getTypeSize(BaseTy);
  6811. llvm::Value *ElemSize;
  6812. if (const auto *PTy = BaseTy->getAs<PointerType>()) {
  6813. ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
  6814. } else {
  6815. const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
  6816. assert(ATy && "Expecting array type if not a pointer type.");
  6817. ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
  6818. }
  6819. // If we don't have a length at this point, that is because we have an
  6820. // array section with a single element.
  6821. if (!OAE->getLength() && OAE->getColonLoc().isInvalid())
  6822. return ElemSize;
  6823. if (const Expr *LenExpr = OAE->getLength()) {
  6824. llvm::Value *LengthVal = CGF.EmitScalarExpr(LenExpr);
  6825. LengthVal = CGF.EmitScalarConversion(LengthVal, LenExpr->getType(),
  6826. CGF.getContext().getSizeType(),
  6827. LenExpr->getExprLoc());
  6828. return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
  6829. }
  6830. assert(!OAE->getLength() && OAE->getColonLoc().isValid() &&
  6831. OAE->getLowerBound() && "expected array_section[lb:].");
  6832. // Size = sizetype - lb * elemtype;
  6833. llvm::Value *LengthVal = CGF.getTypeSize(BaseTy);
  6834. llvm::Value *LBVal = CGF.EmitScalarExpr(OAE->getLowerBound());
  6835. LBVal = CGF.EmitScalarConversion(LBVal, OAE->getLowerBound()->getType(),
  6836. CGF.getContext().getSizeType(),
  6837. OAE->getLowerBound()->getExprLoc());
  6838. LBVal = CGF.Builder.CreateNUWMul(LBVal, ElemSize);
  6839. llvm::Value *Cmp = CGF.Builder.CreateICmpUGT(LengthVal, LBVal);
  6840. llvm::Value *TrueVal = CGF.Builder.CreateNUWSub(LengthVal, LBVal);
  6841. LengthVal = CGF.Builder.CreateSelect(
  6842. Cmp, TrueVal, llvm::ConstantInt::get(CGF.SizeTy, 0));
  6843. return LengthVal;
  6844. }
  6845. return CGF.getTypeSize(ExprTy);
  6846. }
  6847. /// Return the corresponding bits for a given map clause modifier. Add
  6848. /// a flag marking the map as a pointer if requested. Add a flag marking the
  6849. /// map as the first one of a series of maps that relate to the same map
  6850. /// expression.
  6851. OpenMPOffloadMappingFlags getMapTypeBits(
  6852. OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
  6853. bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
  6854. OpenMPOffloadMappingFlags Bits =
  6855. IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
  6856. switch (MapType) {
  6857. case OMPC_MAP_alloc:
  6858. case OMPC_MAP_release:
  6859. // alloc and release is the default behavior in the runtime library, i.e.
  6860. // if we don't pass any bits alloc/release that is what the runtime is
  6861. // going to do. Therefore, we don't need to signal anything for these two
  6862. // type modifiers.
  6863. break;
  6864. case OMPC_MAP_to:
  6865. Bits |= OMP_MAP_TO;
  6866. break;
  6867. case OMPC_MAP_from:
  6868. Bits |= OMP_MAP_FROM;
  6869. break;
  6870. case OMPC_MAP_tofrom:
  6871. Bits |= OMP_MAP_TO | OMP_MAP_FROM;
  6872. break;
  6873. case OMPC_MAP_delete:
  6874. Bits |= OMP_MAP_DELETE;
  6875. break;
  6876. case OMPC_MAP_unknown:
  6877. llvm_unreachable("Unexpected map type!");
  6878. }
  6879. if (AddPtrFlag)
  6880. Bits |= OMP_MAP_PTR_AND_OBJ;
  6881. if (AddIsTargetParamFlag)
  6882. Bits |= OMP_MAP_TARGET_PARAM;
  6883. if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
  6884. != MapModifiers.end())
  6885. Bits |= OMP_MAP_ALWAYS;
  6886. if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_close)
  6887. != MapModifiers.end())
  6888. Bits |= OMP_MAP_CLOSE;
  6889. return Bits;
  6890. }
  6891. /// Return true if the provided expression is a final array section. A
  6892. /// final array section, is one whose length can't be proved to be one.
  6893. bool isFinalArraySectionExpression(const Expr *E) const {
  6894. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  6895. // It is not an array section and therefore not a unity-size one.
  6896. if (!OASE)
  6897. return false;
  6898. // An array section with no colon always refer to a single element.
  6899. if (OASE->getColonLoc().isInvalid())
  6900. return false;
  6901. const Expr *Length = OASE->getLength();
  6902. // If we don't have a length we have to check if the array has size 1
  6903. // for this dimension. Also, we should always expect a length if the
  6904. // base type is pointer.
  6905. if (!Length) {
  6906. QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
  6907. OASE->getBase()->IgnoreParenImpCasts())
  6908. .getCanonicalType();
  6909. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  6910. return ATy->getSize().getSExtValue() != 1;
  6911. // If we don't have a constant dimension length, we have to consider
  6912. // the current section as having any size, so it is not necessarily
  6913. // unitary. If it happen to be unity size, that's user fault.
  6914. return true;
  6915. }
  6916. // Check if the length evaluates to 1.
  6917. Expr::EvalResult Result;
  6918. if (!Length->EvaluateAsInt(Result, CGF.getContext()))
  6919. return true; // Can have more that size 1.
  6920. llvm::APSInt ConstLength = Result.Val.getInt();
  6921. return ConstLength.getSExtValue() != 1;
  6922. }
  6923. /// Generate the base pointers, section pointers, sizes and map type
  6924. /// bits for the provided map type, map modifier, and expression components.
  6925. /// \a IsFirstComponent should be set to true if the provided set of
  6926. /// components is the first associated with a capture.
  6927. void generateInfoForComponentList(
  6928. OpenMPMapClauseKind MapType,
  6929. ArrayRef<OpenMPMapModifierKind> MapModifiers,
  6930. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  6931. MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
  6932. MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
  6933. StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
  6934. bool IsImplicit,
  6935. ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
  6936. OverlappedElements = llvm::None) const {
  6937. // The following summarizes what has to be generated for each map and the
  6938. // types below. The generated information is expressed in this order:
  6939. // base pointer, section pointer, size, flags
  6940. // (to add to the ones that come from the map type and modifier).
  6941. //
  6942. // double d;
  6943. // int i[100];
  6944. // float *p;
  6945. //
  6946. // struct S1 {
  6947. // int i;
  6948. // float f[50];
  6949. // }
  6950. // struct S2 {
  6951. // int i;
  6952. // float f[50];
  6953. // S1 s;
  6954. // double *p;
  6955. // struct S2 *ps;
  6956. // }
  6957. // S2 s;
  6958. // S2 *ps;
  6959. //
  6960. // map(d)
  6961. // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
  6962. //
  6963. // map(i)
  6964. // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
  6965. //
  6966. // map(i[1:23])
  6967. // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
  6968. //
  6969. // map(p)
  6970. // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
  6971. //
  6972. // map(p[1:24])
  6973. // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
  6974. //
  6975. // map(s)
  6976. // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
  6977. //
  6978. // map(s.i)
  6979. // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
  6980. //
  6981. // map(s.s.f)
  6982. // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
  6983. //
  6984. // map(s.p)
  6985. // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
  6986. //
  6987. // map(to: s.p[:22])
  6988. // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
  6989. // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
  6990. // &(s.p), &(s.p[0]), 22*sizeof(double),
  6991. // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
  6992. // (*) alloc space for struct members, only this is a target parameter
  6993. // (**) map the pointer (nothing to be mapped in this example) (the compiler
  6994. // optimizes this entry out, same in the examples below)
  6995. // (***) map the pointee (map: to)
  6996. //
  6997. // map(s.ps)
  6998. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
  6999. //
  7000. // map(from: s.ps->s.i)
  7001. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  7002. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  7003. // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  7004. //
  7005. // map(to: s.ps->ps)
  7006. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  7007. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  7008. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
  7009. //
  7010. // map(s.ps->ps->ps)
  7011. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  7012. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  7013. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  7014. // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
  7015. //
  7016. // map(to: s.ps->ps->s.f[:22])
  7017. // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
  7018. // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
  7019. // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  7020. // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
  7021. //
  7022. // map(ps)
  7023. // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
  7024. //
  7025. // map(ps->i)
  7026. // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
  7027. //
  7028. // map(ps->s.f)
  7029. // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
  7030. //
  7031. // map(from: ps->p)
  7032. // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
  7033. //
  7034. // map(to: ps->p[:22])
  7035. // ps, &(ps->p), sizeof(double*), TARGET_PARAM
  7036. // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
  7037. // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
  7038. //
  7039. // map(ps->ps)
  7040. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
  7041. //
  7042. // map(from: ps->ps->s.i)
  7043. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  7044. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  7045. // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  7046. //
  7047. // map(from: ps->ps->ps)
  7048. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  7049. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  7050. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  7051. //
  7052. // map(ps->ps->ps->ps)
  7053. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  7054. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  7055. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  7056. // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
  7057. //
  7058. // map(to: ps->ps->ps->s.f[:22])
  7059. // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
  7060. // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
  7061. // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
  7062. // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
  7063. //
  7064. // map(to: s.f[:22]) map(from: s.p[:33])
  7065. // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
  7066. // sizeof(double*) (**), TARGET_PARAM
  7067. // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
  7068. // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
  7069. // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
  7070. // (*) allocate contiguous space needed to fit all mapped members even if
  7071. // we allocate space for members not mapped (in this example,
  7072. // s.f[22..49] and s.s are not mapped, yet we must allocate space for
  7073. // them as well because they fall between &s.f[0] and &s.p)
  7074. //
  7075. // map(from: s.f[:22]) map(to: ps->p[:33])
  7076. // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
  7077. // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
  7078. // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
  7079. // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
  7080. // (*) the struct this entry pertains to is the 2nd element in the list of
  7081. // arguments, hence MEMBER_OF(2)
  7082. //
  7083. // map(from: s.f[:22], s.s) map(to: ps->p[:33])
  7084. // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
  7085. // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
  7086. // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
  7087. // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
  7088. // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
  7089. // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
  7090. // (*) the struct this entry pertains to is the 4th element in the list
  7091. // of arguments, hence MEMBER_OF(4)
  7092. // Track if the map information being generated is the first for a capture.
  7093. bool IsCaptureFirstInfo = IsFirstComponentList;
  7094. // When the variable is on a declare target link or in a to clause with
  7095. // unified memory, a reference is needed to hold the host/device address
  7096. // of the variable.
  7097. bool RequiresReference = false;
  7098. // Scan the components from the base to the complete expression.
  7099. auto CI = Components.rbegin();
  7100. auto CE = Components.rend();
  7101. auto I = CI;
  7102. // Track if the map information being generated is the first for a list of
  7103. // components.
  7104. bool IsExpressionFirstInfo = true;
  7105. Address BP = Address::invalid();
  7106. const Expr *AssocExpr = I->getAssociatedExpression();
  7107. const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
  7108. const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
  7109. if (isa<MemberExpr>(AssocExpr)) {
  7110. // The base is the 'this' pointer. The content of the pointer is going
  7111. // to be the base of the field being mapped.
  7112. BP = CGF.LoadCXXThisAddress();
  7113. } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
  7114. (OASE &&
  7115. isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
  7116. BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
  7117. } else {
  7118. // The base is the reference to the variable.
  7119. // BP = &Var.
  7120. BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
  7121. if (const auto *VD =
  7122. dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
  7123. if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  7124. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  7125. if ((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  7126. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  7127. CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) {
  7128. RequiresReference = true;
  7129. BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  7130. }
  7131. }
  7132. }
  7133. // If the variable is a pointer and is being dereferenced (i.e. is not
  7134. // the last component), the base has to be the pointer itself, not its
  7135. // reference. References are ignored for mapping purposes.
  7136. QualType Ty =
  7137. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  7138. if (Ty->isAnyPointerType() && std::next(I) != CE) {
  7139. BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
  7140. // We do not need to generate individual map information for the
  7141. // pointer, it can be associated with the combined storage.
  7142. ++I;
  7143. }
  7144. }
  7145. // Track whether a component of the list should be marked as MEMBER_OF some
  7146. // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
  7147. // in a component list should be marked as MEMBER_OF, all subsequent entries
  7148. // do not belong to the base struct. E.g.
  7149. // struct S2 s;
  7150. // s.ps->ps->ps->f[:]
  7151. // (1) (2) (3) (4)
  7152. // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
  7153. // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
  7154. // is the pointee of ps(2) which is not member of struct s, so it should not
  7155. // be marked as such (it is still PTR_AND_OBJ).
  7156. // The variable is initialized to false so that PTR_AND_OBJ entries which
  7157. // are not struct members are not considered (e.g. array of pointers to
  7158. // data).
  7159. bool ShouldBeMemberOf = false;
  7160. // Variable keeping track of whether or not we have encountered a component
  7161. // in the component list which is a member expression. Useful when we have a
  7162. // pointer or a final array section, in which case it is the previous
  7163. // component in the list which tells us whether we have a member expression.
  7164. // E.g. X.f[:]
  7165. // While processing the final array section "[:]" it is "f" which tells us
  7166. // whether we are dealing with a member of a declared struct.
  7167. const MemberExpr *EncounteredME = nullptr;
  7168. for (; I != CE; ++I) {
  7169. // If the current component is member of a struct (parent struct) mark it.
  7170. if (!EncounteredME) {
  7171. EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
  7172. // If we encounter a PTR_AND_OBJ entry from now on it should be marked
  7173. // as MEMBER_OF the parent struct.
  7174. if (EncounteredME)
  7175. ShouldBeMemberOf = true;
  7176. }
  7177. auto Next = std::next(I);
  7178. // We need to generate the addresses and sizes if this is the last
  7179. // component, if the component is a pointer or if it is an array section
  7180. // whose length can't be proved to be one. If this is a pointer, it
  7181. // becomes the base address for the following components.
  7182. // A final array section, is one whose length can't be proved to be one.
  7183. bool IsFinalArraySection =
  7184. isFinalArraySectionExpression(I->getAssociatedExpression());
  7185. // Get information on whether the element is a pointer. Have to do a
  7186. // special treatment for array sections given that they are built-in
  7187. // types.
  7188. const auto *OASE =
  7189. dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
  7190. bool IsPointer =
  7191. (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
  7192. .getCanonicalType()
  7193. ->isAnyPointerType()) ||
  7194. I->getAssociatedExpression()->getType()->isAnyPointerType();
  7195. if (Next == CE || IsPointer || IsFinalArraySection) {
  7196. // If this is not the last component, we expect the pointer to be
  7197. // associated with an array expression or member expression.
  7198. assert((Next == CE ||
  7199. isa<MemberExpr>(Next->getAssociatedExpression()) ||
  7200. isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
  7201. isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
  7202. "Unexpected expression");
  7203. Address LB =
  7204. CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
  7205. // If this component is a pointer inside the base struct then we don't
  7206. // need to create any entry for it - it will be combined with the object
  7207. // it is pointing to into a single PTR_AND_OBJ entry.
  7208. bool IsMemberPointer =
  7209. IsPointer && EncounteredME &&
  7210. (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
  7211. EncounteredME);
  7212. if (!OverlappedElements.empty()) {
  7213. // Handle base element with the info for overlapped elements.
  7214. assert(!PartialStruct.Base.isValid() && "The base element is set.");
  7215. assert(Next == CE &&
  7216. "Expected last element for the overlapped elements.");
  7217. assert(!IsPointer &&
  7218. "Unexpected base element with the pointer type.");
  7219. // Mark the whole struct as the struct that requires allocation on the
  7220. // device.
  7221. PartialStruct.LowestElem = {0, LB};
  7222. CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
  7223. I->getAssociatedExpression()->getType());
  7224. Address HB = CGF.Builder.CreateConstGEP(
  7225. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
  7226. CGF.VoidPtrTy),
  7227. TypeSize.getQuantity() - 1);
  7228. PartialStruct.HighestElem = {
  7229. std::numeric_limits<decltype(
  7230. PartialStruct.HighestElem.first)>::max(),
  7231. HB};
  7232. PartialStruct.Base = BP;
  7233. // Emit data for non-overlapped data.
  7234. OpenMPOffloadMappingFlags Flags =
  7235. OMP_MAP_MEMBER_OF |
  7236. getMapTypeBits(MapType, MapModifiers, IsImplicit,
  7237. /*AddPtrFlag=*/false,
  7238. /*AddIsTargetParamFlag=*/false);
  7239. LB = BP;
  7240. llvm::Value *Size = nullptr;
  7241. // Do bitcopy of all non-overlapped structure elements.
  7242. for (OMPClauseMappableExprCommon::MappableExprComponentListRef
  7243. Component : OverlappedElements) {
  7244. Address ComponentLB = Address::invalid();
  7245. for (const OMPClauseMappableExprCommon::MappableComponent &MC :
  7246. Component) {
  7247. if (MC.getAssociatedDeclaration()) {
  7248. ComponentLB =
  7249. CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
  7250. .getAddress();
  7251. Size = CGF.Builder.CreatePtrDiff(
  7252. CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
  7253. CGF.EmitCastToVoidPtr(LB.getPointer()));
  7254. break;
  7255. }
  7256. }
  7257. BasePointers.push_back(BP.getPointer());
  7258. Pointers.push_back(LB.getPointer());
  7259. Sizes.push_back(CGF.Builder.CreateIntCast(Size, CGF.Int64Ty,
  7260. /*isSigned=*/true));
  7261. Types.push_back(Flags);
  7262. LB = CGF.Builder.CreateConstGEP(ComponentLB, 1);
  7263. }
  7264. BasePointers.push_back(BP.getPointer());
  7265. Pointers.push_back(LB.getPointer());
  7266. Size = CGF.Builder.CreatePtrDiff(
  7267. CGF.EmitCastToVoidPtr(
  7268. CGF.Builder.CreateConstGEP(HB, 1).getPointer()),
  7269. CGF.EmitCastToVoidPtr(LB.getPointer()));
  7270. Sizes.push_back(
  7271. CGF.Builder.CreateIntCast(Size, CGF.Int64Ty, /*isSigned=*/true));
  7272. Types.push_back(Flags);
  7273. break;
  7274. }
  7275. llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
  7276. if (!IsMemberPointer) {
  7277. BasePointers.push_back(BP.getPointer());
  7278. Pointers.push_back(LB.getPointer());
  7279. Sizes.push_back(
  7280. CGF.Builder.CreateIntCast(Size, CGF.Int64Ty, /*isSigned=*/true));
  7281. // We need to add a pointer flag for each map that comes from the
  7282. // same expression except for the first one. We also need to signal
  7283. // this map is the first one that relates with the current capture
  7284. // (there is a set of entries for each capture).
  7285. OpenMPOffloadMappingFlags Flags = getMapTypeBits(
  7286. MapType, MapModifiers, IsImplicit,
  7287. !IsExpressionFirstInfo || RequiresReference,
  7288. IsCaptureFirstInfo && !RequiresReference);
  7289. if (!IsExpressionFirstInfo) {
  7290. // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
  7291. // then we reset the TO/FROM/ALWAYS/DELETE/CLOSE flags.
  7292. if (IsPointer)
  7293. Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
  7294. OMP_MAP_DELETE | OMP_MAP_CLOSE);
  7295. if (ShouldBeMemberOf) {
  7296. // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
  7297. // should be later updated with the correct value of MEMBER_OF.
  7298. Flags |= OMP_MAP_MEMBER_OF;
  7299. // From now on, all subsequent PTR_AND_OBJ entries should not be
  7300. // marked as MEMBER_OF.
  7301. ShouldBeMemberOf = false;
  7302. }
  7303. }
  7304. Types.push_back(Flags);
  7305. }
  7306. // If we have encountered a member expression so far, keep track of the
  7307. // mapped member. If the parent is "*this", then the value declaration
  7308. // is nullptr.
  7309. if (EncounteredME) {
  7310. const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
  7311. unsigned FieldIndex = FD->getFieldIndex();
  7312. // Update info about the lowest and highest elements for this struct
  7313. if (!PartialStruct.Base.isValid()) {
  7314. PartialStruct.LowestElem = {FieldIndex, LB};
  7315. PartialStruct.HighestElem = {FieldIndex, LB};
  7316. PartialStruct.Base = BP;
  7317. } else if (FieldIndex < PartialStruct.LowestElem.first) {
  7318. PartialStruct.LowestElem = {FieldIndex, LB};
  7319. } else if (FieldIndex > PartialStruct.HighestElem.first) {
  7320. PartialStruct.HighestElem = {FieldIndex, LB};
  7321. }
  7322. }
  7323. // If we have a final array section, we are done with this expression.
  7324. if (IsFinalArraySection)
  7325. break;
  7326. // The pointer becomes the base for the next element.
  7327. if (Next != CE)
  7328. BP = LB;
  7329. IsExpressionFirstInfo = false;
  7330. IsCaptureFirstInfo = false;
  7331. }
  7332. }
  7333. }
  7334. /// Return the adjusted map modifiers if the declaration a capture refers to
  7335. /// appears in a first-private clause. This is expected to be used only with
  7336. /// directives that start with 'target'.
  7337. MappableExprsHandler::OpenMPOffloadMappingFlags
  7338. getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
  7339. assert(Cap.capturesVariable() && "Expected capture by reference only!");
  7340. // A first private variable captured by reference will use only the
  7341. // 'private ptr' and 'map to' flag. Return the right flags if the captured
  7342. // declaration is known as first-private in this handler.
  7343. if (FirstPrivateDecls.count(Cap.getCapturedVar())) {
  7344. if (Cap.getCapturedVar()->getType().isConstant(CGF.getContext()) &&
  7345. Cap.getCaptureKind() == CapturedStmt::VCK_ByRef)
  7346. return MappableExprsHandler::OMP_MAP_ALWAYS |
  7347. MappableExprsHandler::OMP_MAP_TO;
  7348. if (Cap.getCapturedVar()->getType()->isAnyPointerType())
  7349. return MappableExprsHandler::OMP_MAP_TO |
  7350. MappableExprsHandler::OMP_MAP_PTR_AND_OBJ;
  7351. return MappableExprsHandler::OMP_MAP_PRIVATE |
  7352. MappableExprsHandler::OMP_MAP_TO;
  7353. }
  7354. return MappableExprsHandler::OMP_MAP_TO |
  7355. MappableExprsHandler::OMP_MAP_FROM;
  7356. }
  7357. static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
  7358. // Rotate by getFlagMemberOffset() bits.
  7359. return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
  7360. << getFlagMemberOffset());
  7361. }
  7362. static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
  7363. OpenMPOffloadMappingFlags MemberOfFlag) {
  7364. // If the entry is PTR_AND_OBJ but has not been marked with the special
  7365. // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
  7366. // marked as MEMBER_OF.
  7367. if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
  7368. ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
  7369. return;
  7370. // Reset the placeholder value to prepare the flag for the assignment of the
  7371. // proper MEMBER_OF value.
  7372. Flags &= ~OMP_MAP_MEMBER_OF;
  7373. Flags |= MemberOfFlag;
  7374. }
  7375. void getPlainLayout(const CXXRecordDecl *RD,
  7376. llvm::SmallVectorImpl<const FieldDecl *> &Layout,
  7377. bool AsBase) const {
  7378. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  7379. llvm::StructType *St =
  7380. AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
  7381. unsigned NumElements = St->getNumElements();
  7382. llvm::SmallVector<
  7383. llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
  7384. RecordLayout(NumElements);
  7385. // Fill bases.
  7386. for (const auto &I : RD->bases()) {
  7387. if (I.isVirtual())
  7388. continue;
  7389. const auto *Base = I.getType()->getAsCXXRecordDecl();
  7390. // Ignore empty bases.
  7391. if (Base->isEmpty() || CGF.getContext()
  7392. .getASTRecordLayout(Base)
  7393. .getNonVirtualSize()
  7394. .isZero())
  7395. continue;
  7396. unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
  7397. RecordLayout[FieldIndex] = Base;
  7398. }
  7399. // Fill in virtual bases.
  7400. for (const auto &I : RD->vbases()) {
  7401. const auto *Base = I.getType()->getAsCXXRecordDecl();
  7402. // Ignore empty bases.
  7403. if (Base->isEmpty())
  7404. continue;
  7405. unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
  7406. if (RecordLayout[FieldIndex])
  7407. continue;
  7408. RecordLayout[FieldIndex] = Base;
  7409. }
  7410. // Fill in all the fields.
  7411. assert(!RD->isUnion() && "Unexpected union.");
  7412. for (const auto *Field : RD->fields()) {
  7413. // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
  7414. // will fill in later.)
  7415. if (!Field->isBitField() && !Field->isZeroSize(CGF.getContext())) {
  7416. unsigned FieldIndex = RL.getLLVMFieldNo(Field);
  7417. RecordLayout[FieldIndex] = Field;
  7418. }
  7419. }
  7420. for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
  7421. &Data : RecordLayout) {
  7422. if (Data.isNull())
  7423. continue;
  7424. if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
  7425. getPlainLayout(Base, Layout, /*AsBase=*/true);
  7426. else
  7427. Layout.push_back(Data.get<const FieldDecl *>());
  7428. }
  7429. }
  7430. public:
  7431. MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
  7432. : CurDir(&Dir), CGF(CGF) {
  7433. // Extract firstprivate clause information.
  7434. for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
  7435. for (const auto *D : C->varlists())
  7436. FirstPrivateDecls.try_emplace(
  7437. cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl()), C->isImplicit());
  7438. // Extract device pointer clause information.
  7439. for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
  7440. for (auto L : C->component_lists())
  7441. DevPointersMap[L.first].push_back(L.second);
  7442. }
  7443. /// Constructor for the declare mapper directive.
  7444. MappableExprsHandler(const OMPDeclareMapperDecl &Dir, CodeGenFunction &CGF)
  7445. : CurDir(&Dir), CGF(CGF) {}
  7446. /// Generate code for the combined entry if we have a partially mapped struct
  7447. /// and take care of the mapping flags of the arguments corresponding to
  7448. /// individual struct members.
  7449. void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
  7450. MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
  7451. MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
  7452. const StructRangeInfoTy &PartialStruct) const {
  7453. // Base is the base of the struct
  7454. BasePointers.push_back(PartialStruct.Base.getPointer());
  7455. // Pointer is the address of the lowest element
  7456. llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
  7457. Pointers.push_back(LB);
  7458. // Size is (addr of {highest+1} element) - (addr of lowest element)
  7459. llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
  7460. llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
  7461. llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
  7462. llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
  7463. llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
  7464. llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.Int64Ty,
  7465. /*isSigned=*/false);
  7466. Sizes.push_back(Size);
  7467. // Map type is always TARGET_PARAM
  7468. Types.push_back(OMP_MAP_TARGET_PARAM);
  7469. // Remove TARGET_PARAM flag from the first element
  7470. (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
  7471. // All other current entries will be MEMBER_OF the combined entry
  7472. // (except for PTR_AND_OBJ entries which do not have a placeholder value
  7473. // 0xFFFF in the MEMBER_OF field).
  7474. OpenMPOffloadMappingFlags MemberOfFlag =
  7475. getMemberOfFlag(BasePointers.size() - 1);
  7476. for (auto &M : CurTypes)
  7477. setCorrectMemberOfFlag(M, MemberOfFlag);
  7478. }
  7479. /// Generate all the base pointers, section pointers, sizes and map
  7480. /// types for the extracted mappable expressions. Also, for each item that
  7481. /// relates with a device pointer, a pair of the relevant declaration and
  7482. /// index where it occurs is appended to the device pointers info array.
  7483. void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
  7484. MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
  7485. MapFlagsArrayTy &Types) const {
  7486. // We have to process the component lists that relate with the same
  7487. // declaration in a single chunk so that we can generate the map flags
  7488. // correctly. Therefore, we organize all lists in a map.
  7489. llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
  7490. // Helper function to fill the information map for the different supported
  7491. // clauses.
  7492. auto &&InfoGen = [&Info](
  7493. const ValueDecl *D,
  7494. OMPClauseMappableExprCommon::MappableExprComponentListRef L,
  7495. OpenMPMapClauseKind MapType,
  7496. ArrayRef<OpenMPMapModifierKind> MapModifiers,
  7497. bool ReturnDevicePointer, bool IsImplicit) {
  7498. const ValueDecl *VD =
  7499. D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
  7500. Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
  7501. IsImplicit);
  7502. };
  7503. assert(CurDir.is<const OMPExecutableDirective *>() &&
  7504. "Expect a executable directive");
  7505. const auto *CurExecDir = CurDir.get<const OMPExecutableDirective *>();
  7506. for (const auto *C : CurExecDir->getClausesOfKind<OMPMapClause>())
  7507. for (const auto &L : C->component_lists()) {
  7508. InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
  7509. /*ReturnDevicePointer=*/false, C->isImplicit());
  7510. }
  7511. for (const auto *C : CurExecDir->getClausesOfKind<OMPToClause>())
  7512. for (const auto &L : C->component_lists()) {
  7513. InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
  7514. /*ReturnDevicePointer=*/false, C->isImplicit());
  7515. }
  7516. for (const auto *C : CurExecDir->getClausesOfKind<OMPFromClause>())
  7517. for (const auto &L : C->component_lists()) {
  7518. InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
  7519. /*ReturnDevicePointer=*/false, C->isImplicit());
  7520. }
  7521. // Look at the use_device_ptr clause information and mark the existing map
  7522. // entries as such. If there is no map information for an entry in the
  7523. // use_device_ptr list, we create one with map type 'alloc' and zero size
  7524. // section. It is the user fault if that was not mapped before. If there is
  7525. // no map information and the pointer is a struct member, then we defer the
  7526. // emission of that entry until the whole struct has been processed.
  7527. llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
  7528. DeferredInfo;
  7529. for (const auto *C :
  7530. CurExecDir->getClausesOfKind<OMPUseDevicePtrClause>()) {
  7531. for (const auto &L : C->component_lists()) {
  7532. assert(!L.second.empty() && "Not expecting empty list of components!");
  7533. const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
  7534. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  7535. const Expr *IE = L.second.back().getAssociatedExpression();
  7536. // If the first component is a member expression, we have to look into
  7537. // 'this', which maps to null in the map of map information. Otherwise
  7538. // look directly for the information.
  7539. auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
  7540. // We potentially have map information for this declaration already.
  7541. // Look for the first set of components that refer to it.
  7542. if (It != Info.end()) {
  7543. auto CI = std::find_if(
  7544. It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
  7545. return MI.Components.back().getAssociatedDeclaration() == VD;
  7546. });
  7547. // If we found a map entry, signal that the pointer has to be returned
  7548. // and move on to the next declaration.
  7549. if (CI != It->second.end()) {
  7550. CI->ReturnDevicePointer = true;
  7551. continue;
  7552. }
  7553. }
  7554. // We didn't find any match in our map information - generate a zero
  7555. // size array section - if the pointer is a struct member we defer this
  7556. // action until the whole struct has been processed.
  7557. if (isa<MemberExpr>(IE)) {
  7558. // Insert the pointer into Info to be processed by
  7559. // generateInfoForComponentList. Because it is a member pointer
  7560. // without a pointee, no entry will be generated for it, therefore
  7561. // we need to generate one after the whole struct has been processed.
  7562. // Nonetheless, generateInfoForComponentList must be called to take
  7563. // the pointer into account for the calculation of the range of the
  7564. // partial struct.
  7565. InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
  7566. /*ReturnDevicePointer=*/false, C->isImplicit());
  7567. DeferredInfo[nullptr].emplace_back(IE, VD);
  7568. } else {
  7569. llvm::Value *Ptr =
  7570. CGF.EmitLoadOfScalar(CGF.EmitLValue(IE), IE->getExprLoc());
  7571. BasePointers.emplace_back(Ptr, VD);
  7572. Pointers.push_back(Ptr);
  7573. Sizes.push_back(llvm::Constant::getNullValue(CGF.Int64Ty));
  7574. Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
  7575. }
  7576. }
  7577. }
  7578. for (const auto &M : Info) {
  7579. // We need to know when we generate information for the first component
  7580. // associated with a capture, because the mapping flags depend on it.
  7581. bool IsFirstComponentList = true;
  7582. // Temporary versions of arrays
  7583. MapBaseValuesArrayTy CurBasePointers;
  7584. MapValuesArrayTy CurPointers;
  7585. MapValuesArrayTy CurSizes;
  7586. MapFlagsArrayTy CurTypes;
  7587. StructRangeInfoTy PartialStruct;
  7588. for (const MapInfo &L : M.second) {
  7589. assert(!L.Components.empty() &&
  7590. "Not expecting declaration with no component lists.");
  7591. // Remember the current base pointer index.
  7592. unsigned CurrentBasePointersIdx = CurBasePointers.size();
  7593. generateInfoForComponentList(L.MapType, L.MapModifiers, L.Components,
  7594. CurBasePointers, CurPointers, CurSizes,
  7595. CurTypes, PartialStruct,
  7596. IsFirstComponentList, L.IsImplicit);
  7597. // If this entry relates with a device pointer, set the relevant
  7598. // declaration and add the 'return pointer' flag.
  7599. if (L.ReturnDevicePointer) {
  7600. assert(CurBasePointers.size() > CurrentBasePointersIdx &&
  7601. "Unexpected number of mapped base pointers.");
  7602. const ValueDecl *RelevantVD =
  7603. L.Components.back().getAssociatedDeclaration();
  7604. assert(RelevantVD &&
  7605. "No relevant declaration related with device pointer??");
  7606. CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
  7607. CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
  7608. }
  7609. IsFirstComponentList = false;
  7610. }
  7611. // Append any pending zero-length pointers which are struct members and
  7612. // used with use_device_ptr.
  7613. auto CI = DeferredInfo.find(M.first);
  7614. if (CI != DeferredInfo.end()) {
  7615. for (const DeferredDevicePtrEntryTy &L : CI->second) {
  7616. llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
  7617. llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
  7618. this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
  7619. CurBasePointers.emplace_back(BasePtr, L.VD);
  7620. CurPointers.push_back(Ptr);
  7621. CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.Int64Ty));
  7622. // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
  7623. // value MEMBER_OF=FFFF so that the entry is later updated with the
  7624. // correct value of MEMBER_OF.
  7625. CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
  7626. OMP_MAP_MEMBER_OF);
  7627. }
  7628. }
  7629. // If there is an entry in PartialStruct it means we have a struct with
  7630. // individual members mapped. Emit an extra combined entry.
  7631. if (PartialStruct.Base.isValid())
  7632. emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
  7633. PartialStruct);
  7634. // We need to append the results of this capture to what we already have.
  7635. BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
  7636. Pointers.append(CurPointers.begin(), CurPointers.end());
  7637. Sizes.append(CurSizes.begin(), CurSizes.end());
  7638. Types.append(CurTypes.begin(), CurTypes.end());
  7639. }
  7640. }
  7641. /// Generate all the base pointers, section pointers, sizes and map types for
  7642. /// the extracted map clauses of user-defined mapper.
  7643. void generateAllInfoForMapper(MapBaseValuesArrayTy &BasePointers,
  7644. MapValuesArrayTy &Pointers,
  7645. MapValuesArrayTy &Sizes,
  7646. MapFlagsArrayTy &Types) const {
  7647. assert(CurDir.is<const OMPDeclareMapperDecl *>() &&
  7648. "Expect a declare mapper directive");
  7649. const auto *CurMapperDir = CurDir.get<const OMPDeclareMapperDecl *>();
  7650. // We have to process the component lists that relate with the same
  7651. // declaration in a single chunk so that we can generate the map flags
  7652. // correctly. Therefore, we organize all lists in a map.
  7653. llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
  7654. // Helper function to fill the information map for the different supported
  7655. // clauses.
  7656. auto &&InfoGen = [&Info](
  7657. const ValueDecl *D,
  7658. OMPClauseMappableExprCommon::MappableExprComponentListRef L,
  7659. OpenMPMapClauseKind MapType,
  7660. ArrayRef<OpenMPMapModifierKind> MapModifiers,
  7661. bool ReturnDevicePointer, bool IsImplicit) {
  7662. const ValueDecl *VD =
  7663. D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
  7664. Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
  7665. IsImplicit);
  7666. };
  7667. for (const auto *C : CurMapperDir->clauselists()) {
  7668. const auto *MC = cast<OMPMapClause>(C);
  7669. for (const auto &L : MC->component_lists()) {
  7670. InfoGen(L.first, L.second, MC->getMapType(), MC->getMapTypeModifiers(),
  7671. /*ReturnDevicePointer=*/false, MC->isImplicit());
  7672. }
  7673. }
  7674. for (const auto &M : Info) {
  7675. // We need to know when we generate information for the first component
  7676. // associated with a capture, because the mapping flags depend on it.
  7677. bool IsFirstComponentList = true;
  7678. // Temporary versions of arrays
  7679. MapBaseValuesArrayTy CurBasePointers;
  7680. MapValuesArrayTy CurPointers;
  7681. MapValuesArrayTy CurSizes;
  7682. MapFlagsArrayTy CurTypes;
  7683. StructRangeInfoTy PartialStruct;
  7684. for (const MapInfo &L : M.second) {
  7685. assert(!L.Components.empty() &&
  7686. "Not expecting declaration with no component lists.");
  7687. generateInfoForComponentList(L.MapType, L.MapModifiers, L.Components,
  7688. CurBasePointers, CurPointers, CurSizes,
  7689. CurTypes, PartialStruct,
  7690. IsFirstComponentList, L.IsImplicit);
  7691. IsFirstComponentList = false;
  7692. }
  7693. // If there is an entry in PartialStruct it means we have a struct with
  7694. // individual members mapped. Emit an extra combined entry.
  7695. if (PartialStruct.Base.isValid())
  7696. emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
  7697. PartialStruct);
  7698. // We need to append the results of this capture to what we already have.
  7699. BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
  7700. Pointers.append(CurPointers.begin(), CurPointers.end());
  7701. Sizes.append(CurSizes.begin(), CurSizes.end());
  7702. Types.append(CurTypes.begin(), CurTypes.end());
  7703. }
  7704. }
  7705. /// Emit capture info for lambdas for variables captured by reference.
  7706. void generateInfoForLambdaCaptures(
  7707. const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
  7708. MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
  7709. MapFlagsArrayTy &Types,
  7710. llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
  7711. const auto *RD = VD->getType()
  7712. .getCanonicalType()
  7713. .getNonReferenceType()
  7714. ->getAsCXXRecordDecl();
  7715. if (!RD || !RD->isLambda())
  7716. return;
  7717. Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
  7718. LValue VDLVal = CGF.MakeAddrLValue(
  7719. VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
  7720. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  7721. FieldDecl *ThisCapture = nullptr;
  7722. RD->getCaptureFields(Captures, ThisCapture);
  7723. if (ThisCapture) {
  7724. LValue ThisLVal =
  7725. CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
  7726. LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
  7727. LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
  7728. BasePointers.push_back(ThisLVal.getPointer());
  7729. Pointers.push_back(ThisLValVal.getPointer());
  7730. Sizes.push_back(
  7731. CGF.Builder.CreateIntCast(CGF.getTypeSize(CGF.getContext().VoidPtrTy),
  7732. CGF.Int64Ty, /*isSigned=*/true));
  7733. Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
  7734. OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
  7735. }
  7736. for (const LambdaCapture &LC : RD->captures()) {
  7737. if (!LC.capturesVariable())
  7738. continue;
  7739. const VarDecl *VD = LC.getCapturedVar();
  7740. if (LC.getCaptureKind() != LCK_ByRef && !VD->getType()->isPointerType())
  7741. continue;
  7742. auto It = Captures.find(VD);
  7743. assert(It != Captures.end() && "Found lambda capture without field.");
  7744. LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
  7745. if (LC.getCaptureKind() == LCK_ByRef) {
  7746. LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
  7747. LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
  7748. BasePointers.push_back(VarLVal.getPointer());
  7749. Pointers.push_back(VarLValVal.getPointer());
  7750. Sizes.push_back(CGF.Builder.CreateIntCast(
  7751. CGF.getTypeSize(
  7752. VD->getType().getCanonicalType().getNonReferenceType()),
  7753. CGF.Int64Ty, /*isSigned=*/true));
  7754. } else {
  7755. RValue VarRVal = CGF.EmitLoadOfLValue(VarLVal, RD->getLocation());
  7756. LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
  7757. BasePointers.push_back(VarLVal.getPointer());
  7758. Pointers.push_back(VarRVal.getScalarVal());
  7759. Sizes.push_back(llvm::ConstantInt::get(CGF.Int64Ty, 0));
  7760. }
  7761. Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
  7762. OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
  7763. }
  7764. }
  7765. /// Set correct indices for lambdas captures.
  7766. void adjustMemberOfForLambdaCaptures(
  7767. const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
  7768. MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
  7769. MapFlagsArrayTy &Types) const {
  7770. for (unsigned I = 0, E = Types.size(); I < E; ++I) {
  7771. // Set correct member_of idx for all implicit lambda captures.
  7772. if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
  7773. OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
  7774. continue;
  7775. llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
  7776. assert(BasePtr && "Unable to find base lambda address.");
  7777. int TgtIdx = -1;
  7778. for (unsigned J = I; J > 0; --J) {
  7779. unsigned Idx = J - 1;
  7780. if (Pointers[Idx] != BasePtr)
  7781. continue;
  7782. TgtIdx = Idx;
  7783. break;
  7784. }
  7785. assert(TgtIdx != -1 && "Unable to find parent lambda.");
  7786. // All other current entries will be MEMBER_OF the combined entry
  7787. // (except for PTR_AND_OBJ entries which do not have a placeholder value
  7788. // 0xFFFF in the MEMBER_OF field).
  7789. OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
  7790. setCorrectMemberOfFlag(Types[I], MemberOfFlag);
  7791. }
  7792. }
  7793. /// Generate the base pointers, section pointers, sizes and map types
  7794. /// associated to a given capture.
  7795. void generateInfoForCapture(const CapturedStmt::Capture *Cap,
  7796. llvm::Value *Arg,
  7797. MapBaseValuesArrayTy &BasePointers,
  7798. MapValuesArrayTy &Pointers,
  7799. MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
  7800. StructRangeInfoTy &PartialStruct) const {
  7801. assert(!Cap->capturesVariableArrayType() &&
  7802. "Not expecting to generate map info for a variable array type!");
  7803. // We need to know when we generating information for the first component
  7804. const ValueDecl *VD = Cap->capturesThis()
  7805. ? nullptr
  7806. : Cap->getCapturedVar()->getCanonicalDecl();
  7807. // If this declaration appears in a is_device_ptr clause we just have to
  7808. // pass the pointer by value. If it is a reference to a declaration, we just
  7809. // pass its value.
  7810. if (DevPointersMap.count(VD)) {
  7811. BasePointers.emplace_back(Arg, VD);
  7812. Pointers.push_back(Arg);
  7813. Sizes.push_back(
  7814. CGF.Builder.CreateIntCast(CGF.getTypeSize(CGF.getContext().VoidPtrTy),
  7815. CGF.Int64Ty, /*isSigned=*/true));
  7816. Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
  7817. return;
  7818. }
  7819. using MapData =
  7820. std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
  7821. OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
  7822. SmallVector<MapData, 4> DeclComponentLists;
  7823. assert(CurDir.is<const OMPExecutableDirective *>() &&
  7824. "Expect a executable directive");
  7825. const auto *CurExecDir = CurDir.get<const OMPExecutableDirective *>();
  7826. for (const auto *C : CurExecDir->getClausesOfKind<OMPMapClause>()) {
  7827. for (const auto &L : C->decl_component_lists(VD)) {
  7828. assert(L.first == VD &&
  7829. "We got information for the wrong declaration??");
  7830. assert(!L.second.empty() &&
  7831. "Not expecting declaration with no component lists.");
  7832. DeclComponentLists.emplace_back(L.second, C->getMapType(),
  7833. C->getMapTypeModifiers(),
  7834. C->isImplicit());
  7835. }
  7836. }
  7837. // Find overlapping elements (including the offset from the base element).
  7838. llvm::SmallDenseMap<
  7839. const MapData *,
  7840. llvm::SmallVector<
  7841. OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
  7842. 4>
  7843. OverlappedData;
  7844. size_t Count = 0;
  7845. for (const MapData &L : DeclComponentLists) {
  7846. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7847. OpenMPMapClauseKind MapType;
  7848. ArrayRef<OpenMPMapModifierKind> MapModifiers;
  7849. bool IsImplicit;
  7850. std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
  7851. ++Count;
  7852. for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
  7853. OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
  7854. std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
  7855. auto CI = Components.rbegin();
  7856. auto CE = Components.rend();
  7857. auto SI = Components1.rbegin();
  7858. auto SE = Components1.rend();
  7859. for (; CI != CE && SI != SE; ++CI, ++SI) {
  7860. if (CI->getAssociatedExpression()->getStmtClass() !=
  7861. SI->getAssociatedExpression()->getStmtClass())
  7862. break;
  7863. // Are we dealing with different variables/fields?
  7864. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  7865. break;
  7866. }
  7867. // Found overlapping if, at least for one component, reached the head of
  7868. // the components list.
  7869. if (CI == CE || SI == SE) {
  7870. assert((CI != CE || SI != SE) &&
  7871. "Unexpected full match of the mapping components.");
  7872. const MapData &BaseData = CI == CE ? L : L1;
  7873. OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
  7874. SI == SE ? Components : Components1;
  7875. auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
  7876. OverlappedElements.getSecond().push_back(SubData);
  7877. }
  7878. }
  7879. }
  7880. // Sort the overlapped elements for each item.
  7881. llvm::SmallVector<const FieldDecl *, 4> Layout;
  7882. if (!OverlappedData.empty()) {
  7883. if (const auto *CRD =
  7884. VD->getType().getCanonicalType()->getAsCXXRecordDecl())
  7885. getPlainLayout(CRD, Layout, /*AsBase=*/false);
  7886. else {
  7887. const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
  7888. Layout.append(RD->field_begin(), RD->field_end());
  7889. }
  7890. }
  7891. for (auto &Pair : OverlappedData) {
  7892. llvm::sort(
  7893. Pair.getSecond(),
  7894. [&Layout](
  7895. OMPClauseMappableExprCommon::MappableExprComponentListRef First,
  7896. OMPClauseMappableExprCommon::MappableExprComponentListRef
  7897. Second) {
  7898. auto CI = First.rbegin();
  7899. auto CE = First.rend();
  7900. auto SI = Second.rbegin();
  7901. auto SE = Second.rend();
  7902. for (; CI != CE && SI != SE; ++CI, ++SI) {
  7903. if (CI->getAssociatedExpression()->getStmtClass() !=
  7904. SI->getAssociatedExpression()->getStmtClass())
  7905. break;
  7906. // Are we dealing with different variables/fields?
  7907. if (CI->getAssociatedDeclaration() !=
  7908. SI->getAssociatedDeclaration())
  7909. break;
  7910. }
  7911. // Lists contain the same elements.
  7912. if (CI == CE && SI == SE)
  7913. return false;
  7914. // List with less elements is less than list with more elements.
  7915. if (CI == CE || SI == SE)
  7916. return CI == CE;
  7917. const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
  7918. const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
  7919. if (FD1->getParent() == FD2->getParent())
  7920. return FD1->getFieldIndex() < FD2->getFieldIndex();
  7921. const auto It =
  7922. llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
  7923. return FD == FD1 || FD == FD2;
  7924. });
  7925. return *It == FD1;
  7926. });
  7927. }
  7928. // Associated with a capture, because the mapping flags depend on it.
  7929. // Go through all of the elements with the overlapped elements.
  7930. for (const auto &Pair : OverlappedData) {
  7931. const MapData &L = *Pair.getFirst();
  7932. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7933. OpenMPMapClauseKind MapType;
  7934. ArrayRef<OpenMPMapModifierKind> MapModifiers;
  7935. bool IsImplicit;
  7936. std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
  7937. ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
  7938. OverlappedComponents = Pair.getSecond();
  7939. bool IsFirstComponentList = true;
  7940. generateInfoForComponentList(MapType, MapModifiers, Components,
  7941. BasePointers, Pointers, Sizes, Types,
  7942. PartialStruct, IsFirstComponentList,
  7943. IsImplicit, OverlappedComponents);
  7944. }
  7945. // Go through other elements without overlapped elements.
  7946. bool IsFirstComponentList = OverlappedData.empty();
  7947. for (const MapData &L : DeclComponentLists) {
  7948. OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
  7949. OpenMPMapClauseKind MapType;
  7950. ArrayRef<OpenMPMapModifierKind> MapModifiers;
  7951. bool IsImplicit;
  7952. std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
  7953. auto It = OverlappedData.find(&L);
  7954. if (It == OverlappedData.end())
  7955. generateInfoForComponentList(MapType, MapModifiers, Components,
  7956. BasePointers, Pointers, Sizes, Types,
  7957. PartialStruct, IsFirstComponentList,
  7958. IsImplicit);
  7959. IsFirstComponentList = false;
  7960. }
  7961. }
  7962. /// Generate the base pointers, section pointers, sizes and map types
  7963. /// associated with the declare target link variables.
  7964. void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
  7965. MapValuesArrayTy &Pointers,
  7966. MapValuesArrayTy &Sizes,
  7967. MapFlagsArrayTy &Types) const {
  7968. assert(CurDir.is<const OMPExecutableDirective *>() &&
  7969. "Expect a executable directive");
  7970. const auto *CurExecDir = CurDir.get<const OMPExecutableDirective *>();
  7971. // Map other list items in the map clause which are not captured variables
  7972. // but "declare target link" global variables.
  7973. for (const auto *C : CurExecDir->getClausesOfKind<OMPMapClause>()) {
  7974. for (const auto &L : C->component_lists()) {
  7975. if (!L.first)
  7976. continue;
  7977. const auto *VD = dyn_cast<VarDecl>(L.first);
  7978. if (!VD)
  7979. continue;
  7980. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  7981. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  7982. if (CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory() ||
  7983. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
  7984. continue;
  7985. StructRangeInfoTy PartialStruct;
  7986. generateInfoForComponentList(
  7987. C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
  7988. Pointers, Sizes, Types, PartialStruct,
  7989. /*IsFirstComponentList=*/true, C->isImplicit());
  7990. assert(!PartialStruct.Base.isValid() &&
  7991. "No partial structs for declare target link expected.");
  7992. }
  7993. }
  7994. }
  7995. /// Generate the default map information for a given capture \a CI,
  7996. /// record field declaration \a RI and captured value \a CV.
  7997. void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
  7998. const FieldDecl &RI, llvm::Value *CV,
  7999. MapBaseValuesArrayTy &CurBasePointers,
  8000. MapValuesArrayTy &CurPointers,
  8001. MapValuesArrayTy &CurSizes,
  8002. MapFlagsArrayTy &CurMapTypes) const {
  8003. bool IsImplicit = true;
  8004. // Do the default mapping.
  8005. if (CI.capturesThis()) {
  8006. CurBasePointers.push_back(CV);
  8007. CurPointers.push_back(CV);
  8008. const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
  8009. CurSizes.push_back(
  8010. CGF.Builder.CreateIntCast(CGF.getTypeSize(PtrTy->getPointeeType()),
  8011. CGF.Int64Ty, /*isSigned=*/true));
  8012. // Default map type.
  8013. CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
  8014. } else if (CI.capturesVariableByCopy()) {
  8015. CurBasePointers.push_back(CV);
  8016. CurPointers.push_back(CV);
  8017. if (!RI.getType()->isAnyPointerType()) {
  8018. // We have to signal to the runtime captures passed by value that are
  8019. // not pointers.
  8020. CurMapTypes.push_back(OMP_MAP_LITERAL);
  8021. CurSizes.push_back(CGF.Builder.CreateIntCast(
  8022. CGF.getTypeSize(RI.getType()), CGF.Int64Ty, /*isSigned=*/true));
  8023. } else {
  8024. // Pointers are implicitly mapped with a zero size and no flags
  8025. // (other than first map that is added for all implicit maps).
  8026. CurMapTypes.push_back(OMP_MAP_NONE);
  8027. CurSizes.push_back(llvm::Constant::getNullValue(CGF.Int64Ty));
  8028. }
  8029. const VarDecl *VD = CI.getCapturedVar();
  8030. auto I = FirstPrivateDecls.find(VD);
  8031. if (I != FirstPrivateDecls.end())
  8032. IsImplicit = I->getSecond();
  8033. } else {
  8034. assert(CI.capturesVariable() && "Expected captured reference.");
  8035. const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
  8036. QualType ElementType = PtrTy->getPointeeType();
  8037. CurSizes.push_back(CGF.Builder.CreateIntCast(
  8038. CGF.getTypeSize(ElementType), CGF.Int64Ty, /*isSigned=*/true));
  8039. // The default map type for a scalar/complex type is 'to' because by
  8040. // default the value doesn't have to be retrieved. For an aggregate
  8041. // type, the default is 'tofrom'.
  8042. CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
  8043. const VarDecl *VD = CI.getCapturedVar();
  8044. auto I = FirstPrivateDecls.find(VD);
  8045. if (I != FirstPrivateDecls.end() &&
  8046. VD->getType().isConstant(CGF.getContext())) {
  8047. llvm::Constant *Addr =
  8048. CGF.CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(CGF, VD);
  8049. // Copy the value of the original variable to the new global copy.
  8050. CGF.Builder.CreateMemCpy(
  8051. CGF.MakeNaturalAlignAddrLValue(Addr, ElementType).getAddress(),
  8052. Address(CV, CGF.getContext().getTypeAlignInChars(ElementType)),
  8053. CurSizes.back(), /*IsVolatile=*/false);
  8054. // Use new global variable as the base pointers.
  8055. CurBasePointers.push_back(Addr);
  8056. CurPointers.push_back(Addr);
  8057. } else {
  8058. CurBasePointers.push_back(CV);
  8059. if (I != FirstPrivateDecls.end() && ElementType->isAnyPointerType()) {
  8060. Address PtrAddr = CGF.EmitLoadOfReference(CGF.MakeAddrLValue(
  8061. CV, ElementType, CGF.getContext().getDeclAlign(VD),
  8062. AlignmentSource::Decl));
  8063. CurPointers.push_back(PtrAddr.getPointer());
  8064. } else {
  8065. CurPointers.push_back(CV);
  8066. }
  8067. }
  8068. if (I != FirstPrivateDecls.end())
  8069. IsImplicit = I->getSecond();
  8070. }
  8071. // Every default map produces a single argument which is a target parameter.
  8072. CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
  8073. // Add flag stating this is an implicit map.
  8074. if (IsImplicit)
  8075. CurMapTypes.back() |= OMP_MAP_IMPLICIT;
  8076. }
  8077. };
  8078. } // anonymous namespace
  8079. /// Emit the arrays used to pass the captures and map information to the
  8080. /// offloading runtime library. If there is no map or capture information,
  8081. /// return nullptr by reference.
  8082. static void
  8083. emitOffloadingArrays(CodeGenFunction &CGF,
  8084. MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
  8085. MappableExprsHandler::MapValuesArrayTy &Pointers,
  8086. MappableExprsHandler::MapValuesArrayTy &Sizes,
  8087. MappableExprsHandler::MapFlagsArrayTy &MapTypes,
  8088. CGOpenMPRuntime::TargetDataInfo &Info) {
  8089. CodeGenModule &CGM = CGF.CGM;
  8090. ASTContext &Ctx = CGF.getContext();
  8091. // Reset the array information.
  8092. Info.clearArrayInfo();
  8093. Info.NumberOfPtrs = BasePointers.size();
  8094. if (Info.NumberOfPtrs) {
  8095. // Detect if we have any capture size requiring runtime evaluation of the
  8096. // size so that a constant array could be eventually used.
  8097. bool hasRuntimeEvaluationCaptureSize = false;
  8098. for (llvm::Value *S : Sizes)
  8099. if (!isa<llvm::Constant>(S)) {
  8100. hasRuntimeEvaluationCaptureSize = true;
  8101. break;
  8102. }
  8103. llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
  8104. QualType PointerArrayType = Ctx.getConstantArrayType(
  8105. Ctx.VoidPtrTy, PointerNumAP, nullptr, ArrayType::Normal,
  8106. /*IndexTypeQuals=*/0);
  8107. Info.BasePointersArray =
  8108. CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
  8109. Info.PointersArray =
  8110. CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
  8111. // If we don't have any VLA types or other types that require runtime
  8112. // evaluation, we can use a constant array for the map sizes, otherwise we
  8113. // need to fill up the arrays as we do for the pointers.
  8114. QualType Int64Ty =
  8115. Ctx.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  8116. if (hasRuntimeEvaluationCaptureSize) {
  8117. QualType SizeArrayType = Ctx.getConstantArrayType(
  8118. Int64Ty, PointerNumAP, nullptr, ArrayType::Normal,
  8119. /*IndexTypeQuals=*/0);
  8120. Info.SizesArray =
  8121. CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
  8122. } else {
  8123. // We expect all the sizes to be constant, so we collect them to create
  8124. // a constant array.
  8125. SmallVector<llvm::Constant *, 16> ConstSizes;
  8126. for (llvm::Value *S : Sizes)
  8127. ConstSizes.push_back(cast<llvm::Constant>(S));
  8128. auto *SizesArrayInit = llvm::ConstantArray::get(
  8129. llvm::ArrayType::get(CGM.Int64Ty, ConstSizes.size()), ConstSizes);
  8130. std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
  8131. auto *SizesArrayGbl = new llvm::GlobalVariable(
  8132. CGM.getModule(), SizesArrayInit->getType(),
  8133. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
  8134. SizesArrayInit, Name);
  8135. SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  8136. Info.SizesArray = SizesArrayGbl;
  8137. }
  8138. // The map types are always constant so we don't need to generate code to
  8139. // fill arrays. Instead, we create an array constant.
  8140. SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
  8141. llvm::copy(MapTypes, Mapping.begin());
  8142. llvm::Constant *MapTypesArrayInit =
  8143. llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
  8144. std::string MaptypesName =
  8145. CGM.getOpenMPRuntime().getName({"offload_maptypes"});
  8146. auto *MapTypesArrayGbl = new llvm::GlobalVariable(
  8147. CGM.getModule(), MapTypesArrayInit->getType(),
  8148. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
  8149. MapTypesArrayInit, MaptypesName);
  8150. MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  8151. Info.MapTypesArray = MapTypesArrayGbl;
  8152. for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
  8153. llvm::Value *BPVal = *BasePointers[I];
  8154. llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
  8155. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  8156. Info.BasePointersArray, 0, I);
  8157. BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  8158. BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
  8159. Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
  8160. CGF.Builder.CreateStore(BPVal, BPAddr);
  8161. if (Info.requiresDevicePointerInfo())
  8162. if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
  8163. Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
  8164. llvm::Value *PVal = Pointers[I];
  8165. llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
  8166. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  8167. Info.PointersArray, 0, I);
  8168. P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  8169. P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
  8170. Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
  8171. CGF.Builder.CreateStore(PVal, PAddr);
  8172. if (hasRuntimeEvaluationCaptureSize) {
  8173. llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
  8174. llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
  8175. Info.SizesArray,
  8176. /*Idx0=*/0,
  8177. /*Idx1=*/I);
  8178. Address SAddr(S, Ctx.getTypeAlignInChars(Int64Ty));
  8179. CGF.Builder.CreateStore(
  8180. CGF.Builder.CreateIntCast(Sizes[I], CGM.Int64Ty, /*isSigned=*/true),
  8181. SAddr);
  8182. }
  8183. }
  8184. }
  8185. }
  8186. /// Emit the arguments to be passed to the runtime library based on the
  8187. /// arrays of pointers, sizes and map types.
  8188. static void emitOffloadingArraysArgument(
  8189. CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
  8190. llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
  8191. llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
  8192. CodeGenModule &CGM = CGF.CGM;
  8193. if (Info.NumberOfPtrs) {
  8194. BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  8195. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  8196. Info.BasePointersArray,
  8197. /*Idx0=*/0, /*Idx1=*/0);
  8198. PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  8199. llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
  8200. Info.PointersArray,
  8201. /*Idx0=*/0,
  8202. /*Idx1=*/0);
  8203. SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  8204. llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs), Info.SizesArray,
  8205. /*Idx0=*/0, /*Idx1=*/0);
  8206. MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
  8207. llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
  8208. Info.MapTypesArray,
  8209. /*Idx0=*/0,
  8210. /*Idx1=*/0);
  8211. } else {
  8212. BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
  8213. PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
  8214. SizesArrayArg = llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
  8215. MapTypesArrayArg =
  8216. llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
  8217. }
  8218. }
  8219. /// Check for inner distribute directive.
  8220. static const OMPExecutableDirective *
  8221. getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
  8222. const auto *CS = D.getInnermostCapturedStmt();
  8223. const auto *Body =
  8224. CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  8225. const Stmt *ChildStmt =
  8226. CGOpenMPSIMDRuntime::getSingleCompoundChild(Ctx, Body);
  8227. if (const auto *NestedDir =
  8228. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  8229. OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
  8230. switch (D.getDirectiveKind()) {
  8231. case OMPD_target:
  8232. if (isOpenMPDistributeDirective(DKind))
  8233. return NestedDir;
  8234. if (DKind == OMPD_teams) {
  8235. Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
  8236. /*IgnoreCaptured=*/true);
  8237. if (!Body)
  8238. return nullptr;
  8239. ChildStmt = CGOpenMPSIMDRuntime::getSingleCompoundChild(Ctx, Body);
  8240. if (const auto *NND =
  8241. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  8242. DKind = NND->getDirectiveKind();
  8243. if (isOpenMPDistributeDirective(DKind))
  8244. return NND;
  8245. }
  8246. }
  8247. return nullptr;
  8248. case OMPD_target_teams:
  8249. if (isOpenMPDistributeDirective(DKind))
  8250. return NestedDir;
  8251. return nullptr;
  8252. case OMPD_target_parallel:
  8253. case OMPD_target_simd:
  8254. case OMPD_target_parallel_for:
  8255. case OMPD_target_parallel_for_simd:
  8256. return nullptr;
  8257. case OMPD_target_teams_distribute:
  8258. case OMPD_target_teams_distribute_simd:
  8259. case OMPD_target_teams_distribute_parallel_for:
  8260. case OMPD_target_teams_distribute_parallel_for_simd:
  8261. case OMPD_parallel:
  8262. case OMPD_for:
  8263. case OMPD_parallel_for:
  8264. case OMPD_parallel_sections:
  8265. case OMPD_for_simd:
  8266. case OMPD_parallel_for_simd:
  8267. case OMPD_cancel:
  8268. case OMPD_cancellation_point:
  8269. case OMPD_ordered:
  8270. case OMPD_threadprivate:
  8271. case OMPD_allocate:
  8272. case OMPD_task:
  8273. case OMPD_simd:
  8274. case OMPD_sections:
  8275. case OMPD_section:
  8276. case OMPD_single:
  8277. case OMPD_master:
  8278. case OMPD_critical:
  8279. case OMPD_taskyield:
  8280. case OMPD_barrier:
  8281. case OMPD_taskwait:
  8282. case OMPD_taskgroup:
  8283. case OMPD_atomic:
  8284. case OMPD_flush:
  8285. case OMPD_teams:
  8286. case OMPD_target_data:
  8287. case OMPD_target_exit_data:
  8288. case OMPD_target_enter_data:
  8289. case OMPD_distribute:
  8290. case OMPD_distribute_simd:
  8291. case OMPD_distribute_parallel_for:
  8292. case OMPD_distribute_parallel_for_simd:
  8293. case OMPD_teams_distribute:
  8294. case OMPD_teams_distribute_simd:
  8295. case OMPD_teams_distribute_parallel_for:
  8296. case OMPD_teams_distribute_parallel_for_simd:
  8297. case OMPD_target_update:
  8298. case OMPD_declare_simd:
  8299. case OMPD_declare_variant:
  8300. case OMPD_declare_target:
  8301. case OMPD_end_declare_target:
  8302. case OMPD_declare_reduction:
  8303. case OMPD_declare_mapper:
  8304. case OMPD_taskloop:
  8305. case OMPD_taskloop_simd:
  8306. case OMPD_master_taskloop:
  8307. case OMPD_master_taskloop_simd:
  8308. case OMPD_parallel_master_taskloop:
  8309. case OMPD_requires:
  8310. case OMPD_unknown:
  8311. llvm_unreachable("Unexpected directive.");
  8312. }
  8313. }
  8314. return nullptr;
  8315. }
  8316. /// Emit the user-defined mapper function. The code generation follows the
  8317. /// pattern in the example below.
  8318. /// \code
  8319. /// void .omp_mapper.<type_name>.<mapper_id>.(void *rt_mapper_handle,
  8320. /// void *base, void *begin,
  8321. /// int64_t size, int64_t type) {
  8322. /// // Allocate space for an array section first.
  8323. /// if (size > 1 && !maptype.IsDelete)
  8324. /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
  8325. /// size*sizeof(Ty), clearToFrom(type));
  8326. /// // Map members.
  8327. /// for (unsigned i = 0; i < size; i++) {
  8328. /// // For each component specified by this mapper:
  8329. /// for (auto c : all_components) {
  8330. /// if (c.hasMapper())
  8331. /// (*c.Mapper())(rt_mapper_handle, c.arg_base, c.arg_begin, c.arg_size,
  8332. /// c.arg_type);
  8333. /// else
  8334. /// __tgt_push_mapper_component(rt_mapper_handle, c.arg_base,
  8335. /// c.arg_begin, c.arg_size, c.arg_type);
  8336. /// }
  8337. /// }
  8338. /// // Delete the array section.
  8339. /// if (size > 1 && maptype.IsDelete)
  8340. /// __tgt_push_mapper_component(rt_mapper_handle, base, begin,
  8341. /// size*sizeof(Ty), clearToFrom(type));
  8342. /// }
  8343. /// \endcode
  8344. void CGOpenMPRuntime::emitUserDefinedMapper(const OMPDeclareMapperDecl *D,
  8345. CodeGenFunction *CGF) {
  8346. if (UDMMap.count(D) > 0)
  8347. return;
  8348. ASTContext &C = CGM.getContext();
  8349. QualType Ty = D->getType();
  8350. QualType PtrTy = C.getPointerType(Ty).withRestrict();
  8351. QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
  8352. auto *MapperVarDecl =
  8353. cast<VarDecl>(cast<DeclRefExpr>(D->getMapperVarRef())->getDecl());
  8354. SourceLocation Loc = D->getLocation();
  8355. CharUnits ElementSize = C.getTypeSizeInChars(Ty);
  8356. // Prepare mapper function arguments and attributes.
  8357. ImplicitParamDecl HandleArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  8358. C.VoidPtrTy, ImplicitParamDecl::Other);
  8359. ImplicitParamDecl BaseArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
  8360. ImplicitParamDecl::Other);
  8361. ImplicitParamDecl BeginArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  8362. C.VoidPtrTy, ImplicitParamDecl::Other);
  8363. ImplicitParamDecl SizeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int64Ty,
  8364. ImplicitParamDecl::Other);
  8365. ImplicitParamDecl TypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, Int64Ty,
  8366. ImplicitParamDecl::Other);
  8367. FunctionArgList Args;
  8368. Args.push_back(&HandleArg);
  8369. Args.push_back(&BaseArg);
  8370. Args.push_back(&BeginArg);
  8371. Args.push_back(&SizeArg);
  8372. Args.push_back(&TypeArg);
  8373. const CGFunctionInfo &FnInfo =
  8374. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  8375. llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
  8376. SmallString<64> TyStr;
  8377. llvm::raw_svector_ostream Out(TyStr);
  8378. CGM.getCXXABI().getMangleContext().mangleTypeName(Ty, Out);
  8379. std::string Name = getName({"omp_mapper", TyStr, D->getName()});
  8380. auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
  8381. Name, &CGM.getModule());
  8382. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
  8383. Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
  8384. // Start the mapper function code generation.
  8385. CodeGenFunction MapperCGF(CGM);
  8386. MapperCGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
  8387. // Compute the starting and end addreses of array elements.
  8388. llvm::Value *Size = MapperCGF.EmitLoadOfScalar(
  8389. MapperCGF.GetAddrOfLocalVar(&SizeArg), /*Volatile=*/false,
  8390. C.getPointerType(Int64Ty), Loc);
  8391. llvm::Value *PtrBegin = MapperCGF.Builder.CreateBitCast(
  8392. MapperCGF.GetAddrOfLocalVar(&BeginArg).getPointer(),
  8393. CGM.getTypes().ConvertTypeForMem(C.getPointerType(PtrTy)));
  8394. llvm::Value *PtrEnd = MapperCGF.Builder.CreateGEP(PtrBegin, Size);
  8395. llvm::Value *MapType = MapperCGF.EmitLoadOfScalar(
  8396. MapperCGF.GetAddrOfLocalVar(&TypeArg), /*Volatile=*/false,
  8397. C.getPointerType(Int64Ty), Loc);
  8398. // Prepare common arguments for array initiation and deletion.
  8399. llvm::Value *Handle = MapperCGF.EmitLoadOfScalar(
  8400. MapperCGF.GetAddrOfLocalVar(&HandleArg),
  8401. /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
  8402. llvm::Value *BaseIn = MapperCGF.EmitLoadOfScalar(
  8403. MapperCGF.GetAddrOfLocalVar(&BaseArg),
  8404. /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
  8405. llvm::Value *BeginIn = MapperCGF.EmitLoadOfScalar(
  8406. MapperCGF.GetAddrOfLocalVar(&BeginArg),
  8407. /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
  8408. // Emit array initiation if this is an array section and \p MapType indicates
  8409. // that memory allocation is required.
  8410. llvm::BasicBlock *HeadBB = MapperCGF.createBasicBlock("omp.arraymap.head");
  8411. emitUDMapperArrayInitOrDel(MapperCGF, Handle, BaseIn, BeginIn, Size, MapType,
  8412. ElementSize, HeadBB, /*IsInit=*/true);
  8413. // Emit a for loop to iterate through SizeArg of elements and map all of them.
  8414. // Emit the loop header block.
  8415. MapperCGF.EmitBlock(HeadBB);
  8416. llvm::BasicBlock *BodyBB = MapperCGF.createBasicBlock("omp.arraymap.body");
  8417. llvm::BasicBlock *DoneBB = MapperCGF.createBasicBlock("omp.done");
  8418. // Evaluate whether the initial condition is satisfied.
  8419. llvm::Value *IsEmpty =
  8420. MapperCGF.Builder.CreateICmpEQ(PtrBegin, PtrEnd, "omp.arraymap.isempty");
  8421. MapperCGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  8422. llvm::BasicBlock *EntryBB = MapperCGF.Builder.GetInsertBlock();
  8423. // Emit the loop body block.
  8424. MapperCGF.EmitBlock(BodyBB);
  8425. llvm::PHINode *PtrPHI = MapperCGF.Builder.CreatePHI(
  8426. PtrBegin->getType(), 2, "omp.arraymap.ptrcurrent");
  8427. PtrPHI->addIncoming(PtrBegin, EntryBB);
  8428. Address PtrCurrent =
  8429. Address(PtrPHI, MapperCGF.GetAddrOfLocalVar(&BeginArg)
  8430. .getAlignment()
  8431. .alignmentOfArrayElement(ElementSize));
  8432. // Privatize the declared variable of mapper to be the current array element.
  8433. CodeGenFunction::OMPPrivateScope Scope(MapperCGF);
  8434. Scope.addPrivate(MapperVarDecl, [&MapperCGF, PtrCurrent, PtrTy]() {
  8435. return MapperCGF
  8436. .EmitLoadOfPointerLValue(PtrCurrent, PtrTy->castAs<PointerType>())
  8437. .getAddress();
  8438. });
  8439. (void)Scope.Privatize();
  8440. // Get map clause information. Fill up the arrays with all mapped variables.
  8441. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  8442. MappableExprsHandler::MapValuesArrayTy Pointers;
  8443. MappableExprsHandler::MapValuesArrayTy Sizes;
  8444. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  8445. MappableExprsHandler MEHandler(*D, MapperCGF);
  8446. MEHandler.generateAllInfoForMapper(BasePointers, Pointers, Sizes, MapTypes);
  8447. // Call the runtime API __tgt_mapper_num_components to get the number of
  8448. // pre-existing components.
  8449. llvm::Value *OffloadingArgs[] = {Handle};
  8450. llvm::Value *PreviousSize = MapperCGF.EmitRuntimeCall(
  8451. createRuntimeFunction(OMPRTL__tgt_mapper_num_components), OffloadingArgs);
  8452. llvm::Value *ShiftedPreviousSize = MapperCGF.Builder.CreateShl(
  8453. PreviousSize,
  8454. MapperCGF.Builder.getInt64(MappableExprsHandler::getFlagMemberOffset()));
  8455. // Fill up the runtime mapper handle for all components.
  8456. for (unsigned I = 0; I < BasePointers.size(); ++I) {
  8457. llvm::Value *CurBaseArg = MapperCGF.Builder.CreateBitCast(
  8458. *BasePointers[I], CGM.getTypes().ConvertTypeForMem(C.VoidPtrTy));
  8459. llvm::Value *CurBeginArg = MapperCGF.Builder.CreateBitCast(
  8460. Pointers[I], CGM.getTypes().ConvertTypeForMem(C.VoidPtrTy));
  8461. llvm::Value *CurSizeArg = Sizes[I];
  8462. // Extract the MEMBER_OF field from the map type.
  8463. llvm::BasicBlock *MemberBB = MapperCGF.createBasicBlock("omp.member");
  8464. MapperCGF.EmitBlock(MemberBB);
  8465. llvm::Value *OriMapType = MapperCGF.Builder.getInt64(MapTypes[I]);
  8466. llvm::Value *Member = MapperCGF.Builder.CreateAnd(
  8467. OriMapType,
  8468. MapperCGF.Builder.getInt64(MappableExprsHandler::OMP_MAP_MEMBER_OF));
  8469. llvm::BasicBlock *MemberCombineBB =
  8470. MapperCGF.createBasicBlock("omp.member.combine");
  8471. llvm::BasicBlock *TypeBB = MapperCGF.createBasicBlock("omp.type");
  8472. llvm::Value *IsMember = MapperCGF.Builder.CreateIsNull(Member);
  8473. MapperCGF.Builder.CreateCondBr(IsMember, TypeBB, MemberCombineBB);
  8474. // Add the number of pre-existing components to the MEMBER_OF field if it
  8475. // is valid.
  8476. MapperCGF.EmitBlock(MemberCombineBB);
  8477. llvm::Value *CombinedMember =
  8478. MapperCGF.Builder.CreateNUWAdd(OriMapType, ShiftedPreviousSize);
  8479. // Do nothing if it is not a member of previous components.
  8480. MapperCGF.EmitBlock(TypeBB);
  8481. llvm::PHINode *MemberMapType =
  8482. MapperCGF.Builder.CreatePHI(CGM.Int64Ty, 4, "omp.membermaptype");
  8483. MemberMapType->addIncoming(OriMapType, MemberBB);
  8484. MemberMapType->addIncoming(CombinedMember, MemberCombineBB);
  8485. // Combine the map type inherited from user-defined mapper with that
  8486. // specified in the program. According to the OMP_MAP_TO and OMP_MAP_FROM
  8487. // bits of the \a MapType, which is the input argument of the mapper
  8488. // function, the following code will set the OMP_MAP_TO and OMP_MAP_FROM
  8489. // bits of MemberMapType.
  8490. // [OpenMP 5.0], 1.2.6. map-type decay.
  8491. // | alloc | to | from | tofrom | release | delete
  8492. // ----------------------------------------------------------
  8493. // alloc | alloc | alloc | alloc | alloc | release | delete
  8494. // to | alloc | to | alloc | to | release | delete
  8495. // from | alloc | alloc | from | from | release | delete
  8496. // tofrom | alloc | to | from | tofrom | release | delete
  8497. llvm::Value *LeftToFrom = MapperCGF.Builder.CreateAnd(
  8498. MapType,
  8499. MapperCGF.Builder.getInt64(MappableExprsHandler::OMP_MAP_TO |
  8500. MappableExprsHandler::OMP_MAP_FROM));
  8501. llvm::BasicBlock *AllocBB = MapperCGF.createBasicBlock("omp.type.alloc");
  8502. llvm::BasicBlock *AllocElseBB =
  8503. MapperCGF.createBasicBlock("omp.type.alloc.else");
  8504. llvm::BasicBlock *ToBB = MapperCGF.createBasicBlock("omp.type.to");
  8505. llvm::BasicBlock *ToElseBB = MapperCGF.createBasicBlock("omp.type.to.else");
  8506. llvm::BasicBlock *FromBB = MapperCGF.createBasicBlock("omp.type.from");
  8507. llvm::BasicBlock *EndBB = MapperCGF.createBasicBlock("omp.type.end");
  8508. llvm::Value *IsAlloc = MapperCGF.Builder.CreateIsNull(LeftToFrom);
  8509. MapperCGF.Builder.CreateCondBr(IsAlloc, AllocBB, AllocElseBB);
  8510. // In case of alloc, clear OMP_MAP_TO and OMP_MAP_FROM.
  8511. MapperCGF.EmitBlock(AllocBB);
  8512. llvm::Value *AllocMapType = MapperCGF.Builder.CreateAnd(
  8513. MemberMapType,
  8514. MapperCGF.Builder.getInt64(~(MappableExprsHandler::OMP_MAP_TO |
  8515. MappableExprsHandler::OMP_MAP_FROM)));
  8516. MapperCGF.Builder.CreateBr(EndBB);
  8517. MapperCGF.EmitBlock(AllocElseBB);
  8518. llvm::Value *IsTo = MapperCGF.Builder.CreateICmpEQ(
  8519. LeftToFrom,
  8520. MapperCGF.Builder.getInt64(MappableExprsHandler::OMP_MAP_TO));
  8521. MapperCGF.Builder.CreateCondBr(IsTo, ToBB, ToElseBB);
  8522. // In case of to, clear OMP_MAP_FROM.
  8523. MapperCGF.EmitBlock(ToBB);
  8524. llvm::Value *ToMapType = MapperCGF.Builder.CreateAnd(
  8525. MemberMapType,
  8526. MapperCGF.Builder.getInt64(~MappableExprsHandler::OMP_MAP_FROM));
  8527. MapperCGF.Builder.CreateBr(EndBB);
  8528. MapperCGF.EmitBlock(ToElseBB);
  8529. llvm::Value *IsFrom = MapperCGF.Builder.CreateICmpEQ(
  8530. LeftToFrom,
  8531. MapperCGF.Builder.getInt64(MappableExprsHandler::OMP_MAP_FROM));
  8532. MapperCGF.Builder.CreateCondBr(IsFrom, FromBB, EndBB);
  8533. // In case of from, clear OMP_MAP_TO.
  8534. MapperCGF.EmitBlock(FromBB);
  8535. llvm::Value *FromMapType = MapperCGF.Builder.CreateAnd(
  8536. MemberMapType,
  8537. MapperCGF.Builder.getInt64(~MappableExprsHandler::OMP_MAP_TO));
  8538. // In case of tofrom, do nothing.
  8539. MapperCGF.EmitBlock(EndBB);
  8540. llvm::PHINode *CurMapType =
  8541. MapperCGF.Builder.CreatePHI(CGM.Int64Ty, 4, "omp.maptype");
  8542. CurMapType->addIncoming(AllocMapType, AllocBB);
  8543. CurMapType->addIncoming(ToMapType, ToBB);
  8544. CurMapType->addIncoming(FromMapType, FromBB);
  8545. CurMapType->addIncoming(MemberMapType, ToElseBB);
  8546. // TODO: call the corresponding mapper function if a user-defined mapper is
  8547. // associated with this map clause.
  8548. // Call the runtime API __tgt_push_mapper_component to fill up the runtime
  8549. // data structure.
  8550. llvm::Value *OffloadingArgs[] = {Handle, CurBaseArg, CurBeginArg,
  8551. CurSizeArg, CurMapType};
  8552. MapperCGF.EmitRuntimeCall(
  8553. createRuntimeFunction(OMPRTL__tgt_push_mapper_component),
  8554. OffloadingArgs);
  8555. }
  8556. // Update the pointer to point to the next element that needs to be mapped,
  8557. // and check whether we have mapped all elements.
  8558. llvm::Value *PtrNext = MapperCGF.Builder.CreateConstGEP1_32(
  8559. PtrPHI, /*Idx0=*/1, "omp.arraymap.next");
  8560. PtrPHI->addIncoming(PtrNext, BodyBB);
  8561. llvm::Value *IsDone =
  8562. MapperCGF.Builder.CreateICmpEQ(PtrNext, PtrEnd, "omp.arraymap.isdone");
  8563. llvm::BasicBlock *ExitBB = MapperCGF.createBasicBlock("omp.arraymap.exit");
  8564. MapperCGF.Builder.CreateCondBr(IsDone, ExitBB, BodyBB);
  8565. MapperCGF.EmitBlock(ExitBB);
  8566. // Emit array deletion if this is an array section and \p MapType indicates
  8567. // that deletion is required.
  8568. emitUDMapperArrayInitOrDel(MapperCGF, Handle, BaseIn, BeginIn, Size, MapType,
  8569. ElementSize, DoneBB, /*IsInit=*/false);
  8570. // Emit the function exit block.
  8571. MapperCGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  8572. MapperCGF.FinishFunction();
  8573. UDMMap.try_emplace(D, Fn);
  8574. if (CGF) {
  8575. auto &Decls = FunctionUDMMap.FindAndConstruct(CGF->CurFn);
  8576. Decls.second.push_back(D);
  8577. }
  8578. }
  8579. /// Emit the array initialization or deletion portion for user-defined mapper
  8580. /// code generation. First, it evaluates whether an array section is mapped and
  8581. /// whether the \a MapType instructs to delete this section. If \a IsInit is
  8582. /// true, and \a MapType indicates to not delete this array, array
  8583. /// initialization code is generated. If \a IsInit is false, and \a MapType
  8584. /// indicates to not this array, array deletion code is generated.
  8585. void CGOpenMPRuntime::emitUDMapperArrayInitOrDel(
  8586. CodeGenFunction &MapperCGF, llvm::Value *Handle, llvm::Value *Base,
  8587. llvm::Value *Begin, llvm::Value *Size, llvm::Value *MapType,
  8588. CharUnits ElementSize, llvm::BasicBlock *ExitBB, bool IsInit) {
  8589. StringRef Prefix = IsInit ? ".init" : ".del";
  8590. // Evaluate if this is an array section.
  8591. llvm::BasicBlock *IsDeleteBB =
  8592. MapperCGF.createBasicBlock("omp.array" + Prefix + ".evaldelete");
  8593. llvm::BasicBlock *BodyBB = MapperCGF.createBasicBlock("omp.array" + Prefix);
  8594. llvm::Value *IsArray = MapperCGF.Builder.CreateICmpSGE(
  8595. Size, MapperCGF.Builder.getInt64(1), "omp.arrayinit.isarray");
  8596. MapperCGF.Builder.CreateCondBr(IsArray, IsDeleteBB, ExitBB);
  8597. // Evaluate if we are going to delete this section.
  8598. MapperCGF.EmitBlock(IsDeleteBB);
  8599. llvm::Value *DeleteBit = MapperCGF.Builder.CreateAnd(
  8600. MapType,
  8601. MapperCGF.Builder.getInt64(MappableExprsHandler::OMP_MAP_DELETE));
  8602. llvm::Value *DeleteCond;
  8603. if (IsInit) {
  8604. DeleteCond = MapperCGF.Builder.CreateIsNull(
  8605. DeleteBit, "omp.array" + Prefix + ".delete");
  8606. } else {
  8607. DeleteCond = MapperCGF.Builder.CreateIsNotNull(
  8608. DeleteBit, "omp.array" + Prefix + ".delete");
  8609. }
  8610. MapperCGF.Builder.CreateCondBr(DeleteCond, BodyBB, ExitBB);
  8611. MapperCGF.EmitBlock(BodyBB);
  8612. // Get the array size by multiplying element size and element number (i.e., \p
  8613. // Size).
  8614. llvm::Value *ArraySize = MapperCGF.Builder.CreateNUWMul(
  8615. Size, MapperCGF.Builder.getInt64(ElementSize.getQuantity()));
  8616. // Remove OMP_MAP_TO and OMP_MAP_FROM from the map type, so that it achieves
  8617. // memory allocation/deletion purpose only.
  8618. llvm::Value *MapTypeArg = MapperCGF.Builder.CreateAnd(
  8619. MapType,
  8620. MapperCGF.Builder.getInt64(~(MappableExprsHandler::OMP_MAP_TO |
  8621. MappableExprsHandler::OMP_MAP_FROM)));
  8622. // Call the runtime API __tgt_push_mapper_component to fill up the runtime
  8623. // data structure.
  8624. llvm::Value *OffloadingArgs[] = {Handle, Base, Begin, ArraySize, MapTypeArg};
  8625. MapperCGF.EmitRuntimeCall(
  8626. createRuntimeFunction(OMPRTL__tgt_push_mapper_component), OffloadingArgs);
  8627. }
  8628. void CGOpenMPRuntime::emitTargetNumIterationsCall(
  8629. CodeGenFunction &CGF, const OMPExecutableDirective &D,
  8630. llvm::Value *DeviceID,
  8631. llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
  8632. const OMPLoopDirective &D)>
  8633. SizeEmitter) {
  8634. OpenMPDirectiveKind Kind = D.getDirectiveKind();
  8635. const OMPExecutableDirective *TD = &D;
  8636. // Get nested teams distribute kind directive, if any.
  8637. if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind))
  8638. TD = getNestedDistributeDirective(CGM.getContext(), D);
  8639. if (!TD)
  8640. return;
  8641. const auto *LD = cast<OMPLoopDirective>(TD);
  8642. auto &&CodeGen = [LD, DeviceID, SizeEmitter, this](CodeGenFunction &CGF,
  8643. PrePostActionTy &) {
  8644. if (llvm::Value *NumIterations = SizeEmitter(CGF, *LD)) {
  8645. llvm::Value *Args[] = {DeviceID, NumIterations};
  8646. CGF.EmitRuntimeCall(
  8647. createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args);
  8648. }
  8649. };
  8650. emitInlinedDirective(CGF, OMPD_unknown, CodeGen);
  8651. }
  8652. void CGOpenMPRuntime::emitTargetCall(
  8653. CodeGenFunction &CGF, const OMPExecutableDirective &D,
  8654. llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,
  8655. const Expr *Device,
  8656. llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
  8657. const OMPLoopDirective &D)>
  8658. SizeEmitter) {
  8659. if (!CGF.HaveInsertPoint())
  8660. return;
  8661. assert(OutlinedFn && "Invalid outlined function!");
  8662. const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
  8663. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  8664. const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
  8665. auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
  8666. PrePostActionTy &) {
  8667. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  8668. };
  8669. emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
  8670. CodeGenFunction::OMPTargetDataInfo InputInfo;
  8671. llvm::Value *MapTypesArray = nullptr;
  8672. // Fill up the pointer arrays and transfer execution to the device.
  8673. auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
  8674. &MapTypesArray, &CS, RequiresOuterTask, &CapturedVars,
  8675. SizeEmitter](CodeGenFunction &CGF, PrePostActionTy &) {
  8676. // On top of the arrays that were filled up, the target offloading call
  8677. // takes as arguments the device id as well as the host pointer. The host
  8678. // pointer is used by the runtime library to identify the current target
  8679. // region, so it only has to be unique and not necessarily point to
  8680. // anything. It could be the pointer to the outlined function that
  8681. // implements the target region, but we aren't using that so that the
  8682. // compiler doesn't need to keep that, and could therefore inline the host
  8683. // function if proven worthwhile during optimization.
  8684. // From this point on, we need to have an ID of the target region defined.
  8685. assert(OutlinedFnID && "Invalid outlined function ID!");
  8686. // Emit device ID if any.
  8687. llvm::Value *DeviceID;
  8688. if (Device) {
  8689. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  8690. CGF.Int64Ty, /*isSigned=*/true);
  8691. } else {
  8692. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  8693. }
  8694. // Emit the number of elements in the offloading arrays.
  8695. llvm::Value *PointerNum =
  8696. CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
  8697. // Return value of the runtime offloading call.
  8698. llvm::Value *Return;
  8699. llvm::Value *NumTeams = emitNumTeamsForTargetDirective(CGF, D);
  8700. llvm::Value *NumThreads = emitNumThreadsForTargetDirective(CGF, D);
  8701. // Emit tripcount for the target loop-based directive.
  8702. emitTargetNumIterationsCall(CGF, D, DeviceID, SizeEmitter);
  8703. bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
  8704. // The target region is an outlined function launched by the runtime
  8705. // via calls __tgt_target() or __tgt_target_teams().
  8706. //
  8707. // __tgt_target() launches a target region with one team and one thread,
  8708. // executing a serial region. This master thread may in turn launch
  8709. // more threads within its team upon encountering a parallel region,
  8710. // however, no additional teams can be launched on the device.
  8711. //
  8712. // __tgt_target_teams() launches a target region with one or more teams,
  8713. // each with one or more threads. This call is required for target
  8714. // constructs such as:
  8715. // 'target teams'
  8716. // 'target' / 'teams'
  8717. // 'target teams distribute parallel for'
  8718. // 'target parallel'
  8719. // and so on.
  8720. //
  8721. // Note that on the host and CPU targets, the runtime implementation of
  8722. // these calls simply call the outlined function without forking threads.
  8723. // The outlined functions themselves have runtime calls to
  8724. // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
  8725. // the compiler in emitTeamsCall() and emitParallelCall().
  8726. //
  8727. // In contrast, on the NVPTX target, the implementation of
  8728. // __tgt_target_teams() launches a GPU kernel with the requested number
  8729. // of teams and threads so no additional calls to the runtime are required.
  8730. if (NumTeams) {
  8731. // If we have NumTeams defined this means that we have an enclosed teams
  8732. // region. Therefore we also expect to have NumThreads defined. These two
  8733. // values should be defined in the presence of a teams directive,
  8734. // regardless of having any clauses associated. If the user is using teams
  8735. // but no clauses, these two values will be the default that should be
  8736. // passed to the runtime library - a 32-bit integer with the value zero.
  8737. assert(NumThreads && "Thread limit expression should be available along "
  8738. "with number of teams.");
  8739. llvm::Value *OffloadingArgs[] = {DeviceID,
  8740. OutlinedFnID,
  8741. PointerNum,
  8742. InputInfo.BasePointersArray.getPointer(),
  8743. InputInfo.PointersArray.getPointer(),
  8744. InputInfo.SizesArray.getPointer(),
  8745. MapTypesArray,
  8746. NumTeams,
  8747. NumThreads};
  8748. Return = CGF.EmitRuntimeCall(
  8749. createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
  8750. : OMPRTL__tgt_target_teams),
  8751. OffloadingArgs);
  8752. } else {
  8753. llvm::Value *OffloadingArgs[] = {DeviceID,
  8754. OutlinedFnID,
  8755. PointerNum,
  8756. InputInfo.BasePointersArray.getPointer(),
  8757. InputInfo.PointersArray.getPointer(),
  8758. InputInfo.SizesArray.getPointer(),
  8759. MapTypesArray};
  8760. Return = CGF.EmitRuntimeCall(
  8761. createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
  8762. : OMPRTL__tgt_target),
  8763. OffloadingArgs);
  8764. }
  8765. // Check the error code and execute the host version if required.
  8766. llvm::BasicBlock *OffloadFailedBlock =
  8767. CGF.createBasicBlock("omp_offload.failed");
  8768. llvm::BasicBlock *OffloadContBlock =
  8769. CGF.createBasicBlock("omp_offload.cont");
  8770. llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
  8771. CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
  8772. CGF.EmitBlock(OffloadFailedBlock);
  8773. if (RequiresOuterTask) {
  8774. CapturedVars.clear();
  8775. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  8776. }
  8777. emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
  8778. CGF.EmitBranch(OffloadContBlock);
  8779. CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
  8780. };
  8781. // Notify that the host version must be executed.
  8782. auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
  8783. RequiresOuterTask](CodeGenFunction &CGF,
  8784. PrePostActionTy &) {
  8785. if (RequiresOuterTask) {
  8786. CapturedVars.clear();
  8787. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  8788. }
  8789. emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
  8790. };
  8791. auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
  8792. &CapturedVars, RequiresOuterTask,
  8793. &CS](CodeGenFunction &CGF, PrePostActionTy &) {
  8794. // Fill up the arrays with all the captured variables.
  8795. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  8796. MappableExprsHandler::MapValuesArrayTy Pointers;
  8797. MappableExprsHandler::MapValuesArrayTy Sizes;
  8798. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  8799. // Get mappable expression information.
  8800. MappableExprsHandler MEHandler(D, CGF);
  8801. llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
  8802. auto RI = CS.getCapturedRecordDecl()->field_begin();
  8803. auto CV = CapturedVars.begin();
  8804. for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
  8805. CE = CS.capture_end();
  8806. CI != CE; ++CI, ++RI, ++CV) {
  8807. MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
  8808. MappableExprsHandler::MapValuesArrayTy CurPointers;
  8809. MappableExprsHandler::MapValuesArrayTy CurSizes;
  8810. MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
  8811. MappableExprsHandler::StructRangeInfoTy PartialStruct;
  8812. // VLA sizes are passed to the outlined region by copy and do not have map
  8813. // information associated.
  8814. if (CI->capturesVariableArrayType()) {
  8815. CurBasePointers.push_back(*CV);
  8816. CurPointers.push_back(*CV);
  8817. CurSizes.push_back(CGF.Builder.CreateIntCast(
  8818. CGF.getTypeSize(RI->getType()), CGF.Int64Ty, /*isSigned=*/true));
  8819. // Copy to the device as an argument. No need to retrieve it.
  8820. CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
  8821. MappableExprsHandler::OMP_MAP_TARGET_PARAM |
  8822. MappableExprsHandler::OMP_MAP_IMPLICIT);
  8823. } else {
  8824. // If we have any information in the map clause, we use it, otherwise we
  8825. // just do a default mapping.
  8826. MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
  8827. CurSizes, CurMapTypes, PartialStruct);
  8828. if (CurBasePointers.empty())
  8829. MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
  8830. CurPointers, CurSizes, CurMapTypes);
  8831. // Generate correct mapping for variables captured by reference in
  8832. // lambdas.
  8833. if (CI->capturesVariable())
  8834. MEHandler.generateInfoForLambdaCaptures(
  8835. CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
  8836. CurMapTypes, LambdaPointers);
  8837. }
  8838. // We expect to have at least an element of information for this capture.
  8839. assert(!CurBasePointers.empty() &&
  8840. "Non-existing map pointer for capture!");
  8841. assert(CurBasePointers.size() == CurPointers.size() &&
  8842. CurBasePointers.size() == CurSizes.size() &&
  8843. CurBasePointers.size() == CurMapTypes.size() &&
  8844. "Inconsistent map information sizes!");
  8845. // If there is an entry in PartialStruct it means we have a struct with
  8846. // individual members mapped. Emit an extra combined entry.
  8847. if (PartialStruct.Base.isValid())
  8848. MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
  8849. CurMapTypes, PartialStruct);
  8850. // We need to append the results of this capture to what we already have.
  8851. BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
  8852. Pointers.append(CurPointers.begin(), CurPointers.end());
  8853. Sizes.append(CurSizes.begin(), CurSizes.end());
  8854. MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
  8855. }
  8856. // Adjust MEMBER_OF flags for the lambdas captures.
  8857. MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
  8858. Pointers, MapTypes);
  8859. // Map other list items in the map clause which are not captured variables
  8860. // but "declare target link" global variables.
  8861. MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
  8862. MapTypes);
  8863. TargetDataInfo Info;
  8864. // Fill up the arrays and create the arguments.
  8865. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  8866. emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
  8867. Info.PointersArray, Info.SizesArray,
  8868. Info.MapTypesArray, Info);
  8869. InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
  8870. InputInfo.BasePointersArray =
  8871. Address(Info.BasePointersArray, CGM.getPointerAlign());
  8872. InputInfo.PointersArray =
  8873. Address(Info.PointersArray, CGM.getPointerAlign());
  8874. InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
  8875. MapTypesArray = Info.MapTypesArray;
  8876. if (RequiresOuterTask)
  8877. CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
  8878. else
  8879. emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
  8880. };
  8881. auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
  8882. CodeGenFunction &CGF, PrePostActionTy &) {
  8883. if (RequiresOuterTask) {
  8884. CodeGenFunction::OMPTargetDataInfo InputInfo;
  8885. CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
  8886. } else {
  8887. emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
  8888. }
  8889. };
  8890. // If we have a target function ID it means that we need to support
  8891. // offloading, otherwise, just execute on the host. We need to execute on host
  8892. // regardless of the conditional in the if clause if, e.g., the user do not
  8893. // specify target triples.
  8894. if (OutlinedFnID) {
  8895. if (IfCond) {
  8896. emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
  8897. } else {
  8898. RegionCodeGenTy ThenRCG(TargetThenGen);
  8899. ThenRCG(CGF);
  8900. }
  8901. } else {
  8902. RegionCodeGenTy ElseRCG(TargetElseGen);
  8903. ElseRCG(CGF);
  8904. }
  8905. }
  8906. void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
  8907. StringRef ParentName) {
  8908. if (!S)
  8909. return;
  8910. // Codegen OMP target directives that offload compute to the device.
  8911. bool RequiresDeviceCodegen =
  8912. isa<OMPExecutableDirective>(S) &&
  8913. isOpenMPTargetExecutionDirective(
  8914. cast<OMPExecutableDirective>(S)->getDirectiveKind());
  8915. if (RequiresDeviceCodegen) {
  8916. const auto &E = *cast<OMPExecutableDirective>(S);
  8917. unsigned DeviceID;
  8918. unsigned FileID;
  8919. unsigned Line;
  8920. getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
  8921. FileID, Line);
  8922. // Is this a target region that should not be emitted as an entry point? If
  8923. // so just signal we are done with this target region.
  8924. if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
  8925. ParentName, Line))
  8926. return;
  8927. switch (E.getDirectiveKind()) {
  8928. case OMPD_target:
  8929. CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
  8930. cast<OMPTargetDirective>(E));
  8931. break;
  8932. case OMPD_target_parallel:
  8933. CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
  8934. CGM, ParentName, cast<OMPTargetParallelDirective>(E));
  8935. break;
  8936. case OMPD_target_teams:
  8937. CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
  8938. CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
  8939. break;
  8940. case OMPD_target_teams_distribute:
  8941. CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
  8942. CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
  8943. break;
  8944. case OMPD_target_teams_distribute_simd:
  8945. CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  8946. CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
  8947. break;
  8948. case OMPD_target_parallel_for:
  8949. CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
  8950. CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
  8951. break;
  8952. case OMPD_target_parallel_for_simd:
  8953. CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
  8954. CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
  8955. break;
  8956. case OMPD_target_simd:
  8957. CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
  8958. CGM, ParentName, cast<OMPTargetSimdDirective>(E));
  8959. break;
  8960. case OMPD_target_teams_distribute_parallel_for:
  8961. CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
  8962. CGM, ParentName,
  8963. cast<OMPTargetTeamsDistributeParallelForDirective>(E));
  8964. break;
  8965. case OMPD_target_teams_distribute_parallel_for_simd:
  8966. CodeGenFunction::
  8967. EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
  8968. CGM, ParentName,
  8969. cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
  8970. break;
  8971. case OMPD_parallel:
  8972. case OMPD_for:
  8973. case OMPD_parallel_for:
  8974. case OMPD_parallel_sections:
  8975. case OMPD_for_simd:
  8976. case OMPD_parallel_for_simd:
  8977. case OMPD_cancel:
  8978. case OMPD_cancellation_point:
  8979. case OMPD_ordered:
  8980. case OMPD_threadprivate:
  8981. case OMPD_allocate:
  8982. case OMPD_task:
  8983. case OMPD_simd:
  8984. case OMPD_sections:
  8985. case OMPD_section:
  8986. case OMPD_single:
  8987. case OMPD_master:
  8988. case OMPD_critical:
  8989. case OMPD_taskyield:
  8990. case OMPD_barrier:
  8991. case OMPD_taskwait:
  8992. case OMPD_taskgroup:
  8993. case OMPD_atomic:
  8994. case OMPD_flush:
  8995. case OMPD_teams:
  8996. case OMPD_target_data:
  8997. case OMPD_target_exit_data:
  8998. case OMPD_target_enter_data:
  8999. case OMPD_distribute:
  9000. case OMPD_distribute_simd:
  9001. case OMPD_distribute_parallel_for:
  9002. case OMPD_distribute_parallel_for_simd:
  9003. case OMPD_teams_distribute:
  9004. case OMPD_teams_distribute_simd:
  9005. case OMPD_teams_distribute_parallel_for:
  9006. case OMPD_teams_distribute_parallel_for_simd:
  9007. case OMPD_target_update:
  9008. case OMPD_declare_simd:
  9009. case OMPD_declare_variant:
  9010. case OMPD_declare_target:
  9011. case OMPD_end_declare_target:
  9012. case OMPD_declare_reduction:
  9013. case OMPD_declare_mapper:
  9014. case OMPD_taskloop:
  9015. case OMPD_taskloop_simd:
  9016. case OMPD_master_taskloop:
  9017. case OMPD_master_taskloop_simd:
  9018. case OMPD_parallel_master_taskloop:
  9019. case OMPD_requires:
  9020. case OMPD_unknown:
  9021. llvm_unreachable("Unknown target directive for OpenMP device codegen.");
  9022. }
  9023. return;
  9024. }
  9025. if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
  9026. if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
  9027. return;
  9028. scanForTargetRegionsFunctions(
  9029. E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
  9030. return;
  9031. }
  9032. // If this is a lambda function, look into its body.
  9033. if (const auto *L = dyn_cast<LambdaExpr>(S))
  9034. S = L->getBody();
  9035. // Keep looking for target regions recursively.
  9036. for (const Stmt *II : S->children())
  9037. scanForTargetRegionsFunctions(II, ParentName);
  9038. }
  9039. bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
  9040. // If emitting code for the host, we do not process FD here. Instead we do
  9041. // the normal code generation.
  9042. if (!CGM.getLangOpts().OpenMPIsDevice) {
  9043. if (const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl())) {
  9044. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  9045. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  9046. // Do not emit device_type(nohost) functions for the host.
  9047. if (DevTy && *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  9048. return true;
  9049. }
  9050. return false;
  9051. }
  9052. const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
  9053. StringRef Name = CGM.getMangledName(GD);
  9054. // Try to detect target regions in the function.
  9055. if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
  9056. scanForTargetRegionsFunctions(FD->getBody(), Name);
  9057. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  9058. OMPDeclareTargetDeclAttr::getDeviceType(FD);
  9059. // Do not emit device_type(nohost) functions for the host.
  9060. if (DevTy && *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  9061. return true;
  9062. }
  9063. // Do not to emit function if it is not marked as declare target.
  9064. return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  9065. AlreadyEmittedTargetFunctions.count(Name) == 0;
  9066. }
  9067. bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
  9068. if (!CGM.getLangOpts().OpenMPIsDevice)
  9069. return false;
  9070. // Check if there are Ctors/Dtors in this declaration and look for target
  9071. // regions in it. We use the complete variant to produce the kernel name
  9072. // mangling.
  9073. QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
  9074. if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
  9075. for (const CXXConstructorDecl *Ctor : RD->ctors()) {
  9076. StringRef ParentName =
  9077. CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
  9078. scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
  9079. }
  9080. if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
  9081. StringRef ParentName =
  9082. CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
  9083. scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
  9084. }
  9085. }
  9086. // Do not to emit variable if it is not marked as declare target.
  9087. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  9088. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  9089. cast<VarDecl>(GD.getDecl()));
  9090. if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link ||
  9091. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  9092. HasRequiresUnifiedSharedMemory)) {
  9093. DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
  9094. return true;
  9095. }
  9096. return false;
  9097. }
  9098. llvm::Constant *
  9099. CGOpenMPRuntime::registerTargetFirstprivateCopy(CodeGenFunction &CGF,
  9100. const VarDecl *VD) {
  9101. assert(VD->getType().isConstant(CGM.getContext()) &&
  9102. "Expected constant variable.");
  9103. StringRef VarName;
  9104. llvm::Constant *Addr;
  9105. llvm::GlobalValue::LinkageTypes Linkage;
  9106. QualType Ty = VD->getType();
  9107. SmallString<128> Buffer;
  9108. {
  9109. unsigned DeviceID;
  9110. unsigned FileID;
  9111. unsigned Line;
  9112. getTargetEntryUniqueInfo(CGM.getContext(), VD->getLocation(), DeviceID,
  9113. FileID, Line);
  9114. llvm::raw_svector_ostream OS(Buffer);
  9115. OS << "__omp_offloading_firstprivate_" << llvm::format("_%x", DeviceID)
  9116. << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
  9117. VarName = OS.str();
  9118. }
  9119. Linkage = llvm::GlobalValue::InternalLinkage;
  9120. Addr =
  9121. getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(Ty), VarName,
  9122. getDefaultFirstprivateAddressSpace());
  9123. cast<llvm::GlobalValue>(Addr)->setLinkage(Linkage);
  9124. CharUnits VarSize = CGM.getContext().getTypeSizeInChars(Ty);
  9125. CGM.addCompilerUsedGlobal(cast<llvm::GlobalValue>(Addr));
  9126. OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
  9127. VarName, Addr, VarSize,
  9128. OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo, Linkage);
  9129. return Addr;
  9130. }
  9131. void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
  9132. llvm::Constant *Addr) {
  9133. if (CGM.getLangOpts().OMPTargetTriples.empty() &&
  9134. !CGM.getLangOpts().OpenMPIsDevice)
  9135. return;
  9136. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  9137. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  9138. if (!Res) {
  9139. if (CGM.getLangOpts().OpenMPIsDevice) {
  9140. // Register non-target variables being emitted in device code (debug info
  9141. // may cause this).
  9142. StringRef VarName = CGM.getMangledName(VD);
  9143. EmittedNonTargetVariables.try_emplace(VarName, Addr);
  9144. }
  9145. return;
  9146. }
  9147. // Register declare target variables.
  9148. OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
  9149. StringRef VarName;
  9150. CharUnits VarSize;
  9151. llvm::GlobalValue::LinkageTypes Linkage;
  9152. if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  9153. !HasRequiresUnifiedSharedMemory) {
  9154. Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
  9155. VarName = CGM.getMangledName(VD);
  9156. if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
  9157. VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
  9158. assert(!VarSize.isZero() && "Expected non-zero size of the variable");
  9159. } else {
  9160. VarSize = CharUnits::Zero();
  9161. }
  9162. Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
  9163. // Temp solution to prevent optimizations of the internal variables.
  9164. if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
  9165. std::string RefName = getName({VarName, "ref"});
  9166. if (!CGM.GetGlobalValue(RefName)) {
  9167. llvm::Constant *AddrRef =
  9168. getOrCreateInternalVariable(Addr->getType(), RefName);
  9169. auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
  9170. GVAddrRef->setConstant(/*Val=*/true);
  9171. GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
  9172. GVAddrRef->setInitializer(Addr);
  9173. CGM.addCompilerUsedGlobal(GVAddrRef);
  9174. }
  9175. }
  9176. } else {
  9177. assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  9178. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  9179. HasRequiresUnifiedSharedMemory)) &&
  9180. "Declare target attribute must link or to with unified memory.");
  9181. if (*Res == OMPDeclareTargetDeclAttr::MT_Link)
  9182. Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
  9183. else
  9184. Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
  9185. if (CGM.getLangOpts().OpenMPIsDevice) {
  9186. VarName = Addr->getName();
  9187. Addr = nullptr;
  9188. } else {
  9189. VarName = getAddrOfDeclareTargetVar(VD).getName();
  9190. Addr = cast<llvm::Constant>(getAddrOfDeclareTargetVar(VD).getPointer());
  9191. }
  9192. VarSize = CGM.getPointerSize();
  9193. Linkage = llvm::GlobalValue::WeakAnyLinkage;
  9194. }
  9195. OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
  9196. VarName, Addr, VarSize, Flags, Linkage);
  9197. }
  9198. bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
  9199. if (isa<FunctionDecl>(GD.getDecl()) ||
  9200. isa<OMPDeclareReductionDecl>(GD.getDecl()))
  9201. return emitTargetFunctions(GD);
  9202. return emitTargetGlobalVariable(GD);
  9203. }
  9204. void CGOpenMPRuntime::emitDeferredTargetDecls() const {
  9205. for (const VarDecl *VD : DeferredGlobalVariables) {
  9206. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  9207. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  9208. if (!Res)
  9209. continue;
  9210. if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  9211. !HasRequiresUnifiedSharedMemory) {
  9212. CGM.EmitGlobal(VD);
  9213. } else {
  9214. assert((*Res == OMPDeclareTargetDeclAttr::MT_Link ||
  9215. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  9216. HasRequiresUnifiedSharedMemory)) &&
  9217. "Expected link clause or to clause with unified memory.");
  9218. (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  9219. }
  9220. }
  9221. }
  9222. void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
  9223. CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
  9224. assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
  9225. " Expected target-based directive.");
  9226. }
  9227. void CGOpenMPRuntime::checkArchForUnifiedAddressing(
  9228. const OMPRequiresDecl *D) {
  9229. for (const OMPClause *Clause : D->clauselists()) {
  9230. if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
  9231. HasRequiresUnifiedSharedMemory = true;
  9232. break;
  9233. }
  9234. }
  9235. }
  9236. bool CGOpenMPRuntime::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
  9237. LangAS &AS) {
  9238. if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
  9239. return false;
  9240. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  9241. switch(A->getAllocatorType()) {
  9242. case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
  9243. // Not supported, fallback to the default mem space.
  9244. case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
  9245. case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
  9246. case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
  9247. case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
  9248. case OMPAllocateDeclAttr::OMPThreadMemAlloc:
  9249. case OMPAllocateDeclAttr::OMPConstMemAlloc:
  9250. case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
  9251. AS = LangAS::Default;
  9252. return true;
  9253. case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
  9254. llvm_unreachable("Expected predefined allocator for the variables with the "
  9255. "static storage.");
  9256. }
  9257. return false;
  9258. }
  9259. bool CGOpenMPRuntime::hasRequiresUnifiedSharedMemory() const {
  9260. return HasRequiresUnifiedSharedMemory;
  9261. }
  9262. CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
  9263. CodeGenModule &CGM)
  9264. : CGM(CGM) {
  9265. if (CGM.getLangOpts().OpenMPIsDevice) {
  9266. SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
  9267. CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
  9268. }
  9269. }
  9270. CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
  9271. if (CGM.getLangOpts().OpenMPIsDevice)
  9272. CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
  9273. }
  9274. bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
  9275. if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
  9276. return true;
  9277. StringRef Name = CGM.getMangledName(GD);
  9278. const auto *D = cast<FunctionDecl>(GD.getDecl());
  9279. // Do not to emit function if it is marked as declare target as it was already
  9280. // emitted.
  9281. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
  9282. if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
  9283. if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
  9284. return !F->isDeclaration();
  9285. return false;
  9286. }
  9287. return true;
  9288. }
  9289. return !AlreadyEmittedTargetFunctions.insert(Name).second;
  9290. }
  9291. llvm::Function *CGOpenMPRuntime::emitRequiresDirectiveRegFun() {
  9292. // If we don't have entries or if we are emitting code for the device, we
  9293. // don't need to do anything.
  9294. if (CGM.getLangOpts().OMPTargetTriples.empty() ||
  9295. CGM.getLangOpts().OpenMPSimd || CGM.getLangOpts().OpenMPIsDevice ||
  9296. (OffloadEntriesInfoManager.empty() &&
  9297. !HasEmittedDeclareTargetRegion &&
  9298. !HasEmittedTargetRegion))
  9299. return nullptr;
  9300. // Create and register the function that handles the requires directives.
  9301. ASTContext &C = CGM.getContext();
  9302. llvm::Function *RequiresRegFn;
  9303. {
  9304. CodeGenFunction CGF(CGM);
  9305. const auto &FI = CGM.getTypes().arrangeNullaryFunction();
  9306. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  9307. std::string ReqName = getName({"omp_offloading", "requires_reg"});
  9308. RequiresRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, ReqName, FI);
  9309. CGF.StartFunction(GlobalDecl(), C.VoidTy, RequiresRegFn, FI, {});
  9310. OpenMPOffloadingRequiresDirFlags Flags = OMP_REQ_NONE;
  9311. // TODO: check for other requires clauses.
  9312. // The requires directive takes effect only when a target region is
  9313. // present in the compilation unit. Otherwise it is ignored and not
  9314. // passed to the runtime. This avoids the runtime from throwing an error
  9315. // for mismatching requires clauses across compilation units that don't
  9316. // contain at least 1 target region.
  9317. assert((HasEmittedTargetRegion ||
  9318. HasEmittedDeclareTargetRegion ||
  9319. !OffloadEntriesInfoManager.empty()) &&
  9320. "Target or declare target region expected.");
  9321. if (HasRequiresUnifiedSharedMemory)
  9322. Flags = OMP_REQ_UNIFIED_SHARED_MEMORY;
  9323. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_requires),
  9324. llvm::ConstantInt::get(CGM.Int64Ty, Flags));
  9325. CGF.FinishFunction();
  9326. }
  9327. return RequiresRegFn;
  9328. }
  9329. void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
  9330. const OMPExecutableDirective &D,
  9331. SourceLocation Loc,
  9332. llvm::Function *OutlinedFn,
  9333. ArrayRef<llvm::Value *> CapturedVars) {
  9334. if (!CGF.HaveInsertPoint())
  9335. return;
  9336. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  9337. CodeGenFunction::RunCleanupsScope Scope(CGF);
  9338. // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
  9339. llvm::Value *Args[] = {
  9340. RTLoc,
  9341. CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
  9342. CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
  9343. llvm::SmallVector<llvm::Value *, 16> RealArgs;
  9344. RealArgs.append(std::begin(Args), std::end(Args));
  9345. RealArgs.append(CapturedVars.begin(), CapturedVars.end());
  9346. llvm::FunctionCallee RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
  9347. CGF.EmitRuntimeCall(RTLFn, RealArgs);
  9348. }
  9349. void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
  9350. const Expr *NumTeams,
  9351. const Expr *ThreadLimit,
  9352. SourceLocation Loc) {
  9353. if (!CGF.HaveInsertPoint())
  9354. return;
  9355. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  9356. llvm::Value *NumTeamsVal =
  9357. NumTeams
  9358. ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
  9359. CGF.CGM.Int32Ty, /* isSigned = */ true)
  9360. : CGF.Builder.getInt32(0);
  9361. llvm::Value *ThreadLimitVal =
  9362. ThreadLimit
  9363. ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
  9364. CGF.CGM.Int32Ty, /* isSigned = */ true)
  9365. : CGF.Builder.getInt32(0);
  9366. // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
  9367. llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
  9368. ThreadLimitVal};
  9369. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
  9370. PushNumTeamsArgs);
  9371. }
  9372. void CGOpenMPRuntime::emitTargetDataCalls(
  9373. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  9374. const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
  9375. if (!CGF.HaveInsertPoint())
  9376. return;
  9377. // Action used to replace the default codegen action and turn privatization
  9378. // off.
  9379. PrePostActionTy NoPrivAction;
  9380. // Generate the code for the opening of the data environment. Capture all the
  9381. // arguments of the runtime call by reference because they are used in the
  9382. // closing of the region.
  9383. auto &&BeginThenGen = [this, &D, Device, &Info,
  9384. &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
  9385. // Fill up the arrays with all the mapped variables.
  9386. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  9387. MappableExprsHandler::MapValuesArrayTy Pointers;
  9388. MappableExprsHandler::MapValuesArrayTy Sizes;
  9389. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  9390. // Get map clause information.
  9391. MappableExprsHandler MCHandler(D, CGF);
  9392. MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
  9393. // Fill up the arrays and create the arguments.
  9394. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  9395. llvm::Value *BasePointersArrayArg = nullptr;
  9396. llvm::Value *PointersArrayArg = nullptr;
  9397. llvm::Value *SizesArrayArg = nullptr;
  9398. llvm::Value *MapTypesArrayArg = nullptr;
  9399. emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
  9400. SizesArrayArg, MapTypesArrayArg, Info);
  9401. // Emit device ID if any.
  9402. llvm::Value *DeviceID = nullptr;
  9403. if (Device) {
  9404. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  9405. CGF.Int64Ty, /*isSigned=*/true);
  9406. } else {
  9407. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  9408. }
  9409. // Emit the number of elements in the offloading arrays.
  9410. llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
  9411. llvm::Value *OffloadingArgs[] = {
  9412. DeviceID, PointerNum, BasePointersArrayArg,
  9413. PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
  9414. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
  9415. OffloadingArgs);
  9416. // If device pointer privatization is required, emit the body of the region
  9417. // here. It will have to be duplicated: with and without privatization.
  9418. if (!Info.CaptureDeviceAddrMap.empty())
  9419. CodeGen(CGF);
  9420. };
  9421. // Generate code for the closing of the data region.
  9422. auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
  9423. PrePostActionTy &) {
  9424. assert(Info.isValid() && "Invalid data environment closing arguments.");
  9425. llvm::Value *BasePointersArrayArg = nullptr;
  9426. llvm::Value *PointersArrayArg = nullptr;
  9427. llvm::Value *SizesArrayArg = nullptr;
  9428. llvm::Value *MapTypesArrayArg = nullptr;
  9429. emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
  9430. SizesArrayArg, MapTypesArrayArg, Info);
  9431. // Emit device ID if any.
  9432. llvm::Value *DeviceID = nullptr;
  9433. if (Device) {
  9434. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  9435. CGF.Int64Ty, /*isSigned=*/true);
  9436. } else {
  9437. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  9438. }
  9439. // Emit the number of elements in the offloading arrays.
  9440. llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
  9441. llvm::Value *OffloadingArgs[] = {
  9442. DeviceID, PointerNum, BasePointersArrayArg,
  9443. PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
  9444. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
  9445. OffloadingArgs);
  9446. };
  9447. // If we need device pointer privatization, we need to emit the body of the
  9448. // region with no privatization in the 'else' branch of the conditional.
  9449. // Otherwise, we don't have to do anything.
  9450. auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
  9451. PrePostActionTy &) {
  9452. if (!Info.CaptureDeviceAddrMap.empty()) {
  9453. CodeGen.setAction(NoPrivAction);
  9454. CodeGen(CGF);
  9455. }
  9456. };
  9457. // We don't have to do anything to close the region if the if clause evaluates
  9458. // to false.
  9459. auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
  9460. if (IfCond) {
  9461. emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
  9462. } else {
  9463. RegionCodeGenTy RCG(BeginThenGen);
  9464. RCG(CGF);
  9465. }
  9466. // If we don't require privatization of device pointers, we emit the body in
  9467. // between the runtime calls. This avoids duplicating the body code.
  9468. if (Info.CaptureDeviceAddrMap.empty()) {
  9469. CodeGen.setAction(NoPrivAction);
  9470. CodeGen(CGF);
  9471. }
  9472. if (IfCond) {
  9473. emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
  9474. } else {
  9475. RegionCodeGenTy RCG(EndThenGen);
  9476. RCG(CGF);
  9477. }
  9478. }
  9479. void CGOpenMPRuntime::emitTargetDataStandAloneCall(
  9480. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  9481. const Expr *Device) {
  9482. if (!CGF.HaveInsertPoint())
  9483. return;
  9484. assert((isa<OMPTargetEnterDataDirective>(D) ||
  9485. isa<OMPTargetExitDataDirective>(D) ||
  9486. isa<OMPTargetUpdateDirective>(D)) &&
  9487. "Expecting either target enter, exit data, or update directives.");
  9488. CodeGenFunction::OMPTargetDataInfo InputInfo;
  9489. llvm::Value *MapTypesArray = nullptr;
  9490. // Generate the code for the opening of the data environment.
  9491. auto &&ThenGen = [this, &D, Device, &InputInfo,
  9492. &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
  9493. // Emit device ID if any.
  9494. llvm::Value *DeviceID = nullptr;
  9495. if (Device) {
  9496. DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
  9497. CGF.Int64Ty, /*isSigned=*/true);
  9498. } else {
  9499. DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
  9500. }
  9501. // Emit the number of elements in the offloading arrays.
  9502. llvm::Constant *PointerNum =
  9503. CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
  9504. llvm::Value *OffloadingArgs[] = {DeviceID,
  9505. PointerNum,
  9506. InputInfo.BasePointersArray.getPointer(),
  9507. InputInfo.PointersArray.getPointer(),
  9508. InputInfo.SizesArray.getPointer(),
  9509. MapTypesArray};
  9510. // Select the right runtime function call for each expected standalone
  9511. // directive.
  9512. const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
  9513. OpenMPRTLFunction RTLFn;
  9514. switch (D.getDirectiveKind()) {
  9515. case OMPD_target_enter_data:
  9516. RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
  9517. : OMPRTL__tgt_target_data_begin;
  9518. break;
  9519. case OMPD_target_exit_data:
  9520. RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
  9521. : OMPRTL__tgt_target_data_end;
  9522. break;
  9523. case OMPD_target_update:
  9524. RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
  9525. : OMPRTL__tgt_target_data_update;
  9526. break;
  9527. case OMPD_parallel:
  9528. case OMPD_for:
  9529. case OMPD_parallel_for:
  9530. case OMPD_parallel_sections:
  9531. case OMPD_for_simd:
  9532. case OMPD_parallel_for_simd:
  9533. case OMPD_cancel:
  9534. case OMPD_cancellation_point:
  9535. case OMPD_ordered:
  9536. case OMPD_threadprivate:
  9537. case OMPD_allocate:
  9538. case OMPD_task:
  9539. case OMPD_simd:
  9540. case OMPD_sections:
  9541. case OMPD_section:
  9542. case OMPD_single:
  9543. case OMPD_master:
  9544. case OMPD_critical:
  9545. case OMPD_taskyield:
  9546. case OMPD_barrier:
  9547. case OMPD_taskwait:
  9548. case OMPD_taskgroup:
  9549. case OMPD_atomic:
  9550. case OMPD_flush:
  9551. case OMPD_teams:
  9552. case OMPD_target_data:
  9553. case OMPD_distribute:
  9554. case OMPD_distribute_simd:
  9555. case OMPD_distribute_parallel_for:
  9556. case OMPD_distribute_parallel_for_simd:
  9557. case OMPD_teams_distribute:
  9558. case OMPD_teams_distribute_simd:
  9559. case OMPD_teams_distribute_parallel_for:
  9560. case OMPD_teams_distribute_parallel_for_simd:
  9561. case OMPD_declare_simd:
  9562. case OMPD_declare_variant:
  9563. case OMPD_declare_target:
  9564. case OMPD_end_declare_target:
  9565. case OMPD_declare_reduction:
  9566. case OMPD_declare_mapper:
  9567. case OMPD_taskloop:
  9568. case OMPD_taskloop_simd:
  9569. case OMPD_master_taskloop:
  9570. case OMPD_master_taskloop_simd:
  9571. case OMPD_parallel_master_taskloop:
  9572. case OMPD_target:
  9573. case OMPD_target_simd:
  9574. case OMPD_target_teams_distribute:
  9575. case OMPD_target_teams_distribute_simd:
  9576. case OMPD_target_teams_distribute_parallel_for:
  9577. case OMPD_target_teams_distribute_parallel_for_simd:
  9578. case OMPD_target_teams:
  9579. case OMPD_target_parallel:
  9580. case OMPD_target_parallel_for:
  9581. case OMPD_target_parallel_for_simd:
  9582. case OMPD_requires:
  9583. case OMPD_unknown:
  9584. llvm_unreachable("Unexpected standalone target data directive.");
  9585. break;
  9586. }
  9587. CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
  9588. };
  9589. auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
  9590. CodeGenFunction &CGF, PrePostActionTy &) {
  9591. // Fill up the arrays with all the mapped variables.
  9592. MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
  9593. MappableExprsHandler::MapValuesArrayTy Pointers;
  9594. MappableExprsHandler::MapValuesArrayTy Sizes;
  9595. MappableExprsHandler::MapFlagsArrayTy MapTypes;
  9596. // Get map clause information.
  9597. MappableExprsHandler MEHandler(D, CGF);
  9598. MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
  9599. TargetDataInfo Info;
  9600. // Fill up the arrays and create the arguments.
  9601. emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
  9602. emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
  9603. Info.PointersArray, Info.SizesArray,
  9604. Info.MapTypesArray, Info);
  9605. InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
  9606. InputInfo.BasePointersArray =
  9607. Address(Info.BasePointersArray, CGM.getPointerAlign());
  9608. InputInfo.PointersArray =
  9609. Address(Info.PointersArray, CGM.getPointerAlign());
  9610. InputInfo.SizesArray =
  9611. Address(Info.SizesArray, CGM.getPointerAlign());
  9612. MapTypesArray = Info.MapTypesArray;
  9613. if (D.hasClausesOfKind<OMPDependClause>())
  9614. CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
  9615. else
  9616. emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
  9617. };
  9618. if (IfCond) {
  9619. emitOMPIfClause(CGF, IfCond, TargetThenGen,
  9620. [](CodeGenFunction &CGF, PrePostActionTy &) {});
  9621. } else {
  9622. RegionCodeGenTy ThenRCG(TargetThenGen);
  9623. ThenRCG(CGF);
  9624. }
  9625. }
  9626. namespace {
  9627. /// Kind of parameter in a function with 'declare simd' directive.
  9628. enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
  9629. /// Attribute set of the parameter.
  9630. struct ParamAttrTy {
  9631. ParamKindTy Kind = Vector;
  9632. llvm::APSInt StrideOrArg;
  9633. llvm::APSInt Alignment;
  9634. };
  9635. } // namespace
  9636. static unsigned evaluateCDTSize(const FunctionDecl *FD,
  9637. ArrayRef<ParamAttrTy> ParamAttrs) {
  9638. // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
  9639. // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
  9640. // of that clause. The VLEN value must be power of 2.
  9641. // In other case the notion of the function`s "characteristic data type" (CDT)
  9642. // is used to compute the vector length.
  9643. // CDT is defined in the following order:
  9644. // a) For non-void function, the CDT is the return type.
  9645. // b) If the function has any non-uniform, non-linear parameters, then the
  9646. // CDT is the type of the first such parameter.
  9647. // c) If the CDT determined by a) or b) above is struct, union, or class
  9648. // type which is pass-by-value (except for the type that maps to the
  9649. // built-in complex data type), the characteristic data type is int.
  9650. // d) If none of the above three cases is applicable, the CDT is int.
  9651. // The VLEN is then determined based on the CDT and the size of vector
  9652. // register of that ISA for which current vector version is generated. The
  9653. // VLEN is computed using the formula below:
  9654. // VLEN = sizeof(vector_register) / sizeof(CDT),
  9655. // where vector register size specified in section 3.2.1 Registers and the
  9656. // Stack Frame of original AMD64 ABI document.
  9657. QualType RetType = FD->getReturnType();
  9658. if (RetType.isNull())
  9659. return 0;
  9660. ASTContext &C = FD->getASTContext();
  9661. QualType CDT;
  9662. if (!RetType.isNull() && !RetType->isVoidType()) {
  9663. CDT = RetType;
  9664. } else {
  9665. unsigned Offset = 0;
  9666. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  9667. if (ParamAttrs[Offset].Kind == Vector)
  9668. CDT = C.getPointerType(C.getRecordType(MD->getParent()));
  9669. ++Offset;
  9670. }
  9671. if (CDT.isNull()) {
  9672. for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
  9673. if (ParamAttrs[I + Offset].Kind == Vector) {
  9674. CDT = FD->getParamDecl(I)->getType();
  9675. break;
  9676. }
  9677. }
  9678. }
  9679. }
  9680. if (CDT.isNull())
  9681. CDT = C.IntTy;
  9682. CDT = CDT->getCanonicalTypeUnqualified();
  9683. if (CDT->isRecordType() || CDT->isUnionType())
  9684. CDT = C.IntTy;
  9685. return C.getTypeSize(CDT);
  9686. }
  9687. static void
  9688. emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
  9689. const llvm::APSInt &VLENVal,
  9690. ArrayRef<ParamAttrTy> ParamAttrs,
  9691. OMPDeclareSimdDeclAttr::BranchStateTy State) {
  9692. struct ISADataTy {
  9693. char ISA;
  9694. unsigned VecRegSize;
  9695. };
  9696. ISADataTy ISAData[] = {
  9697. {
  9698. 'b', 128
  9699. }, // SSE
  9700. {
  9701. 'c', 256
  9702. }, // AVX
  9703. {
  9704. 'd', 256
  9705. }, // AVX2
  9706. {
  9707. 'e', 512
  9708. }, // AVX512
  9709. };
  9710. llvm::SmallVector<char, 2> Masked;
  9711. switch (State) {
  9712. case OMPDeclareSimdDeclAttr::BS_Undefined:
  9713. Masked.push_back('N');
  9714. Masked.push_back('M');
  9715. break;
  9716. case OMPDeclareSimdDeclAttr::BS_Notinbranch:
  9717. Masked.push_back('N');
  9718. break;
  9719. case OMPDeclareSimdDeclAttr::BS_Inbranch:
  9720. Masked.push_back('M');
  9721. break;
  9722. }
  9723. for (char Mask : Masked) {
  9724. for (const ISADataTy &Data : ISAData) {
  9725. SmallString<256> Buffer;
  9726. llvm::raw_svector_ostream Out(Buffer);
  9727. Out << "_ZGV" << Data.ISA << Mask;
  9728. if (!VLENVal) {
  9729. unsigned NumElts = evaluateCDTSize(FD, ParamAttrs);
  9730. assert(NumElts && "Non-zero simdlen/cdtsize expected");
  9731. Out << llvm::APSInt::getUnsigned(Data.VecRegSize / NumElts);
  9732. } else {
  9733. Out << VLENVal;
  9734. }
  9735. for (const ParamAttrTy &ParamAttr : ParamAttrs) {
  9736. switch (ParamAttr.Kind){
  9737. case LinearWithVarStride:
  9738. Out << 's' << ParamAttr.StrideOrArg;
  9739. break;
  9740. case Linear:
  9741. Out << 'l';
  9742. if (!!ParamAttr.StrideOrArg)
  9743. Out << ParamAttr.StrideOrArg;
  9744. break;
  9745. case Uniform:
  9746. Out << 'u';
  9747. break;
  9748. case Vector:
  9749. Out << 'v';
  9750. break;
  9751. }
  9752. if (!!ParamAttr.Alignment)
  9753. Out << 'a' << ParamAttr.Alignment;
  9754. }
  9755. Out << '_' << Fn->getName();
  9756. Fn->addFnAttr(Out.str());
  9757. }
  9758. }
  9759. }
  9760. // This are the Functions that are needed to mangle the name of the
  9761. // vector functions generated by the compiler, according to the rules
  9762. // defined in the "Vector Function ABI specifications for AArch64",
  9763. // available at
  9764. // https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi.
  9765. /// Maps To Vector (MTV), as defined in 3.1.1 of the AAVFABI.
  9766. ///
  9767. /// TODO: Need to implement the behavior for reference marked with a
  9768. /// var or no linear modifiers (1.b in the section). For this, we
  9769. /// need to extend ParamKindTy to support the linear modifiers.
  9770. static bool getAArch64MTV(QualType QT, ParamKindTy Kind) {
  9771. QT = QT.getCanonicalType();
  9772. if (QT->isVoidType())
  9773. return false;
  9774. if (Kind == ParamKindTy::Uniform)
  9775. return false;
  9776. if (Kind == ParamKindTy::Linear)
  9777. return false;
  9778. // TODO: Handle linear references with modifiers
  9779. if (Kind == ParamKindTy::LinearWithVarStride)
  9780. return false;
  9781. return true;
  9782. }
  9783. /// Pass By Value (PBV), as defined in 3.1.2 of the AAVFABI.
  9784. static bool getAArch64PBV(QualType QT, ASTContext &C) {
  9785. QT = QT.getCanonicalType();
  9786. unsigned Size = C.getTypeSize(QT);
  9787. // Only scalars and complex within 16 bytes wide set PVB to true.
  9788. if (Size != 8 && Size != 16 && Size != 32 && Size != 64 && Size != 128)
  9789. return false;
  9790. if (QT->isFloatingType())
  9791. return true;
  9792. if (QT->isIntegerType())
  9793. return true;
  9794. if (QT->isPointerType())
  9795. return true;
  9796. // TODO: Add support for complex types (section 3.1.2, item 2).
  9797. return false;
  9798. }
  9799. /// Computes the lane size (LS) of a return type or of an input parameter,
  9800. /// as defined by `LS(P)` in 3.2.1 of the AAVFABI.
  9801. /// TODO: Add support for references, section 3.2.1, item 1.
  9802. static unsigned getAArch64LS(QualType QT, ParamKindTy Kind, ASTContext &C) {
  9803. if (getAArch64MTV(QT, Kind) && QT.getCanonicalType()->isPointerType()) {
  9804. QualType PTy = QT.getCanonicalType()->getPointeeType();
  9805. if (getAArch64PBV(PTy, C))
  9806. return C.getTypeSize(PTy);
  9807. }
  9808. if (getAArch64PBV(QT, C))
  9809. return C.getTypeSize(QT);
  9810. return C.getTypeSize(C.getUIntPtrType());
  9811. }
  9812. // Get Narrowest Data Size (NDS) and Widest Data Size (WDS) from the
  9813. // signature of the scalar function, as defined in 3.2.2 of the
  9814. // AAVFABI.
  9815. static std::tuple<unsigned, unsigned, bool>
  9816. getNDSWDS(const FunctionDecl *FD, ArrayRef<ParamAttrTy> ParamAttrs) {
  9817. QualType RetType = FD->getReturnType().getCanonicalType();
  9818. ASTContext &C = FD->getASTContext();
  9819. bool OutputBecomesInput = false;
  9820. llvm::SmallVector<unsigned, 8> Sizes;
  9821. if (!RetType->isVoidType()) {
  9822. Sizes.push_back(getAArch64LS(RetType, ParamKindTy::Vector, C));
  9823. if (!getAArch64PBV(RetType, C) && getAArch64MTV(RetType, {}))
  9824. OutputBecomesInput = true;
  9825. }
  9826. for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
  9827. QualType QT = FD->getParamDecl(I)->getType().getCanonicalType();
  9828. Sizes.push_back(getAArch64LS(QT, ParamAttrs[I].Kind, C));
  9829. }
  9830. assert(!Sizes.empty() && "Unable to determine NDS and WDS.");
  9831. // The LS of a function parameter / return value can only be a power
  9832. // of 2, starting from 8 bits, up to 128.
  9833. assert(std::all_of(Sizes.begin(), Sizes.end(),
  9834. [](unsigned Size) {
  9835. return Size == 8 || Size == 16 || Size == 32 ||
  9836. Size == 64 || Size == 128;
  9837. }) &&
  9838. "Invalid size");
  9839. return std::make_tuple(*std::min_element(std::begin(Sizes), std::end(Sizes)),
  9840. *std::max_element(std::begin(Sizes), std::end(Sizes)),
  9841. OutputBecomesInput);
  9842. }
  9843. /// Mangle the parameter part of the vector function name according to
  9844. /// their OpenMP classification. The mangling function is defined in
  9845. /// section 3.5 of the AAVFABI.
  9846. static std::string mangleVectorParameters(ArrayRef<ParamAttrTy> ParamAttrs) {
  9847. SmallString<256> Buffer;
  9848. llvm::raw_svector_ostream Out(Buffer);
  9849. for (const auto &ParamAttr : ParamAttrs) {
  9850. switch (ParamAttr.Kind) {
  9851. case LinearWithVarStride:
  9852. Out << "ls" << ParamAttr.StrideOrArg;
  9853. break;
  9854. case Linear:
  9855. Out << 'l';
  9856. // Don't print the step value if it is not present or if it is
  9857. // equal to 1.
  9858. if (!!ParamAttr.StrideOrArg && ParamAttr.StrideOrArg != 1)
  9859. Out << ParamAttr.StrideOrArg;
  9860. break;
  9861. case Uniform:
  9862. Out << 'u';
  9863. break;
  9864. case Vector:
  9865. Out << 'v';
  9866. break;
  9867. }
  9868. if (!!ParamAttr.Alignment)
  9869. Out << 'a' << ParamAttr.Alignment;
  9870. }
  9871. return Out.str();
  9872. }
  9873. // Function used to add the attribute. The parameter `VLEN` is
  9874. // templated to allow the use of "x" when targeting scalable functions
  9875. // for SVE.
  9876. template <typename T>
  9877. static void addAArch64VectorName(T VLEN, StringRef LMask, StringRef Prefix,
  9878. char ISA, StringRef ParSeq,
  9879. StringRef MangledName, bool OutputBecomesInput,
  9880. llvm::Function *Fn) {
  9881. SmallString<256> Buffer;
  9882. llvm::raw_svector_ostream Out(Buffer);
  9883. Out << Prefix << ISA << LMask << VLEN;
  9884. if (OutputBecomesInput)
  9885. Out << "v";
  9886. Out << ParSeq << "_" << MangledName;
  9887. Fn->addFnAttr(Out.str());
  9888. }
  9889. // Helper function to generate the Advanced SIMD names depending on
  9890. // the value of the NDS when simdlen is not present.
  9891. static void addAArch64AdvSIMDNDSNames(unsigned NDS, StringRef Mask,
  9892. StringRef Prefix, char ISA,
  9893. StringRef ParSeq, StringRef MangledName,
  9894. bool OutputBecomesInput,
  9895. llvm::Function *Fn) {
  9896. switch (NDS) {
  9897. case 8:
  9898. addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
  9899. OutputBecomesInput, Fn);
  9900. addAArch64VectorName(16, Mask, Prefix, ISA, ParSeq, MangledName,
  9901. OutputBecomesInput, Fn);
  9902. break;
  9903. case 16:
  9904. addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
  9905. OutputBecomesInput, Fn);
  9906. addAArch64VectorName(8, Mask, Prefix, ISA, ParSeq, MangledName,
  9907. OutputBecomesInput, Fn);
  9908. break;
  9909. case 32:
  9910. addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
  9911. OutputBecomesInput, Fn);
  9912. addAArch64VectorName(4, Mask, Prefix, ISA, ParSeq, MangledName,
  9913. OutputBecomesInput, Fn);
  9914. break;
  9915. case 64:
  9916. case 128:
  9917. addAArch64VectorName(2, Mask, Prefix, ISA, ParSeq, MangledName,
  9918. OutputBecomesInput, Fn);
  9919. break;
  9920. default:
  9921. llvm_unreachable("Scalar type is too wide.");
  9922. }
  9923. }
  9924. /// Emit vector function attributes for AArch64, as defined in the AAVFABI.
  9925. static void emitAArch64DeclareSimdFunction(
  9926. CodeGenModule &CGM, const FunctionDecl *FD, unsigned UserVLEN,
  9927. ArrayRef<ParamAttrTy> ParamAttrs,
  9928. OMPDeclareSimdDeclAttr::BranchStateTy State, StringRef MangledName,
  9929. char ISA, unsigned VecRegSize, llvm::Function *Fn, SourceLocation SLoc) {
  9930. // Get basic data for building the vector signature.
  9931. const auto Data = getNDSWDS(FD, ParamAttrs);
  9932. const unsigned NDS = std::get<0>(Data);
  9933. const unsigned WDS = std::get<1>(Data);
  9934. const bool OutputBecomesInput = std::get<2>(Data);
  9935. // Check the values provided via `simdlen` by the user.
  9936. // 1. A `simdlen(1)` doesn't produce vector signatures,
  9937. if (UserVLEN == 1) {
  9938. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  9939. DiagnosticsEngine::Warning,
  9940. "The clause simdlen(1) has no effect when targeting aarch64.");
  9941. CGM.getDiags().Report(SLoc, DiagID);
  9942. return;
  9943. }
  9944. // 2. Section 3.3.1, item 1: user input must be a power of 2 for
  9945. // Advanced SIMD output.
  9946. if (ISA == 'n' && UserVLEN && !llvm::isPowerOf2_32(UserVLEN)) {
  9947. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  9948. DiagnosticsEngine::Warning, "The value specified in simdlen must be a "
  9949. "power of 2 when targeting Advanced SIMD.");
  9950. CGM.getDiags().Report(SLoc, DiagID);
  9951. return;
  9952. }
  9953. // 3. Section 3.4.1. SVE fixed lengh must obey the architectural
  9954. // limits.
  9955. if (ISA == 's' && UserVLEN != 0) {
  9956. if ((UserVLEN * WDS > 2048) || (UserVLEN * WDS % 128 != 0)) {
  9957. unsigned DiagID = CGM.getDiags().getCustomDiagID(
  9958. DiagnosticsEngine::Warning, "The clause simdlen must fit the %0-bit "
  9959. "lanes in the architectural constraints "
  9960. "for SVE (min is 128-bit, max is "
  9961. "2048-bit, by steps of 128-bit)");
  9962. CGM.getDiags().Report(SLoc, DiagID) << WDS;
  9963. return;
  9964. }
  9965. }
  9966. // Sort out parameter sequence.
  9967. const std::string ParSeq = mangleVectorParameters(ParamAttrs);
  9968. StringRef Prefix = "_ZGV";
  9969. // Generate simdlen from user input (if any).
  9970. if (UserVLEN) {
  9971. if (ISA == 's') {
  9972. // SVE generates only a masked function.
  9973. addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
  9974. OutputBecomesInput, Fn);
  9975. } else {
  9976. assert(ISA == 'n' && "Expected ISA either 's' or 'n'.");
  9977. // Advanced SIMD generates one or two functions, depending on
  9978. // the `[not]inbranch` clause.
  9979. switch (State) {
  9980. case OMPDeclareSimdDeclAttr::BS_Undefined:
  9981. addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
  9982. OutputBecomesInput, Fn);
  9983. addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
  9984. OutputBecomesInput, Fn);
  9985. break;
  9986. case OMPDeclareSimdDeclAttr::BS_Notinbranch:
  9987. addAArch64VectorName(UserVLEN, "N", Prefix, ISA, ParSeq, MangledName,
  9988. OutputBecomesInput, Fn);
  9989. break;
  9990. case OMPDeclareSimdDeclAttr::BS_Inbranch:
  9991. addAArch64VectorName(UserVLEN, "M", Prefix, ISA, ParSeq, MangledName,
  9992. OutputBecomesInput, Fn);
  9993. break;
  9994. }
  9995. }
  9996. } else {
  9997. // If no user simdlen is provided, follow the AAVFABI rules for
  9998. // generating the vector length.
  9999. if (ISA == 's') {
  10000. // SVE, section 3.4.1, item 1.
  10001. addAArch64VectorName("x", "M", Prefix, ISA, ParSeq, MangledName,
  10002. OutputBecomesInput, Fn);
  10003. } else {
  10004. assert(ISA == 'n' && "Expected ISA either 's' or 'n'.");
  10005. // Advanced SIMD, Section 3.3.1 of the AAVFABI, generates one or
  10006. // two vector names depending on the use of the clause
  10007. // `[not]inbranch`.
  10008. switch (State) {
  10009. case OMPDeclareSimdDeclAttr::BS_Undefined:
  10010. addAArch64AdvSIMDNDSNames(NDS, "N", Prefix, ISA, ParSeq, MangledName,
  10011. OutputBecomesInput, Fn);
  10012. addAArch64AdvSIMDNDSNames(NDS, "M", Prefix, ISA, ParSeq, MangledName,
  10013. OutputBecomesInput, Fn);
  10014. break;
  10015. case OMPDeclareSimdDeclAttr::BS_Notinbranch:
  10016. addAArch64AdvSIMDNDSNames(NDS, "N", Prefix, ISA, ParSeq, MangledName,
  10017. OutputBecomesInput, Fn);
  10018. break;
  10019. case OMPDeclareSimdDeclAttr::BS_Inbranch:
  10020. addAArch64AdvSIMDNDSNames(NDS, "M", Prefix, ISA, ParSeq, MangledName,
  10021. OutputBecomesInput, Fn);
  10022. break;
  10023. }
  10024. }
  10025. }
  10026. }
  10027. void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
  10028. llvm::Function *Fn) {
  10029. ASTContext &C = CGM.getContext();
  10030. FD = FD->getMostRecentDecl();
  10031. // Map params to their positions in function decl.
  10032. llvm::DenseMap<const Decl *, unsigned> ParamPositions;
  10033. if (isa<CXXMethodDecl>(FD))
  10034. ParamPositions.try_emplace(FD, 0);
  10035. unsigned ParamPos = ParamPositions.size();
  10036. for (const ParmVarDecl *P : FD->parameters()) {
  10037. ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
  10038. ++ParamPos;
  10039. }
  10040. while (FD) {
  10041. for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
  10042. llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
  10043. // Mark uniform parameters.
  10044. for (const Expr *E : Attr->uniforms()) {
  10045. E = E->IgnoreParenImpCasts();
  10046. unsigned Pos;
  10047. if (isa<CXXThisExpr>(E)) {
  10048. Pos = ParamPositions[FD];
  10049. } else {
  10050. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  10051. ->getCanonicalDecl();
  10052. Pos = ParamPositions[PVD];
  10053. }
  10054. ParamAttrs[Pos].Kind = Uniform;
  10055. }
  10056. // Get alignment info.
  10057. auto NI = Attr->alignments_begin();
  10058. for (const Expr *E : Attr->aligneds()) {
  10059. E = E->IgnoreParenImpCasts();
  10060. unsigned Pos;
  10061. QualType ParmTy;
  10062. if (isa<CXXThisExpr>(E)) {
  10063. Pos = ParamPositions[FD];
  10064. ParmTy = E->getType();
  10065. } else {
  10066. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  10067. ->getCanonicalDecl();
  10068. Pos = ParamPositions[PVD];
  10069. ParmTy = PVD->getType();
  10070. }
  10071. ParamAttrs[Pos].Alignment =
  10072. (*NI)
  10073. ? (*NI)->EvaluateKnownConstInt(C)
  10074. : llvm::APSInt::getUnsigned(
  10075. C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
  10076. .getQuantity());
  10077. ++NI;
  10078. }
  10079. // Mark linear parameters.
  10080. auto SI = Attr->steps_begin();
  10081. auto MI = Attr->modifiers_begin();
  10082. for (const Expr *E : Attr->linears()) {
  10083. E = E->IgnoreParenImpCasts();
  10084. unsigned Pos;
  10085. if (isa<CXXThisExpr>(E)) {
  10086. Pos = ParamPositions[FD];
  10087. } else {
  10088. const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
  10089. ->getCanonicalDecl();
  10090. Pos = ParamPositions[PVD];
  10091. }
  10092. ParamAttrTy &ParamAttr = ParamAttrs[Pos];
  10093. ParamAttr.Kind = Linear;
  10094. if (*SI) {
  10095. Expr::EvalResult Result;
  10096. if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
  10097. if (const auto *DRE =
  10098. cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
  10099. if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
  10100. ParamAttr.Kind = LinearWithVarStride;
  10101. ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
  10102. ParamPositions[StridePVD->getCanonicalDecl()]);
  10103. }
  10104. }
  10105. } else {
  10106. ParamAttr.StrideOrArg = Result.Val.getInt();
  10107. }
  10108. }
  10109. ++SI;
  10110. ++MI;
  10111. }
  10112. llvm::APSInt VLENVal;
  10113. SourceLocation ExprLoc;
  10114. const Expr *VLENExpr = Attr->getSimdlen();
  10115. if (VLENExpr) {
  10116. VLENVal = VLENExpr->EvaluateKnownConstInt(C);
  10117. ExprLoc = VLENExpr->getExprLoc();
  10118. }
  10119. OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
  10120. if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
  10121. CGM.getTriple().getArch() == llvm::Triple::x86_64) {
  10122. emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
  10123. } else if (CGM.getTriple().getArch() == llvm::Triple::aarch64) {
  10124. unsigned VLEN = VLENVal.getExtValue();
  10125. StringRef MangledName = Fn->getName();
  10126. if (CGM.getTarget().hasFeature("sve"))
  10127. emitAArch64DeclareSimdFunction(CGM, FD, VLEN, ParamAttrs, State,
  10128. MangledName, 's', 128, Fn, ExprLoc);
  10129. if (CGM.getTarget().hasFeature("neon"))
  10130. emitAArch64DeclareSimdFunction(CGM, FD, VLEN, ParamAttrs, State,
  10131. MangledName, 'n', 128, Fn, ExprLoc);
  10132. }
  10133. }
  10134. FD = FD->getPreviousDecl();
  10135. }
  10136. }
  10137. namespace {
  10138. /// Cleanup action for doacross support.
  10139. class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
  10140. public:
  10141. static const int DoacrossFinArgs = 2;
  10142. private:
  10143. llvm::FunctionCallee RTLFn;
  10144. llvm::Value *Args[DoacrossFinArgs];
  10145. public:
  10146. DoacrossCleanupTy(llvm::FunctionCallee RTLFn,
  10147. ArrayRef<llvm::Value *> CallArgs)
  10148. : RTLFn(RTLFn) {
  10149. assert(CallArgs.size() == DoacrossFinArgs);
  10150. std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
  10151. }
  10152. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  10153. if (!CGF.HaveInsertPoint())
  10154. return;
  10155. CGF.EmitRuntimeCall(RTLFn, Args);
  10156. }
  10157. };
  10158. } // namespace
  10159. void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
  10160. const OMPLoopDirective &D,
  10161. ArrayRef<Expr *> NumIterations) {
  10162. if (!CGF.HaveInsertPoint())
  10163. return;
  10164. ASTContext &C = CGM.getContext();
  10165. QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
  10166. RecordDecl *RD;
  10167. if (KmpDimTy.isNull()) {
  10168. // Build struct kmp_dim { // loop bounds info casted to kmp_int64
  10169. // kmp_int64 lo; // lower
  10170. // kmp_int64 up; // upper
  10171. // kmp_int64 st; // stride
  10172. // };
  10173. RD = C.buildImplicitRecord("kmp_dim");
  10174. RD->startDefinition();
  10175. addFieldToRecordDecl(C, RD, Int64Ty);
  10176. addFieldToRecordDecl(C, RD, Int64Ty);
  10177. addFieldToRecordDecl(C, RD, Int64Ty);
  10178. RD->completeDefinition();
  10179. KmpDimTy = C.getRecordType(RD);
  10180. } else {
  10181. RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
  10182. }
  10183. llvm::APInt Size(/*numBits=*/32, NumIterations.size());
  10184. QualType ArrayTy =
  10185. C.getConstantArrayType(KmpDimTy, Size, nullptr, ArrayType::Normal, 0);
  10186. Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
  10187. CGF.EmitNullInitialization(DimsAddr, ArrayTy);
  10188. enum { LowerFD = 0, UpperFD, StrideFD };
  10189. // Fill dims with data.
  10190. for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
  10191. LValue DimsLVal = CGF.MakeAddrLValue(
  10192. CGF.Builder.CreateConstArrayGEP(DimsAddr, I), KmpDimTy);
  10193. // dims.upper = num_iterations;
  10194. LValue UpperLVal = CGF.EmitLValueForField(
  10195. DimsLVal, *std::next(RD->field_begin(), UpperFD));
  10196. llvm::Value *NumIterVal =
  10197. CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
  10198. D.getNumIterations()->getType(), Int64Ty,
  10199. D.getNumIterations()->getExprLoc());
  10200. CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
  10201. // dims.stride = 1;
  10202. LValue StrideLVal = CGF.EmitLValueForField(
  10203. DimsLVal, *std::next(RD->field_begin(), StrideFD));
  10204. CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
  10205. StrideLVal);
  10206. }
  10207. // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
  10208. // kmp_int32 num_dims, struct kmp_dim * dims);
  10209. llvm::Value *Args[] = {
  10210. emitUpdateLocation(CGF, D.getBeginLoc()),
  10211. getThreadID(CGF, D.getBeginLoc()),
  10212. llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
  10213. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  10214. CGF.Builder.CreateConstArrayGEP(DimsAddr, 0).getPointer(),
  10215. CGM.VoidPtrTy)};
  10216. llvm::FunctionCallee RTLFn =
  10217. createRuntimeFunction(OMPRTL__kmpc_doacross_init);
  10218. CGF.EmitRuntimeCall(RTLFn, Args);
  10219. llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
  10220. emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
  10221. llvm::FunctionCallee FiniRTLFn =
  10222. createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
  10223. CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
  10224. llvm::makeArrayRef(FiniArgs));
  10225. }
  10226. void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
  10227. const OMPDependClause *C) {
  10228. QualType Int64Ty =
  10229. CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  10230. llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
  10231. QualType ArrayTy = CGM.getContext().getConstantArrayType(
  10232. Int64Ty, Size, nullptr, ArrayType::Normal, 0);
  10233. Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
  10234. for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
  10235. const Expr *CounterVal = C->getLoopData(I);
  10236. assert(CounterVal);
  10237. llvm::Value *CntVal = CGF.EmitScalarConversion(
  10238. CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
  10239. CounterVal->getExprLoc());
  10240. CGF.EmitStoreOfScalar(CntVal, CGF.Builder.CreateConstArrayGEP(CntAddr, I),
  10241. /*Volatile=*/false, Int64Ty);
  10242. }
  10243. llvm::Value *Args[] = {
  10244. emitUpdateLocation(CGF, C->getBeginLoc()),
  10245. getThreadID(CGF, C->getBeginLoc()),
  10246. CGF.Builder.CreateConstArrayGEP(CntAddr, 0).getPointer()};
  10247. llvm::FunctionCallee RTLFn;
  10248. if (C->getDependencyKind() == OMPC_DEPEND_source) {
  10249. RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
  10250. } else {
  10251. assert(C->getDependencyKind() == OMPC_DEPEND_sink);
  10252. RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
  10253. }
  10254. CGF.EmitRuntimeCall(RTLFn, Args);
  10255. }
  10256. void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
  10257. llvm::FunctionCallee Callee,
  10258. ArrayRef<llvm::Value *> Args) const {
  10259. assert(Loc.isValid() && "Outlined function call location must be valid.");
  10260. auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
  10261. if (auto *Fn = dyn_cast<llvm::Function>(Callee.getCallee())) {
  10262. if (Fn->doesNotThrow()) {
  10263. CGF.EmitNounwindRuntimeCall(Fn, Args);
  10264. return;
  10265. }
  10266. }
  10267. CGF.EmitRuntimeCall(Callee, Args);
  10268. }
  10269. void CGOpenMPRuntime::emitOutlinedFunctionCall(
  10270. CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
  10271. ArrayRef<llvm::Value *> Args) const {
  10272. emitCall(CGF, Loc, OutlinedFn, Args);
  10273. }
  10274. void CGOpenMPRuntime::emitFunctionProlog(CodeGenFunction &CGF, const Decl *D) {
  10275. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  10276. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD))
  10277. HasEmittedDeclareTargetRegion = true;
  10278. }
  10279. Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
  10280. const VarDecl *NativeParam,
  10281. const VarDecl *TargetParam) const {
  10282. return CGF.GetAddrOfLocalVar(NativeParam);
  10283. }
  10284. namespace {
  10285. /// Cleanup action for allocate support.
  10286. class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup {
  10287. public:
  10288. static const int CleanupArgs = 3;
  10289. private:
  10290. llvm::FunctionCallee RTLFn;
  10291. llvm::Value *Args[CleanupArgs];
  10292. public:
  10293. OMPAllocateCleanupTy(llvm::FunctionCallee RTLFn,
  10294. ArrayRef<llvm::Value *> CallArgs)
  10295. : RTLFn(RTLFn) {
  10296. assert(CallArgs.size() == CleanupArgs &&
  10297. "Size of arguments does not match.");
  10298. std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
  10299. }
  10300. void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
  10301. if (!CGF.HaveInsertPoint())
  10302. return;
  10303. CGF.EmitRuntimeCall(RTLFn, Args);
  10304. }
  10305. };
  10306. } // namespace
  10307. Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
  10308. const VarDecl *VD) {
  10309. if (!VD)
  10310. return Address::invalid();
  10311. const VarDecl *CVD = VD->getCanonicalDecl();
  10312. if (!CVD->hasAttr<OMPAllocateDeclAttr>())
  10313. return Address::invalid();
  10314. const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
  10315. // Use the default allocation.
  10316. if (AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc &&
  10317. !AA->getAllocator())
  10318. return Address::invalid();
  10319. llvm::Value *Size;
  10320. CharUnits Align = CGM.getContext().getDeclAlign(CVD);
  10321. if (CVD->getType()->isVariablyModifiedType()) {
  10322. Size = CGF.getTypeSize(CVD->getType());
  10323. // Align the size: ((size + align - 1) / align) * align
  10324. Size = CGF.Builder.CreateNUWAdd(
  10325. Size, CGM.getSize(Align - CharUnits::fromQuantity(1)));
  10326. Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align));
  10327. Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align));
  10328. } else {
  10329. CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType());
  10330. Size = CGM.getSize(Sz.alignTo(Align));
  10331. }
  10332. llvm::Value *ThreadID = getThreadID(CGF, CVD->getBeginLoc());
  10333. assert(AA->getAllocator() &&
  10334. "Expected allocator expression for non-default allocator.");
  10335. llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator());
  10336. // According to the standard, the original allocator type is a enum (integer).
  10337. // Convert to pointer type, if required.
  10338. if (Allocator->getType()->isIntegerTy())
  10339. Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy);
  10340. else if (Allocator->getType()->isPointerTy())
  10341. Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator,
  10342. CGM.VoidPtrTy);
  10343. llvm::Value *Args[] = {ThreadID, Size, Allocator};
  10344. llvm::Value *Addr =
  10345. CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_alloc), Args,
  10346. CVD->getName() + ".void.addr");
  10347. llvm::Value *FiniArgs[OMPAllocateCleanupTy::CleanupArgs] = {ThreadID, Addr,
  10348. Allocator};
  10349. llvm::FunctionCallee FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_free);
  10350. CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
  10351. llvm::makeArrayRef(FiniArgs));
  10352. Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  10353. Addr,
  10354. CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())),
  10355. CVD->getName() + ".addr");
  10356. return Address(Addr, Align);
  10357. }
  10358. /// Checks current context and returns true if it matches the context selector.
  10359. template <OMPDeclareVariantAttr::CtxSelectorSetType CtxSet,
  10360. OMPDeclareVariantAttr::CtxSelectorType Ctx>
  10361. static bool checkContext(const OMPDeclareVariantAttr *A) {
  10362. assert(CtxSet != OMPDeclareVariantAttr::CtxSetUnknown &&
  10363. Ctx != OMPDeclareVariantAttr::CtxUnknown &&
  10364. "Unknown context selector or context selector set.");
  10365. return false;
  10366. }
  10367. /// Checks for implementation={vendor(<vendor>)} context selector.
  10368. /// \returns true iff <vendor>="llvm", false otherwise.
  10369. template <>
  10370. bool checkContext<OMPDeclareVariantAttr::CtxSetImplementation,
  10371. OMPDeclareVariantAttr::CtxVendor>(
  10372. const OMPDeclareVariantAttr *A) {
  10373. return llvm::all_of(A->implVendors(),
  10374. [](StringRef S) { return !S.compare_lower("llvm"); });
  10375. }
  10376. static bool greaterCtxScore(ASTContext &Ctx, const Expr *LHS, const Expr *RHS) {
  10377. // If both scores are unknown, choose the very first one.
  10378. if (!LHS && !RHS)
  10379. return true;
  10380. // If only one is known, return this one.
  10381. if (LHS && !RHS)
  10382. return true;
  10383. if (!LHS && RHS)
  10384. return false;
  10385. llvm::APSInt LHSVal = LHS->EvaluateKnownConstInt(Ctx);
  10386. llvm::APSInt RHSVal = RHS->EvaluateKnownConstInt(Ctx);
  10387. return llvm::APSInt::compareValues(LHSVal, RHSVal) >= 0;
  10388. }
  10389. namespace {
  10390. /// Comparator for the priority queue for context selector.
  10391. class OMPDeclareVariantAttrComparer
  10392. : public std::greater<const OMPDeclareVariantAttr *> {
  10393. private:
  10394. ASTContext &Ctx;
  10395. public:
  10396. OMPDeclareVariantAttrComparer(ASTContext &Ctx) : Ctx(Ctx) {}
  10397. bool operator()(const OMPDeclareVariantAttr *LHS,
  10398. const OMPDeclareVariantAttr *RHS) const {
  10399. const Expr *LHSExpr = nullptr;
  10400. const Expr *RHSExpr = nullptr;
  10401. if (LHS->getCtxScore() == OMPDeclareVariantAttr::ScoreSpecified)
  10402. LHSExpr = LHS->getScore();
  10403. if (RHS->getCtxScore() == OMPDeclareVariantAttr::ScoreSpecified)
  10404. RHSExpr = RHS->getScore();
  10405. return greaterCtxScore(Ctx, LHSExpr, RHSExpr);
  10406. }
  10407. };
  10408. } // anonymous namespace
  10409. /// Finds the variant function that matches current context with its context
  10410. /// selector.
  10411. static const FunctionDecl *getDeclareVariantFunction(ASTContext &Ctx,
  10412. const FunctionDecl *FD) {
  10413. if (!FD->hasAttrs() || !FD->hasAttr<OMPDeclareVariantAttr>())
  10414. return FD;
  10415. // Iterate through all DeclareVariant attributes and check context selectors.
  10416. auto &&Comparer = [&Ctx](const OMPDeclareVariantAttr *LHS,
  10417. const OMPDeclareVariantAttr *RHS) {
  10418. const Expr *LHSExpr = nullptr;
  10419. const Expr *RHSExpr = nullptr;
  10420. if (LHS->getCtxScore() == OMPDeclareVariantAttr::ScoreSpecified)
  10421. LHSExpr = LHS->getScore();
  10422. if (RHS->getCtxScore() == OMPDeclareVariantAttr::ScoreSpecified)
  10423. RHSExpr = RHS->getScore();
  10424. return greaterCtxScore(Ctx, LHSExpr, RHSExpr);
  10425. };
  10426. const OMPDeclareVariantAttr *TopMostAttr = nullptr;
  10427. for (const auto *A : FD->specific_attrs<OMPDeclareVariantAttr>()) {
  10428. const OMPDeclareVariantAttr *SelectedAttr = nullptr;
  10429. switch (A->getCtxSelectorSet()) {
  10430. case OMPDeclareVariantAttr::CtxSetImplementation:
  10431. switch (A->getCtxSelector()) {
  10432. case OMPDeclareVariantAttr::CtxVendor:
  10433. if (checkContext<OMPDeclareVariantAttr::CtxSetImplementation,
  10434. OMPDeclareVariantAttr::CtxVendor>(A))
  10435. SelectedAttr = A;
  10436. break;
  10437. case OMPDeclareVariantAttr::CtxUnknown:
  10438. llvm_unreachable(
  10439. "Unknown context selector in implementation selector set.");
  10440. }
  10441. break;
  10442. case OMPDeclareVariantAttr::CtxSetUnknown:
  10443. llvm_unreachable("Unknown context selector set.");
  10444. }
  10445. // If the attribute matches the context, find the attribute with the highest
  10446. // score.
  10447. if (SelectedAttr && (!TopMostAttr || !Comparer(TopMostAttr, SelectedAttr)))
  10448. TopMostAttr = SelectedAttr;
  10449. }
  10450. if (!TopMostAttr)
  10451. return FD;
  10452. return cast<FunctionDecl>(
  10453. cast<DeclRefExpr>(TopMostAttr->getVariantFuncRef()->IgnoreParenImpCasts())
  10454. ->getDecl());
  10455. }
  10456. bool CGOpenMPRuntime::emitDeclareVariant(GlobalDecl GD, bool IsForDefinition) {
  10457. const auto *D = cast<FunctionDecl>(GD.getDecl());
  10458. // If the original function is defined already, use its definition.
  10459. StringRef MangledName = CGM.getMangledName(GD);
  10460. llvm::GlobalValue *Orig = CGM.GetGlobalValue(MangledName);
  10461. if (Orig && !Orig->isDeclaration())
  10462. return false;
  10463. const FunctionDecl *NewFD = getDeclareVariantFunction(CGM.getContext(), D);
  10464. // Emit original function if it does not have declare variant attribute or the
  10465. // context does not match.
  10466. if (NewFD == D)
  10467. return false;
  10468. GlobalDecl NewGD = GD.getWithDecl(NewFD);
  10469. if (tryEmitDeclareVariant(NewGD, GD, Orig, IsForDefinition)) {
  10470. DeferredVariantFunction.erase(D);
  10471. return true;
  10472. }
  10473. DeferredVariantFunction.insert(std::make_pair(D, std::make_pair(NewGD, GD)));
  10474. return true;
  10475. }
  10476. llvm::Function *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
  10477. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  10478. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  10479. llvm_unreachable("Not supported in SIMD-only mode");
  10480. }
  10481. llvm::Function *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
  10482. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  10483. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  10484. llvm_unreachable("Not supported in SIMD-only mode");
  10485. }
  10486. llvm::Function *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
  10487. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  10488. const VarDecl *PartIDVar, const VarDecl *TaskTVar,
  10489. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  10490. bool Tied, unsigned &NumberOfParts) {
  10491. llvm_unreachable("Not supported in SIMD-only mode");
  10492. }
  10493. void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
  10494. SourceLocation Loc,
  10495. llvm::Function *OutlinedFn,
  10496. ArrayRef<llvm::Value *> CapturedVars,
  10497. const Expr *IfCond) {
  10498. llvm_unreachable("Not supported in SIMD-only mode");
  10499. }
  10500. void CGOpenMPSIMDRuntime::emitCriticalRegion(
  10501. CodeGenFunction &CGF, StringRef CriticalName,
  10502. const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
  10503. const Expr *Hint) {
  10504. llvm_unreachable("Not supported in SIMD-only mode");
  10505. }
  10506. void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
  10507. const RegionCodeGenTy &MasterOpGen,
  10508. SourceLocation Loc) {
  10509. llvm_unreachable("Not supported in SIMD-only mode");
  10510. }
  10511. void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
  10512. SourceLocation Loc) {
  10513. llvm_unreachable("Not supported in SIMD-only mode");
  10514. }
  10515. void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
  10516. CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
  10517. SourceLocation Loc) {
  10518. llvm_unreachable("Not supported in SIMD-only mode");
  10519. }
  10520. void CGOpenMPSIMDRuntime::emitSingleRegion(
  10521. CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
  10522. SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
  10523. ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
  10524. ArrayRef<const Expr *> AssignmentOps) {
  10525. llvm_unreachable("Not supported in SIMD-only mode");
  10526. }
  10527. void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
  10528. const RegionCodeGenTy &OrderedOpGen,
  10529. SourceLocation Loc,
  10530. bool IsThreads) {
  10531. llvm_unreachable("Not supported in SIMD-only mode");
  10532. }
  10533. void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
  10534. SourceLocation Loc,
  10535. OpenMPDirectiveKind Kind,
  10536. bool EmitChecks,
  10537. bool ForceSimpleCall) {
  10538. llvm_unreachable("Not supported in SIMD-only mode");
  10539. }
  10540. void CGOpenMPSIMDRuntime::emitForDispatchInit(
  10541. CodeGenFunction &CGF, SourceLocation Loc,
  10542. const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
  10543. bool Ordered, const DispatchRTInput &DispatchValues) {
  10544. llvm_unreachable("Not supported in SIMD-only mode");
  10545. }
  10546. void CGOpenMPSIMDRuntime::emitForStaticInit(
  10547. CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
  10548. const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
  10549. llvm_unreachable("Not supported in SIMD-only mode");
  10550. }
  10551. void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
  10552. CodeGenFunction &CGF, SourceLocation Loc,
  10553. OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
  10554. llvm_unreachable("Not supported in SIMD-only mode");
  10555. }
  10556. void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
  10557. SourceLocation Loc,
  10558. unsigned IVSize,
  10559. bool IVSigned) {
  10560. llvm_unreachable("Not supported in SIMD-only mode");
  10561. }
  10562. void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
  10563. SourceLocation Loc,
  10564. OpenMPDirectiveKind DKind) {
  10565. llvm_unreachable("Not supported in SIMD-only mode");
  10566. }
  10567. llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
  10568. SourceLocation Loc,
  10569. unsigned IVSize, bool IVSigned,
  10570. Address IL, Address LB,
  10571. Address UB, Address ST) {
  10572. llvm_unreachable("Not supported in SIMD-only mode");
  10573. }
  10574. void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
  10575. llvm::Value *NumThreads,
  10576. SourceLocation Loc) {
  10577. llvm_unreachable("Not supported in SIMD-only mode");
  10578. }
  10579. void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
  10580. OpenMPProcBindClauseKind ProcBind,
  10581. SourceLocation Loc) {
  10582. llvm_unreachable("Not supported in SIMD-only mode");
  10583. }
  10584. Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
  10585. const VarDecl *VD,
  10586. Address VDAddr,
  10587. SourceLocation Loc) {
  10588. llvm_unreachable("Not supported in SIMD-only mode");
  10589. }
  10590. llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
  10591. const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
  10592. CodeGenFunction *CGF) {
  10593. llvm_unreachable("Not supported in SIMD-only mode");
  10594. }
  10595. Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
  10596. CodeGenFunction &CGF, QualType VarType, StringRef Name) {
  10597. llvm_unreachable("Not supported in SIMD-only mode");
  10598. }
  10599. void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
  10600. ArrayRef<const Expr *> Vars,
  10601. SourceLocation Loc) {
  10602. llvm_unreachable("Not supported in SIMD-only mode");
  10603. }
  10604. void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
  10605. const OMPExecutableDirective &D,
  10606. llvm::Function *TaskFunction,
  10607. QualType SharedsTy, Address Shareds,
  10608. const Expr *IfCond,
  10609. const OMPTaskDataTy &Data) {
  10610. llvm_unreachable("Not supported in SIMD-only mode");
  10611. }
  10612. void CGOpenMPSIMDRuntime::emitTaskLoopCall(
  10613. CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
  10614. llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds,
  10615. const Expr *IfCond, const OMPTaskDataTy &Data) {
  10616. llvm_unreachable("Not supported in SIMD-only mode");
  10617. }
  10618. void CGOpenMPSIMDRuntime::emitReduction(
  10619. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
  10620. ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
  10621. ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
  10622. assert(Options.SimpleReduction && "Only simple reduction is expected.");
  10623. CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
  10624. ReductionOps, Options);
  10625. }
  10626. llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
  10627. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
  10628. ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
  10629. llvm_unreachable("Not supported in SIMD-only mode");
  10630. }
  10631. void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
  10632. SourceLocation Loc,
  10633. ReductionCodeGen &RCG,
  10634. unsigned N) {
  10635. llvm_unreachable("Not supported in SIMD-only mode");
  10636. }
  10637. Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
  10638. SourceLocation Loc,
  10639. llvm::Value *ReductionsPtr,
  10640. LValue SharedLVal) {
  10641. llvm_unreachable("Not supported in SIMD-only mode");
  10642. }
  10643. void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
  10644. SourceLocation Loc) {
  10645. llvm_unreachable("Not supported in SIMD-only mode");
  10646. }
  10647. void CGOpenMPSIMDRuntime::emitCancellationPointCall(
  10648. CodeGenFunction &CGF, SourceLocation Loc,
  10649. OpenMPDirectiveKind CancelRegion) {
  10650. llvm_unreachable("Not supported in SIMD-only mode");
  10651. }
  10652. void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
  10653. SourceLocation Loc, const Expr *IfCond,
  10654. OpenMPDirectiveKind CancelRegion) {
  10655. llvm_unreachable("Not supported in SIMD-only mode");
  10656. }
  10657. void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
  10658. const OMPExecutableDirective &D, StringRef ParentName,
  10659. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  10660. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  10661. llvm_unreachable("Not supported in SIMD-only mode");
  10662. }
  10663. void CGOpenMPSIMDRuntime::emitTargetCall(
  10664. CodeGenFunction &CGF, const OMPExecutableDirective &D,
  10665. llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,
  10666. const Expr *Device,
  10667. llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
  10668. const OMPLoopDirective &D)>
  10669. SizeEmitter) {
  10670. llvm_unreachable("Not supported in SIMD-only mode");
  10671. }
  10672. bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
  10673. llvm_unreachable("Not supported in SIMD-only mode");
  10674. }
  10675. bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
  10676. llvm_unreachable("Not supported in SIMD-only mode");
  10677. }
  10678. bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
  10679. return false;
  10680. }
  10681. void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
  10682. const OMPExecutableDirective &D,
  10683. SourceLocation Loc,
  10684. llvm::Function *OutlinedFn,
  10685. ArrayRef<llvm::Value *> CapturedVars) {
  10686. llvm_unreachable("Not supported in SIMD-only mode");
  10687. }
  10688. void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
  10689. const Expr *NumTeams,
  10690. const Expr *ThreadLimit,
  10691. SourceLocation Loc) {
  10692. llvm_unreachable("Not supported in SIMD-only mode");
  10693. }
  10694. void CGOpenMPSIMDRuntime::emitTargetDataCalls(
  10695. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  10696. const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
  10697. llvm_unreachable("Not supported in SIMD-only mode");
  10698. }
  10699. void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
  10700. CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
  10701. const Expr *Device) {
  10702. llvm_unreachable("Not supported in SIMD-only mode");
  10703. }
  10704. void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
  10705. const OMPLoopDirective &D,
  10706. ArrayRef<Expr *> NumIterations) {
  10707. llvm_unreachable("Not supported in SIMD-only mode");
  10708. }
  10709. void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
  10710. const OMPDependClause *C) {
  10711. llvm_unreachable("Not supported in SIMD-only mode");
  10712. }
  10713. const VarDecl *
  10714. CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
  10715. const VarDecl *NativeParam) const {
  10716. llvm_unreachable("Not supported in SIMD-only mode");
  10717. }
  10718. Address
  10719. CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
  10720. const VarDecl *NativeParam,
  10721. const VarDecl *TargetParam) const {
  10722. llvm_unreachable("Not supported in SIMD-only mode");
  10723. }