SPIRVEmitter.cpp 397 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945
  1. //===------- SPIRVEmitter.h - SPIR-V Binary Code Emitter --------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a SPIR-V emitter class that takes in HLSL AST and emits
  10. // SPIR-V binary words.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "SPIRVEmitter.h"
  14. #include "dxc/HlslIntrinsicOp.h"
  15. #include "spirv-tools/optimizer.hpp"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "InitListHandler.h"
  18. namespace clang {
  19. namespace spirv {
  20. namespace {
  21. // Returns true if the given decl has the given semantic.
  22. bool hasSemantic(const DeclaratorDecl *decl,
  23. hlsl::DXIL::SemanticKind semanticKind) {
  24. using namespace hlsl;
  25. for (auto *annotation : decl->getUnusualAnnotations()) {
  26. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  27. llvm::StringRef semanticName;
  28. uint32_t semanticIndex = 0;
  29. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  30. &semanticIndex);
  31. const auto *semantic = Semantic::GetByName(semanticName);
  32. if (semantic->GetKind() == semanticKind)
  33. return true;
  34. }
  35. }
  36. return false;
  37. }
  38. bool patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  39. for (const auto *param : pcf->parameters())
  40. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  41. return true;
  42. return false;
  43. }
  44. // TODO: Maybe we should move these type probing functions to TypeTranslator.
  45. /// Returns true if the given type is a bool or vector of bool type.
  46. bool isBoolOrVecOfBoolType(QualType type) {
  47. QualType elemType = {};
  48. return (TypeTranslator::isScalarType(type, &elemType) ||
  49. TypeTranslator::isVectorType(type, &elemType)) &&
  50. elemType->isBooleanType();
  51. }
  52. /// Returns true if the given type is a signed integer or vector of signed
  53. /// integer type.
  54. bool isSintOrVecOfSintType(QualType type) {
  55. QualType elemType = {};
  56. return (TypeTranslator::isScalarType(type, &elemType) ||
  57. TypeTranslator::isVectorType(type, &elemType)) &&
  58. elemType->isSignedIntegerType();
  59. }
  60. /// Returns true if the given type is an unsigned integer or vector of unsigned
  61. /// integer type.
  62. bool isUintOrVecOfUintType(QualType type) {
  63. QualType elemType = {};
  64. return (TypeTranslator::isScalarType(type, &elemType) ||
  65. TypeTranslator::isVectorType(type, &elemType)) &&
  66. elemType->isUnsignedIntegerType();
  67. }
  68. /// Returns true if the given type is a float or vector of float type.
  69. bool isFloatOrVecOfFloatType(QualType type) {
  70. QualType elemType = {};
  71. return (TypeTranslator::isScalarType(type, &elemType) ||
  72. TypeTranslator::isVectorType(type, &elemType)) &&
  73. elemType->isFloatingType();
  74. }
  75. /// Returns true if the given type is a bool or vector/matrix of bool type.
  76. bool isBoolOrVecMatOfBoolType(QualType type) {
  77. return isBoolOrVecOfBoolType(type) ||
  78. (hlsl::IsHLSLMatType(type) &&
  79. hlsl::GetHLSLMatElementType(type)->isBooleanType());
  80. }
  81. /// Returns true if the given type is a signed integer or vector/matrix of
  82. /// signed integer type.
  83. bool isSintOrVecMatOfSintType(QualType type) {
  84. return isSintOrVecOfSintType(type) ||
  85. (hlsl::IsHLSLMatType(type) &&
  86. hlsl::GetHLSLMatElementType(type)->isSignedIntegerType());
  87. }
  88. /// Returns true if the given type is an unsigned integer or vector/matrix of
  89. /// unsigned integer type.
  90. bool isUintOrVecMatOfUintType(QualType type) {
  91. return isUintOrVecOfUintType(type) ||
  92. (hlsl::IsHLSLMatType(type) &&
  93. hlsl::GetHLSLMatElementType(type)->isUnsignedIntegerType());
  94. }
  95. /// Returns true if the given type is a float or vector/matrix of float type.
  96. bool isFloatOrVecMatOfFloatType(QualType type) {
  97. return isFloatOrVecOfFloatType(type) ||
  98. (hlsl::IsHLSLMatType(type) &&
  99. hlsl::GetHLSLMatElementType(type)->isFloatingType());
  100. }
  101. inline bool isSpirvMatrixOp(spv::Op opcode) {
  102. return opcode == spv::Op::OpMatrixTimesMatrix ||
  103. opcode == spv::Op::OpMatrixTimesVector ||
  104. opcode == spv::Op::OpMatrixTimesScalar;
  105. }
  106. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  107. /// index. Otherwiser, returns false.
  108. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  109. // duplicate of doCXXMemberCallExpr.
  110. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  111. using namespace hlsl;
  112. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  113. const auto *callee = indexing->getDirectCallee();
  114. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  115. llvm::StringRef group;
  116. if (GetIntrinsicOp(callee, opcode, group)) {
  117. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  118. const auto *object = indexing->getImplicitObjectArgument();
  119. if (TypeTranslator::isStructuredBuffer(object->getType())) {
  120. *index = indexing->getArg(0);
  121. return indexing->getImplicitObjectArgument();
  122. }
  123. }
  124. }
  125. }
  126. return nullptr;
  127. }
  128. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  129. /// not in the Private or Function storage class.
  130. inline bool isExternalVar(const VarDecl *var) {
  131. // Class static variables should be put in the Private storage class.
  132. // groupshared variables are allowed to be declared as "static". But we still
  133. // need to put them in the Workgroup storage class. That is, when seeing
  134. // "static groupshared", ignore "static".
  135. return var->hasExternalFormalLinkage()
  136. ? !var->isStaticDataMember()
  137. : (var->getAttr<HLSLGroupSharedAttr>() != nullptr);
  138. }
  139. /// Returns the referenced variable's DeclContext if the given expr is
  140. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  141. /// returns nullptr.
  142. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  143. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  144. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  145. if (TypeTranslator::isConstantTextureBuffer(varDecl))
  146. return varDecl->getType()->getAs<RecordType>()->getDecl();
  147. return nullptr;
  148. }
  149. /// Returns true if
  150. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  151. /// buffer and it is non-alias one, or
  152. /// * the given expr is an CallExpr returning a kind of structured or byte
  153. /// buffer.
  154. /// * the given expr is an ArraySubscriptExpr referencing a kind of structured
  155. /// or byte buffer.
  156. ///
  157. /// Note: legalization specific code
  158. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  159. expr = expr->IgnoreParenCasts();
  160. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  161. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  162. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  163. return isExternalVar(varDecl);
  164. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  165. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  166. return true;
  167. } else if (const auto *arrSubExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  168. return isReferencingNonAliasStructuredOrByteBuffer(arrSubExpr->getBase());
  169. }
  170. return false;
  171. }
  172. bool spirvToolsLegalize(spv_target_env env, std::vector<uint32_t> *module,
  173. std::string *messages) {
  174. spvtools::Optimizer optimizer(env);
  175. optimizer.SetMessageConsumer(
  176. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  177. const spv_position_t & /*position*/,
  178. const char *message) { *messages += message; });
  179. optimizer.RegisterLegalizationPasses();
  180. optimizer.RegisterPass(spvtools::CreateReplaceInvalidOpcodePass());
  181. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  182. return optimizer.Run(module->data(), module->size(), module);
  183. }
  184. bool spirvToolsOptimize(spv_target_env env, std::vector<uint32_t> *module,
  185. std::string *messages) {
  186. spvtools::Optimizer optimizer(env);
  187. optimizer.SetMessageConsumer(
  188. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  189. const spv_position_t & /*position*/,
  190. const char *message) { *messages += message; });
  191. optimizer.RegisterPerformancePasses();
  192. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  193. return optimizer.Run(module->data(), module->size(), module);
  194. }
  195. bool spirvToolsValidate(spv_target_env env, std::vector<uint32_t> *module,
  196. std::string *messages, bool relaxLogicalPointer,
  197. bool glLayout, bool dxLayout) {
  198. spvtools::SpirvTools tools(env);
  199. tools.SetMessageConsumer(
  200. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  201. const spv_position_t & /*position*/,
  202. const char *message) { *messages += message; });
  203. spvtools::ValidatorOptions options;
  204. options.SetRelaxLogicalPointer(relaxLogicalPointer);
  205. // GL: strict block layout rules
  206. // VK: relaxed block layout rules
  207. // DX: Skip block layout rules
  208. options.SetRelaxBlockLayout(!glLayout && !dxLayout);
  209. options.SetSkipBlockLayout(dxLayout);
  210. return tools.Validate(module->data(), module->size(), options);
  211. }
  212. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  213. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  214. using namespace hlsl;
  215. using namespace spv;
  216. switch (opcode) {
  217. case IntrinsicOp::IOP_InterlockedAdd:
  218. case IntrinsicOp::MOP_InterlockedAdd:
  219. return Op::OpAtomicIAdd;
  220. case IntrinsicOp::IOP_InterlockedAnd:
  221. case IntrinsicOp::MOP_InterlockedAnd:
  222. return Op::OpAtomicAnd;
  223. case IntrinsicOp::IOP_InterlockedOr:
  224. case IntrinsicOp::MOP_InterlockedOr:
  225. return Op::OpAtomicOr;
  226. case IntrinsicOp::IOP_InterlockedXor:
  227. case IntrinsicOp::MOP_InterlockedXor:
  228. return Op::OpAtomicXor;
  229. case IntrinsicOp::IOP_InterlockedUMax:
  230. case IntrinsicOp::MOP_InterlockedUMax:
  231. return Op::OpAtomicUMax;
  232. case IntrinsicOp::IOP_InterlockedUMin:
  233. case IntrinsicOp::MOP_InterlockedUMin:
  234. return Op::OpAtomicUMin;
  235. case IntrinsicOp::IOP_InterlockedMax:
  236. case IntrinsicOp::MOP_InterlockedMax:
  237. return Op::OpAtomicSMax;
  238. case IntrinsicOp::IOP_InterlockedMin:
  239. case IntrinsicOp::MOP_InterlockedMin:
  240. return Op::OpAtomicSMin;
  241. case IntrinsicOp::IOP_InterlockedExchange:
  242. case IntrinsicOp::MOP_InterlockedExchange:
  243. return Op::OpAtomicExchange;
  244. default:
  245. // Only atomic opcodes are relevant.
  246. break;
  247. }
  248. assert(false && "unimplemented hlsl intrinsic opcode");
  249. return Op::Max;
  250. }
  251. // Returns true if the given opcode is an accepted binary opcode in
  252. // OpSpecConstantOp.
  253. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  254. switch (op) {
  255. case spv::Op::OpIAdd:
  256. case spv::Op::OpISub:
  257. case spv::Op::OpIMul:
  258. case spv::Op::OpUDiv:
  259. case spv::Op::OpSDiv:
  260. case spv::Op::OpUMod:
  261. case spv::Op::OpSRem:
  262. case spv::Op::OpSMod:
  263. case spv::Op::OpShiftRightLogical:
  264. case spv::Op::OpShiftRightArithmetic:
  265. case spv::Op::OpShiftLeftLogical:
  266. case spv::Op::OpBitwiseOr:
  267. case spv::Op::OpBitwiseXor:
  268. case spv::Op::OpBitwiseAnd:
  269. case spv::Op::OpVectorShuffle:
  270. case spv::Op::OpCompositeExtract:
  271. case spv::Op::OpCompositeInsert:
  272. case spv::Op::OpLogicalOr:
  273. case spv::Op::OpLogicalAnd:
  274. case spv::Op::OpLogicalNot:
  275. case spv::Op::OpLogicalEqual:
  276. case spv::Op::OpLogicalNotEqual:
  277. case spv::Op::OpIEqual:
  278. case spv::Op::OpINotEqual:
  279. case spv::Op::OpULessThan:
  280. case spv::Op::OpSLessThan:
  281. case spv::Op::OpUGreaterThan:
  282. case spv::Op::OpSGreaterThan:
  283. case spv::Op::OpULessThanEqual:
  284. case spv::Op::OpSLessThanEqual:
  285. case spv::Op::OpUGreaterThanEqual:
  286. case spv::Op::OpSGreaterThanEqual:
  287. return true;
  288. default:
  289. // Accepted binary opcodes return true. Anything else is false.
  290. return false;
  291. }
  292. return false;
  293. }
  294. /// Returns true if the given expression is an accepted initializer for a spec
  295. /// constant.
  296. bool isAcceptedSpecConstantInit(const Expr *init) {
  297. // Allow numeric casts
  298. init = init->IgnoreParenCasts();
  299. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  300. isa<FloatingLiteral>(init))
  301. return true;
  302. // Allow the minus operator which is used to specify negative values
  303. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  304. return unaryOp->getOpcode() == UO_Minus &&
  305. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  306. return false;
  307. }
  308. /// Returns true if the given function parameter can act as shader stage
  309. /// input parameter.
  310. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  311. // If the parameter has no in/out/inout attribute, it is defaulted to
  312. // an in parameter.
  313. return !param->hasAttr<HLSLOutAttr>() &&
  314. // GS output streams are marked as inout, but it should not be
  315. // used as in parameter.
  316. !hlsl::IsHLSLStreamOutputType(param->getType());
  317. }
  318. /// Returns true if the given function parameter can act as shader stage
  319. /// output parameter.
  320. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  321. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>();
  322. }
  323. /// Returns true if the given expression is of builtin type and can be evaluated
  324. /// to a constant zero. Returns false otherwise.
  325. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  326. const auto type = expr->getType();
  327. if (!type->isBuiltinType())
  328. return false;
  329. Expr::EvalResult evalResult;
  330. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  331. !evalResult.HasSideEffects) {
  332. const auto &val = evalResult.Val;
  333. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  334. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  335. (type->isFloatingType() && val.getFloat().isZero()));
  336. }
  337. return false;
  338. }
  339. /// Returns the HLSLBufferDecl if the given VarDecl is inside a cbuffer/tbuffer.
  340. /// Returns nullptr otherwise, including varDecl is a ConstantBuffer or
  341. /// TextureBuffer itself.
  342. inline const HLSLBufferDecl *getCTBufferContext(const VarDecl *varDecl) {
  343. if (const auto *bufferDecl =
  344. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  345. // Filter ConstantBuffer/TextureBuffer
  346. if (!bufferDecl->isConstantBufferView())
  347. return bufferDecl;
  348. return nullptr;
  349. }
  350. /// Returns the real definition of the callee of the given CallExpr.
  351. ///
  352. /// If we are calling a forward-declared function, callee will be the
  353. /// FunctionDecl for the foward-declared function, not the actual
  354. /// definition. The foward-delcaration and defintion are two completely
  355. /// different AST nodes.
  356. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  357. const auto *callee = expr->getDirectCallee();
  358. if (callee->isThisDeclarationADefinition())
  359. return callee;
  360. // We need to update callee to the actual definition here
  361. if (!callee->isDefined(callee))
  362. return nullptr;
  363. return callee;
  364. }
  365. /// Returns the referenced definition. The given expr is expected to be a
  366. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  367. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  368. if (!expr)
  369. return nullptr;
  370. expr = expr->IgnoreParenCasts();
  371. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  372. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  373. }
  374. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  375. return getCalleeDefinition(callExpr);
  376. }
  377. return nullptr;
  378. }
  379. /// Returns the number of base classes if this type is a derived class/struct.
  380. /// Returns zero otherwise.
  381. inline uint32_t getNumBaseClasses(QualType type) {
  382. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  383. return cxxDecl->getNumBases();
  384. return 0;
  385. }
  386. /// Gets the index sequence of casting a derived object to a base object by
  387. /// following the cast chain.
  388. void getBaseClassIndices(const CastExpr *expr,
  389. llvm::SmallVectorImpl<uint32_t> *indices) {
  390. assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
  391. expr->getCastKind() == CK_HLSLDerivedToBase);
  392. indices->clear();
  393. QualType derivedType = expr->getSubExpr()->getType();
  394. const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
  395. // Go through the base cast chain: for each of the derived to base cast, find
  396. // the index of the base in question in the derived's bases.
  397. for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
  398. pathIt != pathIe; ++pathIt) {
  399. // The type of the base in question
  400. const auto baseType = (*pathIt)->getType();
  401. uint32_t index = 0;
  402. for (auto baseIt = derivedDecl->bases_begin(),
  403. baseIe = derivedDecl->bases_end();
  404. baseIt != baseIe; ++baseIt, ++index)
  405. if (baseIt->getType() == baseType) {
  406. indices->push_back(index);
  407. break;
  408. }
  409. assert(index < derivedDecl->getNumBases());
  410. // Continue to proceed the next base in the chain
  411. derivedType = baseType;
  412. derivedDecl = derivedType->getAsCXXRecordDecl();
  413. }
  414. }
  415. spv::Capability getCapabilityForGroupNonUniform(spv::Op opcode) {
  416. switch (opcode) {
  417. case spv::Op::OpGroupNonUniformElect:
  418. return spv::Capability::GroupNonUniform;
  419. case spv::Op::OpGroupNonUniformAny:
  420. case spv::Op::OpGroupNonUniformAll:
  421. case spv::Op::OpGroupNonUniformAllEqual:
  422. return spv::Capability::GroupNonUniformVote;
  423. case spv::Op::OpGroupNonUniformBallot:
  424. case spv::Op::OpGroupNonUniformBallotBitCount:
  425. case spv::Op::OpGroupNonUniformBroadcast:
  426. case spv::Op::OpGroupNonUniformBroadcastFirst:
  427. return spv::Capability::GroupNonUniformBallot;
  428. case spv::Op::OpGroupNonUniformIAdd:
  429. case spv::Op::OpGroupNonUniformFAdd:
  430. case spv::Op::OpGroupNonUniformIMul:
  431. case spv::Op::OpGroupNonUniformFMul:
  432. case spv::Op::OpGroupNonUniformSMax:
  433. case spv::Op::OpGroupNonUniformUMax:
  434. case spv::Op::OpGroupNonUniformFMax:
  435. case spv::Op::OpGroupNonUniformSMin:
  436. case spv::Op::OpGroupNonUniformUMin:
  437. case spv::Op::OpGroupNonUniformFMin:
  438. case spv::Op::OpGroupNonUniformBitwiseAnd:
  439. case spv::Op::OpGroupNonUniformBitwiseOr:
  440. case spv::Op::OpGroupNonUniformBitwiseXor:
  441. return spv::Capability::GroupNonUniformArithmetic;
  442. case spv::Op::OpGroupNonUniformQuadBroadcast:
  443. case spv::Op::OpGroupNonUniformQuadSwap:
  444. return spv::Capability::GroupNonUniformQuad;
  445. default:
  446. assert(false && "unhandled opcode");
  447. break;
  448. }
  449. assert(false && "unhandled opcode");
  450. return spv::Capability::Max;
  451. }
  452. std::string getNamespacePrefix(const Decl *decl) {
  453. std::string nsPrefix = "";
  454. const DeclContext *dc = decl->getDeclContext();
  455. while (dc && !dc->isTranslationUnit()) {
  456. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(dc)) {
  457. if (!ns->isAnonymousNamespace()) {
  458. nsPrefix = ns->getName().str() + "::" + nsPrefix;
  459. }
  460. }
  461. dc = dc->getParent();
  462. }
  463. return nsPrefix;
  464. }
  465. std::string getFnName(const FunctionDecl *fn) {
  466. // Prefix the function name with the struct name if necessary
  467. std::string classOrStructName = "";
  468. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(fn))
  469. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  470. classOrStructName = st->getName().str() + ".";
  471. return getNamespacePrefix(fn) + classOrStructName + fn->getName().str();
  472. }
  473. /// Returns the capability required to non-uniformly index into the given type.
  474. spv::Capability getNonUniformCapability(QualType type) {
  475. using spv::Capability;
  476. if (type->isArrayType()) {
  477. return getNonUniformCapability(
  478. type->getAsArrayTypeUnsafe()->getElementType());
  479. }
  480. if (TypeTranslator::isTexture(type) || TypeTranslator::isSampler(type)) {
  481. return Capability::SampledImageArrayNonUniformIndexingEXT;
  482. }
  483. if (TypeTranslator::isRWTexture(type)) {
  484. return Capability::StorageImageArrayNonUniformIndexingEXT;
  485. }
  486. if (TypeTranslator::isBuffer(type)) {
  487. return Capability::UniformTexelBufferArrayNonUniformIndexingEXT;
  488. }
  489. if (TypeTranslator::isRWBuffer(type)) {
  490. return Capability::StorageTexelBufferArrayNonUniformIndexingEXT;
  491. }
  492. if (const auto *recordType = type->getAs<RecordType>()) {
  493. const auto name = recordType->getDecl()->getName();
  494. if (name == "SubpassInput" || name == "SubpassInputMS") {
  495. return Capability::InputAttachmentArrayNonUniformIndexingEXT;
  496. }
  497. }
  498. return Capability::Max;
  499. }
  500. } // namespace
  501. SPIRVEmitter::SPIRVEmitter(CompilerInstance &ci, EmitSPIRVOptions &options)
  502. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  503. diags(ci.getDiagnostics()), spirvOptions(options),
  504. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction),
  505. shaderModel(*hlsl::ShaderModel::GetByName(
  506. ci.getCodeGenOpts().HLSLProfile.c_str())),
  507. theContext(), featureManager(diags, options),
  508. theBuilder(&theContext, &featureManager, options.enableReflect),
  509. typeTranslator(astContext, theBuilder, diags, options),
  510. declIdMapper(shaderModel, astContext, theBuilder, typeTranslator,
  511. featureManager, options),
  512. entryFunctionId(0), curFunction(nullptr), curThis(0),
  513. seenPushConstantAt(), isSpecConstantMode(false),
  514. foundNonUniformResourceIndex(false), needsLegalization(false) {
  515. if (shaderModel.GetKind() == hlsl::ShaderModel::Kind::Invalid)
  516. emitError("unknown shader module: %0", {}) << shaderModel.GetName();
  517. if (options.invertY && !shaderModel.IsVS() && !shaderModel.IsDS() &&
  518. !shaderModel.IsGS())
  519. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  520. if (options.useGlLayout && options.useDxLayout)
  521. emitError("cannot specify both -fvk-use-dx-layout and -fvk-use-gl-layout",
  522. {});
  523. options.Initialize();
  524. // Set shader module version
  525. theBuilder.setShaderModelVersion(shaderModel.GetMajor(),
  526. shaderModel.GetMinor());
  527. // Set debug info
  528. const auto &inputFiles = ci.getFrontendOpts().Inputs;
  529. if (options.enableDebugInfo && !inputFiles.empty())
  530. theBuilder.setSourceFileName(theContext.takeNextId(),
  531. inputFiles.front().getFile().str());
  532. }
  533. void SPIRVEmitter::HandleTranslationUnit(ASTContext &context) {
  534. // Stop translating if there are errors in previous compilation stages.
  535. if (context.getDiagnostics().hasErrorOccurred())
  536. return;
  537. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  538. // The entry function is the seed of the queue.
  539. for (auto *decl : tu->decls()) {
  540. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  541. if (funcDecl->getName() == entryFunctionName) {
  542. workQueue.insert(funcDecl);
  543. }
  544. } else {
  545. doDecl(decl);
  546. }
  547. }
  548. // Translate all functions reachable from the entry function.
  549. // The queue can grow in the meanwhile; so need to keep evaluating
  550. // workQueue.size().
  551. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  552. doDecl(workQueue[i]);
  553. }
  554. if (context.getDiagnostics().hasErrorOccurred())
  555. return;
  556. const spv_target_env targetEnv = featureManager.getTargetEnv();
  557. AddRequiredCapabilitiesForShaderModel();
  558. // Addressing and memory model are required in a valid SPIR-V module.
  559. theBuilder.setAddressingModel(spv::AddressingModel::Logical);
  560. theBuilder.setMemoryModel(spv::MemoryModel::GLSL450);
  561. theBuilder.addEntryPoint(getSpirvShaderStage(shaderModel), entryFunctionId,
  562. entryFunctionName, declIdMapper.collectStageVars());
  563. // Add Location decorations to stage input/output variables.
  564. if (!declIdMapper.decorateStageIOLocations())
  565. return;
  566. // Add descriptor set and binding decorations to resource variables.
  567. if (!declIdMapper.decorateResourceBindings())
  568. return;
  569. // Output the constructed module.
  570. std::vector<uint32_t> m = theBuilder.takeModule();
  571. if (!spirvOptions.codeGenHighLevel) {
  572. // Run legalization passes
  573. if (needsLegalization || declIdMapper.requiresLegalization()) {
  574. std::string messages;
  575. if (!spirvToolsLegalize(targetEnv, &m, &messages)) {
  576. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  577. emitNote("please file a bug report on "
  578. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  579. "with source code if possible",
  580. {});
  581. return;
  582. } else if (!messages.empty()) {
  583. emitWarning("SPIR-V legalization: %0", {}) << messages;
  584. }
  585. }
  586. // Run optimization passes
  587. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  588. std::string messages;
  589. if (!spirvToolsOptimize(targetEnv, &m, &messages)) {
  590. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  591. emitNote("please file a bug report on "
  592. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  593. "with source code if possible",
  594. {});
  595. return;
  596. }
  597. }
  598. }
  599. // Validate the generated SPIR-V code
  600. if (!spirvOptions.disableValidation) {
  601. std::string messages;
  602. if (!spirvToolsValidate(
  603. targetEnv, &m, &messages, declIdMapper.requiresLegalization(),
  604. spirvOptions.useGlLayout, spirvOptions.useDxLayout)) {
  605. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  606. emitNote("please file a bug report on "
  607. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  608. "with source code if possible",
  609. {});
  610. return;
  611. }
  612. }
  613. theCompilerInstance.getOutStream()->write(
  614. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  615. }
  616. void SPIRVEmitter::doDecl(const Decl *decl) {
  617. if (decl->isImplicit() || isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  618. return;
  619. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  620. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  621. // to emit their cbuffer/tbuffer as a whole and access each individual one
  622. // using access chains.
  623. if (const auto *bufferDecl = getCTBufferContext(varDecl)) {
  624. doHLSLBufferDecl(bufferDecl);
  625. } else {
  626. doVarDecl(varDecl);
  627. }
  628. } else if (const auto *namespaceDecl = dyn_cast<NamespaceDecl>(decl)) {
  629. for (auto *subDecl : namespaceDecl->decls())
  630. // Note: We only emit functions as they are discovered through the call
  631. // graph starting from the entry-point. We should not emit unused
  632. // functions inside namespaces.
  633. if (!isa<FunctionDecl>(subDecl))
  634. doDecl(subDecl);
  635. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  636. doFunctionDecl(funcDecl);
  637. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  638. doHLSLBufferDecl(bufferDecl);
  639. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  640. doRecordDecl(recordDecl);
  641. } else {
  642. emitError("decl type %0 unimplemented", decl->getLocation())
  643. << decl->getDeclKindName();
  644. }
  645. }
  646. void SPIRVEmitter::doStmt(const Stmt *stmt,
  647. llvm::ArrayRef<const Attr *> attrs) {
  648. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  649. for (auto *st : compoundStmt->body())
  650. doStmt(st);
  651. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  652. doReturnStmt(retStmt);
  653. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  654. doDeclStmt(declStmt);
  655. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  656. doIfStmt(ifStmt, attrs);
  657. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  658. doSwitchStmt(switchStmt, attrs);
  659. } else if (dyn_cast<CaseStmt>(stmt)) {
  660. processCaseStmtOrDefaultStmt(stmt);
  661. } else if (dyn_cast<DefaultStmt>(stmt)) {
  662. processCaseStmtOrDefaultStmt(stmt);
  663. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  664. doBreakStmt(breakStmt);
  665. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  666. doDoStmt(theDoStmt, attrs);
  667. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  668. doDiscardStmt(discardStmt);
  669. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  670. doContinueStmt(continueStmt);
  671. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  672. doWhileStmt(whileStmt, attrs);
  673. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  674. doForStmt(forStmt, attrs);
  675. } else if (dyn_cast<NullStmt>(stmt)) {
  676. // For the null statement ";". We don't need to do anything.
  677. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  678. // All cases for expressions used as statements
  679. doExpr(expr);
  680. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  681. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  682. } else {
  683. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  684. << stmt->getStmtClassName() << stmt->getSourceRange();
  685. }
  686. }
  687. SpirvEvalInfo SPIRVEmitter::doExpr(const Expr *expr) {
  688. SpirvEvalInfo result(/*id*/ 0);
  689. // Provide a hint to the typeTranslator that if a literal is discovered, its
  690. // intended usage is as this expression type.
  691. TypeTranslator::LiteralTypeHint hint(typeTranslator, expr->getType());
  692. expr = expr->IgnoreParens();
  693. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  694. result = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl());
  695. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  696. result = doMemberExpr(memberExpr);
  697. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  698. result = doCastExpr(castExpr);
  699. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  700. result = doInitListExpr(initListExpr);
  701. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  702. const auto value =
  703. theBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  704. result = SpirvEvalInfo(value).setConstant().setRValue();
  705. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  706. const auto value = translateAPInt(intLiteral->getValue(), expr->getType());
  707. result = SpirvEvalInfo(value).setConstant().setRValue();
  708. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  709. const auto value =
  710. translateAPFloat(floatLiteral->getValue(), expr->getType());
  711. result = SpirvEvalInfo(value).setConstant().setRValue();
  712. } else if (const auto *compoundAssignOp =
  713. dyn_cast<CompoundAssignOperator>(expr)) {
  714. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  715. // checked before BinaryOperator.
  716. result = doCompoundAssignOperator(compoundAssignOp);
  717. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  718. result = doBinaryOperator(binOp);
  719. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  720. result = doUnaryOperator(unaryOp);
  721. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  722. result = doHLSLVectorElementExpr(vecElemExpr);
  723. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  724. result = doExtMatrixElementExpr(matElemExpr);
  725. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  726. result = doCallExpr(funcCall);
  727. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  728. result = doArraySubscriptExpr(subscriptExpr);
  729. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  730. result = doConditionalOperator(condExpr);
  731. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  732. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  733. } else if (isa<CXXThisExpr>(expr)) {
  734. assert(curThis);
  735. result = curThis;
  736. } else {
  737. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  738. << expr->getStmtClassName() << expr->getSourceRange();
  739. }
  740. return result;
  741. }
  742. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr) {
  743. // We are trying to load the value here, which is what an LValueToRValue
  744. // implicit cast is intended to do. We can ignore the cast if exists.
  745. expr = expr->IgnoreParenLValueCasts();
  746. return loadIfGLValue(expr, doExpr(expr));
  747. }
  748. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr,
  749. SpirvEvalInfo info) {
  750. // Do nothing if this is already rvalue
  751. if (info.isRValue())
  752. return info;
  753. // Check whether we are trying to load an array of opaque objects as a whole.
  754. // If true, we are likely to copy it as a whole. To assist per-element
  755. // copying, avoid the load here and return the pointer directly.
  756. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  757. if (TypeTranslator::isOpaqueArrayType(expr->getType()))
  758. return info;
  759. // Check whether we are trying to load an externally visible structured/byte
  760. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  761. // the load and write the pointer directly to the alias variable then.
  762. //
  763. // Also for the case of alias function returns. If we are trying to load an
  764. // alias function return as a whole, it means we are assigning it to another
  765. // alias variable. Avoid the load and write the pointer directly.
  766. //
  767. // Note: legalization specific code
  768. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  769. return info.setRValue();
  770. }
  771. if (loadIfAliasVarRef(expr, info)) {
  772. // We are loading an alias variable as a whole here. This is likely for
  773. // wholesale assignments or function returns. Need to load the pointer.
  774. //
  775. // Note: legalization specific code
  776. return info;
  777. }
  778. uint32_t valType = 0;
  779. // TODO: Ouch. Very hacky. We need special path to get the value type if
  780. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  781. // type translation path won't work.
  782. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  783. valType = declIdMapper.getCTBufferPushConstantTypeId(declContext);
  784. } else {
  785. valType =
  786. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  787. }
  788. uint32_t loadedId = theBuilder.createLoad(valType, info);
  789. // Decorate with NonUniformEXT if loading from a pointer with that property.
  790. // We are likely loading an element from the resource array here.
  791. if (info.isNonUniform()) {
  792. theBuilder.decorateNonUniformEXT(loadedId);
  793. }
  794. // Special-case: According to the SPIR-V Spec: There is no physical size or
  795. // bit pattern defined for boolean type. Therefore an unsigned integer is used
  796. // to represent booleans when layout is required. In such cases, after loading
  797. // the uint, we should perform a comparison.
  798. {
  799. uint32_t vecSize = 1, numRows = 0, numCols = 0;
  800. if (info.getLayoutRule() != LayoutRule::Void &&
  801. isBoolOrVecMatOfBoolType(expr->getType())) {
  802. const auto exprType = expr->getType();
  803. QualType uintType = astContext.UnsignedIntTy;
  804. QualType boolType = astContext.BoolTy;
  805. if (TypeTranslator::isScalarType(exprType) ||
  806. TypeTranslator::isVectorType(exprType, nullptr, &vecSize)) {
  807. const auto fromType =
  808. vecSize == 1 ? uintType
  809. : astContext.getExtVectorType(uintType, vecSize);
  810. const auto toType =
  811. vecSize == 1 ? boolType
  812. : astContext.getExtVectorType(boolType, vecSize);
  813. loadedId = castToBool(loadedId, fromType, toType);
  814. } else {
  815. const bool isMat =
  816. TypeTranslator::isMxNMatrix(exprType, nullptr, &numRows, &numCols);
  817. assert(isMat);
  818. (void)isMat;
  819. const auto uintRowQualType =
  820. astContext.getExtVectorType(uintType, numCols);
  821. const auto uintRowQualTypeId =
  822. typeTranslator.translateType(uintRowQualType);
  823. const auto boolRowQualType =
  824. astContext.getExtVectorType(boolType, numCols);
  825. const auto boolRowQualTypeId =
  826. typeTranslator.translateType(boolRowQualType);
  827. const uint32_t resultTypeId =
  828. theBuilder.getMatType(boolType, boolRowQualTypeId, numRows);
  829. llvm::SmallVector<uint32_t, 4> rows;
  830. for (uint32_t i = 0; i < numRows; ++i) {
  831. const auto row = theBuilder.createCompositeExtract(uintRowQualTypeId,
  832. loadedId, {i});
  833. rows.push_back(castToBool(row, uintRowQualType, boolRowQualType));
  834. }
  835. loadedId = theBuilder.createCompositeConstruct(resultTypeId, rows);
  836. }
  837. // Now that it is converted to Bool, it has no layout rule.
  838. // This result-id should be evaluated as bool from here on out.
  839. info.setLayoutRule(LayoutRule::Void);
  840. }
  841. }
  842. return info.setResultId(loadedId).setRValue();
  843. }
  844. SpirvEvalInfo SPIRVEmitter::loadIfAliasVarRef(const Expr *expr) {
  845. auto info = doExpr(expr);
  846. loadIfAliasVarRef(expr, info);
  847. return info;
  848. }
  849. bool SPIRVEmitter::loadIfAliasVarRef(const Expr *varExpr, SpirvEvalInfo &info) {
  850. if (info.containsAliasComponent() &&
  851. TypeTranslator::isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  852. // Aliased-to variables are all in the Uniform storage class with GLSL
  853. // std430 layout rules.
  854. const auto ptrType = typeTranslator.translateType(varExpr->getType());
  855. // Load the pointer of the aliased-to-variable if the expression has a
  856. // pointer to pointer type. That is, the expression itself is a lvalue.
  857. // (Note that we translate alias function return values as pointer types,
  858. // not pointer to pointer types.)
  859. if (varExpr->isGLValue())
  860. info.setResultId(theBuilder.createLoad(ptrType, info));
  861. info.setStorageClass(spv::StorageClass::Uniform)
  862. .setLayoutRule(spirvOptions.sBufferLayoutRule)
  863. // Now it is a pointer to the global resource, which is lvalue.
  864. .setRValue(false)
  865. // Set to false to indicate that we've performed dereference over the
  866. // pointer-to-pointer and now should fallback to the normal path
  867. .setContainsAliasComponent(false);
  868. return true;
  869. }
  870. return false;
  871. }
  872. uint32_t SPIRVEmitter::castToType(uint32_t value, QualType fromType,
  873. QualType toType, SourceLocation srcLoc) {
  874. if (isFloatOrVecOfFloatType(toType))
  875. return castToFloat(value, fromType, toType, srcLoc);
  876. // Order matters here. Bool (vector) values will also be considered as uint
  877. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  878. // will also return true. We need to check bool before uint. The opposite is
  879. // not true.
  880. if (isBoolOrVecOfBoolType(toType))
  881. return castToBool(value, fromType, toType);
  882. if (isSintOrVecOfSintType(toType) || isUintOrVecOfUintType(toType))
  883. return castToInt(value, fromType, toType, srcLoc);
  884. emitError("casting to type %0 unimplemented", {}) << toType;
  885. return 0;
  886. }
  887. void SPIRVEmitter::doFunctionDecl(const FunctionDecl *decl) {
  888. assert(decl->isThisDeclarationADefinition());
  889. // A RAII class for maintaining the current function under traversal.
  890. class FnEnvRAII {
  891. public:
  892. // Creates a new instance which sets fnEnv to the newFn on creation,
  893. // and resets fnEnv to its original value on destruction.
  894. FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
  895. : oldFn(*fnEnv), fnSlot(fnEnv) {
  896. *fnEnv = newFn;
  897. }
  898. ~FnEnvRAII() { *fnSlot = oldFn; }
  899. private:
  900. const FunctionDecl *oldFn;
  901. const FunctionDecl **fnSlot;
  902. };
  903. FnEnvRAII fnEnvRAII(&curFunction, decl);
  904. // We are about to start translation for a new function. Clear the break stack
  905. // and the continue stack.
  906. breakStack = std::stack<uint32_t>();
  907. continueStack = std::stack<uint32_t>();
  908. // This will allow the entry-point name to be something like
  909. // myNamespace::myEntrypointFunc.
  910. std::string funcName = getFnName(decl);
  911. uint32_t funcId = 0;
  912. if (funcName == entryFunctionName) {
  913. // The entry function surely does not have pre-assigned <result-id> for
  914. // it like other functions that got added to the work queue following
  915. // function calls.
  916. funcId = theContext.takeNextId();
  917. funcName = "src." + funcName;
  918. // Create wrapper for the entry function
  919. if (!emitEntryFunctionWrapper(decl, funcId))
  920. return;
  921. } else {
  922. // Non-entry functions are added to the work queue following function
  923. // calls. We have already assigned <result-id>s for it when translating
  924. // its call site. Query it here.
  925. funcId = declIdMapper.getDeclEvalInfo(decl);
  926. }
  927. const uint32_t retType =
  928. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  929. // Construct the function signature.
  930. llvm::SmallVector<uint32_t, 4> paramTypes;
  931. bool isNonStaticMemberFn = false;
  932. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  933. isNonStaticMemberFn = !memberFn->isStatic();
  934. if (isNonStaticMemberFn) {
  935. // For non-static member function, the first parameter should be the
  936. // object on which we are invoking this method.
  937. const uint32_t valueType = typeTranslator.translateType(
  938. memberFn->getThisType(astContext)->getPointeeType());
  939. const uint32_t ptrType =
  940. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  941. paramTypes.push_back(ptrType);
  942. }
  943. }
  944. for (const auto *param : decl->params()) {
  945. const uint32_t valueType =
  946. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  947. const uint32_t ptrType =
  948. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  949. paramTypes.push_back(ptrType);
  950. }
  951. const uint32_t funcType = theBuilder.getFunctionType(retType, paramTypes);
  952. theBuilder.beginFunction(funcType, retType, funcName, funcId);
  953. if (isNonStaticMemberFn) {
  954. // Remember the parameter for the this object so later we can handle
  955. // CXXThisExpr correctly.
  956. curThis = theBuilder.addFnParam(paramTypes[0], "param.this");
  957. }
  958. // Create all parameters.
  959. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  960. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  961. (void)declIdMapper.createFnParam(paramDecl);
  962. }
  963. if (decl->hasBody()) {
  964. // The entry basic block.
  965. const uint32_t entryLabel = theBuilder.createBasicBlock("bb.entry");
  966. theBuilder.setInsertPoint(entryLabel);
  967. // Process all statments in the body.
  968. doStmt(decl->getBody());
  969. // We have processed all Stmts in this function and now in the last
  970. // basic block. Make sure we have a termination instruction.
  971. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  972. const auto retType = decl->getReturnType();
  973. if (retType->isVoidType()) {
  974. theBuilder.createReturn();
  975. } else {
  976. // If the source code does not provide a proper return value for some
  977. // control flow path, it's undefined behavior. We just return null
  978. // value here.
  979. theBuilder.createReturnValue(
  980. theBuilder.getConstantNull(typeTranslator.translateType(retType)));
  981. }
  982. }
  983. }
  984. theBuilder.endFunction();
  985. }
  986. bool SPIRVEmitter::validateVKAttributes(const NamedDecl *decl) {
  987. bool success = true;
  988. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  989. const auto varType = varDecl->getType();
  990. if ((TypeTranslator::isSubpassInput(varType) ||
  991. TypeTranslator::isSubpassInputMS(varType)) &&
  992. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  993. emitError("missing vk::input_attachment_index attribute",
  994. varDecl->getLocation());
  995. success = false;
  996. }
  997. }
  998. if (decl->getAttr<VKInputAttachmentIndexAttr>()) {
  999. if (!shaderModel.IsPS()) {
  1000. emitError("SubpassInput(MS) only allowed in pixel shader",
  1001. decl->getLocation());
  1002. success = false;
  1003. }
  1004. if (!decl->isExternallyVisible()) {
  1005. emitError("SubpassInput(MS) must be externally visible",
  1006. decl->getLocation());
  1007. success = false;
  1008. }
  1009. // We only allow VKInputAttachmentIndexAttr to be attached to global
  1010. // variables. So it should be fine to cast here.
  1011. const auto elementType =
  1012. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  1013. if (!TypeTranslator::isScalarType(elementType) &&
  1014. !TypeTranslator::isVectorType(elementType)) {
  1015. emitError(
  1016. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  1017. decl->getLocation());
  1018. // Return directly to avoid further type processing, which will hit
  1019. // asserts in TypeTranslator.
  1020. return false;
  1021. }
  1022. }
  1023. // The frontend will make sure that
  1024. // * vk::push_constant applies to global variables of struct type
  1025. // * vk::binding applies to global variables or cbuffers/tbuffers
  1026. // * vk::counter_binding applies to global variables of RW/Append/Consume
  1027. // StructuredBuffer
  1028. // * vk::location applies to function parameters/returns and struct fields
  1029. // So the only case we need to check co-existence is vk::push_constant and
  1030. // vk::binding.
  1031. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  1032. const auto loc = pcAttr->getLocation();
  1033. if (seenPushConstantAt.isInvalid()) {
  1034. seenPushConstantAt = loc;
  1035. } else {
  1036. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  1037. // There must be no more than one push constant block statically used
  1038. // per shader entry point.
  1039. // But we are checking whether there are more than one push constant
  1040. // blocks defined. Tracking usage requires more work.
  1041. emitError("cannot have more than one push constant block", loc);
  1042. emitNote("push constant block previously defined here",
  1043. seenPushConstantAt);
  1044. success = false;
  1045. }
  1046. if (decl->hasAttr<VKBindingAttr>()) {
  1047. emitError("vk::push_constant attribute cannot be used together with "
  1048. "vk::binding attribute",
  1049. loc);
  1050. success = false;
  1051. }
  1052. }
  1053. return success;
  1054. }
  1055. void SPIRVEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  1056. // This is a cbuffer/tbuffer decl.
  1057. // Check and emit warnings for member intializers which are not
  1058. // supported in Vulkan
  1059. for (const auto *member : bufferDecl->decls()) {
  1060. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  1061. if (!spirvOptions.noWarnIgnoredFeatures) {
  1062. if (const auto *init = varMember->getInit())
  1063. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  1064. "ignored since no Vulkan equivalent",
  1065. init->getExprLoc())
  1066. << bufferDecl->isCBuffer() << init->getSourceRange();
  1067. }
  1068. // We cannot handle external initialization of column-major matrices now.
  1069. if (typeTranslator.isOrContainsNonFpColMajorMatrix(varMember->getType(),
  1070. varMember)) {
  1071. emitError("externally initialized non-floating-point column-major "
  1072. "matrices not supported yet",
  1073. varMember->getLocation());
  1074. }
  1075. }
  1076. }
  1077. if (!validateVKAttributes(bufferDecl))
  1078. return;
  1079. (void)declIdMapper.createCTBuffer(bufferDecl);
  1080. }
  1081. void SPIRVEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  1082. // Ignore implict records
  1083. // Somehow we'll have implicit records with:
  1084. // static const int Length = count;
  1085. // that can mess up with the normal CodeGen.
  1086. if (recordDecl->isImplicit())
  1087. return;
  1088. // Handle each static member with inline initializer.
  1089. // Each static member has a corresponding VarDecl inside the
  1090. // RecordDecl. For those defined in the translation unit,
  1091. // their VarDecls do not have initializer.
  1092. for (auto *subDecl : recordDecl->decls())
  1093. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  1094. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  1095. doVarDecl(varDecl);
  1096. }
  1097. void SPIRVEmitter::doVarDecl(const VarDecl *decl) {
  1098. if (!validateVKAttributes(decl))
  1099. return;
  1100. // We cannot handle external initialization of column-major matrices now.
  1101. if (isExternalVar(decl) &&
  1102. typeTranslator.isOrContainsNonFpColMajorMatrix(decl->getType(), decl)) {
  1103. emitError("externally initialized non-floating-point column-major "
  1104. "matrices not supported yet",
  1105. decl->getLocation());
  1106. }
  1107. // Reject arrays of RW/append/consume structured buffers. They have assoicated
  1108. // counters, which are quite nasty to handle.
  1109. if (decl->getType()->isArrayType()) {
  1110. auto type = decl->getType();
  1111. do {
  1112. type = type->getAsArrayTypeUnsafe()->getElementType();
  1113. } while (type->isArrayType());
  1114. if (TypeTranslator::isRWAppendConsumeSBuffer(type)) {
  1115. emitError("arrays of RW/append/consume structured buffers unsupported",
  1116. decl->getLocation());
  1117. return;
  1118. }
  1119. }
  1120. if (decl->hasAttr<VKConstantIdAttr>()) {
  1121. // This is a VarDecl for specialization constant.
  1122. createSpecConstant(decl);
  1123. return;
  1124. }
  1125. if (decl->hasAttr<VKPushConstantAttr>()) {
  1126. // This is a VarDecl for PushConstant block.
  1127. (void)declIdMapper.createPushConstant(decl);
  1128. return;
  1129. }
  1130. if (isa<HLSLBufferDecl>(decl->getDeclContext())) {
  1131. // This is a VarDecl of a ConstantBuffer/TextureBuffer type.
  1132. (void)declIdMapper.createCTBuffer(decl);
  1133. return;
  1134. }
  1135. SpirvEvalInfo varId(0);
  1136. // The contents in externally visible variables can be updated via the
  1137. // pipeline. They should be handled differently from file and function scope
  1138. // variables.
  1139. // File scope variables (static "global" and "local" variables) belongs to
  1140. // the Private storage class, while function scope variables (normal "local"
  1141. // variables) belongs to the Function storage class.
  1142. if (isExternalVar(decl)) {
  1143. varId = declIdMapper.createExternVar(decl);
  1144. } else {
  1145. // We already know the variable is not externally visible here. If it does
  1146. // not have local storage, it should be file scope variable.
  1147. const bool isFileScopeVar = !decl->hasLocalStorage();
  1148. if (isFileScopeVar)
  1149. varId = declIdMapper.createFileVar(decl, llvm::None);
  1150. else
  1151. varId = declIdMapper.createFnVar(decl, llvm::None);
  1152. // Emit OpStore to initialize the variable
  1153. // TODO: revert back to use OpVariable initializer
  1154. // We should only evaluate the initializer once for a static variable.
  1155. if (isFileScopeVar) {
  1156. if (decl->isStaticLocal()) {
  1157. initOnce(decl->getType(), decl->getName(), varId, decl->getInit());
  1158. } else {
  1159. // Defer to initialize these global variables at the beginning of the
  1160. // entry function.
  1161. toInitGloalVars.push_back(decl);
  1162. }
  1163. }
  1164. // Function local variables. Just emit OpStore at the current insert point.
  1165. else if (const Expr *init = decl->getInit()) {
  1166. if (const auto constId = tryToEvaluateAsConst(init))
  1167. theBuilder.createStore(varId, constId);
  1168. else
  1169. storeValue(varId, loadIfGLValue(init), decl->getType());
  1170. // Update counter variable associated with local variables
  1171. tryToAssignCounterVar(decl, init);
  1172. }
  1173. // Variables that are not externally visible and of opaque types should
  1174. // request legalization.
  1175. if (!needsLegalization && TypeTranslator::isOpaqueType(decl->getType()))
  1176. needsLegalization = true;
  1177. }
  1178. if (TypeTranslator::isRelaxedPrecisionType(decl->getType(), spirvOptions)) {
  1179. theBuilder.decorateRelaxedPrecision(varId);
  1180. }
  1181. // All variables that are of opaque struct types should request legalization.
  1182. if (!needsLegalization && TypeTranslator::isOpaqueStructType(decl->getType()))
  1183. needsLegalization = true;
  1184. }
  1185. spv::LoopControlMask SPIRVEmitter::translateLoopAttribute(const Stmt *stmt,
  1186. const Attr &attr) {
  1187. switch (attr.getKind()) {
  1188. case attr::HLSLLoop:
  1189. case attr::HLSLFastOpt:
  1190. return spv::LoopControlMask::DontUnroll;
  1191. case attr::HLSLUnroll:
  1192. return spv::LoopControlMask::Unroll;
  1193. case attr::HLSLAllowUAVCondition:
  1194. emitWarning("unsupported allow_uav_condition attribute ignored",
  1195. stmt->getLocStart());
  1196. break;
  1197. default:
  1198. llvm_unreachable("found unknown loop attribute");
  1199. }
  1200. return spv::LoopControlMask::MaskNone;
  1201. }
  1202. void SPIRVEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1203. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1204. theBuilder.createKill();
  1205. // Some statements that alter the control flow (break, continue, return, and
  1206. // discard), require creation of a new basic block to hold any statement that
  1207. // may follow them.
  1208. const uint32_t newBB = theBuilder.createBasicBlock();
  1209. theBuilder.setInsertPoint(newBB);
  1210. }
  1211. void SPIRVEmitter::doDoStmt(const DoStmt *theDoStmt,
  1212. llvm::ArrayRef<const Attr *> attrs) {
  1213. // do-while loops are composed of:
  1214. //
  1215. // do {
  1216. // <body>
  1217. // } while(<check>);
  1218. //
  1219. // SPIR-V requires loops to have a merge basic block as well as a continue
  1220. // basic block. Even though do-while loops do not have an explicit continue
  1221. // block as in for-loops, we still do need to create a continue block.
  1222. //
  1223. // Since SPIR-V requires structured control flow, we need two more basic
  1224. // blocks, <header> and <merge>. <header> is the block before control flow
  1225. // diverges, and <merge> is the block where control flow subsequently
  1226. // converges. The <check> can be performed in the <continue> basic block.
  1227. // The final CFG should normally be like the following. Exceptions
  1228. // will occur with non-local exits like loop breaks or early returns.
  1229. //
  1230. // +----------+
  1231. // | header | <-----------------------------------+
  1232. // +----------+ |
  1233. // | | (true)
  1234. // v |
  1235. // +------+ +--------------------+ |
  1236. // | body | ----> | continue (<check>) |-----------+
  1237. // +------+ +--------------------+
  1238. // |
  1239. // | (false)
  1240. // +-------+ |
  1241. // | merge | <-------------+
  1242. // +-------+
  1243. //
  1244. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1245. const spv::LoopControlMask loopControl =
  1246. attrs.empty() ? spv::LoopControlMask::MaskNone
  1247. : translateLoopAttribute(theDoStmt, *attrs.front());
  1248. // Create basic blocks
  1249. const uint32_t headerBB = theBuilder.createBasicBlock("do_while.header");
  1250. const uint32_t bodyBB = theBuilder.createBasicBlock("do_while.body");
  1251. const uint32_t continueBB = theBuilder.createBasicBlock("do_while.continue");
  1252. const uint32_t mergeBB = theBuilder.createBasicBlock("do_while.merge");
  1253. // Make sure any continue statements branch to the continue block, and any
  1254. // break statements branch to the merge block.
  1255. continueStack.push(continueBB);
  1256. breakStack.push(mergeBB);
  1257. // Branch from the current insert point to the header block.
  1258. theBuilder.createBranch(headerBB);
  1259. theBuilder.addSuccessor(headerBB);
  1260. // Process the <header> block
  1261. // The header block must always branch to the body.
  1262. theBuilder.setInsertPoint(headerBB);
  1263. theBuilder.createBranch(bodyBB, mergeBB, continueBB, loopControl);
  1264. theBuilder.addSuccessor(bodyBB);
  1265. // The current basic block has OpLoopMerge instruction. We need to set its
  1266. // continue and merge target.
  1267. theBuilder.setContinueTarget(continueBB);
  1268. theBuilder.setMergeTarget(mergeBB);
  1269. // Process the <body> block
  1270. theBuilder.setInsertPoint(bodyBB);
  1271. if (const Stmt *body = theDoStmt->getBody()) {
  1272. doStmt(body);
  1273. }
  1274. if (!theBuilder.isCurrentBasicBlockTerminated())
  1275. theBuilder.createBranch(continueBB);
  1276. theBuilder.addSuccessor(continueBB);
  1277. // Process the <continue> block. The check for whether the loop should
  1278. // continue lies in the continue block.
  1279. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1280. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1281. // OpBranchConditional must be specified.
  1282. theBuilder.setInsertPoint(continueBB);
  1283. uint32_t condition = 0;
  1284. if (const Expr *check = theDoStmt->getCond()) {
  1285. condition = doExpr(check);
  1286. } else {
  1287. condition = theBuilder.getConstantBool(true);
  1288. }
  1289. theBuilder.createConditionalBranch(condition, headerBB, mergeBB);
  1290. theBuilder.addSuccessor(headerBB);
  1291. theBuilder.addSuccessor(mergeBB);
  1292. // Set insertion point to the <merge> block for subsequent statements
  1293. theBuilder.setInsertPoint(mergeBB);
  1294. // Done with the current scope's continue block and merge block.
  1295. continueStack.pop();
  1296. breakStack.pop();
  1297. }
  1298. void SPIRVEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1299. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1300. const uint32_t continueTargetBB = continueStack.top();
  1301. theBuilder.createBranch(continueTargetBB);
  1302. theBuilder.addSuccessor(continueTargetBB);
  1303. // Some statements that alter the control flow (break, continue, return, and
  1304. // discard), require creation of a new basic block to hold any statement that
  1305. // may follow them. For example: StmtB and StmtC below are put inside a new
  1306. // basic block which is unreachable.
  1307. //
  1308. // while (true) {
  1309. // StmtA;
  1310. // continue;
  1311. // StmtB;
  1312. // StmtC;
  1313. // }
  1314. const uint32_t newBB = theBuilder.createBasicBlock();
  1315. theBuilder.setInsertPoint(newBB);
  1316. }
  1317. void SPIRVEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1318. llvm::ArrayRef<const Attr *> attrs) {
  1319. // While loops are composed of:
  1320. // while (<check>) { <body> }
  1321. //
  1322. // SPIR-V requires loops to have a merge basic block as well as a continue
  1323. // basic block. Even though while loops do not have an explicit continue
  1324. // block as in for-loops, we still do need to create a continue block.
  1325. //
  1326. // Since SPIR-V requires structured control flow, we need two more basic
  1327. // blocks, <header> and <merge>. <header> is the block before control flow
  1328. // diverges, and <merge> is the block where control flow subsequently
  1329. // converges. The <check> block can take the responsibility of the <header>
  1330. // block. The final CFG should normally be like the following. Exceptions
  1331. // will occur with non-local exits like loop breaks or early returns.
  1332. //
  1333. // +----------+
  1334. // | header | <------------------+
  1335. // | (check) | |
  1336. // +----------+ |
  1337. // | |
  1338. // +-------+-------+ |
  1339. // | false | true |
  1340. // | v |
  1341. // | +------+ +------------------+
  1342. // | | body | --> | continue (no-op) |
  1343. // v +------+ +------------------+
  1344. // +-------+
  1345. // | merge |
  1346. // +-------+
  1347. //
  1348. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1349. const spv::LoopControlMask loopControl =
  1350. attrs.empty() ? spv::LoopControlMask::MaskNone
  1351. : translateLoopAttribute(whileStmt, *attrs.front());
  1352. // Create basic blocks
  1353. const uint32_t checkBB = theBuilder.createBasicBlock("while.check");
  1354. const uint32_t bodyBB = theBuilder.createBasicBlock("while.body");
  1355. const uint32_t continueBB = theBuilder.createBasicBlock("while.continue");
  1356. const uint32_t mergeBB = theBuilder.createBasicBlock("while.merge");
  1357. // Make sure any continue statements branch to the continue block, and any
  1358. // break statements branch to the merge block.
  1359. continueStack.push(continueBB);
  1360. breakStack.push(mergeBB);
  1361. // Process the <check> block
  1362. theBuilder.createBranch(checkBB);
  1363. theBuilder.addSuccessor(checkBB);
  1364. theBuilder.setInsertPoint(checkBB);
  1365. // If we have:
  1366. // while (int a = foo()) {...}
  1367. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1368. // to occur.
  1369. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1370. doStmt(condVarDecl);
  1371. uint32_t condition = 0;
  1372. if (const Expr *check = whileStmt->getCond()) {
  1373. condition = doExpr(check);
  1374. } else {
  1375. condition = theBuilder.getConstantBool(true);
  1376. }
  1377. theBuilder.createConditionalBranch(condition, bodyBB,
  1378. /*false branch*/ mergeBB,
  1379. /*merge*/ mergeBB, continueBB,
  1380. spv::SelectionControlMask::MaskNone,
  1381. loopControl);
  1382. theBuilder.addSuccessor(bodyBB);
  1383. theBuilder.addSuccessor(mergeBB);
  1384. // The current basic block has OpLoopMerge instruction. We need to set its
  1385. // continue and merge target.
  1386. theBuilder.setContinueTarget(continueBB);
  1387. theBuilder.setMergeTarget(mergeBB);
  1388. // Process the <body> block
  1389. theBuilder.setInsertPoint(bodyBB);
  1390. if (const Stmt *body = whileStmt->getBody()) {
  1391. doStmt(body);
  1392. }
  1393. if (!theBuilder.isCurrentBasicBlockTerminated())
  1394. theBuilder.createBranch(continueBB);
  1395. theBuilder.addSuccessor(continueBB);
  1396. // Process the <continue> block. While loops do not have an explicit
  1397. // continue block. The continue block just branches to the <check> block.
  1398. theBuilder.setInsertPoint(continueBB);
  1399. theBuilder.createBranch(checkBB);
  1400. theBuilder.addSuccessor(checkBB);
  1401. // Set insertion point to the <merge> block for subsequent statements
  1402. theBuilder.setInsertPoint(mergeBB);
  1403. // Done with the current scope's continue and merge blocks.
  1404. continueStack.pop();
  1405. breakStack.pop();
  1406. }
  1407. void SPIRVEmitter::doForStmt(const ForStmt *forStmt,
  1408. llvm::ArrayRef<const Attr *> attrs) {
  1409. // for loops are composed of:
  1410. // for (<init>; <check>; <continue>) <body>
  1411. //
  1412. // To translate a for loop, we'll need to emit all <init> statements
  1413. // in the current basic block, and then have separate basic blocks for
  1414. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1415. // structured control flow, we need two more basic blocks, <header>
  1416. // and <merge>. <header> is the block before control flow diverges,
  1417. // while <merge> is the block where control flow subsequently converges.
  1418. // The <check> block can take the responsibility of the <header> block.
  1419. // The final CFG should normally be like the following. Exceptions will
  1420. // occur with non-local exits like loop breaks or early returns.
  1421. // +--------+
  1422. // | init |
  1423. // +--------+
  1424. // |
  1425. // v
  1426. // +----------+
  1427. // | header | <---------------+
  1428. // | (check) | |
  1429. // +----------+ |
  1430. // | |
  1431. // +-------+-------+ |
  1432. // | false | true |
  1433. // | v |
  1434. // | +------+ +----------+
  1435. // | | body | --> | continue |
  1436. // v +------+ +----------+
  1437. // +-------+
  1438. // | merge |
  1439. // +-------+
  1440. //
  1441. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1442. const spv::LoopControlMask loopControl =
  1443. attrs.empty() ? spv::LoopControlMask::MaskNone
  1444. : translateLoopAttribute(forStmt, *attrs.front());
  1445. // Create basic blocks
  1446. const uint32_t checkBB = theBuilder.createBasicBlock("for.check");
  1447. const uint32_t bodyBB = theBuilder.createBasicBlock("for.body");
  1448. const uint32_t continueBB = theBuilder.createBasicBlock("for.continue");
  1449. const uint32_t mergeBB = theBuilder.createBasicBlock("for.merge");
  1450. // Make sure any continue statements branch to the continue block, and any
  1451. // break statements branch to the merge block.
  1452. continueStack.push(continueBB);
  1453. breakStack.push(mergeBB);
  1454. // Process the <init> block
  1455. if (const Stmt *initStmt = forStmt->getInit()) {
  1456. doStmt(initStmt);
  1457. }
  1458. theBuilder.createBranch(checkBB);
  1459. theBuilder.addSuccessor(checkBB);
  1460. // Process the <check> block
  1461. theBuilder.setInsertPoint(checkBB);
  1462. uint32_t condition;
  1463. if (const Expr *check = forStmt->getCond()) {
  1464. condition = doExpr(check);
  1465. } else {
  1466. condition = theBuilder.getConstantBool(true);
  1467. }
  1468. theBuilder.createConditionalBranch(condition, bodyBB,
  1469. /*false branch*/ mergeBB,
  1470. /*merge*/ mergeBB, continueBB,
  1471. spv::SelectionControlMask::MaskNone,
  1472. loopControl);
  1473. theBuilder.addSuccessor(bodyBB);
  1474. theBuilder.addSuccessor(mergeBB);
  1475. // The current basic block has OpLoopMerge instruction. We need to set its
  1476. // continue and merge target.
  1477. theBuilder.setContinueTarget(continueBB);
  1478. theBuilder.setMergeTarget(mergeBB);
  1479. // Process the <body> block
  1480. theBuilder.setInsertPoint(bodyBB);
  1481. if (const Stmt *body = forStmt->getBody()) {
  1482. doStmt(body);
  1483. }
  1484. if (!theBuilder.isCurrentBasicBlockTerminated())
  1485. theBuilder.createBranch(continueBB);
  1486. theBuilder.addSuccessor(continueBB);
  1487. // Process the <continue> block
  1488. theBuilder.setInsertPoint(continueBB);
  1489. if (const Expr *cont = forStmt->getInc()) {
  1490. doExpr(cont);
  1491. }
  1492. theBuilder.createBranch(checkBB); // <continue> should jump back to header
  1493. theBuilder.addSuccessor(checkBB);
  1494. // Set insertion point to the <merge> block for subsequent statements
  1495. theBuilder.setInsertPoint(mergeBB);
  1496. // Done with the current scope's continue block and merge block.
  1497. continueStack.pop();
  1498. breakStack.pop();
  1499. }
  1500. void SPIRVEmitter::doIfStmt(const IfStmt *ifStmt,
  1501. llvm::ArrayRef<const Attr *> attrs) {
  1502. // if statements are composed of:
  1503. // if (<check>) { <then> } else { <else> }
  1504. //
  1505. // To translate if statements, we'll need to emit the <check> expressions
  1506. // in the current basic block, and then create separate basic blocks for
  1507. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1508. // SPIR-V's structured control flow requirements. Depending whether there
  1509. // exists the else branch, the final CFG should normally be like the
  1510. // following. Exceptions will occur with non-local exits like loop breaks
  1511. // or early returns.
  1512. // +-------+ +-------+
  1513. // | check | | check |
  1514. // +-------+ +-------+
  1515. // | |
  1516. // +-------+-------+ +-----+-----+
  1517. // | true | false | true | false
  1518. // v v or v |
  1519. // +------+ +------+ +------+ |
  1520. // | then | | else | | then | |
  1521. // +------+ +------+ +------+ |
  1522. // | | | v
  1523. // | +-------+ | | +-------+
  1524. // +-> | merge | <-+ +---> | merge |
  1525. // +-------+ +-------+
  1526. { // Try to see if we can const-eval the condition
  1527. bool condition = false;
  1528. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1529. if (condition) {
  1530. doStmt(ifStmt->getThen());
  1531. } else if (ifStmt->getElse()) {
  1532. doStmt(ifStmt->getElse());
  1533. }
  1534. return;
  1535. }
  1536. }
  1537. auto selectionControl = spv::SelectionControlMask::MaskNone;
  1538. if (!attrs.empty()) {
  1539. const Attr *attribute = attrs.front();
  1540. switch (attribute->getKind()) {
  1541. case attr::HLSLBranch:
  1542. selectionControl = spv::SelectionControlMask::DontFlatten;
  1543. break;
  1544. case attr::HLSLFlatten:
  1545. selectionControl = spv::SelectionControlMask::Flatten;
  1546. break;
  1547. default:
  1548. emitWarning("unknown if statement attribute '%0' ignored",
  1549. attribute->getLocation())
  1550. << attribute->getSpelling();
  1551. break;
  1552. }
  1553. }
  1554. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1555. doDeclStmt(declStmt);
  1556. // First emit the instruction for evaluating the condition.
  1557. const uint32_t condition = doExpr(ifStmt->getCond());
  1558. // Then we need to emit the instruction for the conditional branch.
  1559. // We'll need the <label-id> for the then/else/merge block to do so.
  1560. const bool hasElse = ifStmt->getElse() != nullptr;
  1561. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  1562. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  1563. const uint32_t elseBB =
  1564. hasElse ? theBuilder.createBasicBlock("if.false") : mergeBB;
  1565. // Create the branch instruction. This will end the current basic block.
  1566. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB,
  1567. /*continue*/ 0, selectionControl);
  1568. theBuilder.addSuccessor(thenBB);
  1569. theBuilder.addSuccessor(elseBB);
  1570. // The current basic block has the OpSelectionMerge instruction. We need
  1571. // to record its merge target.
  1572. theBuilder.setMergeTarget(mergeBB);
  1573. // Handle the then branch
  1574. theBuilder.setInsertPoint(thenBB);
  1575. doStmt(ifStmt->getThen());
  1576. if (!theBuilder.isCurrentBasicBlockTerminated())
  1577. theBuilder.createBranch(mergeBB);
  1578. theBuilder.addSuccessor(mergeBB);
  1579. // Handle the else branch (if exists)
  1580. if (hasElse) {
  1581. theBuilder.setInsertPoint(elseBB);
  1582. doStmt(ifStmt->getElse());
  1583. if (!theBuilder.isCurrentBasicBlockTerminated())
  1584. theBuilder.createBranch(mergeBB);
  1585. theBuilder.addSuccessor(mergeBB);
  1586. }
  1587. // From now on, we'll emit instructions into the merge block.
  1588. theBuilder.setInsertPoint(mergeBB);
  1589. }
  1590. void SPIRVEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1591. if (const auto *retVal = stmt->getRetValue()) {
  1592. // Update counter variable associated with function returns
  1593. tryToAssignCounterVar(curFunction, retVal);
  1594. const auto retInfo = loadIfGLValue(retVal);
  1595. const auto retType = retVal->getType();
  1596. if (retInfo.getStorageClass() != spv::StorageClass::Function &&
  1597. retType->isStructureType()) {
  1598. // We are returning some value from a non-Function storage class. Need to
  1599. // create a temporary variable to "convert" the value to Function storage
  1600. // class and then return.
  1601. const uint32_t valType = typeTranslator.translateType(retType);
  1602. const uint32_t tempVar = theBuilder.addFnVar(valType, "temp.var.ret");
  1603. storeValue(tempVar, retInfo, retType);
  1604. theBuilder.createReturnValue(theBuilder.createLoad(valType, tempVar));
  1605. } else {
  1606. theBuilder.createReturnValue(retInfo);
  1607. }
  1608. } else {
  1609. theBuilder.createReturn();
  1610. }
  1611. // We are translating a ReturnStmt, we should be in some function's body.
  1612. assert(curFunction->hasBody());
  1613. // If this return statement is the last statement in the function, then
  1614. // whe have no more work to do.
  1615. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1616. return;
  1617. // Some statements that alter the control flow (break, continue, return, and
  1618. // discard), require creation of a new basic block to hold any statement that
  1619. // may follow them. In this case, the newly created basic block will contain
  1620. // any statement that may come after an early return.
  1621. const uint32_t newBB = theBuilder.createBasicBlock();
  1622. theBuilder.setInsertPoint(newBB);
  1623. }
  1624. void SPIRVEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1625. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1626. uint32_t breakTargetBB = breakStack.top();
  1627. theBuilder.addSuccessor(breakTargetBB);
  1628. theBuilder.createBranch(breakTargetBB);
  1629. // Some statements that alter the control flow (break, continue, return, and
  1630. // discard), require creation of a new basic block to hold any statement that
  1631. // may follow them. For example: StmtB and StmtC below are put inside a new
  1632. // basic block which is unreachable.
  1633. //
  1634. // while (true) {
  1635. // StmtA;
  1636. // break;
  1637. // StmtB;
  1638. // StmtC;
  1639. // }
  1640. const uint32_t newBB = theBuilder.createBasicBlock();
  1641. theBuilder.setInsertPoint(newBB);
  1642. }
  1643. void SPIRVEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1644. llvm::ArrayRef<const Attr *> attrs) {
  1645. // Switch statements are composed of:
  1646. // switch (<condition variable>) {
  1647. // <CaseStmt>
  1648. // <CaseStmt>
  1649. // <CaseStmt>
  1650. // <DefaultStmt> (optional)
  1651. // }
  1652. //
  1653. // +-------+
  1654. // | check |
  1655. // +-------+
  1656. // |
  1657. // +-------+-------+----------------+---------------+
  1658. // | 1 | 2 | 3 | (others)
  1659. // v v v v
  1660. // +-------+ +-------------+ +-------+ +------------+
  1661. // | case1 | | case2 | | case3 | ... | default |
  1662. // | | |(fallthrough)|---->| | | (optional) |
  1663. // +-------+ |+------------+ +-------+ +------------+
  1664. // | | |
  1665. // | | |
  1666. // | +-------+ | |
  1667. // | | | <--------------------+ |
  1668. // +-> | merge | |
  1669. // | | <-------------------------------------+
  1670. // +-------+
  1671. // If no attributes are given, or if "forcecase" attribute was provided,
  1672. // we'll do our best to use OpSwitch if possible.
  1673. // If any of the cases compares to a variable (rather than an integer
  1674. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1675. // numbers as parameters.
  1676. const bool isAttrForceCase =
  1677. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1678. const bool canUseSpirvOpSwitch =
  1679. (attrs.empty() || isAttrForceCase) &&
  1680. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1681. if (isAttrForceCase && !canUseSpirvOpSwitch)
  1682. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1683. "since one or more case values are not integer literals",
  1684. switchStmt->getLocStart());
  1685. if (canUseSpirvOpSwitch)
  1686. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1687. else
  1688. processSwitchStmtUsingIfStmts(switchStmt);
  1689. }
  1690. SpirvEvalInfo
  1691. SPIRVEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1692. // Make sure we don't have previously unhandled NonUniformResourceIndex()
  1693. assert(!foundNonUniformResourceIndex);
  1694. llvm::SmallVector<uint32_t, 4> indices;
  1695. const auto *base = collectArrayStructIndices(expr, &indices);
  1696. auto info = loadIfAliasVarRef(base);
  1697. if (foundNonUniformResourceIndex) {
  1698. // Add the necessary capability required for indexing into this kind
  1699. // of resource
  1700. theBuilder.requireCapability(getNonUniformCapability(base->getType()));
  1701. info.setNonUniform(); // Carry forward the NonUniformEXT decoration
  1702. foundNonUniformResourceIndex = false;
  1703. }
  1704. if (!indices.empty()) {
  1705. (void)turnIntoElementPtr(base->getType(), info, expr->getType(), indices);
  1706. }
  1707. return info;
  1708. }
  1709. SpirvEvalInfo SPIRVEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1710. const auto opcode = expr->getOpcode();
  1711. // Handle assignment first since we need to evaluate rhs before lhs.
  1712. // For other binary operations, we need to evaluate lhs before rhs.
  1713. if (opcode == BO_Assign) {
  1714. // Update counter variable associated with lhs of assignments
  1715. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1716. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1717. /*isCompoundAssignment=*/false);
  1718. }
  1719. // Try to optimize floatMxN * float and floatN * float case
  1720. if (opcode == BO_Mul) {
  1721. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  1722. return result;
  1723. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  1724. return result;
  1725. }
  1726. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1727. expr->getLHS()->getType(), expr->getType(),
  1728. expr->getSourceRange());
  1729. }
  1730. SpirvEvalInfo SPIRVEmitter::doCallExpr(const CallExpr *callExpr) {
  1731. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1732. return doCXXOperatorCallExpr(operatorCall);
  1733. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1734. return doCXXMemberCallExpr(memberCall);
  1735. // Intrinsic functions such as 'dot' or 'mul'
  1736. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1737. return processIntrinsicCallExpr(callExpr);
  1738. }
  1739. // Normal standalone functions
  1740. return processCall(callExpr);
  1741. }
  1742. SpirvEvalInfo SPIRVEmitter::processCall(const CallExpr *callExpr) {
  1743. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1744. // Note that we always want the defintion because Stmts/Exprs in the
  1745. // function body references the parameters in the definition.
  1746. if (!callee) {
  1747. emitError("found undefined function", callExpr->getExprLoc());
  1748. return 0;
  1749. }
  1750. const auto numParams = callee->getNumParams();
  1751. bool isNonStaticMemberCall = false;
  1752. QualType objectType = {}; // Type of the object (if exists)
  1753. SpirvEvalInfo objectEvalInfo = 0; // EvalInfo for the object (if exists)
  1754. bool needsTempVar = false; // Whether we need temporary variable.
  1755. llvm::SmallVector<uint32_t, 4> vars; // Variables for function call
  1756. llvm::SmallVector<bool, 4> isTempVar; // Temporary variable or not
  1757. llvm::SmallVector<SpirvEvalInfo, 4> args; // Evaluated arguments
  1758. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  1759. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  1760. isNonStaticMemberCall = !memberFn->isStatic();
  1761. if (isNonStaticMemberCall) {
  1762. // For non-static member calls, evaluate the object and pass it as the
  1763. // first argument.
  1764. const auto *object = memberCall->getImplicitObjectArgument();
  1765. object = object->IgnoreParenNoopCasts(astContext);
  1766. // Update counter variable associated with the implicit object
  1767. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  1768. objectType = object->getType();
  1769. objectEvalInfo = doExpr(object);
  1770. uint32_t objectId = objectEvalInfo;
  1771. // If not already a variable, we need to create a temporary variable and
  1772. // pass the object pointer to the function. Example:
  1773. // getObject().objectMethod();
  1774. // Also, any parameter passed to the member function must be of Function
  1775. // storage class.
  1776. needsTempVar =
  1777. objectEvalInfo.isRValue() ||
  1778. objectEvalInfo.getStorageClass() != spv::StorageClass::Function;
  1779. if (needsTempVar) {
  1780. objectId =
  1781. createTemporaryVar(objectType, TypeTranslator::getName(objectType),
  1782. // May need to load to use as initializer
  1783. loadIfGLValue(object, objectEvalInfo));
  1784. }
  1785. args.push_back(objectId);
  1786. // We do not need to create a new temporary variable for the this
  1787. // object. Use the evaluated argument.
  1788. vars.push_back(args.back());
  1789. isTempVar.push_back(false);
  1790. }
  1791. }
  1792. // Evaluate parameters
  1793. for (uint32_t i = 0; i < numParams; ++i) {
  1794. // We want the argument variable here so that we can write back to it
  1795. // later. We will do the OpLoad of this argument manually. So ingore
  1796. // the LValueToRValue implicit cast here.
  1797. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  1798. const auto *param = callee->getParamDecl(i);
  1799. // Get the evaluation info if this argument is referencing some variable
  1800. // *as a whole*, in which case we can avoid creating the temporary variable
  1801. // for it if it is Function scope and can act as out parameter.
  1802. SpirvEvalInfo argInfo = 0;
  1803. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(arg)) {
  1804. argInfo = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl());
  1805. }
  1806. if (argInfo && argInfo.getStorageClass() == spv::StorageClass::Function &&
  1807. canActAsOutParmVar(param)) {
  1808. vars.push_back(argInfo);
  1809. isTempVar.push_back(false);
  1810. args.push_back(doExpr(arg));
  1811. } else {
  1812. // We need to create variables for holding the values to be used as
  1813. // arguments. The variables themselves are of pointer types.
  1814. const uint32_t varType =
  1815. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  1816. const std::string varName = "param.var." + param->getNameAsString();
  1817. const uint32_t tempVarId = theBuilder.addFnVar(varType, varName);
  1818. vars.push_back(tempVarId);
  1819. isTempVar.push_back(true);
  1820. args.push_back(doExpr(arg));
  1821. // Update counter variable associated with function parameters
  1822. tryToAssignCounterVar(param, arg);
  1823. // Manually load the argument here
  1824. const auto rhsVal = loadIfGLValue(arg, args.back());
  1825. // Initialize the temporary variables using the contents of the arguments
  1826. storeValue(tempVarId, rhsVal, param->getType());
  1827. }
  1828. }
  1829. assert(vars.size() == isTempVar.size());
  1830. assert(vars.size() == args.size());
  1831. // Push the callee into the work queue if it is not there.
  1832. if (!workQueue.count(callee)) {
  1833. workQueue.insert(callee);
  1834. }
  1835. const uint32_t retType =
  1836. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  1837. // Get or forward declare the function <result-id>
  1838. const uint32_t funcId = declIdMapper.getOrRegisterFnResultId(callee);
  1839. const uint32_t retVal = theBuilder.createFunctionCall(retType, funcId, vars);
  1840. // If we created a temporary variable for the lvalue object this method is
  1841. // invoked upon, we need to copy the contents in the temporary variable back
  1842. // to the original object's variable in case there are side effects.
  1843. if (needsTempVar && !objectEvalInfo.isRValue()) {
  1844. const uint32_t typeId = typeTranslator.translateType(objectType);
  1845. const uint32_t value = theBuilder.createLoad(typeId, vars.front());
  1846. storeValue(objectEvalInfo, value, objectType);
  1847. }
  1848. // Go through all parameters and write those marked as out/inout
  1849. for (uint32_t i = 0; i < numParams; ++i) {
  1850. const auto *param = callee->getParamDecl(i);
  1851. if (isTempVar[i] && canActAsOutParmVar(param)) {
  1852. const auto *arg = callExpr->getArg(i);
  1853. const uint32_t index = i + isNonStaticMemberCall;
  1854. const uint32_t typeId = typeTranslator.translateType(param->getType());
  1855. const uint32_t value = theBuilder.createLoad(typeId, vars[index]);
  1856. processAssignment(arg, value, false, args[index]);
  1857. }
  1858. }
  1859. // Inherit the SpirvEvalInfo from the function definition
  1860. return declIdMapper.getDeclEvalInfo(callee).setResultId(retVal);
  1861. }
  1862. SpirvEvalInfo SPIRVEmitter::doCastExpr(const CastExpr *expr) {
  1863. const Expr *subExpr = expr->getSubExpr();
  1864. const QualType subExprType = subExpr->getType();
  1865. const QualType toType = expr->getType();
  1866. // Unfortunately the front-end fails to deduce some types in certain cases.
  1867. // Provide a hint about literal type usage if possible.
  1868. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  1869. // 'literal int' to 'float' conversion. If a literal integer is to be used as
  1870. // a 32-bit float, the hint is a 32-bit integer.
  1871. if (toType->isFloatingType() &&
  1872. subExprType->isSpecificBuiltinType(BuiltinType::LitInt) &&
  1873. llvm::APFloat::getSizeInBits(astContext.getFloatTypeSemantics(toType)) ==
  1874. 32)
  1875. hint.setHint(astContext.IntTy);
  1876. // 'literal float' to 'float' conversion where intended type is float32.
  1877. if (toType->isFloatingType() &&
  1878. subExprType->isSpecificBuiltinType(BuiltinType::LitFloat) &&
  1879. llvm::APFloat::getSizeInBits(astContext.getFloatTypeSemantics(toType)) ==
  1880. 32)
  1881. hint.setHint(astContext.FloatTy);
  1882. // TODO: We could provide other useful hints. For instance:
  1883. // For the case of toType being a boolean, if the fromType is a literal float,
  1884. // we could provide a FloatTy hint and if the fromType is a literal integer,
  1885. // we could provide an IntTy hint. The front-end, however, seems to deduce the
  1886. // correct type in these cases; therefore we currently don't provide any
  1887. // additional hints.
  1888. switch (expr->getCastKind()) {
  1889. case CastKind::CK_LValueToRValue:
  1890. return loadIfGLValue(subExpr);
  1891. case CastKind::CK_NoOp:
  1892. return doExpr(subExpr);
  1893. case CastKind::CK_IntegralCast:
  1894. case CastKind::CK_FloatingToIntegral:
  1895. case CastKind::CK_HLSLCC_IntegralCast:
  1896. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  1897. // Integer literals in the AST are represented using 64bit APInt
  1898. // themselves and then implicitly casted into the expected bitwidth.
  1899. // We need special treatment of integer literals here because generating
  1900. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  1901. // capability. We should avoid introducing unnecessary capabilities to
  1902. // our best.
  1903. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1904. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1905. const auto valueId =
  1906. castToInt(doExpr(subExpr), subExprType, toType, subExpr->getExprLoc());
  1907. return SpirvEvalInfo(valueId).setRValue();
  1908. }
  1909. case CastKind::CK_FloatingCast:
  1910. case CastKind::CK_IntegralToFloating:
  1911. case CastKind::CK_HLSLCC_FloatingCast:
  1912. case CastKind::CK_HLSLCC_IntegralToFloating: {
  1913. // First try to see if we can do constant folding for floating point
  1914. // numbers like what we are doing for integers in the above.
  1915. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1916. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1917. const auto valueId = castToFloat(doExpr(subExpr), subExprType, toType,
  1918. subExpr->getExprLoc());
  1919. return SpirvEvalInfo(valueId).setRValue();
  1920. }
  1921. case CastKind::CK_IntegralToBoolean:
  1922. case CastKind::CK_FloatingToBoolean:
  1923. case CastKind::CK_HLSLCC_IntegralToBoolean:
  1924. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  1925. // First try to see if we can do constant folding.
  1926. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1927. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1928. const auto valueId = castToBool(doExpr(subExpr), subExprType, toType);
  1929. return SpirvEvalInfo(valueId).setRValue();
  1930. }
  1931. case CastKind::CK_HLSLVectorSplat: {
  1932. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  1933. return createVectorSplat(subExpr, size);
  1934. }
  1935. case CastKind::CK_HLSLVectorTruncationCast: {
  1936. const uint32_t toVecTypeId = typeTranslator.translateType(toType);
  1937. const uint32_t elemTypeId =
  1938. typeTranslator.translateType(hlsl::GetHLSLVecElementType(toType));
  1939. const auto toSize = hlsl::GetHLSLVecSize(toType);
  1940. const uint32_t composite = doExpr(subExpr);
  1941. llvm::SmallVector<uint32_t, 4> elements;
  1942. for (uint32_t i = 0; i < toSize; ++i) {
  1943. elements.push_back(
  1944. theBuilder.createCompositeExtract(elemTypeId, composite, {i}));
  1945. }
  1946. auto valueId = elements.front();
  1947. if (toSize > 1)
  1948. valueId = theBuilder.createCompositeConstruct(toVecTypeId, elements);
  1949. return SpirvEvalInfo(valueId).setRValue();
  1950. }
  1951. case CastKind::CK_HLSLVectorToScalarCast: {
  1952. // The underlying should already be a vector of size 1.
  1953. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  1954. return doExpr(subExpr);
  1955. }
  1956. case CastKind::CK_HLSLVectorToMatrixCast: {
  1957. // If target type is already an 1xN matrix type, we just return the
  1958. // underlying vector.
  1959. if (TypeTranslator::is1xNMatrix(toType))
  1960. return doExpr(subExpr);
  1961. // A vector can have no more than 4 elements. The only remaining case
  1962. // is casting from size-4 vector to size-2-by-2 matrix.
  1963. const auto vec = loadIfGLValue(subExpr);
  1964. QualType elemType = {};
  1965. uint32_t rowCount = 0, colCount = 0;
  1966. const bool isMat =
  1967. TypeTranslator::isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  1968. assert(isMat && rowCount == 2 && colCount == 2);
  1969. (void)isMat;
  1970. uint32_t vec2Type =
  1971. theBuilder.getVecType(typeTranslator.translateType(elemType), 2);
  1972. const auto subVec1 =
  1973. theBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1});
  1974. const auto subVec2 =
  1975. theBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3});
  1976. const auto mat = theBuilder.createCompositeConstruct(
  1977. theBuilder.getMatType(elemType, vec2Type, 2), {subVec1, subVec2});
  1978. return SpirvEvalInfo(mat).setRValue();
  1979. }
  1980. case CastKind::CK_HLSLMatrixSplat: {
  1981. // From scalar to matrix
  1982. uint32_t rowCount = 0, colCount = 0;
  1983. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  1984. // Handle degenerated cases first
  1985. if (rowCount == 1 && colCount == 1)
  1986. return doExpr(subExpr);
  1987. if (colCount == 1)
  1988. return createVectorSplat(subExpr, rowCount);
  1989. const auto vecSplat = createVectorSplat(subExpr, colCount);
  1990. if (rowCount == 1)
  1991. return vecSplat;
  1992. const uint32_t matType = typeTranslator.translateType(toType);
  1993. llvm::SmallVector<uint32_t, 4> vectors(size_t(rowCount), vecSplat);
  1994. if (vecSplat.isConstant()) {
  1995. const auto valueId = theBuilder.getConstantComposite(matType, vectors);
  1996. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1997. } else {
  1998. const auto valueId =
  1999. theBuilder.createCompositeConstruct(matType, vectors);
  2000. return SpirvEvalInfo(valueId).setRValue();
  2001. }
  2002. }
  2003. case CastKind::CK_HLSLMatrixTruncationCast: {
  2004. const QualType srcType = subExprType;
  2005. const uint32_t srcId = doExpr(subExpr);
  2006. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  2007. const uint32_t dstTypeId = typeTranslator.translateType(toType);
  2008. llvm::SmallVector<uint32_t, 4> indexes;
  2009. // It is possible that the source matrix is in fact a vector.
  2010. // For example: Truncate float1x3 --> float1x2.
  2011. // The front-end disallows float1x3 --> float2x1.
  2012. {
  2013. uint32_t srcVecSize = 0, dstVecSize = 0;
  2014. if (TypeTranslator::isVectorType(srcType, nullptr, &srcVecSize) &&
  2015. TypeTranslator::isVectorType(toType, nullptr, &dstVecSize)) {
  2016. for (uint32_t i = 0; i < dstVecSize; ++i)
  2017. indexes.push_back(i);
  2018. const auto valId =
  2019. theBuilder.createVectorShuffle(dstTypeId, srcId, srcId, indexes);
  2020. return SpirvEvalInfo(valId).setRValue();
  2021. }
  2022. }
  2023. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  2024. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  2025. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  2026. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  2027. const uint32_t srcRowType = theBuilder.getVecType(elemTypeId, srcCols);
  2028. // Indexes to pass to OpVectorShuffle
  2029. for (uint32_t i = 0; i < dstCols; ++i)
  2030. indexes.push_back(i);
  2031. llvm::SmallVector<uint32_t, 4> extractedVecs;
  2032. for (uint32_t row = 0; row < dstRows; ++row) {
  2033. // Extract a row
  2034. uint32_t rowId =
  2035. theBuilder.createCompositeExtract(srcRowType, srcId, {row});
  2036. // Extract the necessary columns from that row.
  2037. // The front-end ensures dstCols <= srcCols.
  2038. // If dstCols equals srcCols, we can use the whole row directly.
  2039. if (dstCols == 1) {
  2040. rowId = theBuilder.createCompositeExtract(elemTypeId, rowId, {0});
  2041. } else if (dstCols < srcCols) {
  2042. rowId = theBuilder.createVectorShuffle(
  2043. theBuilder.getVecType(elemTypeId, dstCols), rowId, rowId, indexes);
  2044. }
  2045. extractedVecs.push_back(rowId);
  2046. }
  2047. uint32_t valId = extractedVecs.front();
  2048. if (extractedVecs.size() > 1) {
  2049. valId = theBuilder.createCompositeConstruct(
  2050. typeTranslator.translateType(toType), extractedVecs);
  2051. }
  2052. return SpirvEvalInfo(valId).setRValue();
  2053. }
  2054. case CastKind::CK_HLSLMatrixToScalarCast: {
  2055. // The underlying should already be a matrix of 1x1.
  2056. assert(TypeTranslator::is1x1Matrix(subExprType));
  2057. return doExpr(subExpr);
  2058. }
  2059. case CastKind::CK_HLSLMatrixToVectorCast: {
  2060. // The underlying should already be a matrix of 1xN.
  2061. assert(TypeTranslator::is1xNMatrix(subExprType) ||
  2062. TypeTranslator::isMx1Matrix(subExprType));
  2063. return doExpr(subExpr);
  2064. }
  2065. case CastKind::CK_FunctionToPointerDecay:
  2066. // Just need to return the function id
  2067. return doExpr(subExpr);
  2068. case CastKind::CK_FlatConversion: {
  2069. uint32_t subExprId = 0;
  2070. QualType evalType = subExprType;
  2071. // Optimization: we can use OpConstantNull for cases where we want to
  2072. // initialize an entire data structure to zeros.
  2073. if (evaluatesToConstZero(subExpr, astContext)) {
  2074. subExprId =
  2075. theBuilder.getConstantNull(typeTranslator.translateType(toType));
  2076. return SpirvEvalInfo(subExprId).setRValue().setConstant();
  2077. }
  2078. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  2079. // Try to evaluate float literals as float rather than double.
  2080. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  2081. subExprId = tryToEvaluateAsFloat32(floatLiteral->getValue());
  2082. if (subExprId)
  2083. evalType = astContext.FloatTy;
  2084. }
  2085. // Evaluate 'literal float' initializer type as float rather than double.
  2086. // TODO: This could result in rounding error if the initializer is a
  2087. // non-literal expression that requires larger than 32 bits and has the
  2088. // 'literal float' type.
  2089. else if (subExprType->isSpecificBuiltinType(BuiltinType::LitFloat)) {
  2090. evalType = astContext.FloatTy;
  2091. hint.setHint(astContext.FloatTy);
  2092. }
  2093. // Try to evaluate integer literals as 32-bit int rather than 64-bit int.
  2094. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  2095. const bool isSigned = subExprType->isSignedIntegerType();
  2096. subExprId = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  2097. if (subExprId)
  2098. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  2099. }
  2100. // For assigning one array instance to another one with the same array type
  2101. // (regardless of constness and literalness), the rhs will be wrapped in a
  2102. // FlatConversion:
  2103. // |- <lhs>
  2104. // `- ImplicitCastExpr <FlatConversion>
  2105. // `- ImplicitCastExpr <LValueToRValue>
  2106. // `- <rhs>
  2107. // This FlatConversion does not affect CodeGen, so that we can ignore it.
  2108. else if (subExprType->isArrayType() &&
  2109. typeTranslator.isSameType(expr->getType(), subExprType)) {
  2110. return doExpr(subExpr);
  2111. }
  2112. if (!subExprId)
  2113. subExprId = doExpr(subExpr);
  2114. const auto valId =
  2115. processFlatConversion(toType, evalType, subExprId, expr->getExprLoc());
  2116. return SpirvEvalInfo(valId).setRValue();
  2117. }
  2118. case CastKind::CK_UncheckedDerivedToBase:
  2119. case CastKind::CK_HLSLDerivedToBase: {
  2120. // Find the index sequence of the base to which we are casting
  2121. llvm::SmallVector<uint32_t, 4> baseIndices;
  2122. getBaseClassIndices(expr, &baseIndices);
  2123. // Turn them in to SPIR-V constants
  2124. for (uint32_t i = 0; i < baseIndices.size(); ++i)
  2125. baseIndices[i] = theBuilder.getConstantUint32(baseIndices[i]);
  2126. auto derivedInfo = doExpr(subExpr);
  2127. return turnIntoElementPtr(subExpr->getType(), derivedInfo, expr->getType(),
  2128. baseIndices);
  2129. }
  2130. default:
  2131. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  2132. << expr->getCastKindName() << expr->getSourceRange();
  2133. expr->dump();
  2134. return 0;
  2135. }
  2136. }
  2137. uint32_t SPIRVEmitter::processFlatConversion(const QualType type,
  2138. const QualType initType,
  2139. const uint32_t initId,
  2140. SourceLocation srcLoc) {
  2141. // Try to translate the canonical type first
  2142. const auto canonicalType = type.getCanonicalType();
  2143. if (canonicalType != type)
  2144. return processFlatConversion(canonicalType, initType, initId, srcLoc);
  2145. // Primitive types
  2146. {
  2147. QualType ty = {};
  2148. if (TypeTranslator::isScalarType(type, &ty)) {
  2149. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  2150. switch (builtinType->getKind()) {
  2151. case BuiltinType::Void: {
  2152. emitError("cannot create a constant of void type", srcLoc);
  2153. return 0;
  2154. }
  2155. case BuiltinType::Bool:
  2156. return castToBool(initId, initType, ty);
  2157. // Target type is an integer variant.
  2158. case BuiltinType::Int:
  2159. case BuiltinType::Short:
  2160. case BuiltinType::Min12Int:
  2161. case BuiltinType::UShort:
  2162. case BuiltinType::UInt:
  2163. case BuiltinType::Long:
  2164. case BuiltinType::LongLong:
  2165. case BuiltinType::ULong:
  2166. case BuiltinType::ULongLong:
  2167. return castToInt(initId, initType, ty, srcLoc);
  2168. // Target type is a float variant.
  2169. case BuiltinType::Double:
  2170. case BuiltinType::Float:
  2171. case BuiltinType::Half:
  2172. case BuiltinType::Min10Float:
  2173. return castToFloat(initId, initType, ty, srcLoc);
  2174. default:
  2175. emitError("flat conversion of type %0 unimplemented", srcLoc)
  2176. << builtinType->getTypeClassName();
  2177. return 0;
  2178. }
  2179. }
  2180. }
  2181. }
  2182. // Vector types
  2183. {
  2184. QualType elemType = {};
  2185. uint32_t elemCount = {};
  2186. if (TypeTranslator::isVectorType(type, &elemType, &elemCount)) {
  2187. const uint32_t elemId =
  2188. processFlatConversion(elemType, initType, initId, srcLoc);
  2189. llvm::SmallVector<uint32_t, 4> constituents(size_t(elemCount), elemId);
  2190. return theBuilder.createCompositeConstruct(
  2191. typeTranslator.translateType(type), constituents);
  2192. }
  2193. }
  2194. // Matrix types
  2195. {
  2196. QualType elemType = {};
  2197. uint32_t rowCount = 0, colCount = 0;
  2198. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  2199. // By default HLSL matrices are row major, while SPIR-V matrices are
  2200. // column major. We are mapping what HLSL semantically mean a row into a
  2201. // column here.
  2202. const uint32_t vecType = theBuilder.getVecType(
  2203. typeTranslator.translateType(elemType), colCount);
  2204. const uint32_t elemId =
  2205. processFlatConversion(elemType, initType, initId, srcLoc);
  2206. const llvm::SmallVector<uint32_t, 4> constituents(size_t(colCount),
  2207. elemId);
  2208. const uint32_t colId =
  2209. theBuilder.createCompositeConstruct(vecType, constituents);
  2210. const llvm::SmallVector<uint32_t, 4> rows(size_t(rowCount), colId);
  2211. return theBuilder.createCompositeConstruct(
  2212. typeTranslator.translateType(type), rows);
  2213. }
  2214. }
  2215. // Struct type
  2216. if (const auto *structType = type->getAs<RecordType>()) {
  2217. const auto *decl = structType->getDecl();
  2218. llvm::SmallVector<uint32_t, 4> fields;
  2219. for (const auto *field : decl->fields()) {
  2220. // There is a special case for FlatConversion. If T is a struct with only
  2221. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  2222. // constructs a new T instance using the instance of S as its only member.
  2223. // Check whether we are handling that case here first.
  2224. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  2225. fields.push_back(initId);
  2226. } else {
  2227. fields.push_back(
  2228. processFlatConversion(field->getType(), initType, initId, srcLoc));
  2229. }
  2230. }
  2231. return theBuilder.createCompositeConstruct(
  2232. typeTranslator.translateType(type), fields);
  2233. }
  2234. // Array type
  2235. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  2236. const auto size =
  2237. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  2238. const uint32_t elemId = processFlatConversion(arrayType->getElementType(),
  2239. initType, initId, srcLoc);
  2240. llvm::SmallVector<uint32_t, 4> constituents(size_t(size), elemId);
  2241. return theBuilder.createCompositeConstruct(
  2242. typeTranslator.translateType(type), constituents);
  2243. }
  2244. emitError("flat conversion of type %0 unimplemented", {})
  2245. << type->getTypeClassName();
  2246. type->dump();
  2247. return 0;
  2248. }
  2249. SpirvEvalInfo
  2250. SPIRVEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  2251. const auto opcode = expr->getOpcode();
  2252. // Try to optimize floatMxN *= float and floatN *= float case
  2253. if (opcode == BO_MulAssign) {
  2254. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  2255. return result;
  2256. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  2257. return result;
  2258. }
  2259. const auto *rhs = expr->getRHS();
  2260. const auto *lhs = expr->getLHS();
  2261. SpirvEvalInfo lhsPtr = 0;
  2262. const auto result =
  2263. processBinaryOp(lhs, rhs, opcode, expr->getComputationLHSType(),
  2264. expr->getType(), expr->getSourceRange(), &lhsPtr);
  2265. return processAssignment(lhs, result, true, lhsPtr);
  2266. }
  2267. SpirvEvalInfo
  2268. SPIRVEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  2269. const auto type = expr->getType();
  2270. // Enhancement for special case when the ConditionalOperator return type is a
  2271. // literal type. For example:
  2272. //
  2273. // float a = cond ? 1 : 2;
  2274. // int b = cond ? 1.5 : 2.5;
  2275. //
  2276. // There will be no indications about whether '1' and '2' should be used as
  2277. // 32-bit or 64-bit integers. Similarly, there will be no indication about
  2278. // whether '1.5' and '2.5' should be used as 32-bit or 64-bit floats.
  2279. //
  2280. // We want to avoid using 64-bit int and 64-bit float as much as possible.
  2281. //
  2282. // Note that if the literal is in fact large enough that it can't be
  2283. // represented in 32 bits (e.g. integer larger than 3e+9), we should *not*
  2284. // provide a hint.
  2285. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  2286. const bool isLitInt = type->isSpecificBuiltinType(BuiltinType::LitInt);
  2287. const bool isLitFloat = type->isSpecificBuiltinType(BuiltinType::LitFloat);
  2288. // Return type of ConditionalOperator is a 'literal int' or 'literal float'
  2289. if (isLitInt || isLitFloat) {
  2290. // There is no hint about the intended usage of the literal type.
  2291. if (typeTranslator.getIntendedLiteralType(type) == type) {
  2292. // If either branch is a literal that is larger than 32-bits, do not
  2293. // provide a hint.
  2294. if (!isLiteralLargerThan32Bits(expr->getTrueExpr()) &&
  2295. !isLiteralLargerThan32Bits(expr->getFalseExpr())) {
  2296. if (isLitInt)
  2297. hint.setHint(astContext.IntTy);
  2298. else if (isLitFloat)
  2299. hint.setHint(astContext.FloatTy);
  2300. }
  2301. }
  2302. }
  2303. // According to HLSL doc, all sides of the ?: expression are always
  2304. // evaluated.
  2305. const uint32_t typeId = typeTranslator.translateType(type);
  2306. // If we are selecting between two SampleState objects, none of the three
  2307. // operands has a LValueToRValue implicit cast.
  2308. uint32_t condition = loadIfGLValue(expr->getCond());
  2309. const auto trueBranch = loadIfGLValue(expr->getTrueExpr());
  2310. const auto falseBranch = loadIfGLValue(expr->getFalseExpr());
  2311. // For cases where the return type is a scalar or a vector, we can use
  2312. // OpSelect to choose between the two. OpSelect's return type must be either
  2313. // scalar or vector.
  2314. if (TypeTranslator::isScalarType(type) ||
  2315. TypeTranslator::isVectorType(type)) {
  2316. // The SPIR-V OpSelect instruction must have a selection argument that is
  2317. // the same size as the return type. If the return type is a vector, the
  2318. // selection must be a vector of booleans (one per output component).
  2319. uint32_t count = 0;
  2320. if (TypeTranslator::isVectorType(expr->getType(), nullptr, &count) &&
  2321. !TypeTranslator::isVectorType(expr->getCond()->getType())) {
  2322. const uint32_t condVecType =
  2323. theBuilder.getVecType(theBuilder.getBoolType(), count);
  2324. const llvm::SmallVector<uint32_t, 4> components(size_t(count), condition);
  2325. condition = theBuilder.createCompositeConstruct(condVecType, components);
  2326. }
  2327. auto valueId =
  2328. theBuilder.createSelect(typeId, condition, trueBranch, falseBranch);
  2329. return SpirvEvalInfo(valueId).setRValue();
  2330. }
  2331. // If we can't use OpSelect, we need to create if-else control flow.
  2332. const uint32_t tempVar = theBuilder.addFnVar(typeId, "temp.var.ternary");
  2333. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  2334. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  2335. const uint32_t elseBB = theBuilder.createBasicBlock("if.false");
  2336. // Create the branch instruction. This will end the current basic block.
  2337. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB);
  2338. theBuilder.addSuccessor(thenBB);
  2339. theBuilder.addSuccessor(elseBB);
  2340. theBuilder.setMergeTarget(mergeBB);
  2341. // Handle the then branch
  2342. theBuilder.setInsertPoint(thenBB);
  2343. theBuilder.createStore(tempVar, trueBranch);
  2344. theBuilder.createBranch(mergeBB);
  2345. theBuilder.addSuccessor(mergeBB);
  2346. // Handle the else branch
  2347. theBuilder.setInsertPoint(elseBB);
  2348. theBuilder.createStore(tempVar, falseBranch);
  2349. theBuilder.createBranch(mergeBB);
  2350. theBuilder.addSuccessor(mergeBB);
  2351. // From now on, emit instructions into the merge block.
  2352. theBuilder.setInsertPoint(mergeBB);
  2353. return SpirvEvalInfo(theBuilder.createLoad(typeId, tempVar)).setRValue();
  2354. }
  2355. uint32_t SPIRVEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2356. const CXXMemberCallExpr *expr) {
  2357. const auto *object = expr->getImplicitObjectArgument();
  2358. const auto objectId = loadIfAliasVarRef(object);
  2359. const auto type = object->getType();
  2360. const bool isByteAddressBuffer = TypeTranslator::isByteAddressBuffer(type) ||
  2361. TypeTranslator::isRWByteAddressBuffer(type);
  2362. const bool isStructuredBuffer =
  2363. TypeTranslator::isStructuredBuffer(type) ||
  2364. TypeTranslator::isAppendStructuredBuffer(type) ||
  2365. TypeTranslator::isConsumeStructuredBuffer(type);
  2366. assert(isByteAddressBuffer || isStructuredBuffer);
  2367. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2368. // with only one member that is a runtime array. We need to perform
  2369. // OpArrayLength on member 0.
  2370. const auto uintType = theBuilder.getUint32Type();
  2371. uint32_t length =
  2372. theBuilder.createBinaryOp(spv::Op::OpArrayLength, uintType, objectId, 0);
  2373. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2374. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2375. // array. Therefore we must multiply the results by 4.
  2376. if (isByteAddressBuffer) {
  2377. length = theBuilder.createBinaryOp(spv::Op::OpIMul, uintType, length,
  2378. theBuilder.getConstantUint32(4u));
  2379. }
  2380. theBuilder.createStore(doExpr(expr->getArg(0)), length);
  2381. if (isStructuredBuffer) {
  2382. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2383. // size of the struct) must also be written to the second argument.
  2384. uint32_t size = 0, stride = 0;
  2385. std::tie(std::ignore, size) = typeTranslator.getAlignmentAndSize(
  2386. type, spirvOptions.sBufferLayoutRule, &stride);
  2387. const auto sizeId = theBuilder.getConstantUint32(size);
  2388. theBuilder.createStore(doExpr(expr->getArg(1)), sizeId);
  2389. }
  2390. return 0;
  2391. }
  2392. uint32_t SPIRVEmitter::processRWByteAddressBufferAtomicMethods(
  2393. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2394. // The signature of RWByteAddressBuffer atomic methods are largely:
  2395. // void Interlocked*(in UINT dest, in UINT value);
  2396. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2397. const auto *object = expr->getImplicitObjectArgument();
  2398. const auto objectInfo = loadIfAliasVarRef(object);
  2399. const auto uintType = theBuilder.getUint32Type();
  2400. const uint32_t zero = theBuilder.getConstantUint32(0);
  2401. const uint32_t offset = doExpr(expr->getArg(0));
  2402. // Right shift by 2 to convert the byte offset to uint32_t offset
  2403. const uint32_t address =
  2404. theBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, uintType, offset,
  2405. theBuilder.getConstantUint32(2));
  2406. const auto ptrType =
  2407. theBuilder.getPointerType(uintType, objectInfo.getStorageClass());
  2408. const uint32_t ptr =
  2409. theBuilder.createAccessChain(ptrType, objectInfo, {zero, address});
  2410. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  2411. const bool isCompareExchange =
  2412. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2413. const bool isCompareStore =
  2414. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2415. if (isCompareExchange || isCompareStore) {
  2416. const uint32_t comparator = doExpr(expr->getArg(1));
  2417. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  2418. uintType, ptr, scope, zero, zero, doExpr(expr->getArg(2)), comparator);
  2419. if (isCompareExchange)
  2420. theBuilder.createStore(doExpr(expr->getArg(3)), originalVal);
  2421. } else {
  2422. const uint32_t value = doExpr(expr->getArg(1));
  2423. const uint32_t originalVal = theBuilder.createAtomicOp(
  2424. translateAtomicHlslOpcodeToSpirvOpcode(opcode), uintType, ptr, scope,
  2425. zero, value);
  2426. if (expr->getNumArgs() > 2)
  2427. theBuilder.createStore(doExpr(expr->getArg(2)), originalVal);
  2428. }
  2429. return 0;
  2430. }
  2431. uint32_t SPIRVEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2432. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2433. const auto sampleCount = theBuilder.createUnaryOp(
  2434. spv::Op::OpImageQuerySamples, theBuilder.getUint32Type(),
  2435. loadIfGLValue(object));
  2436. emitWarning(
  2437. "GetSamplePosition only supports standard sample settings with 1, 2, 4, "
  2438. "8, or 16 samples and will return float2(0, 0) for other cases",
  2439. expr->getCallee()->getExprLoc());
  2440. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)));
  2441. }
  2442. SpirvEvalInfo SPIRVEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2443. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2444. const uint32_t sample = expr->getNumArgs() == 1
  2445. ? static_cast<uint32_t>(doExpr(expr->getArg(0)))
  2446. : 0;
  2447. const uint32_t zero = theBuilder.getConstantInt32(0);
  2448. const uint32_t location = theBuilder.getConstantComposite(
  2449. theBuilder.getVecType(theBuilder.getInt32Type(), 2), {zero, zero});
  2450. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2451. /*varOffset*/ 0, /*lod*/ sample,
  2452. /*residencyCode*/ 0);
  2453. }
  2454. uint32_t
  2455. SPIRVEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2456. const auto *object = expr->getImplicitObjectArgument();
  2457. const auto objectId = loadIfGLValue(object);
  2458. const auto type = object->getType();
  2459. const auto *recType = type->getAs<RecordType>();
  2460. assert(recType);
  2461. const auto typeName = recType->getDecl()->getName();
  2462. const auto numArgs = expr->getNumArgs();
  2463. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2464. assert(TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2465. TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type));
  2466. // For Texture1D, arguments are either:
  2467. // a) width
  2468. // b) MipLevel, width, NumLevels
  2469. // For Texture1DArray, arguments are either:
  2470. // a) width, elements
  2471. // b) MipLevel, width, elements, NumLevels
  2472. // For Texture2D, arguments are either:
  2473. // a) width, height
  2474. // b) MipLevel, width, height, NumLevels
  2475. // For Texture2DArray, arguments are either:
  2476. // a) width, height, elements
  2477. // b) MipLevel, width, height, elements, NumLevels
  2478. // For Texture3D, arguments are either:
  2479. // a) width, height, depth
  2480. // b) MipLevel, width, height, depth, NumLevels
  2481. // For Texture2DMS, arguments are: width, height, NumSamples
  2482. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2483. // For TextureCube, arguments are either:
  2484. // a) width, height
  2485. // b) MipLevel, width, height, NumLevels
  2486. // For TextureCubeArray, arguments are either:
  2487. // a) width, height, elements
  2488. // b) MipLevel, width, height, elements, NumLevels
  2489. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2490. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2491. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2492. // The HLSL methods, however, have overloaded functions which have float
  2493. // output arguments. Since the AST naturally won't have casting AST nodes for
  2494. // such cases, we'll have to perform the cast ourselves.
  2495. const auto storeToOutputArg = [this](const Expr *outputArg, uint32_t id,
  2496. QualType type) {
  2497. id = castToType(id, type, outputArg->getType(), outputArg->getExprLoc());
  2498. theBuilder.createStore(doExpr(outputArg), id);
  2499. };
  2500. if ((typeName == "Texture1D" && numArgs > 1) ||
  2501. (typeName == "Texture2D" && numArgs > 2) ||
  2502. (typeName == "TextureCube" && numArgs > 2) ||
  2503. (typeName == "Texture3D" && numArgs > 3) ||
  2504. (typeName == "Texture1DArray" && numArgs > 2) ||
  2505. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2506. (typeName == "Texture2DArray" && numArgs > 3)) {
  2507. mipLevel = expr->getArg(0);
  2508. numLevels = expr->getArg(numArgs - 1);
  2509. }
  2510. if (TypeTranslator::isTextureMS(type)) {
  2511. numSamples = expr->getArg(numArgs - 1);
  2512. }
  2513. uint32_t querySize = numArgs;
  2514. // If numLevels arg is present, mipLevel must also be present. These are not
  2515. // queried via ImageQuerySizeLod.
  2516. if (numLevels)
  2517. querySize -= 2;
  2518. // If numLevels arg is present, mipLevel must also be present.
  2519. else if (numSamples)
  2520. querySize -= 1;
  2521. const uint32_t uintId = theBuilder.getUint32Type();
  2522. const QualType resultQualType =
  2523. querySize == 1
  2524. ? astContext.UnsignedIntTy
  2525. : astContext.getExtVectorType(astContext.UnsignedIntTy, querySize);
  2526. const uint32_t resultTypeId = typeTranslator.translateType(resultQualType);
  2527. // Only Texture types use ImageQuerySizeLod.
  2528. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2529. uint32_t lod = 0;
  2530. if (TypeTranslator::isTexture(type) && !numSamples) {
  2531. if (mipLevel) {
  2532. // For Texture types when mipLevel argument is present.
  2533. lod = doExpr(mipLevel);
  2534. } else {
  2535. // For Texture types when mipLevel argument is omitted.
  2536. lod = theBuilder.getConstantInt32(0);
  2537. }
  2538. }
  2539. const uint32_t query =
  2540. lod ? theBuilder.createBinaryOp(spv::Op::OpImageQuerySizeLod,
  2541. resultTypeId, objectId, lod)
  2542. : theBuilder.createUnaryOp(spv::Op::OpImageQuerySize, resultTypeId,
  2543. objectId);
  2544. if (querySize == 1) {
  2545. const uint32_t argIndex = mipLevel ? 1 : 0;
  2546. storeToOutputArg(expr->getArg(argIndex), query, resultQualType);
  2547. } else {
  2548. for (uint32_t i = 0; i < querySize; ++i) {
  2549. const uint32_t component =
  2550. theBuilder.createCompositeExtract(uintId, query, {i});
  2551. // If the first arg is the mipmap level, we must write the results
  2552. // starting from Arg(i+1), not Arg(i).
  2553. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2554. storeToOutputArg(expr->getArg(argIndex), component,
  2555. astContext.UnsignedIntTy);
  2556. }
  2557. }
  2558. if (numLevels || numSamples) {
  2559. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2560. const spv::Op opcode =
  2561. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2562. const uint32_t numLevelsSamplesQuery =
  2563. theBuilder.createUnaryOp(opcode, uintId, objectId);
  2564. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery,
  2565. astContext.UnsignedIntTy);
  2566. }
  2567. return 0;
  2568. }
  2569. uint32_t
  2570. SPIRVEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr,
  2571. bool unclamped) {
  2572. // Possible signatures are as follows:
  2573. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2574. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2575. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2576. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2577. // Return type is always a single float (LOD).
  2578. assert(expr->getNumArgs() == 2u);
  2579. const auto *object = expr->getImplicitObjectArgument();
  2580. const auto objectInfo = loadIfGLValue(object);
  2581. const auto samplerState = doExpr(expr->getArg(0));
  2582. const uint32_t coordinate = doExpr(expr->getArg(1));
  2583. const uint32_t sampledImageType = theBuilder.getSampledImageType(
  2584. typeTranslator.translateType(object->getType()));
  2585. const uint32_t sampledImage = theBuilder.createBinaryOp(
  2586. spv::Op::OpSampledImage, sampledImageType, objectInfo, samplerState);
  2587. if (objectInfo.isNonUniform() || samplerState.isNonUniform()) {
  2588. // The sampled image will be used to access resource's memory, so we need
  2589. // to decorate it with NonUniformEXT.
  2590. theBuilder.decorateNonUniformEXT(sampledImage);
  2591. }
  2592. // The result type of OpImageQueryLod must be a float2.
  2593. const uint32_t queryResultType =
  2594. theBuilder.getVecType(theBuilder.getFloat32Type(), 2u);
  2595. const uint32_t query = theBuilder.createBinaryOp(
  2596. spv::Op::OpImageQueryLod, queryResultType, sampledImage, coordinate);
  2597. // The first component of the float2 contains the mipmap array layer.
  2598. // The second component of the float2 represents the unclamped lod.
  2599. return theBuilder.createCompositeExtract(theBuilder.getFloat32Type(), query,
  2600. unclamped ? 1 : 0);
  2601. }
  2602. uint32_t SPIRVEmitter::processTextureGatherRGBACmpRGBA(
  2603. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  2604. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  2605. // two sets:
  2606. // * SamplerState s, float2 location, int2 offset
  2607. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  2608. // int offset2, int2 offset3
  2609. //
  2610. // An additional 'out uint status' parameter can appear in both of the above.
  2611. //
  2612. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  2613. // two sets:
  2614. // * SamplerState s, float2 location, float compare_value, int2 offset
  2615. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  2616. // int2 offset2, int2 offset3, int2 offset4
  2617. //
  2618. // An additional 'out uint status' parameter can appear in both of the above.
  2619. //
  2620. // TextureCube's signature is somewhat different from the rest.
  2621. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  2622. // * SamplerState s, float2 location, out uint status
  2623. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  2624. // * SamplerState s, float2 location, float compare_value, out uint status
  2625. //
  2626. // Return type is always a 4-component vector.
  2627. const FunctionDecl *callee = expr->getDirectCallee();
  2628. const auto numArgs = expr->getNumArgs();
  2629. const auto *imageExpr = expr->getImplicitObjectArgument();
  2630. const QualType imageType = imageExpr->getType();
  2631. const auto imageTypeId = typeTranslator.translateType(imageType);
  2632. const auto retTypeId = typeTranslator.translateType(callee->getReturnType());
  2633. // If the last arg is an unsigned integer, it must be the status.
  2634. const bool hasStatusArg =
  2635. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2636. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  2637. // it exists), and subtract 2 for SamplerState and location.
  2638. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  2639. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  2640. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  2641. const auto image = loadIfGLValue(imageExpr);
  2642. const auto sampler = doExpr(expr->getArg(0));
  2643. const uint32_t coordinate = doExpr(expr->getArg(1));
  2644. const uint32_t compareVal =
  2645. isCmp ? static_cast<uint32_t>(doExpr(expr->getArg(2))) : 0;
  2646. // Handle offsets (if any).
  2647. bool needsEmulation = false;
  2648. uint32_t constOffset = 0, varOffset = 0, constOffsets = 0;
  2649. if (numOffsetArgs == 1) {
  2650. // The offset arg is not optional.
  2651. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  2652. } else if (numOffsetArgs == 4) {
  2653. const auto offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  2654. const auto offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  2655. const auto offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  2656. const auto offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  2657. // If any of the offsets is not constant, we then need to emulate the call
  2658. // using 4 OpImageGather instructions. Otherwise, we can leverage the
  2659. // ConstOffsets image operand.
  2660. if (offset0 && offset1 && offset2 && offset3) {
  2661. const uint32_t v2i32 =
  2662. theBuilder.getVecType(theBuilder.getInt32Type(), 2);
  2663. const uint32_t offsetType =
  2664. theBuilder.getArrayType(v2i32, theBuilder.getConstantUint32(4));
  2665. constOffsets = theBuilder.getConstantComposite(
  2666. offsetType, {offset0, offset1, offset2, offset3});
  2667. } else {
  2668. needsEmulation = true;
  2669. }
  2670. }
  2671. const auto status =
  2672. hasStatusArg ? static_cast<uint32_t>(doExpr(expr->getArg(numArgs - 1)))
  2673. : 0;
  2674. const bool isNonUniform = image.isNonUniform() || sampler.isNonUniform();
  2675. if (needsEmulation) {
  2676. const auto elemType = typeTranslator.translateType(
  2677. hlsl::GetHLSLVecElementType(callee->getReturnType()));
  2678. uint32_t texels[4];
  2679. for (uint32_t i = 0; i < 4; ++i) {
  2680. varOffset = doExpr(expr->getArg(2 + isCmp + i));
  2681. const uint32_t gatherRet = theBuilder.createImageGather(
  2682. retTypeId, imageTypeId, image, sampler, isNonUniform, coordinate,
  2683. theBuilder.getConstantInt32(component), compareVal, /*constOffset*/ 0,
  2684. varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0, status);
  2685. texels[i] = theBuilder.createCompositeExtract(elemType, gatherRet, {i});
  2686. }
  2687. return theBuilder.createCompositeConstruct(
  2688. retTypeId, {texels[0], texels[1], texels[2], texels[3]});
  2689. }
  2690. return theBuilder.createImageGather(
  2691. retTypeId, imageTypeId, image, sampler, isNonUniform, coordinate,
  2692. theBuilder.getConstantInt32(component), compareVal, constOffset,
  2693. varOffset, constOffsets, /*sampleNumber*/ 0, status);
  2694. }
  2695. uint32_t SPIRVEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  2696. // Signature for Texture2D/Texture2DArray:
  2697. //
  2698. // float4 GatherCmp(
  2699. // in SamplerComparisonState s,
  2700. // in float2 location,
  2701. // in float compare_value
  2702. // [,in int2 offset]
  2703. // [,out uint Status]
  2704. // );
  2705. //
  2706. // Signature for TextureCube/TextureCubeArray:
  2707. //
  2708. // float4 GatherCmp(
  2709. // in SamplerComparisonState s,
  2710. // in float2 location,
  2711. // in float compare_value,
  2712. // out uint Status
  2713. // );
  2714. //
  2715. // Other Texture types do not have the GatherCmp method.
  2716. const FunctionDecl *callee = expr->getDirectCallee();
  2717. const auto numArgs = expr->getNumArgs();
  2718. const bool hasStatusArg =
  2719. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2720. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  2721. const auto *imageExpr = expr->getImplicitObjectArgument();
  2722. const auto image = loadIfGLValue(imageExpr);
  2723. const auto sampler = doExpr(expr->getArg(0));
  2724. const uint32_t coordinate = doExpr(expr->getArg(1));
  2725. const uint32_t comparator = doExpr(expr->getArg(2));
  2726. uint32_t constOffset = 0, varOffset = 0;
  2727. if (hasOffsetArg)
  2728. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  2729. const auto retType = typeTranslator.translateType(callee->getReturnType());
  2730. const auto imageType = typeTranslator.translateType(imageExpr->getType());
  2731. const auto status =
  2732. hasStatusArg ? static_cast<uint32_t>(doExpr(expr->getArg(numArgs - 1)))
  2733. : 0;
  2734. return theBuilder.createImageGather(
  2735. retType, imageType, image, sampler,
  2736. image.isNonUniform() || sampler.isNonUniform(), coordinate,
  2737. /*component*/ 0, comparator, constOffset, varOffset, /*constOffsets*/ 0,
  2738. /*sampleNumber*/ 0, status);
  2739. }
  2740. SpirvEvalInfo SPIRVEmitter::processBufferTextureLoad(
  2741. const Expr *object, const uint32_t locationId, uint32_t constOffset,
  2742. uint32_t varOffset, uint32_t lod, uint32_t residencyCode) {
  2743. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  2744. // The result type of an OpImageFetch must be a vec4 of float or int.
  2745. const auto type = object->getType();
  2746. assert(TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type) ||
  2747. TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2748. TypeTranslator::isSubpassInput(type) ||
  2749. TypeTranslator::isSubpassInputMS(type));
  2750. const bool doFetch =
  2751. TypeTranslator::isBuffer(type) || TypeTranslator::isTexture(type);
  2752. const auto objectInfo = loadIfGLValue(object);
  2753. if (objectInfo.isNonUniform()) {
  2754. // Decoreate the image handle for OpImageFetch/OpImageRead
  2755. theBuilder.decorateNonUniformEXT(objectInfo);
  2756. }
  2757. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  2758. uint32_t sampleNumber = 0;
  2759. if (TypeTranslator::isTextureMS(type) ||
  2760. TypeTranslator::isSubpassInputMS(type)) {
  2761. sampleNumber = lod;
  2762. lod = 0;
  2763. }
  2764. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  2765. QualType elemType = sampledType;
  2766. uint32_t elemCount = 1;
  2767. uint32_t elemTypeId = 0;
  2768. bool isTemplateOverStruct = false;
  2769. // Check whether the template type is a vector type or struct type.
  2770. if (!TypeTranslator::isVectorType(sampledType, &elemType, &elemCount)) {
  2771. if (sampledType->getAsStructureType()) {
  2772. isTemplateOverStruct = true;
  2773. // For struct type, we need to make sure it can fit into a 4-component
  2774. // vector. Detailed failing reasons will be emitted by the function so
  2775. // we don't need to emit errors here.
  2776. if (!typeTranslator.canFitIntoOneRegister(sampledType, &elemType,
  2777. &elemCount))
  2778. return 0;
  2779. }
  2780. }
  2781. if (elemType->isFloatingType()) {
  2782. elemTypeId = theBuilder.getFloat32Type();
  2783. } else if (elemType->isSignedIntegerType()) {
  2784. elemTypeId = theBuilder.getInt32Type();
  2785. } else if (elemType->isUnsignedIntegerType()) {
  2786. elemTypeId = theBuilder.getUint32Type();
  2787. } else {
  2788. emitError("loading %0 value unsupported", object->getExprLoc()) << type;
  2789. return 0;
  2790. }
  2791. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  2792. const uint32_t texelTypeId = theBuilder.getVecType(elemTypeId, 4u);
  2793. const uint32_t texel = theBuilder.createImageFetchOrRead(
  2794. doFetch, texelTypeId, type, objectInfo, locationId, lod, constOffset,
  2795. varOffset, /*constOffsets*/ 0, sampleNumber, residencyCode);
  2796. // If the result type is a vec1, vec2, or vec3, some extra processing
  2797. // (extraction) is required.
  2798. uint32_t retVal = extractVecFromVec4(texel, elemCount, elemTypeId);
  2799. if (isTemplateOverStruct) {
  2800. // Convert to the struct so that we are consistent with types in the AST.
  2801. retVal = convertVectorToStruct(sampledType, elemTypeId, retVal);
  2802. }
  2803. return SpirvEvalInfo(retVal).setRValue();
  2804. }
  2805. SpirvEvalInfo SPIRVEmitter::processByteAddressBufferLoadStore(
  2806. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  2807. uint32_t resultId = 0;
  2808. const auto object = expr->getImplicitObjectArgument();
  2809. const auto objectInfo = loadIfAliasVarRef(object);
  2810. assert(numWords >= 1 && numWords <= 4);
  2811. if (doStore) {
  2812. assert(typeTranslator.isRWByteAddressBuffer(object->getType()));
  2813. assert(expr->getNumArgs() == 2);
  2814. } else {
  2815. assert(typeTranslator.isRWByteAddressBuffer(object->getType()) ||
  2816. typeTranslator.isByteAddressBuffer(object->getType()));
  2817. if (expr->getNumArgs() == 2) {
  2818. emitError(
  2819. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  2820. expr->getExprLoc());
  2821. return 0;
  2822. }
  2823. }
  2824. const Expr *addressExpr = expr->getArg(0);
  2825. const uint32_t byteAddress = doExpr(addressExpr);
  2826. const uint32_t addressTypeId =
  2827. typeTranslator.translateType(addressExpr->getType());
  2828. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  2829. // access). The AST always casts the address to unsinged integer, so shift
  2830. // by unsinged integer 2.
  2831. const uint32_t constUint2 = theBuilder.getConstantUint32(2);
  2832. const uint32_t address = theBuilder.createBinaryOp(
  2833. spv::Op::OpShiftRightLogical, addressTypeId, byteAddress, constUint2);
  2834. // Perform access chain into the RWByteAddressBuffer.
  2835. // First index must be zero (member 0 of the struct is a
  2836. // runtimeArray). The second index passed to OpAccessChain should be
  2837. // the address.
  2838. const uint32_t uintTypeId = theBuilder.getUint32Type();
  2839. const uint32_t ptrType =
  2840. theBuilder.getPointerType(uintTypeId, objectInfo.getStorageClass());
  2841. const uint32_t constUint0 = theBuilder.getConstantUint32(0);
  2842. if (doStore) {
  2843. const uint32_t valuesId = doExpr(expr->getArg(1));
  2844. uint32_t curStoreAddress = address;
  2845. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  2846. // Extract a 32-bit word from the input.
  2847. const uint32_t curValue = numWords == 1
  2848. ? valuesId
  2849. : theBuilder.createCompositeExtract(
  2850. uintTypeId, valuesId, {wordCounter});
  2851. // Update the output address if necessary.
  2852. if (wordCounter > 0) {
  2853. const uint32_t offset = theBuilder.getConstantUint32(wordCounter);
  2854. curStoreAddress = theBuilder.createBinaryOp(
  2855. spv::Op::OpIAdd, addressTypeId, address, offset);
  2856. }
  2857. // Store the word to the right address at the output.
  2858. const uint32_t storePtr = theBuilder.createAccessChain(
  2859. ptrType, objectInfo, {constUint0, curStoreAddress});
  2860. theBuilder.createStore(storePtr, curValue);
  2861. }
  2862. } else {
  2863. uint32_t loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2864. {constUint0, address});
  2865. resultId = theBuilder.createLoad(uintTypeId, loadPtr);
  2866. if (numWords > 1) {
  2867. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  2868. // return a vector result.
  2869. llvm::SmallVector<uint32_t, 4> values;
  2870. values.push_back(resultId);
  2871. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  2872. const uint32_t offset = theBuilder.getConstantUint32(wordCounter - 1);
  2873. const uint32_t newAddress = theBuilder.createBinaryOp(
  2874. spv::Op::OpIAdd, addressTypeId, address, offset);
  2875. loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2876. {constUint0, newAddress});
  2877. values.push_back(theBuilder.createLoad(uintTypeId, loadPtr));
  2878. }
  2879. const uint32_t resultType =
  2880. theBuilder.getVecType(addressTypeId, numWords);
  2881. resultId = theBuilder.createCompositeConstruct(resultType, values);
  2882. }
  2883. }
  2884. return SpirvEvalInfo(resultId).setRValue();
  2885. }
  2886. SpirvEvalInfo
  2887. SPIRVEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  2888. if (expr->getNumArgs() == 2) {
  2889. emitError(
  2890. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  2891. expr->getExprLoc());
  2892. return 0;
  2893. }
  2894. const auto *buffer = expr->getImplicitObjectArgument();
  2895. auto info = loadIfAliasVarRef(buffer);
  2896. const QualType structType =
  2897. hlsl::GetHLSLResourceResultType(buffer->getType());
  2898. const uint32_t zero = theBuilder.getConstantInt32(0);
  2899. const uint32_t index = doExpr(expr->getArg(0));
  2900. return turnIntoElementPtr(buffer->getType(), info, structType, {zero, index});
  2901. }
  2902. uint32_t SPIRVEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  2903. bool isInc, bool loadObject) {
  2904. const uint32_t i32Type = theBuilder.getInt32Type();
  2905. const uint32_t one = theBuilder.getConstantUint32(1); // As scope: Device
  2906. const uint32_t zero = theBuilder.getConstantUint32(0); // As memory sema: None
  2907. const uint32_t sOne = theBuilder.getConstantInt32(1);
  2908. const auto *object =
  2909. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2910. if (loadObject) {
  2911. // We don't need the object's <result-id> here since counter variable is a
  2912. // separate variable. But we still need the side effects of evaluating the
  2913. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  2914. // want to emit the code for foo(...).
  2915. (void)doExpr(object);
  2916. }
  2917. const auto *counterPair = getFinalACSBufferCounter(object);
  2918. if (!counterPair) {
  2919. emitFatalError("cannot find the associated counter variable",
  2920. object->getExprLoc());
  2921. return 0;
  2922. }
  2923. const uint32_t counterPtrType = theBuilder.getPointerType(
  2924. theBuilder.getInt32Type(), spv::StorageClass::Uniform);
  2925. const uint32_t counterPtr = theBuilder.createAccessChain(
  2926. counterPtrType, counterPair->get(theBuilder, typeTranslator), {zero});
  2927. uint32_t index = 0;
  2928. if (isInc) {
  2929. index = theBuilder.createAtomicOp(spv::Op::OpAtomicIAdd, i32Type,
  2930. counterPtr, one, zero, sOne);
  2931. } else {
  2932. // Note that OpAtomicISub returns the value before the subtraction;
  2933. // so we need to do substraction again with OpAtomicISub's return value.
  2934. const auto prev = theBuilder.createAtomicOp(spv::Op::OpAtomicISub, i32Type,
  2935. counterPtr, one, zero, sOne);
  2936. index = theBuilder.createBinaryOp(spv::Op::OpISub, i32Type, prev, sOne);
  2937. }
  2938. return index;
  2939. }
  2940. bool SPIRVEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  2941. const Expr *srcExpr) {
  2942. // We are handling associated counters here. Casts should not alter which
  2943. // associated counter to manipulate.
  2944. srcExpr = srcExpr->IgnoreParenCasts();
  2945. // For parameters of forward-declared functions. We must make sure the
  2946. // associated counter variable is created. But for forward-declared functions,
  2947. // the translation of the real definition may not be started yet.
  2948. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  2949. declIdMapper.createFnParamCounterVar(param);
  2950. // For implicit objects of methods. Similar to the above.
  2951. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  2952. declIdMapper.createFnParamCounterVar(thisObject);
  2953. // Handle AssocCounter#1 (see CounterVarFields comment)
  2954. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  2955. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2956. if (!srcPair) {
  2957. emitFatalError("cannot find the associated counter variable",
  2958. srcExpr->getExprLoc());
  2959. return false;
  2960. }
  2961. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2962. return true;
  2963. }
  2964. // Handle AssocCounter#3
  2965. llvm::SmallVector<uint32_t, 4> srcIndices;
  2966. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  2967. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2968. if (dstFields && srcFields) {
  2969. if (!dstFields->assign(*srcFields, theBuilder, typeTranslator)) {
  2970. emitFatalError("cannot handle associated counter variable assignment",
  2971. srcExpr->getExprLoc());
  2972. return false;
  2973. }
  2974. return true;
  2975. }
  2976. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  2977. // is a stand-alone decl in this method.
  2978. return false;
  2979. }
  2980. bool SPIRVEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  2981. const Expr *srcExpr) {
  2982. dstExpr = dstExpr->IgnoreParenCasts();
  2983. srcExpr = srcExpr->IgnoreParenCasts();
  2984. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  2985. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2986. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  2987. emitFatalError("cannot handle associated counter variable assignment",
  2988. srcExpr->getExprLoc());
  2989. return false;
  2990. }
  2991. // Handle AssocCounter#1 & AssocCounter#2
  2992. if (dstPair && srcPair) {
  2993. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2994. return true;
  2995. }
  2996. // Handle AssocCounter#3 & AssocCounter#4
  2997. llvm::SmallVector<uint32_t, 4> dstIndices;
  2998. llvm::SmallVector<uint32_t, 4> srcIndices;
  2999. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  3000. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  3001. if (dstFields && srcFields) {
  3002. return dstFields->assign(*srcFields, dstIndices, srcIndices, theBuilder,
  3003. typeTranslator);
  3004. }
  3005. return false;
  3006. }
  3007. const CounterIdAliasPair *
  3008. SPIRVEmitter::getFinalACSBufferCounter(const Expr *expr) {
  3009. // AssocCounter#1: referencing some stand-alone variable
  3010. if (const auto *decl = getReferencedDef(expr))
  3011. return declIdMapper.getCounterIdAliasPair(decl);
  3012. // AssocCounter#2: referencing some non-struct field
  3013. llvm::SmallVector<uint32_t, 4> indices;
  3014. const auto *base =
  3015. collectArrayStructIndices(expr, &indices, /*rawIndex=*/true);
  3016. const auto *decl =
  3017. (base && isa<CXXThisExpr>(base))
  3018. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3019. : getReferencedDef(base);
  3020. return declIdMapper.getCounterIdAliasPair(decl, &indices);
  3021. }
  3022. const CounterVarFields *SPIRVEmitter::getIntermediateACSBufferCounter(
  3023. const Expr *expr, llvm::SmallVector<uint32_t, 4> *indices) {
  3024. const auto *base =
  3025. collectArrayStructIndices(expr, indices, /*rawIndex=*/true);
  3026. const auto *decl =
  3027. (base && isa<CXXThisExpr>(base))
  3028. // Use the decl we created to represent the implicit object
  3029. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  3030. // Find the referenced decl from the original source code
  3031. : getReferencedDef(base);
  3032. return declIdMapper.getCounterVarFields(decl);
  3033. }
  3034. const ImplicitParamDecl *
  3035. SPIRVEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  3036. const auto found = thisDecls.find(method);
  3037. if (found != thisDecls.end())
  3038. return found->second;
  3039. const std::string name = method->getName().str() + ".this";
  3040. // Create a new identifier to convey the name
  3041. auto &identifier = astContext.Idents.get(name);
  3042. return thisDecls[method] = ImplicitParamDecl::Create(
  3043. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  3044. method->getThisType(astContext)->getPointeeType());
  3045. }
  3046. SpirvEvalInfo
  3047. SPIRVEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  3048. const bool isAppend = expr->getNumArgs() == 1;
  3049. const uint32_t zero = theBuilder.getConstantUint32(0);
  3050. const auto *object =
  3051. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3052. auto bufferInfo = loadIfAliasVarRef(object);
  3053. uint32_t index = incDecRWACSBufferCounter(
  3054. expr, isAppend,
  3055. // We have already translated the object in the above. Avoid duplication.
  3056. /*loadObject=*/false);
  3057. const auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  3058. (void)turnIntoElementPtr(object->getType(), bufferInfo, bufferElemTy,
  3059. {zero, index});
  3060. if (isAppend) {
  3061. // Write out the value
  3062. auto arg0 = doExpr(expr->getArg(0));
  3063. if (!arg0.isRValue()) {
  3064. arg0.setResultId(theBuilder.createLoad(
  3065. typeTranslator.translateType(bufferElemTy), arg0));
  3066. }
  3067. storeValue(bufferInfo, arg0, bufferElemTy);
  3068. return 0;
  3069. } else {
  3070. // Note that we are returning a pointer (lvalue) here inorder to further
  3071. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  3072. // cannot forcefully set all normal function calls as returning rvalue.
  3073. return bufferInfo;
  3074. }
  3075. }
  3076. uint32_t
  3077. SPIRVEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  3078. // TODO: handle multiple stream-output objects
  3079. const auto *object =
  3080. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  3081. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  3082. const uint32_t value = doExpr(expr->getArg(0));
  3083. declIdMapper.writeBackOutputStream(stream, stream->getType(), value);
  3084. theBuilder.createEmitVertex();
  3085. return 0;
  3086. }
  3087. uint32_t
  3088. SPIRVEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  3089. // TODO: handle multiple stream-output objects
  3090. theBuilder.createEndPrimitive();
  3091. return 0;
  3092. }
  3093. uint32_t SPIRVEmitter::emitGetSamplePosition(const uint32_t sampleCount,
  3094. const uint32_t sampleIndex) {
  3095. struct Float2 {
  3096. float x;
  3097. float y;
  3098. };
  3099. static const Float2 pos2[] = {
  3100. {4.0 / 16.0, 4.0 / 16.0},
  3101. {-4.0 / 16.0, -4.0 / 16.0},
  3102. };
  3103. static const Float2 pos4[] = {
  3104. {-2.0 / 16.0, -6.0 / 16.0},
  3105. {6.0 / 16.0, -2.0 / 16.0},
  3106. {-6.0 / 16.0, 2.0 / 16.0},
  3107. {2.0 / 16.0, 6.0 / 16.0},
  3108. };
  3109. static const Float2 pos8[] = {
  3110. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  3111. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  3112. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  3113. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  3114. };
  3115. static const Float2 pos16[] = {
  3116. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  3117. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  3118. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  3119. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  3120. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  3121. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  3122. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  3123. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  3124. };
  3125. // We are emitting the SPIR-V for the following HLSL source code:
  3126. //
  3127. // float2 position;
  3128. //
  3129. // if (count == 2) {
  3130. // position = pos2[index];
  3131. // }
  3132. // else if (count == 4) {
  3133. // position = pos4[index];
  3134. // }
  3135. // else if (count == 8) {
  3136. // position = pos8[index];
  3137. // }
  3138. // else if (count == 16) {
  3139. // position = pos16[index];
  3140. // }
  3141. // else {
  3142. // position = float2(0.0f, 0.0f);
  3143. // }
  3144. const uint32_t boolType = theBuilder.getBoolType();
  3145. const auto v2f32Type = theBuilder.getVecType(theBuilder.getFloat32Type(), 2);
  3146. const uint32_t ptrType =
  3147. theBuilder.getPointerType(v2f32Type, spv::StorageClass::Function);
  3148. // Creates a SPIR-V function scope variable of type float2[len].
  3149. const auto createArray = [this, v2f32Type](const Float2 *ptr, uint32_t len) {
  3150. llvm::SmallVector<uint32_t, 16> components;
  3151. for (uint32_t i = 0; i < len; ++i) {
  3152. const auto x = theBuilder.getConstantFloat32(ptr[i].x);
  3153. const auto y = theBuilder.getConstantFloat32(ptr[i].y);
  3154. components.push_back(theBuilder.getConstantComposite(v2f32Type, {x, y}));
  3155. }
  3156. const auto arrType =
  3157. theBuilder.getArrayType(v2f32Type, theBuilder.getConstantUint32(len));
  3158. const auto val = theBuilder.getConstantComposite(arrType, components);
  3159. const std::string varName =
  3160. "var.GetSamplePosition.data." + std::to_string(len);
  3161. const auto var = theBuilder.addFnVar(arrType, varName);
  3162. theBuilder.createStore(var, val);
  3163. return var;
  3164. };
  3165. const uint32_t pos2Arr = createArray(pos2, 2);
  3166. const uint32_t pos4Arr = createArray(pos4, 4);
  3167. const uint32_t pos8Arr = createArray(pos8, 8);
  3168. const uint32_t pos16Arr = createArray(pos16, 16);
  3169. const uint32_t resultVar =
  3170. theBuilder.addFnVar(v2f32Type, "var.GetSamplePosition.result");
  3171. const uint32_t then2BB =
  3172. theBuilder.createBasicBlock("if.GetSamplePosition.then2");
  3173. const uint32_t then4BB =
  3174. theBuilder.createBasicBlock("if.GetSamplePosition.then4");
  3175. const uint32_t then8BB =
  3176. theBuilder.createBasicBlock("if.GetSamplePosition.then8");
  3177. const uint32_t then16BB =
  3178. theBuilder.createBasicBlock("if.GetSamplePosition.then16");
  3179. const uint32_t else2BB =
  3180. theBuilder.createBasicBlock("if.GetSamplePosition.else2");
  3181. const uint32_t else4BB =
  3182. theBuilder.createBasicBlock("if.GetSamplePosition.else4");
  3183. const uint32_t else8BB =
  3184. theBuilder.createBasicBlock("if.GetSamplePosition.else8");
  3185. const uint32_t else16BB =
  3186. theBuilder.createBasicBlock("if.GetSamplePosition.else16");
  3187. const uint32_t merge2BB =
  3188. theBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  3189. const uint32_t merge4BB =
  3190. theBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  3191. const uint32_t merge8BB =
  3192. theBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  3193. const uint32_t merge16BB =
  3194. theBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  3195. // if (count == 2) {
  3196. const auto check2 =
  3197. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3198. theBuilder.getConstantUint32(2));
  3199. theBuilder.createConditionalBranch(check2, then2BB, else2BB, merge2BB);
  3200. theBuilder.addSuccessor(then2BB);
  3201. theBuilder.addSuccessor(else2BB);
  3202. theBuilder.setMergeTarget(merge2BB);
  3203. // position = pos2[index];
  3204. // }
  3205. theBuilder.setInsertPoint(then2BB);
  3206. auto ac = theBuilder.createAccessChain(ptrType, pos2Arr, {sampleIndex});
  3207. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3208. theBuilder.createBranch(merge2BB);
  3209. theBuilder.addSuccessor(merge2BB);
  3210. // else if (count == 4) {
  3211. theBuilder.setInsertPoint(else2BB);
  3212. const auto check4 =
  3213. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3214. theBuilder.getConstantUint32(4));
  3215. theBuilder.createConditionalBranch(check4, then4BB, else4BB, merge4BB);
  3216. theBuilder.addSuccessor(then4BB);
  3217. theBuilder.addSuccessor(else4BB);
  3218. theBuilder.setMergeTarget(merge4BB);
  3219. // position = pos4[index];
  3220. // }
  3221. theBuilder.setInsertPoint(then4BB);
  3222. ac = theBuilder.createAccessChain(ptrType, pos4Arr, {sampleIndex});
  3223. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3224. theBuilder.createBranch(merge4BB);
  3225. theBuilder.addSuccessor(merge4BB);
  3226. // else if (count == 8) {
  3227. theBuilder.setInsertPoint(else4BB);
  3228. const auto check8 =
  3229. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3230. theBuilder.getConstantUint32(8));
  3231. theBuilder.createConditionalBranch(check8, then8BB, else8BB, merge8BB);
  3232. theBuilder.addSuccessor(then8BB);
  3233. theBuilder.addSuccessor(else8BB);
  3234. theBuilder.setMergeTarget(merge8BB);
  3235. // position = pos8[index];
  3236. // }
  3237. theBuilder.setInsertPoint(then8BB);
  3238. ac = theBuilder.createAccessChain(ptrType, pos8Arr, {sampleIndex});
  3239. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3240. theBuilder.createBranch(merge8BB);
  3241. theBuilder.addSuccessor(merge8BB);
  3242. // else if (count == 16) {
  3243. theBuilder.setInsertPoint(else8BB);
  3244. const auto check16 =
  3245. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  3246. theBuilder.getConstantUint32(16));
  3247. theBuilder.createConditionalBranch(check16, then16BB, else16BB, merge16BB);
  3248. theBuilder.addSuccessor(then16BB);
  3249. theBuilder.addSuccessor(else16BB);
  3250. theBuilder.setMergeTarget(merge16BB);
  3251. // position = pos16[index];
  3252. // }
  3253. theBuilder.setInsertPoint(then16BB);
  3254. ac = theBuilder.createAccessChain(ptrType, pos16Arr, {sampleIndex});
  3255. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  3256. theBuilder.createBranch(merge16BB);
  3257. theBuilder.addSuccessor(merge16BB);
  3258. // else {
  3259. // position = float2(0.0f, 0.0f);
  3260. // }
  3261. theBuilder.setInsertPoint(else16BB);
  3262. const auto zero = theBuilder.getConstantFloat32(0);
  3263. const auto v2f32Zero =
  3264. theBuilder.getConstantComposite(v2f32Type, {zero, zero});
  3265. theBuilder.createStore(resultVar, v2f32Zero);
  3266. theBuilder.createBranch(merge16BB);
  3267. theBuilder.addSuccessor(merge16BB);
  3268. theBuilder.setInsertPoint(merge16BB);
  3269. theBuilder.createBranch(merge8BB);
  3270. theBuilder.addSuccessor(merge8BB);
  3271. theBuilder.setInsertPoint(merge8BB);
  3272. theBuilder.createBranch(merge4BB);
  3273. theBuilder.addSuccessor(merge4BB);
  3274. theBuilder.setInsertPoint(merge4BB);
  3275. theBuilder.createBranch(merge2BB);
  3276. theBuilder.addSuccessor(merge2BB);
  3277. theBuilder.setInsertPoint(merge2BB);
  3278. return theBuilder.createLoad(v2f32Type, resultVar);
  3279. }
  3280. SpirvEvalInfo SPIRVEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  3281. const FunctionDecl *callee = expr->getDirectCallee();
  3282. llvm::StringRef group;
  3283. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  3284. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  3285. return processIntrinsicMemberCall(expr,
  3286. static_cast<hlsl::IntrinsicOp>(opcode));
  3287. }
  3288. return processCall(expr);
  3289. }
  3290. void SPIRVEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  3291. uint32_t index,
  3292. uint32_t *constOffset,
  3293. uint32_t *varOffset) {
  3294. // Ensure the given arg index is not out-of-range.
  3295. assert(index < expr->getNumArgs());
  3296. *constOffset = *varOffset = 0; // Initialize both first
  3297. if ((*constOffset = tryToEvaluateAsConst(expr->getArg(index))))
  3298. return; // Constant offset
  3299. else
  3300. *varOffset = doExpr(expr->getArg(index));
  3301. }
  3302. SpirvEvalInfo
  3303. SPIRVEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  3304. hlsl::IntrinsicOp opcode) {
  3305. using namespace hlsl;
  3306. uint32_t retVal = 0;
  3307. switch (opcode) {
  3308. case IntrinsicOp::MOP_Sample:
  3309. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  3310. break;
  3311. case IntrinsicOp::MOP_Gather:
  3312. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  3313. break;
  3314. case IntrinsicOp::MOP_SampleBias:
  3315. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  3316. break;
  3317. case IntrinsicOp::MOP_SampleLevel:
  3318. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  3319. break;
  3320. case IntrinsicOp::MOP_SampleGrad:
  3321. retVal = processTextureSampleGrad(expr);
  3322. break;
  3323. case IntrinsicOp::MOP_SampleCmp:
  3324. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  3325. break;
  3326. case IntrinsicOp::MOP_SampleCmpLevelZero:
  3327. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  3328. break;
  3329. case IntrinsicOp::MOP_GatherRed:
  3330. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  3331. break;
  3332. case IntrinsicOp::MOP_GatherGreen:
  3333. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  3334. break;
  3335. case IntrinsicOp::MOP_GatherBlue:
  3336. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  3337. break;
  3338. case IntrinsicOp::MOP_GatherAlpha:
  3339. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  3340. break;
  3341. case IntrinsicOp::MOP_GatherCmp:
  3342. retVal = processTextureGatherCmp(expr);
  3343. break;
  3344. case IntrinsicOp::MOP_GatherCmpRed:
  3345. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  3346. break;
  3347. case IntrinsicOp::MOP_Load:
  3348. return processBufferTextureLoad(expr);
  3349. case IntrinsicOp::MOP_Load2:
  3350. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3351. case IntrinsicOp::MOP_Load3:
  3352. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3353. case IntrinsicOp::MOP_Load4:
  3354. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3355. case IntrinsicOp::MOP_Store:
  3356. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3357. case IntrinsicOp::MOP_Store2:
  3358. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3359. case IntrinsicOp::MOP_Store3:
  3360. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3361. case IntrinsicOp::MOP_Store4:
  3362. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3363. case IntrinsicOp::MOP_GetDimensions:
  3364. retVal = processGetDimensions(expr);
  3365. break;
  3366. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3367. retVal = processTextureLevelOfDetail(expr, /* unclamped */ false);
  3368. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3369. retVal = processTextureLevelOfDetail(expr, /* unclamped */ true);
  3370. break;
  3371. case IntrinsicOp::MOP_IncrementCounter:
  3372. retVal = theBuilder.createUnaryOp(
  3373. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3374. incDecRWACSBufferCounter(expr, /*isInc*/ true));
  3375. break;
  3376. case IntrinsicOp::MOP_DecrementCounter:
  3377. retVal = theBuilder.createUnaryOp(
  3378. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3379. incDecRWACSBufferCounter(expr, /*isInc*/ false));
  3380. break;
  3381. case IntrinsicOp::MOP_Append:
  3382. if (hlsl::IsHLSLStreamOutputType(
  3383. expr->getImplicitObjectArgument()->getType()))
  3384. return processStreamOutputAppend(expr);
  3385. else
  3386. return processACSBufferAppendConsume(expr);
  3387. case IntrinsicOp::MOP_Consume:
  3388. return processACSBufferAppendConsume(expr);
  3389. case IntrinsicOp::MOP_RestartStrip:
  3390. retVal = processStreamOutputRestart(expr);
  3391. break;
  3392. case IntrinsicOp::MOP_InterlockedAdd:
  3393. case IntrinsicOp::MOP_InterlockedAnd:
  3394. case IntrinsicOp::MOP_InterlockedOr:
  3395. case IntrinsicOp::MOP_InterlockedXor:
  3396. case IntrinsicOp::MOP_InterlockedUMax:
  3397. case IntrinsicOp::MOP_InterlockedUMin:
  3398. case IntrinsicOp::MOP_InterlockedMax:
  3399. case IntrinsicOp::MOP_InterlockedMin:
  3400. case IntrinsicOp::MOP_InterlockedExchange:
  3401. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3402. case IntrinsicOp::MOP_InterlockedCompareStore:
  3403. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3404. break;
  3405. case IntrinsicOp::MOP_GetSamplePosition:
  3406. retVal = processGetSamplePosition(expr);
  3407. break;
  3408. case IntrinsicOp::MOP_SubpassLoad:
  3409. retVal = processSubpassLoad(expr);
  3410. break;
  3411. case IntrinsicOp::MOP_GatherCmpGreen:
  3412. case IntrinsicOp::MOP_GatherCmpBlue:
  3413. case IntrinsicOp::MOP_GatherCmpAlpha:
  3414. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3415. expr->getCallee()->getExprLoc())
  3416. << expr->getMethodDecl()->getName();
  3417. return 0;
  3418. default:
  3419. emitError("intrinsic '%0' method unimplemented",
  3420. expr->getCallee()->getExprLoc())
  3421. << expr->getDirectCallee()->getName();
  3422. return 0;
  3423. }
  3424. return SpirvEvalInfo(retVal).setRValue();
  3425. }
  3426. uint32_t SPIRVEmitter::createImageSample(
  3427. QualType retType, uint32_t imageType, uint32_t image, uint32_t sampler,
  3428. bool isNonUniform, uint32_t coordinate, uint32_t compareVal, uint32_t bias,
  3429. uint32_t lod, std::pair<uint32_t, uint32_t> grad, uint32_t constOffset,
  3430. uint32_t varOffset, uint32_t constOffsets, uint32_t sample, uint32_t minLod,
  3431. uint32_t residencyCodeId) {
  3432. const auto retTypeId = typeTranslator.translateType(retType);
  3433. // SampleDref* instructions in SPIR-V always return a scalar.
  3434. // They also have the correct type in HLSL.
  3435. if (compareVal) {
  3436. return theBuilder.createImageSample(
  3437. retTypeId, imageType, image, sampler, isNonUniform, coordinate,
  3438. compareVal, bias, lod, grad, constOffset, varOffset, constOffsets,
  3439. sample, minLod, residencyCodeId);
  3440. }
  3441. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3442. auto texelTypeId = retTypeId;
  3443. QualType elemType = {};
  3444. uint32_t elemTypeId = 0;
  3445. uint32_t retVecSize = 0;
  3446. if (TypeTranslator::isVectorType(retType, &elemType, &retVecSize) &&
  3447. retVecSize != 4) {
  3448. elemTypeId = typeTranslator.translateType(elemType);
  3449. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3450. } else if (TypeTranslator::isScalarType(retType)) {
  3451. retVecSize = 1;
  3452. elemTypeId = typeTranslator.translateType(retType);
  3453. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3454. }
  3455. // The Lod and Grad image operands requires explicit-lod instructions.
  3456. // Otherwise we use implicit-lod instructions.
  3457. const bool isExplicit = lod || (grad.first && grad.second);
  3458. // Implicit-lod instructions are only allowed in pixel shader.
  3459. if (!shaderModel.IsPS() && !isExplicit)
  3460. needsLegalization = true;
  3461. uint32_t retVal = theBuilder.createImageSample(
  3462. texelTypeId, imageType, image, sampler, isNonUniform, coordinate,
  3463. compareVal, bias, lod, grad, constOffset, varOffset, constOffsets, sample,
  3464. minLod, residencyCodeId);
  3465. // Extract smaller vector from the vec4 result if necessary.
  3466. if (texelTypeId != retTypeId) {
  3467. retVal = extractVecFromVec4(retVal, retVecSize, elemTypeId);
  3468. }
  3469. return retVal;
  3470. }
  3471. uint32_t SPIRVEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  3472. const bool isSample) {
  3473. // Signatures:
  3474. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3475. // DXGI_FORMAT Object.Sample(sampler_state S,
  3476. // float Location
  3477. // [, int Offset]
  3478. // [, float Clamp]
  3479. // [, out uint Status]);
  3480. //
  3481. // For TextureCube and TextureCubeArray:
  3482. // DXGI_FORMAT Object.Sample(sampler_state S,
  3483. // float Location
  3484. // [, float Clamp]
  3485. // [, out uint Status]);
  3486. //
  3487. // For Texture2D/Texture2DArray:
  3488. // <Template Type>4 Object.Gather(sampler_state S,
  3489. // float2|3|4 Location,
  3490. // int2 Offset
  3491. // [, uint Status]);
  3492. //
  3493. // For TextureCube/TextureCubeArray:
  3494. // <Template Type>4 Object.Gather(sampler_state S,
  3495. // float2|3|4 Location
  3496. // [, uint Status]);
  3497. //
  3498. // Other Texture types do not have a Gather method.
  3499. const auto numArgs = expr->getNumArgs();
  3500. const bool hasStatusArg =
  3501. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3502. uint32_t clamp = 0;
  3503. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  3504. clamp = doExpr(expr->getArg(2));
  3505. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3506. clamp = doExpr(expr->getArg(3));
  3507. const bool hasClampArg = (clamp != 0);
  3508. const auto status =
  3509. hasStatusArg ? static_cast<uint32_t>(doExpr(expr->getArg(numArgs - 1)))
  3510. : 0;
  3511. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  3512. // and subtract 2 for sampler_state and location.
  3513. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  3514. const auto *imageExpr = expr->getImplicitObjectArgument();
  3515. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3516. const auto image = loadIfGLValue(imageExpr);
  3517. const auto sampler = doExpr(expr->getArg(0));
  3518. const uint32_t coordinate = doExpr(expr->getArg(1));
  3519. // .Sample()/.Gather() may have a third optional paramter for offset.
  3520. uint32_t constOffset = 0, varOffset = 0;
  3521. if (hasOffsetArg)
  3522. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3523. const bool isNonUniform = image.isNonUniform() || sampler.isNonUniform();
  3524. const auto retType = expr->getDirectCallee()->getReturnType();
  3525. const auto retTypeId = typeTranslator.translateType(retType);
  3526. if (isSample) {
  3527. return createImageSample(
  3528. retType, imageType, image, sampler, isNonUniform, coordinate,
  3529. /*compareVal*/ 0, /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0),
  3530. constOffset, varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0,
  3531. /*minLod*/ clamp, status);
  3532. } else {
  3533. return theBuilder.createImageGather(
  3534. retTypeId, imageType, image, sampler, isNonUniform, coordinate,
  3535. // .Gather() doc says we return four components of red data.
  3536. theBuilder.getConstantInt32(0), /*compareVal*/ 0, constOffset,
  3537. varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0, status);
  3538. }
  3539. }
  3540. uint32_t
  3541. SPIRVEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  3542. const bool isBias) {
  3543. // Signatures:
  3544. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3545. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3546. // float Location,
  3547. // float Bias
  3548. // [, int Offset]
  3549. // [, float clamp]
  3550. // [, out uint Status]);
  3551. //
  3552. // For TextureCube and TextureCubeArray:
  3553. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3554. // float Location,
  3555. // float Bias
  3556. // [, float clamp]
  3557. // [, out uint Status]);
  3558. //
  3559. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3560. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3561. // float Location,
  3562. // float LOD
  3563. // [, int Offset]
  3564. // [, out uint Status]);
  3565. //
  3566. // For TextureCube and TextureCubeArray:
  3567. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3568. // float Location,
  3569. // float LOD
  3570. // [, out uint Status]);
  3571. const auto numArgs = expr->getNumArgs();
  3572. const bool hasStatusArg =
  3573. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3574. const auto status =
  3575. hasStatusArg ? static_cast<uint32_t>(doExpr(expr->getArg(numArgs - 1)))
  3576. : 0;
  3577. uint32_t clamp = 0;
  3578. // The .SampleLevel() methods do not take the clamp argument.
  3579. if (isBias) {
  3580. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3581. clamp = doExpr(expr->getArg(3));
  3582. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3583. clamp = doExpr(expr->getArg(4));
  3584. }
  3585. const bool hasClampArg = clamp != 0;
  3586. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3587. // and 3 for sampler_state, location, and Bias/LOD.
  3588. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3589. const auto *imageExpr = expr->getImplicitObjectArgument();
  3590. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3591. const auto image = loadIfGLValue(imageExpr);
  3592. const auto sampler = doExpr(expr->getArg(0));
  3593. const uint32_t coordinate = doExpr(expr->getArg(1));
  3594. uint32_t lod = 0;
  3595. uint32_t bias = 0;
  3596. if (isBias) {
  3597. bias = doExpr(expr->getArg(2));
  3598. } else {
  3599. lod = doExpr(expr->getArg(2));
  3600. }
  3601. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  3602. uint32_t constOffset = 0, varOffset = 0;
  3603. if (hasOffsetArg)
  3604. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3605. const auto retType = expr->getDirectCallee()->getReturnType();
  3606. return createImageSample(
  3607. retType, imageType, image, sampler,
  3608. image.isNonUniform() || sampler.isNonUniform(), coordinate,
  3609. /*compareVal*/ 0, bias, lod, std::make_pair(0, 0), constOffset, varOffset,
  3610. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3611. }
  3612. uint32_t SPIRVEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  3613. // Signature:
  3614. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3615. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3616. // float Location,
  3617. // float DDX,
  3618. // float DDY
  3619. // [, int Offset]
  3620. // [, float Clamp]
  3621. // [, out uint Status]);
  3622. //
  3623. // For TextureCube and TextureCubeArray:
  3624. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3625. // float Location,
  3626. // float DDX,
  3627. // float DDY
  3628. // [, float Clamp]
  3629. // [, out uint Status]);
  3630. const auto numArgs = expr->getNumArgs();
  3631. const bool hasStatusArg =
  3632. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3633. const auto status =
  3634. hasStatusArg ? static_cast<uint32_t>(doExpr(expr->getArg(numArgs - 1)))
  3635. : 0;
  3636. uint32_t clamp = 0;
  3637. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3638. clamp = doExpr(expr->getArg(4));
  3639. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  3640. clamp = doExpr(expr->getArg(5));
  3641. const bool hasClampArg = clamp != 0;
  3642. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3643. // and 4 for sampler_state, location, DDX, and DDY;
  3644. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  3645. const auto *imageExpr = expr->getImplicitObjectArgument();
  3646. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3647. const auto image = loadIfGLValue(imageExpr);
  3648. const auto sampler = doExpr(expr->getArg(0));
  3649. const uint32_t coordinate = doExpr(expr->getArg(1));
  3650. const uint32_t ddx = doExpr(expr->getArg(2));
  3651. const uint32_t ddy = doExpr(expr->getArg(3));
  3652. // If offset is present in .SampleGrad(), it is the fifth argument.
  3653. uint32_t constOffset = 0, varOffset = 0;
  3654. if (hasOffsetArg)
  3655. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  3656. const auto retType = expr->getDirectCallee()->getReturnType();
  3657. return createImageSample(
  3658. retType, imageType, image, sampler,
  3659. image.isNonUniform() || sampler.isNonUniform(), coordinate,
  3660. /*compareVal*/ 0, /*bias*/ 0, /*lod*/ 0, std::make_pair(ddx, ddy),
  3661. constOffset, varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0,
  3662. /*minLod*/ clamp, status);
  3663. }
  3664. uint32_t
  3665. SPIRVEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  3666. const bool isCmp) {
  3667. // .SampleCmp() Signature:
  3668. //
  3669. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3670. // float Object.SampleCmp(
  3671. // SamplerComparisonState S,
  3672. // float Location,
  3673. // float CompareValue
  3674. // [, int Offset]
  3675. // [, float Clamp]
  3676. // [, out uint Status]
  3677. // );
  3678. //
  3679. // For TextureCube and TextureCubeArray:
  3680. // float Object.SampleCmp(
  3681. // SamplerComparisonState S,
  3682. // float Location,
  3683. // float CompareValue
  3684. // [, float Clamp]
  3685. // [, out uint Status]
  3686. // );
  3687. //
  3688. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  3689. // It never takes a clamp argument, which is good because lod and clamp may
  3690. // not be used together.
  3691. //
  3692. // .SampleCmpLevelZero() Signature:
  3693. //
  3694. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3695. // float Object.SampleCmpLevelZero(
  3696. // SamplerComparisonState S,
  3697. // float Location,
  3698. // float CompareValue
  3699. // [, int Offset]
  3700. // [, out uint Status]
  3701. // );
  3702. //
  3703. // For TextureCube and TextureCubeArray:
  3704. // float Object.SampleCmpLevelZero(
  3705. // SamplerComparisonState S,
  3706. // float Location,
  3707. // float CompareValue
  3708. // [, out uint Status]
  3709. // );
  3710. const auto numArgs = expr->getNumArgs();
  3711. const bool hasStatusArg =
  3712. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3713. const auto status =
  3714. hasStatusArg ? static_cast<uint32_t>(doExpr(expr->getArg(numArgs - 1)))
  3715. : 0;
  3716. uint32_t clamp = 0;
  3717. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  3718. if (isCmp) {
  3719. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3720. clamp = doExpr(expr->getArg(3));
  3721. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3722. clamp = doExpr(expr->getArg(4));
  3723. }
  3724. const bool hasClampArg = clamp != 0;
  3725. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3726. // and 3 for sampler_state, location, and compare_value.
  3727. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3728. const auto *imageExpr = expr->getImplicitObjectArgument();
  3729. const auto image = loadIfGLValue(imageExpr);
  3730. const auto sampler = doExpr(expr->getArg(0));
  3731. const uint32_t coordinate = doExpr(expr->getArg(1));
  3732. const uint32_t compareVal = doExpr(expr->getArg(2));
  3733. // If offset is present in .SampleCmp(), it will be the fourth argument.
  3734. uint32_t constOffset = 0, varOffset = 0;
  3735. if (hasOffsetArg)
  3736. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3737. const uint32_t lod = isCmp ? 0 : theBuilder.getConstantFloat32(0);
  3738. const auto retType = expr->getDirectCallee()->getReturnType();
  3739. const auto imageType = typeTranslator.translateType(imageExpr->getType());
  3740. return createImageSample(
  3741. retType, imageType, image, sampler,
  3742. image.isNonUniform() || sampler.isNonUniform(), coordinate, compareVal,
  3743. /*bias*/ 0, lod, std::make_pair(0, 0), constOffset, varOffset,
  3744. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3745. }
  3746. SpirvEvalInfo
  3747. SPIRVEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  3748. // Signature:
  3749. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3750. // ret Object.Load(int Location
  3751. // [, int Offset]
  3752. // [, uint status]);
  3753. //
  3754. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  3755. // ret Object.Load(int Location
  3756. // [, int SampleIndex]
  3757. // [, int Offset]
  3758. // [, uint status]);
  3759. //
  3760. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  3761. // RWTexture2DArray, RWTexture3D:
  3762. // ret Object.Load (int Location
  3763. // [, uint status]);
  3764. //
  3765. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  3766. // methods that take an additional Status argument. However, since these types
  3767. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  3768. // figuring out the Residency Code for them. Therefore having the Status
  3769. // argument for these types is not supported.
  3770. //
  3771. // For (RW)ByteAddressBuffer:
  3772. // ret Object.{Load,Load2,Load3,Load4} (int Location
  3773. // [, uint status]);
  3774. //
  3775. // For (RW)StructuredBuffer:
  3776. // ret Object.Load (int Location
  3777. // [, uint status]);
  3778. //
  3779. const auto *object = expr->getImplicitObjectArgument();
  3780. const auto objectType = object->getType();
  3781. if (typeTranslator.isRWByteAddressBuffer(objectType) ||
  3782. typeTranslator.isByteAddressBuffer(objectType))
  3783. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  3784. if (TypeTranslator::isStructuredBuffer(objectType))
  3785. return processStructuredBufferLoad(expr);
  3786. const auto numArgs = expr->getNumArgs();
  3787. const auto *location = expr->getArg(0);
  3788. const bool isTextureMS = TypeTranslator::isTextureMS(objectType);
  3789. const bool hasStatusArg =
  3790. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3791. const auto status =
  3792. hasStatusArg ? static_cast<uint32_t>(doExpr(expr->getArg(numArgs - 1)))
  3793. : 0;
  3794. if (TypeTranslator::isBuffer(objectType) ||
  3795. TypeTranslator::isRWBuffer(objectType) ||
  3796. TypeTranslator::isRWTexture(objectType))
  3797. return processBufferTextureLoad(object, doExpr(location), /*constOffset*/ 0,
  3798. /*varOffset*/ 0, /*lod*/ 0,
  3799. /*residencyCode*/ status);
  3800. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  3801. // and 1 for location.
  3802. const bool hasOffsetArg = numArgs - hasStatusArg - isTextureMS - 1 > 0;
  3803. if (TypeTranslator::isTexture(objectType)) {
  3804. // .Load() has a second optional paramter for offset.
  3805. const auto locationId = doExpr(location);
  3806. uint32_t constOffset = 0, varOffset = 0;
  3807. uint32_t coordinate = locationId, lod = 0;
  3808. if (isTextureMS) {
  3809. // SampleIndex is only available when the Object is of Texture2DMS or
  3810. // Texture2DMSArray types. Under those cases, Offset will be the third
  3811. // parameter (index 2).
  3812. lod = doExpr(expr->getArg(1));
  3813. if (hasOffsetArg)
  3814. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3815. } else {
  3816. // For Texture Load() functions, the location parameter is a vector
  3817. // that consists of both the coordinate and the mipmap level (via the
  3818. // last vector element). We need to split it here since the
  3819. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  3820. splitVecLastElement(location->getType(), locationId, &coordinate, &lod);
  3821. // For textures other than Texture2DMS(Array), offset should be the
  3822. // second parameter (index 1).
  3823. if (hasOffsetArg)
  3824. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  3825. }
  3826. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  3827. lod, status);
  3828. }
  3829. emitError("Load() of the given object type unimplemented",
  3830. object->getExprLoc());
  3831. return 0;
  3832. }
  3833. uint32_t SPIRVEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  3834. const auto objectType = expr->getImplicitObjectArgument()->getType();
  3835. if (TypeTranslator::isTexture(objectType) ||
  3836. TypeTranslator::isRWTexture(objectType) ||
  3837. TypeTranslator::isBuffer(objectType) ||
  3838. TypeTranslator::isRWBuffer(objectType)) {
  3839. return processBufferTextureGetDimensions(expr);
  3840. } else if (TypeTranslator::isByteAddressBuffer(objectType) ||
  3841. TypeTranslator::isRWByteAddressBuffer(objectType) ||
  3842. TypeTranslator::isStructuredBuffer(objectType) ||
  3843. TypeTranslator::isAppendStructuredBuffer(objectType) ||
  3844. TypeTranslator::isConsumeStructuredBuffer(objectType)) {
  3845. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  3846. } else {
  3847. emitError("GetDimensions() of the given object type unimplemented",
  3848. expr->getExprLoc());
  3849. return 0;
  3850. }
  3851. }
  3852. SpirvEvalInfo
  3853. SPIRVEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  3854. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  3855. const Expr *baseExpr = nullptr;
  3856. const Expr *indexExpr = nullptr;
  3857. const Expr *lodExpr = nullptr;
  3858. // For Textures, regular indexing (operator[]) uses slice 0.
  3859. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  3860. const uint32_t lod = TypeTranslator::isTexture(baseExpr->getType())
  3861. ? theBuilder.getConstantUint32(0)
  3862. : 0;
  3863. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3864. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3865. /*residencyCode*/ 0);
  3866. }
  3867. // .mips[][] or .sample[][] must use the correct slice.
  3868. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  3869. const uint32_t lod = doExpr(lodExpr);
  3870. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3871. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3872. /*residencyCode*/ 0);
  3873. }
  3874. }
  3875. llvm::SmallVector<uint32_t, 4> indices;
  3876. const Expr *baseExpr = collectArrayStructIndices(expr, &indices);
  3877. auto base = loadIfAliasVarRef(baseExpr);
  3878. if (indices.empty())
  3879. return base; // For indexing into size-1 vectors and 1xN matrices
  3880. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  3881. // to create a local variable to hold the rvalue.
  3882. //
  3883. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  3884. // all indices are contant integers.
  3885. if (base.isRValue()) {
  3886. base = createTemporaryVar(baseExpr->getType(), "vector", base);
  3887. }
  3888. return turnIntoElementPtr(baseExpr->getType(), base, expr->getType(),
  3889. indices);
  3890. }
  3891. SpirvEvalInfo
  3892. SPIRVEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  3893. const Expr *baseExpr = expr->getBase();
  3894. const auto baseInfo = doExpr(baseExpr);
  3895. const auto layoutRule = baseInfo.getLayoutRule();
  3896. const auto elemType = hlsl::GetHLSLMatElementType(baseExpr->getType());
  3897. const auto accessor = expr->getEncodedElementAccess();
  3898. const uint32_t elemTypeId =
  3899. typeTranslator.translateType(elemType, layoutRule);
  3900. uint32_t rowCount = 0, colCount = 0;
  3901. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  3902. // Construct a temporary vector out of all elements accessed:
  3903. // 1. Create access chain for each element using OpAccessChain
  3904. // 2. Load each element using OpLoad
  3905. // 3. Create the vector using OpCompositeConstruct
  3906. llvm::SmallVector<uint32_t, 4> elements;
  3907. for (uint32_t i = 0; i < accessor.Count; ++i) {
  3908. uint32_t row = 0, col = 0, elem = 0;
  3909. accessor.GetPosition(i, &row, &col);
  3910. llvm::SmallVector<uint32_t, 2> indices;
  3911. // If the matrix only has one row/column, we are indexing into a vector
  3912. // then. Only one index is needed for such cases.
  3913. if (rowCount > 1)
  3914. indices.push_back(row);
  3915. if (colCount > 1)
  3916. indices.push_back(col);
  3917. if (baseExpr->isGLValue()) {
  3918. for (uint32_t i = 0; i < indices.size(); ++i)
  3919. indices[i] = theBuilder.getConstantInt32(indices[i]);
  3920. const uint32_t ptrType =
  3921. theBuilder.getPointerType(elemTypeId, baseInfo.getStorageClass());
  3922. if (!indices.empty()) {
  3923. assert(!baseInfo.isRValue());
  3924. // Load the element via access chain
  3925. elem = theBuilder.createAccessChain(ptrType, baseInfo, indices);
  3926. } else {
  3927. // The matrix is of size 1x1. No need to use access chain, base should
  3928. // be the source pointer.
  3929. elem = baseInfo;
  3930. }
  3931. elem = theBuilder.createLoad(elemTypeId, elem);
  3932. } else { // e.g., (mat1 + mat2)._m11
  3933. elem = theBuilder.createCompositeExtract(elemTypeId, baseInfo, indices);
  3934. }
  3935. elements.push_back(elem);
  3936. }
  3937. const auto size = elements.size();
  3938. auto valueId = elements.front();
  3939. if (size > 1) {
  3940. const uint32_t vecType = theBuilder.getVecType(elemTypeId, size);
  3941. valueId = theBuilder.createCompositeConstruct(vecType, elements);
  3942. }
  3943. // Note: Special-case: Booleans have no physical layout, and therefore when
  3944. // layout is required booleans are represented as unsigned integers.
  3945. // Therefore, after loading the uint we should convert it boolean.
  3946. if (elemType->isBooleanType() && layoutRule != LayoutRule::Void) {
  3947. const auto fromType =
  3948. size == 1 ? astContext.UnsignedIntTy
  3949. : astContext.getExtVectorType(astContext.UnsignedIntTy, size);
  3950. const auto toType =
  3951. size == 1 ? astContext.BoolTy
  3952. : astContext.getExtVectorType(astContext.BoolTy, size);
  3953. valueId = castToBool(valueId, fromType, toType);
  3954. }
  3955. return SpirvEvalInfo(valueId).setRValue();
  3956. }
  3957. SpirvEvalInfo
  3958. SPIRVEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  3959. const Expr *baseExpr = nullptr;
  3960. hlsl::VectorMemberAccessPositions accessor;
  3961. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  3962. const QualType baseType = baseExpr->getType();
  3963. assert(hlsl::IsHLSLVecType(baseType));
  3964. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  3965. const auto accessorSize = static_cast<size_t>(accessor.Count);
  3966. // Depending on the number of elements selected, we emit different
  3967. // instructions.
  3968. // For vectors of size greater than 1, if we are only selecting one element,
  3969. // typical access chain or composite extraction should be fine. But if we
  3970. // are selecting more than one elements, we must resolve to vector specific
  3971. // operations.
  3972. // For size-1 vectors, if we are selecting their single elements multiple
  3973. // times, we need composite construct instructions.
  3974. if (accessorSize == 1) {
  3975. auto baseInfo = doExpr(baseExpr);
  3976. if (baseSize == 1) {
  3977. // Selecting one element from a size-1 vector. The underlying vector is
  3978. // already treated as a scalar.
  3979. return baseInfo;
  3980. }
  3981. // If the base is an lvalue, we should emit an access chain instruction
  3982. // so that we can load/store the specified element. For rvalue base,
  3983. // we should use composite extraction. We should check the immediate base
  3984. // instead of the original base here since we can have something like
  3985. // v.xyyz to turn a lvalue v into rvalue.
  3986. const auto type =
  3987. typeTranslator.translateType(expr->getType(), baseInfo.getLayoutRule());
  3988. if (!baseInfo.isRValue()) { // E.g., v.x;
  3989. const uint32_t ptrType =
  3990. theBuilder.getPointerType(type, baseInfo.getStorageClass());
  3991. const uint32_t index = theBuilder.getConstantInt32(accessor.Swz0);
  3992. // We need a lvalue here. Do not try to load.
  3993. return baseInfo.setResultId(
  3994. theBuilder.createAccessChain(ptrType, baseInfo, {index}));
  3995. } else { // E.g., (v + w).x;
  3996. // The original base vector may not be a rvalue. Need to load it if
  3997. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  3998. // for that case.
  3999. auto result =
  4000. theBuilder.createCompositeExtract(type, baseInfo, {accessor.Swz0});
  4001. // Special-case: Booleans in SPIR-V do not have a physical layout. Uint is
  4002. // used to represent them when layout is required.
  4003. if (expr->getType()->isBooleanType() &&
  4004. baseInfo.getLayoutRule() != LayoutRule::Void)
  4005. result =
  4006. castToBool(result, astContext.UnsignedIntTy, astContext.BoolTy);
  4007. return baseInfo.setResultId(result);
  4008. }
  4009. }
  4010. if (baseSize == 1) {
  4011. // Selecting more than one element from a size-1 vector, for example,
  4012. // <scalar>.xx. Construct the vector.
  4013. auto info = loadIfGLValue(baseExpr);
  4014. const auto type =
  4015. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  4016. llvm::SmallVector<uint32_t, 4> components(accessorSize, info);
  4017. return info
  4018. .setResultId(theBuilder.createCompositeConstruct(type, components))
  4019. .setRValue();
  4020. }
  4021. llvm::SmallVector<uint32_t, 4> selectors;
  4022. selectors.resize(accessorSize);
  4023. // Whether we are selecting elements in the original order
  4024. bool originalOrder = baseSize == accessorSize;
  4025. for (uint32_t i = 0; i < accessorSize; ++i) {
  4026. accessor.GetPosition(i, &selectors[i]);
  4027. // We can select more elements than the vector provides. This handles
  4028. // that case too.
  4029. originalOrder &= selectors[i] == i;
  4030. }
  4031. if (originalOrder)
  4032. return doExpr(baseExpr);
  4033. auto info = loadIfGLValue(baseExpr);
  4034. const auto type =
  4035. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  4036. // Use base for both vectors. But we are only selecting values from the
  4037. // first one.
  4038. return info.setResultId(
  4039. theBuilder.createVectorShuffle(type, info, info, selectors));
  4040. }
  4041. SpirvEvalInfo SPIRVEmitter::doInitListExpr(const InitListExpr *expr) {
  4042. if (const uint32_t id = tryToEvaluateAsConst(expr))
  4043. return SpirvEvalInfo(id).setRValue();
  4044. return SpirvEvalInfo(InitListHandler(*this).process(expr)).setRValue();
  4045. }
  4046. SpirvEvalInfo SPIRVEmitter::doMemberExpr(const MemberExpr *expr) {
  4047. llvm::SmallVector<uint32_t, 4> indices;
  4048. const Expr *base = collectArrayStructIndices(expr, &indices);
  4049. auto info = loadIfAliasVarRef(base);
  4050. if (!indices.empty()) {
  4051. (void)turnIntoElementPtr(base->getType(), info, expr->getType(), indices);
  4052. }
  4053. return info;
  4054. }
  4055. uint32_t SPIRVEmitter::createTemporaryVar(QualType type, llvm::StringRef name,
  4056. const SpirvEvalInfo &init) {
  4057. // We are creating a temporary variable in the Function storage class here,
  4058. // which means it has void layout rule.
  4059. const uint32_t varType = typeTranslator.translateType(type);
  4060. const std::string varName = "temp.var." + name.str();
  4061. const uint32_t varId = theBuilder.addFnVar(varType, varName);
  4062. storeValue(varId, init, type);
  4063. return varId;
  4064. }
  4065. SpirvEvalInfo SPIRVEmitter::doUnaryOperator(const UnaryOperator *expr) {
  4066. const auto opcode = expr->getOpcode();
  4067. const auto *subExpr = expr->getSubExpr();
  4068. const auto subType = subExpr->getType();
  4069. auto subValue = doExpr(subExpr);
  4070. const auto subTypeId = typeTranslator.translateType(subType);
  4071. switch (opcode) {
  4072. case UO_PreInc:
  4073. case UO_PreDec:
  4074. case UO_PostInc:
  4075. case UO_PostDec: {
  4076. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  4077. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  4078. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  4079. const uint32_t originValue = theBuilder.createLoad(subTypeId, subValue);
  4080. const uint32_t one = hlsl::IsHLSLMatType(subType)
  4081. ? getMatElemValueOne(subType)
  4082. : getValueOne(subType);
  4083. uint32_t incValue = 0;
  4084. if (TypeTranslator::isMxNMatrix(subType)) {
  4085. // For matrices, we can only increment/decrement each vector of it.
  4086. const auto actOnEachVec = [this, spvOp, one](uint32_t /*index*/,
  4087. uint32_t vecType,
  4088. uint32_t lhsVec) {
  4089. const auto valId =
  4090. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, one);
  4091. return SpirvEvalInfo(valId).setRValue();
  4092. };
  4093. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec);
  4094. } else {
  4095. incValue = theBuilder.createBinaryOp(spvOp, subTypeId, originValue, one);
  4096. }
  4097. theBuilder.createStore(subValue, incValue);
  4098. // Prefix increment/decrement operator returns a lvalue, while postfix
  4099. // increment/decrement returns a rvalue.
  4100. return isPre ? subValue : subValue.setResultId(originValue).setRValue();
  4101. }
  4102. case UO_Not: {
  4103. return subValue
  4104. .setResultId(
  4105. theBuilder.createUnaryOp(spv::Op::OpNot, subTypeId, subValue))
  4106. .setRValue();
  4107. }
  4108. case UO_LNot: {
  4109. // Parsing will do the necessary casting to make sure we are applying the
  4110. // ! operator on boolean values.
  4111. return subValue
  4112. .setResultId(theBuilder.createUnaryOp(spv::Op::OpLogicalNot, subTypeId,
  4113. subValue))
  4114. .setRValue();
  4115. }
  4116. case UO_Plus:
  4117. // No need to do anything for the prefix + operator.
  4118. return subValue;
  4119. case UO_Minus: {
  4120. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  4121. const spv::Op spvOp = isFloatOrVecOfFloatType(subType) ? spv::Op::OpFNegate
  4122. : spv::Op::OpSNegate;
  4123. return subValue
  4124. .setResultId(theBuilder.createUnaryOp(spvOp, subTypeId, subValue))
  4125. .setRValue();
  4126. }
  4127. default:
  4128. break;
  4129. }
  4130. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  4131. << expr->getOpcodeStr(opcode);
  4132. expr->dump();
  4133. return 0;
  4134. }
  4135. spv::Op SPIRVEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  4136. const bool isSintType = isSintOrVecMatOfSintType(type);
  4137. const bool isUintType = isUintOrVecMatOfUintType(type);
  4138. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  4139. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  4140. \
  4141. case BO_##kind: { \
  4142. if (isSintType || isUintType) { \
  4143. return spv::Op::Op##intBinOp; \
  4144. } \
  4145. if (isFloatType) { \
  4146. return spv::Op::Op##floatBinOp; \
  4147. } \
  4148. } break
  4149. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  4150. \
  4151. case BO_##kind: { \
  4152. if (isSintType) { \
  4153. return spv::Op::Op##sintBinOp; \
  4154. } \
  4155. if (isUintType) { \
  4156. return spv::Op::Op##uintBinOp; \
  4157. } \
  4158. if (isFloatType) { \
  4159. return spv::Op::Op##floatBinOp; \
  4160. } \
  4161. } break
  4162. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  4163. \
  4164. case BO_##kind: { \
  4165. if (isSintType) { \
  4166. return spv::Op::Op##sintBinOp; \
  4167. } \
  4168. if (isUintType) { \
  4169. return spv::Op::Op##uintBinOp; \
  4170. } \
  4171. } break
  4172. switch (op) {
  4173. case BO_EQ: {
  4174. if (isBoolOrVecMatOfBoolType(type))
  4175. return spv::Op::OpLogicalEqual;
  4176. if (isSintType || isUintType)
  4177. return spv::Op::OpIEqual;
  4178. if (isFloatType)
  4179. return spv::Op::OpFOrdEqual;
  4180. } break;
  4181. case BO_NE: {
  4182. if (isBoolOrVecMatOfBoolType(type))
  4183. return spv::Op::OpLogicalNotEqual;
  4184. if (isSintType || isUintType)
  4185. return spv::Op::OpINotEqual;
  4186. if (isFloatType)
  4187. return spv::Op::OpFOrdNotEqual;
  4188. } break;
  4189. // According to HLSL doc, all sides of the && and || expression are always
  4190. // evaluated.
  4191. case BO_LAnd:
  4192. return spv::Op::OpLogicalAnd;
  4193. case BO_LOr:
  4194. return spv::Op::OpLogicalOr;
  4195. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  4196. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  4197. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  4198. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  4199. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  4200. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  4201. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  4202. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  4203. // According to HLSL spec, "the modulus operator returns the remainder of
  4204. // a division." "The % operator is defined only in cases where either both
  4205. // sides are positive or both sides are negative."
  4206. //
  4207. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  4208. // the former, the sign of a non-0 result comes from Operand 1, while
  4209. // with the latter, from Operand 2.
  4210. //
  4211. // For operands with different signs, technically we can map % to either
  4212. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  4213. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  4214. // const expression evaluation if we map % to Op*Rem.
  4215. //
  4216. // Note there is no OpURem in SPIR-V.
  4217. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  4218. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  4219. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  4220. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  4221. FOrdLessThanEqual);
  4222. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  4223. FOrdGreaterThan);
  4224. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  4225. FOrdGreaterThanEqual);
  4226. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  4227. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  4228. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  4229. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  4230. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  4231. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  4232. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  4233. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  4234. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  4235. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  4236. default:
  4237. break;
  4238. }
  4239. #undef BIN_OP_CASE_INT_FLOAT
  4240. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  4241. #undef BIN_OP_CASE_SINT_UINT
  4242. emitError("translating binary operator '%0' unimplemented", {})
  4243. << BinaryOperator::getOpcodeStr(op);
  4244. return spv::Op::OpNop;
  4245. }
  4246. SpirvEvalInfo SPIRVEmitter::processAssignment(const Expr *lhs,
  4247. const SpirvEvalInfo &rhs,
  4248. const bool isCompoundAssignment,
  4249. SpirvEvalInfo lhsPtr) {
  4250. lhs = lhs->IgnoreParenNoopCasts(astContext);
  4251. // Assigning to vector swizzling should be handled differently.
  4252. if (SpirvEvalInfo result = tryToAssignToVectorElements(lhs, rhs))
  4253. return result;
  4254. // Assigning to matrix swizzling should be handled differently.
  4255. if (SpirvEvalInfo result = tryToAssignToMatrixElements(lhs, rhs))
  4256. return result;
  4257. // Assigning to a RWBuffer/RWTexture should be handled differently.
  4258. if (SpirvEvalInfo result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  4259. return result;
  4260. // Normal assignment procedure
  4261. if (!lhsPtr)
  4262. lhsPtr = doExpr(lhs);
  4263. storeValue(lhsPtr, rhs, lhs->getType());
  4264. // Plain assignment returns a rvalue, while compound assignment returns
  4265. // lvalue.
  4266. return isCompoundAssignment ? lhsPtr : rhs;
  4267. }
  4268. void SPIRVEmitter::storeValue(const SpirvEvalInfo &lhsPtr,
  4269. const SpirvEvalInfo &rhsVal,
  4270. QualType lhsValType) {
  4271. if (const auto *refType = lhsValType->getAs<ReferenceType>())
  4272. lhsValType = refType->getPointeeType();
  4273. QualType matElemType = {};
  4274. const bool lhsIsMat = typeTranslator.isMxNMatrix(lhsValType, &matElemType);
  4275. const bool lhsIsFloatMat = lhsIsMat && matElemType->isFloatingType();
  4276. const bool lhsIsNonFpMat = lhsIsMat && !matElemType->isFloatingType();
  4277. if (typeTranslator.isScalarType(lhsValType) ||
  4278. typeTranslator.isVectorType(lhsValType) || lhsIsFloatMat) {
  4279. uint32_t rhsValId = rhsVal;
  4280. // Special-case: According to the SPIR-V Spec: There is no physical size
  4281. // or bit pattern defined for boolean type. Therefore an unsigned integer
  4282. // is used to represent booleans when layout is required. In such cases,
  4283. // we should cast the boolean to uint before creating OpStore.
  4284. if (isBoolOrVecOfBoolType(lhsValType) &&
  4285. lhsPtr.getLayoutRule() != LayoutRule::Void) {
  4286. uint32_t vecSize = 1;
  4287. const bool isVec =
  4288. TypeTranslator::isVectorType(lhsValType, nullptr, &vecSize);
  4289. const auto toType =
  4290. isVec ? astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize)
  4291. : astContext.UnsignedIntTy;
  4292. const auto fromType =
  4293. isVec ? astContext.getExtVectorType(astContext.BoolTy, vecSize)
  4294. : astContext.BoolTy;
  4295. rhsValId = castToInt(rhsValId, fromType, toType, {});
  4296. }
  4297. theBuilder.createStore(lhsPtr, rhsValId);
  4298. } else if (TypeTranslator::isOpaqueType(lhsValType)) {
  4299. // Resource types are represented using RecordType in the AST.
  4300. // Handle them before the general RecordType.
  4301. //
  4302. // HLSL allows to put resource types that translating into SPIR-V opaque
  4303. // types in structs, or assign to variables of resource types. These can all
  4304. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  4305. // let SPIRV-Tools opt to do the legalization work.
  4306. //
  4307. // Note: legalization specific code
  4308. theBuilder.createStore(lhsPtr, rhsVal);
  4309. needsLegalization = true;
  4310. } else if (TypeTranslator::isAKindOfStructuredOrByteBuffer(lhsValType)) {
  4311. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  4312. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  4313. // up.
  4314. //
  4315. // Note: legalization specific code
  4316. theBuilder.createStore(lhsPtr, rhsVal);
  4317. needsLegalization = true;
  4318. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  4319. // recursively like normal structs using the following logic.
  4320. //
  4321. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  4322. // variables as function parameters/returns/variables, but happily accepts
  4323. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  4324. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  4325. // represented differently as struct T.
  4326. } else if (TypeTranslator::isOpaqueArrayType(lhsValType)) {
  4327. // For opaque array types, we cannot perform OpLoad on the whole array and
  4328. // then write out as a whole; instead, we need to OpLoad each element
  4329. // using access chains. This is to influence later SPIR-V transformations
  4330. // to use access chains to access each opaque object; if we do array
  4331. // wholesale handling here, they will be in the final transformed code.
  4332. // Drivers don't like that.
  4333. // TODO: consider moving this hack into SPIRV-Tools as a transformation.
  4334. assert(lhsValType->isConstantArrayType());
  4335. assert(!rhsVal.isRValue());
  4336. const auto *arrayType = astContext.getAsConstantArrayType(lhsValType);
  4337. const auto elemType = arrayType->getElementType();
  4338. const auto arraySize =
  4339. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4340. // Do separate load of each element via access chain
  4341. llvm::SmallVector<uint32_t, 8> elements;
  4342. for (uint32_t i = 0; i < arraySize; ++i) {
  4343. const auto subRhsValType =
  4344. typeTranslator.translateType(elemType, rhsVal.getLayoutRule());
  4345. const auto subRhsPtrType =
  4346. theBuilder.getPointerType(subRhsValType, rhsVal.getStorageClass());
  4347. const auto subRhsPtr = theBuilder.createAccessChain(
  4348. subRhsPtrType, rhsVal, {theBuilder.getConstantInt32(i)});
  4349. elements.push_back(theBuilder.createLoad(subRhsValType, subRhsPtr));
  4350. }
  4351. // Create a new composite and write out once
  4352. const auto lhsValTypeId =
  4353. typeTranslator.translateType(lhsValType, lhsPtr.getLayoutRule());
  4354. theBuilder.createStore(
  4355. lhsPtr, theBuilder.createCompositeConstruct(lhsValTypeId, elements));
  4356. } else if (lhsPtr.getLayoutRule() == rhsVal.getLayoutRule()) {
  4357. // If lhs and rhs has the same memory layout, we should be safe to load
  4358. // from rhs and directly store into lhs and avoid decomposing rhs.
  4359. // Note: this check should happen after those setting needsLegalization.
  4360. // TODO: is this optimization always correct?
  4361. theBuilder.createStore(lhsPtr, rhsVal);
  4362. } else if (lhsValType->isRecordType() || lhsValType->isConstantArrayType() ||
  4363. lhsIsNonFpMat) {
  4364. theBuilder.createStore(
  4365. lhsPtr, reconstructValue(rhsVal, lhsValType, lhsPtr.getLayoutRule()));
  4366. } else {
  4367. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  4368. }
  4369. }
  4370. uint32_t SPIRVEmitter::reconstructValue(const SpirvEvalInfo &srcVal,
  4371. const QualType valType,
  4372. LayoutRule dstLR) {
  4373. // Lambda for casting scalar or vector of bool<-->uint in cases where one side
  4374. // of the reconstruction (lhs or rhs) has a layout rule.
  4375. const auto handleBooleanLayout = [this, &srcVal, dstLR](uint32_t val,
  4376. QualType valType) {
  4377. // We only need to cast if we have a scalar or vector of booleans.
  4378. if (!isBoolOrVecOfBoolType(valType))
  4379. return val;
  4380. LayoutRule srcLR = srcVal.getLayoutRule();
  4381. // Source value has a layout rule, and has therefore been represented
  4382. // as a uint. Cast it to boolean before using.
  4383. bool shouldCastToBool =
  4384. srcLR != LayoutRule::Void && dstLR == LayoutRule::Void;
  4385. // Destination has a layout rule, and should therefore be represented
  4386. // as a uint. Cast to uint before using.
  4387. bool shouldCastToUint =
  4388. srcLR == LayoutRule::Void && dstLR != LayoutRule::Void;
  4389. // No boolean layout issues to take care of.
  4390. if (!shouldCastToBool && !shouldCastToUint)
  4391. return val;
  4392. uint32_t vecSize = 1;
  4393. TypeTranslator::isVectorType(valType, nullptr, &vecSize);
  4394. QualType boolType =
  4395. vecSize == 1 ? astContext.BoolTy
  4396. : astContext.getExtVectorType(astContext.BoolTy, vecSize);
  4397. QualType uintType =
  4398. vecSize == 1
  4399. ? astContext.UnsignedIntTy
  4400. : astContext.getExtVectorType(astContext.UnsignedIntTy, vecSize);
  4401. if (shouldCastToBool)
  4402. return castToBool(val, uintType, boolType);
  4403. if (shouldCastToUint)
  4404. return castToInt(val, boolType, uintType, {});
  4405. return val;
  4406. };
  4407. // Lambda for cases where we want to reconstruct an array
  4408. const auto reconstructArray = [this, &srcVal, valType,
  4409. dstLR](uint32_t arraySize,
  4410. QualType arrayElemType) {
  4411. llvm::SmallVector<uint32_t, 4> elements;
  4412. for (uint32_t i = 0; i < arraySize; ++i) {
  4413. const auto subSrcValType =
  4414. typeTranslator.translateType(arrayElemType, srcVal.getLayoutRule());
  4415. const auto subSrcVal =
  4416. theBuilder.createCompositeExtract(subSrcValType, srcVal, {i});
  4417. elements.push_back(reconstructValue(srcVal.substResultId(subSrcVal),
  4418. arrayElemType, dstLR));
  4419. }
  4420. const auto dstValType = typeTranslator.translateType(valType, dstLR);
  4421. return theBuilder.createCompositeConstruct(dstValType, elements);
  4422. };
  4423. // Constant arrays
  4424. if (const auto *arrayType = astContext.getAsConstantArrayType(valType)) {
  4425. const auto elemType = arrayType->getElementType();
  4426. const auto size =
  4427. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  4428. return reconstructArray(size, elemType);
  4429. }
  4430. // Non-floating-point matrices
  4431. QualType matElemType = {};
  4432. uint32_t numRows = 0, numCols = 0;
  4433. const bool isNonFpMat =
  4434. typeTranslator.isMxNMatrix(valType, &matElemType, &numRows, &numCols) &&
  4435. !matElemType->isFloatingType();
  4436. if (isNonFpMat) {
  4437. // Note: This check should happen before the RecordType check.
  4438. // Non-fp matrices are represented as arrays of vectors in SPIR-V.
  4439. // Each array element is a vector. Get the QualType for the vector.
  4440. const auto elemType = astContext.getExtVectorType(matElemType, numCols);
  4441. return reconstructArray(numRows, elemType);
  4442. }
  4443. // Note: This check should happen before the RecordType check since
  4444. // vector/matrix/resource types are represented as RecordType in the AST.
  4445. if (hlsl::IsHLSLVecMatType(valType) || hlsl::IsHLSLResourceType(valType))
  4446. return handleBooleanLayout(srcVal, valType);
  4447. // Structs
  4448. if (const auto *recordType = valType->getAs<RecordType>()) {
  4449. uint32_t index = 0;
  4450. llvm::SmallVector<uint32_t, 4> elements;
  4451. for (const auto *field : recordType->getDecl()->fields()) {
  4452. const auto subSrcValType = typeTranslator.translateType(
  4453. field->getType(), srcVal.getLayoutRule());
  4454. const auto subSrcVal =
  4455. theBuilder.createCompositeExtract(subSrcValType, srcVal, {index});
  4456. elements.push_back(reconstructValue(srcVal.substResultId(subSrcVal),
  4457. field->getType(), dstLR));
  4458. ++index;
  4459. }
  4460. const auto dstValType = typeTranslator.translateType(valType, dstLR);
  4461. return theBuilder.createCompositeConstruct(dstValType, elements);
  4462. }
  4463. return handleBooleanLayout(srcVal, valType);
  4464. }
  4465. SpirvEvalInfo SPIRVEmitter::processBinaryOp(const Expr *lhs, const Expr *rhs,
  4466. const BinaryOperatorKind opcode,
  4467. const QualType computationType,
  4468. const QualType resultType,
  4469. SourceRange sourceRange,
  4470. SpirvEvalInfo *lhsInfo,
  4471. const spv::Op mandateGenOpcode) {
  4472. const QualType lhsType = lhs->getType();
  4473. const QualType rhsType = rhs->getType();
  4474. // Binary logical operations (such as ==, !=, etc) that return a boolean type
  4475. // may get a literal (e.g. 0, 1, etc.) as lhs or rhs args. Since only
  4476. // non-zero-ness of these literals matter, they can be translated as 32-bits.
  4477. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  4478. if (resultType->isBooleanType()) {
  4479. if (lhsType->isSpecificBuiltinType(BuiltinType::LitInt) ||
  4480. rhsType->isSpecificBuiltinType(BuiltinType::LitInt))
  4481. hint.setHint(astContext.IntTy);
  4482. if (lhsType->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  4483. rhsType->isSpecificBuiltinType(BuiltinType::LitFloat))
  4484. hint.setHint(astContext.FloatTy);
  4485. }
  4486. // If the operands are of matrix type, we need to dispatch the operation
  4487. // onto each element vector iff the operands are not degenerated matrices
  4488. // and we don't have a matrix specific SPIR-V instruction for the operation.
  4489. if (!isSpirvMatrixOp(mandateGenOpcode) &&
  4490. TypeTranslator::isMxNMatrix(lhsType)) {
  4491. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange);
  4492. }
  4493. // Comma operator works differently from other binary operations as there is
  4494. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  4495. // respectively, and return the results of rhs.
  4496. if (opcode == BO_Comma) {
  4497. (void)doExpr(lhs);
  4498. return doExpr(rhs);
  4499. }
  4500. SpirvEvalInfo rhsVal = 0, lhsPtr = 0, lhsVal = 0;
  4501. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4502. // Evalute rhs before lhs
  4503. rhsVal = loadIfGLValue(rhs);
  4504. lhsVal = lhsPtr = doExpr(lhs);
  4505. // This is a compound assignment. We need to load the lhs value if lhs
  4506. // is not already rvalue and does not generate a vector shuffle.
  4507. if (!lhsPtr.isRValue() && !isVectorShuffle(lhs)) {
  4508. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4509. }
  4510. // For a compound assignments, the AST does not have the proper implicit
  4511. // cast if lhs and rhs have different types. So we need to manually cast lhs
  4512. // to the computation type.
  4513. if (computationType != lhsType)
  4514. lhsVal.setResultId(
  4515. castToType(lhsVal, lhsType, computationType, lhs->getExprLoc()));
  4516. } else {
  4517. // Evalute lhs before rhs
  4518. lhsPtr = doExpr(lhs);
  4519. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4520. rhsVal = loadIfGLValue(rhs);
  4521. }
  4522. if (lhsInfo)
  4523. *lhsInfo = lhsPtr;
  4524. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  4525. ? translateOp(opcode, computationType)
  4526. : mandateGenOpcode;
  4527. switch (opcode) {
  4528. case BO_Shl:
  4529. case BO_Shr:
  4530. case BO_ShlAssign:
  4531. case BO_ShrAssign:
  4532. // We need to cull the RHS to make sure that we are not shifting by an
  4533. // amount that is larger than the bitwidth of the LHS.
  4534. rhsVal.setResultId(theBuilder.createBinaryOp(
  4535. spv::Op::OpBitwiseAnd, typeTranslator.translateType(computationType),
  4536. rhsVal, getMaskForBitwidthValue(rhsType)));
  4537. // Fall through
  4538. case BO_Add:
  4539. case BO_Sub:
  4540. case BO_Mul:
  4541. case BO_Div:
  4542. case BO_Rem:
  4543. case BO_LT:
  4544. case BO_LE:
  4545. case BO_GT:
  4546. case BO_GE:
  4547. case BO_EQ:
  4548. case BO_NE:
  4549. case BO_And:
  4550. case BO_Or:
  4551. case BO_Xor:
  4552. case BO_LAnd:
  4553. case BO_LOr:
  4554. case BO_AddAssign:
  4555. case BO_SubAssign:
  4556. case BO_MulAssign:
  4557. case BO_DivAssign:
  4558. case BO_RemAssign:
  4559. case BO_AndAssign:
  4560. case BO_OrAssign:
  4561. case BO_XorAssign: {
  4562. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  4563. // both operands are constant and at least one of them is a spec constant.
  4564. if (lhsVal.isConstant() && rhsVal.isConstant() &&
  4565. (lhsVal.isSpecConstant() || rhsVal.isSpecConstant()) &&
  4566. isAcceptedSpecConstantBinaryOp(spvOp)) {
  4567. const auto valId = theBuilder.createSpecConstantBinaryOp(
  4568. spvOp, typeTranslator.translateType(resultType), lhsVal, rhsVal);
  4569. return SpirvEvalInfo(valId).setRValue().setSpecConstant();
  4570. }
  4571. // Normal binary operation
  4572. uint32_t valId = 0;
  4573. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4574. valId = theBuilder.createBinaryOp(
  4575. spvOp, typeTranslator.translateType(computationType), lhsVal, rhsVal);
  4576. // For a compound assignments, the AST does not have the proper implicit
  4577. // cast if lhs and rhs have different types. So we need to manually cast
  4578. // the result back to lhs' type.
  4579. if (computationType != lhsType)
  4580. valId = castToType(valId, computationType, lhsType, lhs->getExprLoc());
  4581. } else {
  4582. valId = theBuilder.createBinaryOp(
  4583. spvOp, typeTranslator.translateType(resultType), lhsVal, rhsVal);
  4584. }
  4585. auto result = SpirvEvalInfo(valId).setRValue();
  4586. // Propagate RelaxedPrecision
  4587. if (lhsVal.isRelaxedPrecision() || rhsVal.isRelaxedPrecision())
  4588. result.setRelaxedPrecision();
  4589. // Propagate NonUniformEXT
  4590. if (lhsVal.isNonUniform() || rhsVal.isNonUniform())
  4591. result.setNonUniform();
  4592. return result;
  4593. }
  4594. case BO_Assign:
  4595. llvm_unreachable("assignment should not be handled here");
  4596. break;
  4597. case BO_PtrMemD:
  4598. case BO_PtrMemI:
  4599. case BO_Comma:
  4600. // Unimplemented
  4601. break;
  4602. }
  4603. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  4604. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  4605. return 0;
  4606. }
  4607. void SPIRVEmitter::initOnce(QualType varType, std::string varName,
  4608. uint32_t varPtr, const Expr *varInit) {
  4609. // For uninitialized resource objects, we do nothing since there is no
  4610. // meaningful zero values for them.
  4611. if (!varInit && hlsl::IsHLSLResourceType(varType))
  4612. return;
  4613. const uint32_t boolType = theBuilder.getBoolType();
  4614. varName = "init.done." + varName;
  4615. // Create a file/module visible variable to hold the initialization state.
  4616. const uint32_t initDoneVar =
  4617. theBuilder.addModuleVar(boolType, spv::StorageClass::Private, varName,
  4618. theBuilder.getConstantBool(false));
  4619. const uint32_t condition = theBuilder.createLoad(boolType, initDoneVar);
  4620. const uint32_t todoBB = theBuilder.createBasicBlock("if.init.todo");
  4621. const uint32_t doneBB = theBuilder.createBasicBlock("if.init.done");
  4622. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  4623. // jump to the "todo" basic block.
  4624. theBuilder.createConditionalBranch(condition, doneBB, todoBB, doneBB);
  4625. theBuilder.addSuccessor(todoBB);
  4626. theBuilder.addSuccessor(doneBB);
  4627. theBuilder.setMergeTarget(doneBB);
  4628. theBuilder.setInsertPoint(todoBB);
  4629. // Do initialization and mark done
  4630. if (varInit) {
  4631. storeValue(
  4632. // Static function variable are of private storage class
  4633. SpirvEvalInfo(varPtr).setStorageClass(spv::StorageClass::Private),
  4634. doExpr(varInit), varInit->getType());
  4635. } else {
  4636. const auto typeId = typeTranslator.translateType(varType);
  4637. theBuilder.createStore(varPtr, theBuilder.getConstantNull(typeId));
  4638. }
  4639. theBuilder.createStore(initDoneVar, theBuilder.getConstantBool(true));
  4640. theBuilder.createBranch(doneBB);
  4641. theBuilder.addSuccessor(doneBB);
  4642. theBuilder.setInsertPoint(doneBB);
  4643. }
  4644. bool SPIRVEmitter::isVectorShuffle(const Expr *expr) {
  4645. // TODO: the following check is essentially duplicated from
  4646. // doHLSLVectorElementExpr. Should unify them.
  4647. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  4648. const Expr *base = nullptr;
  4649. hlsl::VectorMemberAccessPositions accessor;
  4650. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  4651. const auto accessorSize = accessor.Count;
  4652. if (accessorSize == 1) {
  4653. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  4654. // such cases.
  4655. return false;
  4656. }
  4657. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  4658. if (accessorSize != baseSize)
  4659. return true;
  4660. for (uint32_t i = 0; i < accessorSize; ++i) {
  4661. uint32_t position;
  4662. accessor.GetPosition(i, &position);
  4663. if (position != i)
  4664. return true;
  4665. }
  4666. // Selecting exactly the original vector. No vector shuffle generated.
  4667. return false;
  4668. }
  4669. return false;
  4670. }
  4671. bool SPIRVEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  4672. const Expr **base,
  4673. const Expr **location,
  4674. const Expr **lod) {
  4675. if (!expr)
  4676. return false;
  4677. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  4678. const CXXOperatorCallExpr *outerExpr = expr;
  4679. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4680. return false;
  4681. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4682. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  4683. // Must have an inner operator[]
  4684. if (!innerExpr ||
  4685. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  4686. return false;
  4687. }
  4688. const Expr *innerArg0 =
  4689. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4690. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  4691. if (!memberExpr)
  4692. return false;
  4693. // Must be accessing the member named "mips" or "sample"
  4694. const auto &memberName =
  4695. memberExpr->getMemberNameInfo().getName().getAsString();
  4696. if (memberName != "mips" && memberName != "sample")
  4697. return false;
  4698. const Expr *object = memberExpr->getBase();
  4699. const auto objectType = object->getType();
  4700. if (!TypeTranslator::isTexture(objectType))
  4701. return false;
  4702. if (base)
  4703. *base = object;
  4704. if (lod)
  4705. *lod = innerExpr->getArg(1);
  4706. if (location)
  4707. *location = outerExpr->getArg(1);
  4708. return true;
  4709. }
  4710. bool SPIRVEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  4711. const Expr **base,
  4712. const Expr **index) {
  4713. if (!indexExpr)
  4714. return false;
  4715. // Must be operator[]
  4716. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4717. return false;
  4718. const Expr *object = indexExpr->getArg(0);
  4719. const auto objectType = object->getType();
  4720. if (TypeTranslator::isBuffer(objectType) ||
  4721. TypeTranslator::isRWBuffer(objectType) ||
  4722. TypeTranslator::isTexture(objectType) ||
  4723. TypeTranslator::isRWTexture(objectType)) {
  4724. if (base)
  4725. *base = object;
  4726. if (index)
  4727. *index = indexExpr->getArg(1);
  4728. return true;
  4729. }
  4730. return false;
  4731. }
  4732. void SPIRVEmitter::condenseVectorElementExpr(
  4733. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  4734. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  4735. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  4736. accessors.push_back(expr->getEncodedElementAccess());
  4737. // Recursively descending until we find the true base vector. In the
  4738. // meanwhile, collecting accessors in the reverse order.
  4739. *basePtr = expr->getBase();
  4740. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  4741. accessors.push_back(vecElemBase->getEncodedElementAccess());
  4742. *basePtr = vecElemBase->getBase();
  4743. }
  4744. *flattenedAccessor = accessors.back();
  4745. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  4746. const auto &currentAccessor = accessors[i];
  4747. // Apply the current level of accessor to the flattened accessor of all
  4748. // previous levels of ones.
  4749. hlsl::VectorMemberAccessPositions combinedAccessor;
  4750. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  4751. uint32_t currentPosition = 0;
  4752. currentAccessor.GetPosition(j, &currentPosition);
  4753. uint32_t previousPosition = 0;
  4754. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  4755. combinedAccessor.SetPosition(j, previousPosition);
  4756. }
  4757. combinedAccessor.Count = currentAccessor.Count;
  4758. combinedAccessor.IsValid =
  4759. flattenedAccessor->IsValid && currentAccessor.IsValid;
  4760. *flattenedAccessor = combinedAccessor;
  4761. }
  4762. }
  4763. SpirvEvalInfo SPIRVEmitter::createVectorSplat(const Expr *scalarExpr,
  4764. uint32_t size) {
  4765. bool isConstVal = false;
  4766. SpirvEvalInfo scalarVal = 0;
  4767. // Try to evaluate the element as constant first. If successful, then we
  4768. // can generate constant instructions for this vector splat.
  4769. if ((scalarVal = tryToEvaluateAsConst(scalarExpr))) {
  4770. isConstVal = true;
  4771. } else {
  4772. scalarVal = doExpr(scalarExpr);
  4773. }
  4774. if (size == 1) {
  4775. // Just return the scalar value for vector splat with size 1.
  4776. // Note that can be used as an lvalue, so we need to carry over
  4777. // the lvalueness for non-constant cases.
  4778. return isConstVal ? scalarVal.setConstant().setRValue() : scalarVal;
  4779. }
  4780. const uint32_t vecType = theBuilder.getVecType(
  4781. typeTranslator.translateType(scalarExpr->getType()), size);
  4782. llvm::SmallVector<uint32_t, 4> elements(size_t(size), scalarVal);
  4783. // TODO: we are saying the constant has Function storage class here.
  4784. // Should find a more meaningful one.
  4785. if (isConstVal) {
  4786. const auto valueId = theBuilder.getConstantComposite(vecType, elements);
  4787. return SpirvEvalInfo(valueId).setConstant().setRValue();
  4788. } else {
  4789. const auto valueId = theBuilder.createCompositeConstruct(vecType, elements);
  4790. return SpirvEvalInfo(valueId).setRValue();
  4791. }
  4792. }
  4793. void SPIRVEmitter::splitVecLastElement(QualType vecType, uint32_t vec,
  4794. uint32_t *residual,
  4795. uint32_t *lastElement) {
  4796. assert(hlsl::IsHLSLVecType(vecType));
  4797. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  4798. assert(count > 1);
  4799. const uint32_t elemTypeId =
  4800. typeTranslator.translateType(hlsl::GetHLSLVecElementType(vecType));
  4801. if (count == 2) {
  4802. *residual = theBuilder.createCompositeExtract(elemTypeId, vec, 0);
  4803. } else {
  4804. llvm::SmallVector<uint32_t, 4> indices;
  4805. for (uint32_t i = 0; i < count - 1; ++i)
  4806. indices.push_back(i);
  4807. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count - 1);
  4808. *residual = theBuilder.createVectorShuffle(typeId, vec, vec, indices);
  4809. }
  4810. *lastElement =
  4811. theBuilder.createCompositeExtract(elemTypeId, vec, {count - 1});
  4812. }
  4813. uint32_t SPIRVEmitter::convertVectorToStruct(QualType structType,
  4814. uint32_t elemTypeId,
  4815. uint32_t vector) {
  4816. assert(structType->isStructureType());
  4817. const auto *structDecl = structType->getAsStructureType()->getDecl();
  4818. uint32_t vectorIndex = 0;
  4819. uint32_t elemCount = 1;
  4820. llvm::SmallVector<uint32_t, 4> members;
  4821. for (const auto *field : structDecl->fields()) {
  4822. if (TypeTranslator::isScalarType(field->getType())) {
  4823. members.push_back(theBuilder.createCompositeExtract(elemTypeId, vector,
  4824. {vectorIndex++}));
  4825. } else if (TypeTranslator::isVectorType(field->getType(), nullptr,
  4826. &elemCount)) {
  4827. llvm::SmallVector<uint32_t, 4> indices;
  4828. for (uint32_t i = 0; i < elemCount; ++i)
  4829. indices.push_back(vectorIndex++);
  4830. const uint32_t type = theBuilder.getVecType(elemTypeId, elemCount);
  4831. members.push_back(
  4832. theBuilder.createVectorShuffle(type, vector, vector, indices));
  4833. } else {
  4834. assert(false && "unhandled type");
  4835. }
  4836. }
  4837. return theBuilder.createCompositeConstruct(
  4838. typeTranslator.translateType(structType), members);
  4839. }
  4840. SpirvEvalInfo
  4841. SPIRVEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  4842. const QualType type = expr->getType();
  4843. const SourceRange range = expr->getSourceRange();
  4844. // We can only translate floatN * float into OpVectorTimesScalar.
  4845. // So the result type must be floatN.
  4846. if (!hlsl::IsHLSLVecType(type) ||
  4847. !hlsl::GetHLSLVecElementType(type)->isFloatingType())
  4848. return 0;
  4849. const Expr *lhs = expr->getLHS();
  4850. const Expr *rhs = expr->getRHS();
  4851. // Multiplying a float vector with a float scalar will be represented in
  4852. // AST via a binary operation with two float vectors as operands; one of
  4853. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  4854. // vector * scalar
  4855. if (hlsl::IsHLSLVecType(lhs->getType())) {
  4856. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4857. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4858. const QualType vecType = expr->getType();
  4859. if (isa<CompoundAssignOperator>(expr)) {
  4860. SpirvEvalInfo lhsPtr = 0;
  4861. const auto result = processBinaryOp(
  4862. lhs, cast->getSubExpr(), expr->getOpcode(), vecType, vecType,
  4863. range, &lhsPtr, spv::Op::OpVectorTimesScalar);
  4864. return processAssignment(lhs, result, true, lhsPtr);
  4865. } else {
  4866. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4867. vecType, vecType, range, nullptr,
  4868. spv::Op::OpVectorTimesScalar);
  4869. }
  4870. }
  4871. }
  4872. }
  4873. // scalar * vector
  4874. if (hlsl::IsHLSLVecType(rhs->getType())) {
  4875. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4876. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4877. const QualType vecType = expr->getType();
  4878. // We need to switch the positions of lhs and rhs here because
  4879. // OpVectorTimesScalar requires the first operand to be a vector and
  4880. // the second to be a scalar.
  4881. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4882. vecType, vecType, range, nullptr,
  4883. spv::Op::OpVectorTimesScalar);
  4884. }
  4885. }
  4886. }
  4887. return 0;
  4888. }
  4889. SpirvEvalInfo
  4890. SPIRVEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  4891. const QualType type = expr->getType();
  4892. const SourceRange range = expr->getSourceRange();
  4893. // We can only translate floatMxN * float into OpMatrixTimesScalar.
  4894. // So the result type must be floatMxN.
  4895. if (!hlsl::IsHLSLMatType(type) ||
  4896. !hlsl::GetHLSLMatElementType(type)->isFloatingType())
  4897. return 0;
  4898. const Expr *lhs = expr->getLHS();
  4899. const Expr *rhs = expr->getRHS();
  4900. const QualType lhsType = lhs->getType();
  4901. const QualType rhsType = rhs->getType();
  4902. const auto selectOpcode = [](const QualType ty) {
  4903. return TypeTranslator::isMx1Matrix(ty) || TypeTranslator::is1xNMatrix(ty)
  4904. ? spv::Op::OpVectorTimesScalar
  4905. : spv::Op::OpMatrixTimesScalar;
  4906. };
  4907. // Multiplying a float matrix with a float scalar will be represented in
  4908. // AST via a binary operation with two float matrices as operands; one of
  4909. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  4910. // matrix * scalar
  4911. if (hlsl::IsHLSLMatType(lhsType)) {
  4912. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4913. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4914. const QualType matType = expr->getType();
  4915. const spv::Op opcode = selectOpcode(lhsType);
  4916. if (isa<CompoundAssignOperator>(expr)) {
  4917. SpirvEvalInfo lhsPtr = 0;
  4918. const auto result =
  4919. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4920. matType, matType, range, &lhsPtr, opcode);
  4921. return processAssignment(lhs, result, true, lhsPtr);
  4922. } else {
  4923. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4924. matType, matType, range, nullptr, opcode);
  4925. }
  4926. }
  4927. }
  4928. }
  4929. // scalar * matrix
  4930. if (hlsl::IsHLSLMatType(rhsType)) {
  4931. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4932. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4933. const QualType matType = expr->getType();
  4934. const spv::Op opcode = selectOpcode(rhsType);
  4935. // We need to switch the positions of lhs and rhs here because
  4936. // OpMatrixTimesScalar requires the first operand to be a matrix and
  4937. // the second to be a scalar.
  4938. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4939. matType, matType, range, nullptr, opcode);
  4940. }
  4941. }
  4942. }
  4943. return 0;
  4944. }
  4945. SpirvEvalInfo
  4946. SPIRVEmitter::tryToAssignToVectorElements(const Expr *lhs,
  4947. const SpirvEvalInfo &rhs) {
  4948. // Assigning to a vector swizzling lhs is tricky if we are neither
  4949. // writing to one element nor all elements in their original order.
  4950. // Under such cases, we need to create a new vector swizzling involving
  4951. // both the lhs and rhs vectors and then write the result of this swizzling
  4952. // into the base vector of lhs.
  4953. // For example, for vec4.yz = vec2, we nee to do the following:
  4954. //
  4955. // %vec4Val = OpLoad %v4float %vec4
  4956. // %vec2Val = OpLoad %v2float %vec2
  4957. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  4958. // OpStore %vec4 %shuffle
  4959. //
  4960. // When doing the vector shuffle, we use the lhs base vector as the first
  4961. // vector and the rhs vector as the second vector. Therefore, all elements
  4962. // in the second vector will be selected into the shuffle result.
  4963. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  4964. if (!lhsExpr)
  4965. return 0;
  4966. // Special case for <scalar-value>.x, which will have an AST of
  4967. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  4968. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  4969. // for such case.
  4970. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  4971. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  4972. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  4973. return processAssignment(baseCast->getSubExpr(), rhs, false);
  4974. const Expr *base = nullptr;
  4975. hlsl::VectorMemberAccessPositions accessor;
  4976. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  4977. const QualType baseType = base->getType();
  4978. assert(hlsl::IsHLSLVecType(baseType));
  4979. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  4980. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4981. const auto accessorSize = accessor.Count;
  4982. // Whether selecting the whole original vector
  4983. bool isSelectOrigin = accessorSize == baseSize;
  4984. // Assigning to one component
  4985. if (accessorSize == 1) {
  4986. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  4987. // Assigning to one component of a RWBuffer/RWTexture element
  4988. // We need to use OpImageWrite here.
  4989. // Compose the new vector value first
  4990. const uint32_t oldVec = doExpr(base);
  4991. const uint32_t newVec = theBuilder.createCompositeInsert(
  4992. baseTypeId, oldVec, {accessor.Swz0}, rhs);
  4993. const auto result = tryToAssignToRWBufferRWTexture(base, newVec);
  4994. assert(result); // Definitely RWBuffer/RWTexture assignment
  4995. (void)result;
  4996. return rhs; // TODO: incorrect for compound assignments
  4997. } else {
  4998. // Assigning to one normal vector component. Nothing special, just fall
  4999. // back to the normal CodeGen path.
  5000. return 0;
  5001. }
  5002. }
  5003. if (isSelectOrigin) {
  5004. for (uint32_t i = 0; i < accessorSize; ++i) {
  5005. uint32_t position;
  5006. accessor.GetPosition(i, &position);
  5007. if (position != i)
  5008. isSelectOrigin = false;
  5009. }
  5010. }
  5011. // Assigning to the original vector
  5012. if (isSelectOrigin) {
  5013. // Ignore this HLSLVectorElementExpr and dispatch to base
  5014. return processAssignment(base, rhs, false);
  5015. }
  5016. llvm::SmallVector<uint32_t, 4> selectors;
  5017. selectors.resize(baseSize);
  5018. // Assume we are selecting all original elements first.
  5019. for (uint32_t i = 0; i < baseSize; ++i) {
  5020. selectors[i] = i;
  5021. }
  5022. // Now fix up the elements that actually got overwritten by the rhs vector.
  5023. // Since we are using the rhs vector as the second vector, their index
  5024. // should be offset'ed by the size of the lhs base vector.
  5025. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5026. uint32_t position;
  5027. accessor.GetPosition(i, &position);
  5028. selectors[position] = baseSize + i;
  5029. }
  5030. const auto vec1 = doExpr(base);
  5031. const uint32_t vec1Val = vec1.isRValue()
  5032. ? static_cast<uint32_t>(vec1)
  5033. : theBuilder.createLoad(baseTypeId, vec1);
  5034. const uint32_t shuffle =
  5035. theBuilder.createVectorShuffle(baseTypeId, vec1Val, rhs, selectors);
  5036. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  5037. theBuilder.createStore(vec1, shuffle);
  5038. // TODO: OK, this return value is incorrect for compound assignments, for
  5039. // which cases we should return lvalues. Should at least emit errors if
  5040. // this return value is used (can be checked via ASTContext.getParents).
  5041. return rhs;
  5042. }
  5043. SpirvEvalInfo
  5044. SPIRVEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  5045. const SpirvEvalInfo &rhs) {
  5046. const Expr *baseExpr = nullptr;
  5047. const Expr *indexExpr = nullptr;
  5048. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  5049. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  5050. const uint32_t locId = doExpr(indexExpr);
  5051. const QualType imageType = baseExpr->getType();
  5052. const auto baseInfo = doExpr(baseExpr);
  5053. const uint32_t imageId = theBuilder.createLoad(
  5054. typeTranslator.translateType(imageType), baseInfo);
  5055. theBuilder.createImageWrite(imageType, imageId, locId, rhs);
  5056. if (baseInfo.isNonUniform()) {
  5057. // Decorate the image handle for OpImageWrite
  5058. theBuilder.decorateNonUniformEXT(imageId);
  5059. }
  5060. return rhs;
  5061. }
  5062. return 0;
  5063. }
  5064. SpirvEvalInfo
  5065. SPIRVEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  5066. const SpirvEvalInfo &rhs) {
  5067. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  5068. if (!lhsExpr)
  5069. return 0;
  5070. const Expr *baseMat = lhsExpr->getBase();
  5071. const auto base = doExpr(baseMat);
  5072. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  5073. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  5074. uint32_t rowCount = 0, colCount = 0;
  5075. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  5076. // For each lhs element written to:
  5077. // 1. Extract the corresponding rhs element using OpCompositeExtract
  5078. // 2. Create access chain for the lhs element using OpAccessChain
  5079. // 3. Write using OpStore
  5080. const auto accessor = lhsExpr->getEncodedElementAccess();
  5081. for (uint32_t i = 0; i < accessor.Count; ++i) {
  5082. uint32_t row = 0, col = 0;
  5083. accessor.GetPosition(i, &row, &col);
  5084. llvm::SmallVector<uint32_t, 2> indices;
  5085. // If the matrix only have one row/column, we are indexing into a vector
  5086. // then. Only one index is needed for such cases.
  5087. if (rowCount > 1)
  5088. indices.push_back(row);
  5089. if (colCount > 1)
  5090. indices.push_back(col);
  5091. for (uint32_t i = 0; i < indices.size(); ++i)
  5092. indices[i] = theBuilder.getConstantInt32(indices[i]);
  5093. // If we are writing to only one element, the rhs should already be a
  5094. // scalar value.
  5095. uint32_t rhsElem = rhs;
  5096. if (accessor.Count > 1)
  5097. rhsElem = theBuilder.createCompositeExtract(elemTypeId, rhs, {i});
  5098. const uint32_t ptrType =
  5099. theBuilder.getPointerType(elemTypeId, base.getStorageClass());
  5100. // If the lhs is actually a matrix of size 1x1, we don't need the access
  5101. // chain. base is already the dest pointer.
  5102. uint32_t lhsElemPtr = base;
  5103. if (!indices.empty()) {
  5104. assert(!base.isRValue());
  5105. // Load the element via access chain
  5106. lhsElemPtr = theBuilder.createAccessChain(ptrType, lhsElemPtr, indices);
  5107. }
  5108. theBuilder.createStore(lhsElemPtr, rhsElem);
  5109. }
  5110. // TODO: OK, this return value is incorrect for compound assignments, for
  5111. // which cases we should return lvalues. Should at least emit errors if
  5112. // this return value is used (can be checked via ASTContext.getParents).
  5113. return rhs;
  5114. }
  5115. SpirvEvalInfo SPIRVEmitter::processEachVectorInMatrix(
  5116. const Expr *matrix, const uint32_t matrixVal,
  5117. llvm::function_ref<uint32_t(uint32_t, uint32_t, uint32_t)>
  5118. actOnEachVector) {
  5119. const auto matType = matrix->getType();
  5120. assert(TypeTranslator::isMxNMatrix(matType));
  5121. const uint32_t vecType = typeTranslator.getComponentVectorType(matType);
  5122. uint32_t rowCount = 0, colCount = 0;
  5123. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  5124. llvm::SmallVector<uint32_t, 4> vectors;
  5125. // Extract each component vector and do operation on it
  5126. for (uint32_t i = 0; i < rowCount; ++i) {
  5127. const uint32_t lhsVec =
  5128. theBuilder.createCompositeExtract(vecType, matrixVal, {i});
  5129. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  5130. }
  5131. // Construct the result matrix
  5132. const auto valId = theBuilder.createCompositeConstruct(
  5133. typeTranslator.translateType(matType), vectors);
  5134. return SpirvEvalInfo(valId).setRValue();
  5135. }
  5136. void SPIRVEmitter::createSpecConstant(const VarDecl *varDecl) {
  5137. class SpecConstantEnvRAII {
  5138. public:
  5139. // Creates a new instance which sets mode to true on creation,
  5140. // and resets mode to false on destruction.
  5141. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  5142. ~SpecConstantEnvRAII() { *modeSlot = false; }
  5143. private:
  5144. bool *modeSlot;
  5145. };
  5146. const QualType varType = varDecl->getType();
  5147. bool hasError = false;
  5148. if (!varDecl->isExternallyVisible()) {
  5149. emitError("specialization constant must be externally visible",
  5150. varDecl->getLocation());
  5151. hasError = true;
  5152. }
  5153. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  5154. switch (builtinType->getKind()) {
  5155. case BuiltinType::Bool:
  5156. case BuiltinType::Int:
  5157. case BuiltinType::UInt:
  5158. case BuiltinType::Float:
  5159. break;
  5160. default:
  5161. emitError("unsupported specialization constant type",
  5162. varDecl->getLocStart());
  5163. hasError = true;
  5164. }
  5165. }
  5166. const auto *init = varDecl->getInit();
  5167. if (!init) {
  5168. emitError("missing default value for specialization constant",
  5169. varDecl->getLocation());
  5170. hasError = true;
  5171. } else if (!isAcceptedSpecConstantInit(init)) {
  5172. emitError("unsupported specialization constant initializer",
  5173. init->getLocStart())
  5174. << init->getSourceRange();
  5175. hasError = true;
  5176. }
  5177. if (hasError)
  5178. return;
  5179. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  5180. const auto specConstant = doExpr(init);
  5181. // We are not creating a variable to hold the spec constant, instead, we
  5182. // translate the varDecl directly into the spec constant here.
  5183. theBuilder.decorateSpecId(
  5184. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId());
  5185. declIdMapper.registerSpecConstant(varDecl, specConstant);
  5186. }
  5187. SpirvEvalInfo
  5188. SPIRVEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  5189. const BinaryOperatorKind opcode,
  5190. SourceRange range) {
  5191. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  5192. const auto lhsType = lhs->getType();
  5193. assert(TypeTranslator::isMxNMatrix(lhsType));
  5194. const spv::Op spvOp = translateOp(opcode, lhsType);
  5195. uint32_t rhsVal, lhsPtr, lhsVal;
  5196. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  5197. // Evalute rhs before lhs
  5198. rhsVal = doExpr(rhs);
  5199. lhsPtr = doExpr(lhs);
  5200. const uint32_t lhsTy = typeTranslator.translateType(lhsType);
  5201. lhsVal = theBuilder.createLoad(lhsTy, lhsPtr);
  5202. } else {
  5203. // Evalute lhs before rhs
  5204. lhsVal = lhsPtr = doExpr(lhs);
  5205. rhsVal = doExpr(rhs);
  5206. }
  5207. switch (opcode) {
  5208. case BO_Add:
  5209. case BO_Sub:
  5210. case BO_Mul:
  5211. case BO_Div:
  5212. case BO_Rem:
  5213. case BO_AddAssign:
  5214. case BO_SubAssign:
  5215. case BO_MulAssign:
  5216. case BO_DivAssign:
  5217. case BO_RemAssign: {
  5218. const auto actOnEachVec = [this, spvOp, rhsVal](uint32_t index,
  5219. uint32_t vecType,
  5220. uint32_t lhsVec) {
  5221. // For each vector of lhs, we need to load the corresponding vector of
  5222. // rhs and do the operation on them.
  5223. const uint32_t rhsVec =
  5224. theBuilder.createCompositeExtract(vecType, rhsVal, {index});
  5225. const auto valId =
  5226. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec);
  5227. return SpirvEvalInfo(valId).setRValue();
  5228. };
  5229. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec);
  5230. }
  5231. case BO_Assign:
  5232. llvm_unreachable("assignment should not be handled here");
  5233. default:
  5234. break;
  5235. }
  5236. emitError("binary operator '%0' over matrix type unimplemented",
  5237. lhs->getExprLoc())
  5238. << BinaryOperator::getOpcodeStr(opcode) << range;
  5239. return 0;
  5240. }
  5241. const Expr *SPIRVEmitter::collectArrayStructIndices(
  5242. const Expr *expr, llvm::SmallVectorImpl<uint32_t> *indices, bool rawIndex) {
  5243. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  5244. // First check whether this is referring to a static member. If it is, we
  5245. // create a DeclRefExpr for it.
  5246. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  5247. if (varDecl->isStaticDataMember())
  5248. return DeclRefExpr::Create(
  5249. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  5250. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  5251. varDecl->getType(), VK_LValue);
  5252. const Expr *base = collectArrayStructIndices(
  5253. indexing->getBase()->IgnoreParenNoopCasts(astContext), indices,
  5254. rawIndex);
  5255. // Append the index of the current level
  5256. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  5257. assert(fieldDecl);
  5258. // If we are accessing a derived struct, we need to account for the number
  5259. // of base structs, since they are placed as fields at the beginning of the
  5260. // derived struct.
  5261. const uint32_t index = getNumBaseClasses(indexing->getBase()->getType()) +
  5262. fieldDecl->getFieldIndex();
  5263. indices->push_back(rawIndex ? index : theBuilder.getConstantInt32(index));
  5264. return base;
  5265. }
  5266. // Provide a hint to the TypeTranslator that the integer literal used to
  5267. // index into the following cases should be translated as a 32-bit integer.
  5268. TypeTranslator::LiteralTypeHint hint(typeTranslator, astContext.IntTy);
  5269. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  5270. if (rawIndex)
  5271. return nullptr; // TODO: handle constant array index
  5272. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  5273. // cast. We need to ingore it to avoid creating OpLoad.
  5274. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  5275. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  5276. indices->push_back(doExpr(indexing->getIdx()));
  5277. return base;
  5278. }
  5279. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  5280. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  5281. if (rawIndex)
  5282. return nullptr; // TODO: handle constant array index
  5283. // If this is indexing into resources, we need specific OpImage*
  5284. // instructions for accessing. Return directly to avoid further building
  5285. // up the access chain.
  5286. if (isBufferTextureIndexing(indexing))
  5287. return indexing;
  5288. const Expr *thisBase =
  5289. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  5290. const auto thisBaseType = thisBase->getType();
  5291. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  5292. if (thisBaseType != base->getType() &&
  5293. TypeTranslator::isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  5294. // The immediate base is a kind of structured or byte buffer. It should
  5295. // be an alias variable. Break the normal index collecting chain.
  5296. // Return the immediate base as the base so that we can apply other
  5297. // hacks for legalization over it.
  5298. //
  5299. // Note: legalization specific code
  5300. indices->clear();
  5301. base = thisBase;
  5302. }
  5303. // If the base is a StructureType, we need to push an addtional index 0
  5304. // here. This is because we created an additional OpTypeRuntimeArray
  5305. // in the structure.
  5306. if (TypeTranslator::isStructuredBuffer(thisBaseType))
  5307. indices->push_back(theBuilder.getConstantInt32(0));
  5308. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  5309. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  5310. typeTranslator.is1x1Matrix(thisBaseType) ||
  5311. typeTranslator.is1xNMatrix(thisBaseType)) {
  5312. // If this is a size-1 vector or 1xN matrix, ignore the index.
  5313. } else {
  5314. indices->push_back(doExpr(indexing->getArg(1)));
  5315. }
  5316. return base;
  5317. }
  5318. {
  5319. const Expr *index = nullptr;
  5320. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  5321. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  5322. if (rawIndex)
  5323. return nullptr; // TODO: handle constant array index
  5324. // For object.Load(index), there should be no more indexing into the
  5325. // object.
  5326. indices->push_back(theBuilder.getConstantInt32(0));
  5327. indices->push_back(doExpr(index));
  5328. return object;
  5329. }
  5330. }
  5331. // This the deepest we can go. No more array or struct indexing.
  5332. return expr;
  5333. }
  5334. SpirvEvalInfo &SPIRVEmitter::turnIntoElementPtr(
  5335. QualType baseType, SpirvEvalInfo &base, QualType elemType,
  5336. const llvm::SmallVector<uint32_t, 4> &indices) {
  5337. // If this is a rvalue, we need a temporary object to hold it
  5338. // so that we can get access chain from it.
  5339. const bool needTempVar = base.isRValue();
  5340. if (needTempVar) {
  5341. auto varName = TypeTranslator::getName(baseType);
  5342. const auto var = createTemporaryVar(baseType, varName, base);
  5343. base.setResultId(var)
  5344. .setLayoutRule(LayoutRule::Void)
  5345. .setStorageClass(spv::StorageClass::Function);
  5346. }
  5347. const uint32_t elemTypeId =
  5348. typeTranslator.translateType(elemType, base.getLayoutRule());
  5349. const uint32_t ptrType =
  5350. theBuilder.getPointerType(elemTypeId, base.getStorageClass());
  5351. base.setResultId(theBuilder.createAccessChain(ptrType, base, indices));
  5352. // Okay, this part seems weird, but it is intended:
  5353. // If the base is originally a rvalue, the whole AST involving the base
  5354. // is consistently set up to handle rvalues. By copying the base into
  5355. // a temporary variable and grab an access chain from it, we are breaking
  5356. // the consistency by turning the base from rvalue into lvalue. Keep in
  5357. // mind that there will be no LValueToRValue casts in the AST for us
  5358. // to rely on to load the access chain if a rvalue is expected. Therefore,
  5359. // we must do the load here. Otherwise, it's up to the consumer of this
  5360. // access chain to do the load, and that can be everywhere.
  5361. if (needTempVar) {
  5362. base.setResultId(theBuilder.createLoad(elemTypeId, base));
  5363. }
  5364. return base;
  5365. }
  5366. uint32_t SPIRVEmitter::castToBool(const uint32_t fromVal, QualType fromType,
  5367. QualType toBoolType) {
  5368. if (TypeTranslator::isSameScalarOrVecType(fromType, toBoolType))
  5369. return fromVal;
  5370. const uint32_t boolType = typeTranslator.translateType(toBoolType);
  5371. { // Special case handling for converting to a matrix of booleans.
  5372. QualType elemType = {};
  5373. uint32_t rowCount = 0, colCount = 0;
  5374. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &rowCount,
  5375. &colCount)) {
  5376. const auto fromRowQualType =
  5377. astContext.getExtVectorType(elemType, colCount);
  5378. const auto fromRowQualTypeId =
  5379. typeTranslator.translateType(fromRowQualType);
  5380. const auto toBoolRowQualType =
  5381. astContext.getExtVectorType(astContext.BoolTy, colCount);
  5382. llvm::SmallVector<uint32_t, 4> rows;
  5383. for (uint32_t i = 0; i < rowCount; ++i) {
  5384. const auto row =
  5385. theBuilder.createCompositeExtract(fromRowQualTypeId, fromVal, {i});
  5386. rows.push_back(castToBool(row, fromRowQualType, toBoolRowQualType));
  5387. }
  5388. return theBuilder.createCompositeConstruct(boolType, rows);
  5389. }
  5390. }
  5391. // Converting to bool means comparing with value zero.
  5392. const spv::Op spvOp = translateOp(BO_NE, fromType);
  5393. const uint32_t zeroVal = getValueZero(fromType);
  5394. return theBuilder.createBinaryOp(spvOp, boolType, fromVal, zeroVal);
  5395. }
  5396. uint32_t SPIRVEmitter::castToInt(uint32_t fromVal, QualType fromType,
  5397. QualType toIntType, SourceLocation srcLoc) {
  5398. if (TypeTranslator::isSameScalarOrVecType(fromType, toIntType))
  5399. return fromVal;
  5400. uint32_t intType = typeTranslator.translateType(toIntType);
  5401. if (isBoolOrVecOfBoolType(fromType)) {
  5402. const uint32_t one = getValueOne(toIntType);
  5403. const uint32_t zero = getValueZero(toIntType);
  5404. return theBuilder.createSelect(intType, fromVal, one, zero);
  5405. }
  5406. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  5407. // First convert the source to the bitwidth of the destination if necessary.
  5408. uint32_t convertedType = 0;
  5409. fromVal = convertBitwidth(fromVal, fromType, toIntType, &convertedType);
  5410. // If bitwidth conversion was the only thing we needed to do, we're done.
  5411. if (convertedType == typeTranslator.translateType(toIntType))
  5412. return fromVal;
  5413. return theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, fromVal);
  5414. }
  5415. if (isFloatOrVecOfFloatType(fromType)) {
  5416. // First convert the source to the bitwidth of the destination if necessary.
  5417. fromVal = convertBitwidth(fromVal, fromType, toIntType);
  5418. if (isSintOrVecOfSintType(toIntType)) {
  5419. return theBuilder.createUnaryOp(spv::Op::OpConvertFToS, intType, fromVal);
  5420. } else if (isUintOrVecOfUintType(toIntType)) {
  5421. return theBuilder.createUnaryOp(spv::Op::OpConvertFToU, intType, fromVal);
  5422. } else {
  5423. emitError("casting from floating point to integer unimplemented", srcLoc);
  5424. }
  5425. }
  5426. {
  5427. QualType elemType = {};
  5428. uint32_t numRows = 0, numCols = 0;
  5429. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5430. // The source matrix and the target matrix must have the same dimensions.
  5431. QualType toElemType = {};
  5432. uint32_t toNumRows = 0, toNumCols = 0;
  5433. const bool isMat = TypeTranslator::isMxNMatrix(toIntType, &toElemType,
  5434. &toNumRows, &toNumCols);
  5435. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5436. (void)isMat;
  5437. (void)toNumRows;
  5438. (void)toNumCols;
  5439. // Casting to a matrix of integers: Cast each row and construct a
  5440. // composite.
  5441. llvm::SmallVector<uint32_t, 4> castedRows;
  5442. const uint32_t vecType = typeTranslator.getComponentVectorType(fromType);
  5443. const auto fromVecQualType =
  5444. astContext.getExtVectorType(elemType, numCols);
  5445. const auto toIntVecQualType =
  5446. astContext.getExtVectorType(toElemType, numCols);
  5447. for (uint32_t row = 0; row < numRows; ++row) {
  5448. const auto rowId =
  5449. theBuilder.createCompositeExtract(vecType, fromVal, {row});
  5450. castedRows.push_back(
  5451. castToInt(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5452. }
  5453. return theBuilder.createCompositeConstruct(intType, castedRows);
  5454. }
  5455. }
  5456. return 0;
  5457. }
  5458. uint32_t SPIRVEmitter::convertBitwidth(uint32_t fromVal, QualType fromType,
  5459. QualType toType, uint32_t *resultType) {
  5460. // At the moment, we will not make bitwidth conversions for literal int and
  5461. // literal float types because they always indicate 64-bit and do not
  5462. // represent what SPIR-V was actually resolved to.
  5463. // TODO: If the evaluated type is added to SpirvEvalInfo, change 'fromVal' to
  5464. // SpirvEvalInfo and use it to handle literal types more accurately.
  5465. if (fromType->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  5466. fromType->isSpecificBuiltinType(BuiltinType::LitInt))
  5467. return fromVal;
  5468. const auto fromBitwidth = typeTranslator.getElementSpirvBitwidth(fromType);
  5469. const auto toBitwidth = typeTranslator.getElementSpirvBitwidth(toType);
  5470. if (fromBitwidth == toBitwidth) {
  5471. if (resultType)
  5472. *resultType = typeTranslator.translateType(fromType);
  5473. return fromVal;
  5474. }
  5475. // We want the 'fromType' with the 'toBitwidth'.
  5476. const uint32_t targetTypeId =
  5477. typeTranslator.getTypeWithCustomBitwidth(fromType, toBitwidth);
  5478. if (resultType)
  5479. *resultType = targetTypeId;
  5480. if (isFloatOrVecOfFloatType(fromType))
  5481. return theBuilder.createUnaryOp(spv::Op::OpFConvert, targetTypeId, fromVal);
  5482. if (isSintOrVecOfSintType(fromType))
  5483. return theBuilder.createUnaryOp(spv::Op::OpSConvert, targetTypeId, fromVal);
  5484. if (isUintOrVecOfUintType(fromType))
  5485. return theBuilder.createUnaryOp(spv::Op::OpUConvert, targetTypeId, fromVal);
  5486. llvm_unreachable("invalid type passed to convertBitwidth");
  5487. }
  5488. uint32_t SPIRVEmitter::castToFloat(uint32_t fromVal, QualType fromType,
  5489. QualType toFloatType,
  5490. SourceLocation srcLoc) {
  5491. if (TypeTranslator::isSameScalarOrVecType(fromType, toFloatType))
  5492. return fromVal;
  5493. const uint32_t floatType = typeTranslator.translateType(toFloatType);
  5494. if (isBoolOrVecOfBoolType(fromType)) {
  5495. const uint32_t one = getValueOne(toFloatType);
  5496. const uint32_t zero = getValueZero(toFloatType);
  5497. return theBuilder.createSelect(floatType, fromVal, one, zero);
  5498. }
  5499. if (isSintOrVecOfSintType(fromType)) {
  5500. // First convert the source to the bitwidth of the destination if necessary.
  5501. fromVal = convertBitwidth(fromVal, fromType, toFloatType);
  5502. return theBuilder.createUnaryOp(spv::Op::OpConvertSToF, floatType, fromVal);
  5503. }
  5504. if (isUintOrVecOfUintType(fromType)) {
  5505. // First convert the source to the bitwidth of the destination if necessary.
  5506. fromVal = convertBitwidth(fromVal, fromType, toFloatType);
  5507. return theBuilder.createUnaryOp(spv::Op::OpConvertUToF, floatType, fromVal);
  5508. }
  5509. if (isFloatOrVecOfFloatType(fromType)) {
  5510. // This is the case of float to float conversion with different bitwidths.
  5511. return convertBitwidth(fromVal, fromType, toFloatType);
  5512. }
  5513. // Casting matrix types
  5514. {
  5515. QualType elemType = {};
  5516. uint32_t numRows = 0, numCols = 0;
  5517. if (TypeTranslator::isMxNMatrix(fromType, &elemType, &numRows, &numCols)) {
  5518. // The source matrix and the target matrix must have the same dimensions.
  5519. QualType toElemType = {};
  5520. uint32_t toNumRows = 0, toNumCols = 0;
  5521. const auto isMat = TypeTranslator::isMxNMatrix(toFloatType, &toElemType,
  5522. &toNumRows, &toNumCols);
  5523. assert(isMat && numRows == toNumRows && numCols == toNumCols);
  5524. (void)isMat;
  5525. (void)toNumRows;
  5526. (void)toNumCols;
  5527. // Casting to a matrix of floats: Cast each row and construct a
  5528. // composite.
  5529. llvm::SmallVector<uint32_t, 4> castedRows;
  5530. const uint32_t vecType = typeTranslator.getComponentVectorType(fromType);
  5531. const auto fromVecQualType =
  5532. astContext.getExtVectorType(elemType, numCols);
  5533. const auto toIntVecQualType =
  5534. astContext.getExtVectorType(toElemType, numCols);
  5535. for (uint32_t row = 0; row < numRows; ++row) {
  5536. const auto rowId =
  5537. theBuilder.createCompositeExtract(vecType, fromVal, {row});
  5538. castedRows.push_back(
  5539. castToFloat(rowId, fromVecQualType, toIntVecQualType, srcLoc));
  5540. }
  5541. return theBuilder.createCompositeConstruct(floatType, castedRows);
  5542. }
  5543. }
  5544. emitError("casting to floating point unimplemented", srcLoc);
  5545. return 0;
  5546. }
  5547. SpirvEvalInfo SPIRVEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  5548. const FunctionDecl *callee = callExpr->getDirectCallee();
  5549. assert(hlsl::IsIntrinsicOp(callee) &&
  5550. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  5551. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  5552. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  5553. // Figure out which intrinsic function to translate.
  5554. llvm::StringRef group;
  5555. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  5556. hlsl::GetIntrinsicOp(callee, opcode, group);
  5557. GLSLstd450 glslOpcode = GLSLstd450Bad;
  5558. uint32_t retVal = 0;
  5559. #define INTRINSIC_SPIRV_OP_WITH_CAP_CASE(intrinsicOp, spirvOp, doEachVec, cap) \
  5560. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5561. theBuilder.requireCapability(cap); \
  5562. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  5563. doEachVec); \
  5564. } break
  5565. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  5566. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5567. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  5568. doEachVec); \
  5569. } break
  5570. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  5571. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5572. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  5573. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5574. } break
  5575. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  5576. doEachVec) \
  5577. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5578. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  5579. : GLSLstd450::GLSLstd450##glslIntOp; \
  5580. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5581. } break
  5582. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  5583. doEachVec) \
  5584. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5585. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  5586. : GLSLstd450::GLSLstd450##glslUintOp; \
  5587. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5588. } break
  5589. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  5590. glslFloatOp, doEachVec) \
  5591. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  5592. glslOpcode = isFloatType \
  5593. ? GLSLstd450::GLSLstd450##glslFloatOp \
  5594. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  5595. : GLSLstd450::GLSLstd450##glslUintOp; \
  5596. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  5597. } break
  5598. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  5599. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  5600. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  5601. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  5602. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  5603. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  5604. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  5605. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  5606. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  5607. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  5608. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  5609. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  5610. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  5611. break;
  5612. case hlsl::IntrinsicOp::IOP_NonUniformResourceIndex:
  5613. retVal = processIntrinsicNonUniformResourceIndex(callExpr);
  5614. break;
  5615. case hlsl::IntrinsicOp::IOP_tex1D:
  5616. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  5617. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  5618. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  5619. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  5620. case hlsl::IntrinsicOp::IOP_tex2D:
  5621. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  5622. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  5623. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  5624. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  5625. case hlsl::IntrinsicOp::IOP_tex3D:
  5626. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  5627. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  5628. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  5629. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  5630. case hlsl::IntrinsicOp::IOP_texCUBE:
  5631. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  5632. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  5633. case hlsl::IntrinsicOp::IOP_texCUBElod:
  5634. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  5635. emitError("deprecated %0 intrinsic function will not be supported",
  5636. callExpr->getExprLoc())
  5637. << callee->getName();
  5638. return 0;
  5639. }
  5640. case hlsl::IntrinsicOp::IOP_dot:
  5641. retVal = processIntrinsicDot(callExpr);
  5642. break;
  5643. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  5644. retVal = processIntrinsicMemoryBarrier(callExpr,
  5645. /*isDevice*/ false,
  5646. /*groupSync*/ false,
  5647. /*isAllBarrier*/ false);
  5648. break;
  5649. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  5650. retVal = processIntrinsicMemoryBarrier(callExpr,
  5651. /*isDevice*/ false,
  5652. /*groupSync*/ true,
  5653. /*isAllBarrier*/ false);
  5654. break;
  5655. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  5656. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5657. /*groupSync*/ false,
  5658. /*isAllBarrier*/ false);
  5659. break;
  5660. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  5661. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5662. /*groupSync*/ true,
  5663. /*isAllBarrier*/ false);
  5664. break;
  5665. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  5666. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5667. /*groupSync*/ false,
  5668. /*isAllBarrier*/ true);
  5669. break;
  5670. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  5671. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  5672. /*groupSync*/ true,
  5673. /*isAllBarrier*/ true);
  5674. break;
  5675. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  5676. retVal =
  5677. theBuilder.createImageSparseTexelsResident(doExpr(callExpr->getArg(0)));
  5678. break;
  5679. case hlsl::IntrinsicOp::IOP_mul:
  5680. case hlsl::IntrinsicOp::IOP_umul:
  5681. retVal = processIntrinsicMul(callExpr);
  5682. break;
  5683. case hlsl::IntrinsicOp::IOP_all:
  5684. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  5685. break;
  5686. case hlsl::IntrinsicOp::IOP_any:
  5687. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  5688. break;
  5689. case hlsl::IntrinsicOp::IOP_asdouble:
  5690. case hlsl::IntrinsicOp::IOP_asfloat:
  5691. case hlsl::IntrinsicOp::IOP_asint:
  5692. case hlsl::IntrinsicOp::IOP_asuint:
  5693. retVal = processIntrinsicAsType(callExpr);
  5694. break;
  5695. case hlsl::IntrinsicOp::IOP_clip:
  5696. retVal = processIntrinsicClip(callExpr);
  5697. break;
  5698. case hlsl::IntrinsicOp::IOP_dst:
  5699. retVal = processIntrinsicDst(callExpr);
  5700. break;
  5701. case hlsl::IntrinsicOp::IOP_clamp:
  5702. case hlsl::IntrinsicOp::IOP_uclamp:
  5703. retVal = processIntrinsicClamp(callExpr);
  5704. break;
  5705. case hlsl::IntrinsicOp::IOP_frexp:
  5706. retVal = processIntrinsicFrexp(callExpr);
  5707. break;
  5708. case hlsl::IntrinsicOp::IOP_ldexp:
  5709. retVal = processIntrinsicLdexp(callExpr);
  5710. break;
  5711. case hlsl::IntrinsicOp::IOP_lit:
  5712. retVal = processIntrinsicLit(callExpr);
  5713. break;
  5714. case hlsl::IntrinsicOp::IOP_modf:
  5715. retVal = processIntrinsicModf(callExpr);
  5716. break;
  5717. case hlsl::IntrinsicOp::IOP_msad4:
  5718. retVal = processIntrinsicMsad4(callExpr);
  5719. break;
  5720. case hlsl::IntrinsicOp::IOP_sign: {
  5721. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  5722. retVal = processIntrinsicFloatSign(callExpr);
  5723. else
  5724. retVal =
  5725. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  5726. /*actPerRowForMatrices*/ true);
  5727. } break;
  5728. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  5729. retVal = processD3DCOLORtoUBYTE4(callExpr);
  5730. break;
  5731. case hlsl::IntrinsicOp::IOP_isfinite:
  5732. retVal = processIntrinsicIsFinite(callExpr);
  5733. break;
  5734. case hlsl::IntrinsicOp::IOP_sincos:
  5735. retVal = processIntrinsicSinCos(callExpr);
  5736. break;
  5737. case hlsl::IntrinsicOp::IOP_rcp:
  5738. retVal = processIntrinsicRcp(callExpr);
  5739. break;
  5740. case hlsl::IntrinsicOp::IOP_saturate:
  5741. retVal = processIntrinsicSaturate(callExpr);
  5742. break;
  5743. case hlsl::IntrinsicOp::IOP_log10:
  5744. retVal = processIntrinsicLog10(callExpr);
  5745. break;
  5746. case hlsl::IntrinsicOp::IOP_f16tof32:
  5747. retVal = processIntrinsicF16ToF32(callExpr);
  5748. break;
  5749. case hlsl::IntrinsicOp::IOP_f32tof16:
  5750. retVal = processIntrinsicF32ToF16(callExpr);
  5751. break;
  5752. case hlsl::IntrinsicOp::IOP_WaveGetLaneCount: {
  5753. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneCount",
  5754. callExpr->getExprLoc());
  5755. const uint32_t retType =
  5756. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5757. const uint32_t varId =
  5758. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupSize);
  5759. retVal = theBuilder.createLoad(retType, varId);
  5760. } break;
  5761. case hlsl::IntrinsicOp::IOP_WaveGetLaneIndex: {
  5762. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "WaveGetLaneIndex",
  5763. callExpr->getExprLoc());
  5764. const uint32_t retType =
  5765. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  5766. const uint32_t varId =
  5767. declIdMapper.getBuiltinVar(spv::BuiltIn::SubgroupLocalInvocationId);
  5768. retVal = theBuilder.createLoad(retType, varId);
  5769. } break;
  5770. case hlsl::IntrinsicOp::IOP_WaveIsFirstLane:
  5771. retVal = processWaveQuery(callExpr, spv::Op::OpGroupNonUniformElect);
  5772. break;
  5773. case hlsl::IntrinsicOp::IOP_WaveActiveAllTrue:
  5774. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAll);
  5775. break;
  5776. case hlsl::IntrinsicOp::IOP_WaveActiveAnyTrue:
  5777. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAny);
  5778. break;
  5779. case hlsl::IntrinsicOp::IOP_WaveActiveBallot:
  5780. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformBallot);
  5781. break;
  5782. case hlsl::IntrinsicOp::IOP_WaveActiveAllEqual:
  5783. retVal = processWaveVote(callExpr, spv::Op::OpGroupNonUniformAllEqual);
  5784. break;
  5785. case hlsl::IntrinsicOp::IOP_WaveActiveCountBits:
  5786. retVal = processWaveReductionOrPrefix(
  5787. callExpr, spv::Op::OpGroupNonUniformBallotBitCount,
  5788. spv::GroupOperation::Reduce);
  5789. break;
  5790. case hlsl::IntrinsicOp::IOP_WaveActiveUSum:
  5791. case hlsl::IntrinsicOp::IOP_WaveActiveSum:
  5792. case hlsl::IntrinsicOp::IOP_WaveActiveUProduct:
  5793. case hlsl::IntrinsicOp::IOP_WaveActiveProduct:
  5794. case hlsl::IntrinsicOp::IOP_WaveActiveUMax:
  5795. case hlsl::IntrinsicOp::IOP_WaveActiveMax:
  5796. case hlsl::IntrinsicOp::IOP_WaveActiveUMin:
  5797. case hlsl::IntrinsicOp::IOP_WaveActiveMin:
  5798. case hlsl::IntrinsicOp::IOP_WaveActiveBitAnd:
  5799. case hlsl::IntrinsicOp::IOP_WaveActiveBitOr:
  5800. case hlsl::IntrinsicOp::IOP_WaveActiveBitXor: {
  5801. const auto retType = callExpr->getCallReturnType(astContext);
  5802. retVal = processWaveReductionOrPrefix(
  5803. callExpr, translateWaveOp(hlslOpcode, retType, callExpr->getExprLoc()),
  5804. spv::GroupOperation::Reduce);
  5805. } break;
  5806. case hlsl::IntrinsicOp::IOP_WavePrefixUSum:
  5807. case hlsl::IntrinsicOp::IOP_WavePrefixSum:
  5808. case hlsl::IntrinsicOp::IOP_WavePrefixUProduct:
  5809. case hlsl::IntrinsicOp::IOP_WavePrefixProduct: {
  5810. const auto retType = callExpr->getCallReturnType(astContext);
  5811. retVal = processWaveReductionOrPrefix(
  5812. callExpr, translateWaveOp(hlslOpcode, retType, callExpr->getExprLoc()),
  5813. spv::GroupOperation::ExclusiveScan);
  5814. } break;
  5815. case hlsl::IntrinsicOp::IOP_WavePrefixCountBits:
  5816. retVal = processWaveReductionOrPrefix(
  5817. callExpr, spv::Op::OpGroupNonUniformBallotBitCount,
  5818. spv::GroupOperation::ExclusiveScan);
  5819. break;
  5820. case hlsl::IntrinsicOp::IOP_WaveReadLaneAt:
  5821. case hlsl::IntrinsicOp::IOP_WaveReadLaneFirst:
  5822. retVal = processWaveBroadcast(callExpr);
  5823. break;
  5824. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  5825. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  5826. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  5827. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  5828. retVal = processWaveQuadWideShuffle(callExpr, hlslOpcode);
  5829. break;
  5830. case hlsl::IntrinsicOp::IOP_abort:
  5831. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  5832. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  5833. emitError("no equivalent for %0 intrinsic function in Vulkan",
  5834. callExpr->getExprLoc())
  5835. << callee->getName();
  5836. return 0;
  5837. }
  5838. case hlsl::IntrinsicOp::IOP_transpose: {
  5839. const Expr *mat = callExpr->getArg(0);
  5840. const QualType matType = mat->getType();
  5841. if (hlsl::GetHLSLMatElementType(matType)->isFloatingType())
  5842. retVal =
  5843. processIntrinsicUsingSpirvInst(callExpr, spv::Op::OpTranspose, false);
  5844. else
  5845. retVal = processNonFpMatrixTranspose(matType, doExpr(mat));
  5846. break;
  5847. }
  5848. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  5849. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_coarse, DPdxCoarse, false,
  5850. spv::Capability::DerivativeControl);
  5851. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_fine, DPdxFine, false,
  5852. spv::Capability::DerivativeControl);
  5853. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  5854. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_coarse, DPdyCoarse, false,
  5855. spv::Capability::DerivativeControl);
  5856. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_fine, DPdyFine, false,
  5857. spv::Capability::DerivativeControl);
  5858. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  5859. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  5860. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  5861. INTRINSIC_SPIRV_OP_CASE(fmod, FMod, true);
  5862. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  5863. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  5864. INTRINSIC_OP_CASE(round, Round, true);
  5865. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  5866. INTRINSIC_OP_CASE(acos, Acos, true);
  5867. INTRINSIC_OP_CASE(asin, Asin, true);
  5868. INTRINSIC_OP_CASE(atan, Atan, true);
  5869. INTRINSIC_OP_CASE(atan2, Atan2, true);
  5870. INTRINSIC_OP_CASE(ceil, Ceil, true);
  5871. INTRINSIC_OP_CASE(cos, Cos, true);
  5872. INTRINSIC_OP_CASE(cosh, Cosh, true);
  5873. INTRINSIC_OP_CASE(cross, Cross, false);
  5874. INTRINSIC_OP_CASE(degrees, Degrees, true);
  5875. INTRINSIC_OP_CASE(distance, Distance, false);
  5876. INTRINSIC_OP_CASE(determinant, Determinant, false);
  5877. INTRINSIC_OP_CASE(exp, Exp, true);
  5878. INTRINSIC_OP_CASE(exp2, Exp2, true);
  5879. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  5880. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  5881. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  5882. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  5883. INTRINSIC_OP_CASE(floor, Floor, true);
  5884. INTRINSIC_OP_CASE(fma, Fma, true);
  5885. INTRINSIC_OP_CASE(frac, Fract, true);
  5886. INTRINSIC_OP_CASE(length, Length, false);
  5887. INTRINSIC_OP_CASE(lerp, FMix, true);
  5888. INTRINSIC_OP_CASE(log, Log, true);
  5889. INTRINSIC_OP_CASE(log2, Log2, true);
  5890. INTRINSIC_OP_CASE(mad, Fma, true);
  5891. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  5892. INTRINSIC_OP_CASE(umax, UMax, true);
  5893. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  5894. INTRINSIC_OP_CASE(umin, UMin, true);
  5895. INTRINSIC_OP_CASE(normalize, Normalize, false);
  5896. INTRINSIC_OP_CASE(pow, Pow, true);
  5897. INTRINSIC_OP_CASE(radians, Radians, true);
  5898. INTRINSIC_OP_CASE(reflect, Reflect, false);
  5899. INTRINSIC_OP_CASE(refract, Refract, false);
  5900. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  5901. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  5902. INTRINSIC_OP_CASE(step, Step, true);
  5903. INTRINSIC_OP_CASE(sin, Sin, true);
  5904. INTRINSIC_OP_CASE(sinh, Sinh, true);
  5905. INTRINSIC_OP_CASE(tan, Tan, true);
  5906. INTRINSIC_OP_CASE(tanh, Tanh, true);
  5907. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  5908. INTRINSIC_OP_CASE(trunc, Trunc, true);
  5909. default:
  5910. emitError("%0 intrinsic function unimplemented", callExpr->getExprLoc())
  5911. << callee->getName();
  5912. return 0;
  5913. }
  5914. #undef INTRINSIC_OP_CASE
  5915. #undef INTRINSIC_OP_CASE_INT_FLOAT
  5916. return SpirvEvalInfo(retVal).setRValue();
  5917. }
  5918. uint32_t
  5919. SPIRVEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  5920. hlsl::IntrinsicOp opcode) {
  5921. // The signature of intrinsic atomic methods are:
  5922. // void Interlocked*(in R dest, in T value);
  5923. // void Interlocked*(in R dest, in T value, out T original_value);
  5924. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  5925. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  5926. // parameter is not an unsigned integer, the frontend inserts an
  5927. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  5928. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  5929. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  5930. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  5931. // the following OpAtomicIAdd is invalid because the pointee type defined in
  5932. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  5933. // unsigned integer.
  5934. //
  5935. // %_ptr_Image_int = OpTypePointer Image %int
  5936. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  5937. // %2 = OpLoad %int %value
  5938. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  5939. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  5940. //
  5941. // In such cases, we bypass the forced IntegralCast.
  5942. // Moreover, the frontend does not add a cast AST node to cast uint to int
  5943. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  5944. const uint32_t zero = theBuilder.getConstantUint32(0);
  5945. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  5946. const auto *dest = expr->getArg(0);
  5947. const auto baseType = dest->getType();
  5948. if (!baseType->isIntegerType()) {
  5949. emitError("can only perform atomic operations on scalar integer values",
  5950. dest->getLocStart());
  5951. return 0;
  5952. }
  5953. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  5954. const auto doArg = [baseType, this](const CallExpr *callExpr,
  5955. uint32_t argIndex) {
  5956. const Expr *valueExpr = callExpr->getArg(argIndex);
  5957. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  5958. if (castExpr->getCastKind() == CK_IntegralCast &&
  5959. castExpr->getSubExpr()->getType() == baseType)
  5960. valueExpr = castExpr->getSubExpr();
  5961. uint32_t argId = doExpr(valueExpr);
  5962. if (valueExpr->getType() != baseType)
  5963. argId = castToInt(argId, valueExpr->getType(), baseType,
  5964. valueExpr->getExprLoc());
  5965. return argId;
  5966. };
  5967. const auto writeToOutputArg = [&baseType, dest, this](
  5968. uint32_t toWrite, const CallExpr *callExpr,
  5969. uint32_t outputArgIndex) {
  5970. const auto outputArg = callExpr->getArg(outputArgIndex);
  5971. const auto outputArgType = outputArg->getType();
  5972. if (baseType != outputArgType)
  5973. toWrite = castToInt(toWrite, baseType, outputArgType, dest->getExprLoc());
  5974. theBuilder.createStore(doExpr(outputArg), toWrite);
  5975. };
  5976. // If the argument is indexing into a texture/buffer, we need to create an
  5977. // OpImageTexelPointer instruction.
  5978. uint32_t ptr = 0;
  5979. if (const auto *callExpr = dyn_cast<CXXOperatorCallExpr>(dest)) {
  5980. const Expr *base = nullptr;
  5981. const Expr *index = nullptr;
  5982. if (isBufferTextureIndexing(callExpr, &base, &index)) {
  5983. const auto ptrType =
  5984. theBuilder.getPointerType(baseTypeId, spv::StorageClass::Image);
  5985. auto baseId = doExpr(base);
  5986. if (baseId.isRValue()) {
  5987. // OpImageTexelPointer's Image argument must have a type of
  5988. // OpTypePointer with Type OpTypeImage. Need to create a temporary
  5989. // variable if the baseId is an rvalue.
  5990. baseId = createTemporaryVar(
  5991. base->getType(), TypeTranslator::getName(base->getType()), baseId);
  5992. }
  5993. const auto coordId = doExpr(index);
  5994. ptr = theBuilder.createImageTexelPointer(ptrType, baseId, coordId, zero);
  5995. if (baseId.isNonUniform()) {
  5996. // Image texel pointer will used to access image memory. Vulkan requires
  5997. // it to be decorated with NonUniformEXT.
  5998. theBuilder.decorateNonUniformEXT(ptr);
  5999. }
  6000. }
  6001. }
  6002. if (!ptr)
  6003. ptr = doExpr(dest);
  6004. const bool isCompareExchange =
  6005. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  6006. const bool isCompareStore =
  6007. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  6008. if (isCompareExchange || isCompareStore) {
  6009. const uint32_t comparator = doArg(expr, 1);
  6010. const uint32_t valueId = doArg(expr, 2);
  6011. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  6012. baseTypeId, ptr, scope, zero, zero, valueId, comparator);
  6013. if (isCompareExchange)
  6014. writeToOutputArg(originalVal, expr, 3);
  6015. } else {
  6016. const uint32_t valueId = doArg(expr, 1);
  6017. // Since these atomic operations write through the provided pointer, the
  6018. // signed vs. unsigned opcode must be decided based on the pointee type
  6019. // of the first argument. However, the frontend decides the opcode based on
  6020. // the second argument (value). Therefore, the HLSL opcode provided by the
  6021. // frontend may be wrong. Therefore we need the following code to make sure
  6022. // we are using the correct SPIR-V opcode.
  6023. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  6024. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  6025. atomicOp = spv::Op::OpAtomicSMax;
  6026. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  6027. atomicOp = spv::Op::OpAtomicUMax;
  6028. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  6029. atomicOp = spv::Op::OpAtomicSMin;
  6030. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  6031. atomicOp = spv::Op::OpAtomicUMin;
  6032. const uint32_t originalVal = theBuilder.createAtomicOp(
  6033. atomicOp, baseTypeId, ptr, scope, zero, valueId);
  6034. if (expr->getNumArgs() > 2)
  6035. writeToOutputArg(originalVal, expr, 2);
  6036. }
  6037. return 0;
  6038. }
  6039. SpirvEvalInfo
  6040. SPIRVEmitter::processIntrinsicNonUniformResourceIndex(const CallExpr *expr) {
  6041. foundNonUniformResourceIndex = true;
  6042. theBuilder.addExtension(Extension::EXT_descriptor_indexing,
  6043. "NonUniformResourceIndex", expr->getExprLoc());
  6044. theBuilder.requireCapability(spv::Capability::ShaderNonUniformEXT);
  6045. auto index = doExpr(expr->getArg(0)).setNonUniform();
  6046. // Decorate the expression in NonUniformResourceIndex() with NonUniformEXT.
  6047. // Aside from this, we also need to eventually populate the NonUniformEXT
  6048. // status to the usage of this expression: the "pointer" operand to a memory
  6049. // access instruction. Vulkan spec has the following rules:
  6050. //
  6051. // If an instruction loads from or stores to a resource (including atomics and
  6052. // image instructions) and the resource descriptor being accessed is not
  6053. // dynamically uniform, then the operand corresponding to that resource (e.g.
  6054. // the pointer or sampled image operand) must be decorated with NonUniformEXT.
  6055. theBuilder.decorateNonUniformEXT(index);
  6056. return index;
  6057. }
  6058. uint32_t SPIRVEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  6059. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  6060. "instructions due to lack of direct SPIR-V equivalent",
  6061. callExpr->getExprLoc());
  6062. // Compares a 4-byte reference value and an 8-byte source value and
  6063. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  6064. // of absolute differences of a different byte alignment between the
  6065. // reference value and the source value.
  6066. // If we have:
  6067. // uint v0; // reference
  6068. // uint2 v1; // source
  6069. // uint4 v2; // accum
  6070. // uint4 o0; // result of msad4
  6071. // uint4 r0, t0; // temporary values
  6072. //
  6073. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  6074. // to fxc:
  6075. // Step 1:
  6076. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  6077. // Step 2:
  6078. // [result], [ width ], [ offset ], [ insert ], [ base ]
  6079. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  6080. // mov t0.x, v1.x
  6081. // Step 3:
  6082. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  6083. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  6084. const auto boolType = theBuilder.getBoolType();
  6085. const auto intType = theBuilder.getInt32Type();
  6086. const auto uintType = theBuilder.getUint32Type();
  6087. const auto uint4Type = theBuilder.getVecType(uintType, 4);
  6088. const uint32_t reference = doExpr(callExpr->getArg(0));
  6089. const uint32_t source = doExpr(callExpr->getArg(1));
  6090. const uint32_t accum = doExpr(callExpr->getArg(2));
  6091. const auto uint0 = theBuilder.getConstantUint32(0);
  6092. const auto uint8 = theBuilder.getConstantUint32(8);
  6093. const auto uint16 = theBuilder.getConstantUint32(16);
  6094. const auto uint24 = theBuilder.getConstantUint32(24);
  6095. // Step 1.
  6096. const uint32_t v1x = theBuilder.createCompositeExtract(uintType, source, {0});
  6097. // r0.x = v1xS8 = v1.x shifted by 8 bits
  6098. uint32_t v1xS8 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  6099. uintType, v1x, uint8);
  6100. // r0.y = v1xS16 = v1.x shifted by 16 bits
  6101. uint32_t v1xS16 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  6102. uintType, v1x, uint16);
  6103. // r0.z = v1xS24 = v1.x shifted by 24 bits
  6104. uint32_t v1xS24 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  6105. uintType, v1x, uint24);
  6106. // Step 2.
  6107. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  6108. const uint32_t v1y = theBuilder.createCompositeExtract(uintType, source, {1});
  6109. // Note that t0.x = v1.x, nothing we need to do for that.
  6110. const uint32_t t0y =
  6111. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  6112. /*offset*/ uint24,
  6113. /*width*/ uint8);
  6114. const uint32_t t0z =
  6115. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  6116. /*offset*/ uint16,
  6117. /*width*/ uint16);
  6118. const uint32_t t0w =
  6119. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  6120. /*offset*/ uint8,
  6121. /*width*/ uint24);
  6122. // Step 3. MSAD (Masked Sum of Absolute Differences)
  6123. // Now perform MSAD four times.
  6124. // Need to mimic this algorithm in SPIR-V!
  6125. //
  6126. // UINT msad( UINT ref, UINT src, UINT accum )
  6127. // {
  6128. // for (UINT i = 0; i < 4; i++)
  6129. // {
  6130. // BYTE refByte, srcByte, absDiff;
  6131. //
  6132. // refByte = (BYTE)(ref >> (i * 8));
  6133. // if (!refByte)
  6134. // {
  6135. // continue;
  6136. // }
  6137. //
  6138. // srcByte = (BYTE)(src >> (i * 8));
  6139. // if (refByte >= srcByte)
  6140. // {
  6141. // absDiff = refByte - srcByte;
  6142. // }
  6143. // else
  6144. // {
  6145. // absDiff = srcByte - refByte;
  6146. // }
  6147. //
  6148. // // The recommended overflow behavior for MSAD is
  6149. // // to do a 32-bit saturate. This is not
  6150. // // required, however, and wrapping is allowed.
  6151. // // So from an application point of view,
  6152. // // overflow behavior is undefined.
  6153. // if (UINT_MAX - accum < absDiff)
  6154. // {
  6155. // accum = UINT_MAX;
  6156. // break;
  6157. // }
  6158. // accum += absDiff;
  6159. // }
  6160. //
  6161. // return accum;
  6162. // }
  6163. llvm::SmallVector<uint32_t, 4> result;
  6164. const uint32_t accum0 =
  6165. theBuilder.createCompositeExtract(uintType, accum, {0});
  6166. const uint32_t accum1 =
  6167. theBuilder.createCompositeExtract(uintType, accum, {1});
  6168. const uint32_t accum2 =
  6169. theBuilder.createCompositeExtract(uintType, accum, {2});
  6170. const uint32_t accum3 =
  6171. theBuilder.createCompositeExtract(uintType, accum, {3});
  6172. const llvm::SmallVector<uint32_t, 4> sources = {v1x, t0y, t0z, t0w};
  6173. llvm::SmallVector<uint32_t, 4> accums = {accum0, accum1, accum2, accum3};
  6174. llvm::SmallVector<uint32_t, 4> refBytes;
  6175. llvm::SmallVector<uint32_t, 4> signedRefBytes;
  6176. llvm::SmallVector<uint32_t, 4> isRefByteZero;
  6177. for (uint32_t i = 0; i < 4; ++i) {
  6178. refBytes.push_back(theBuilder.createBitFieldExtract(
  6179. uintType, reference, /*offset*/ theBuilder.getConstantUint32(i * 8),
  6180. /*count*/ uint8, /*isSigned*/ false));
  6181. signedRefBytes.push_back(
  6182. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, refBytes.back()));
  6183. isRefByteZero.push_back(theBuilder.createBinaryOp(
  6184. spv::Op::OpIEqual, boolType, refBytes.back(), uint0));
  6185. }
  6186. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  6187. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  6188. // 'count' is always 8 because we are extracting 8 bits out of 32.
  6189. const uint32_t srcByte = theBuilder.createBitFieldExtract(
  6190. uintType, sources[msadNum],
  6191. /*offset*/ theBuilder.getConstantUint32(8 * byteCount),
  6192. /*count*/ uint8, /*isSigned*/ false);
  6193. const uint32_t signedSrcByte =
  6194. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte);
  6195. const uint32_t sub = theBuilder.createBinaryOp(
  6196. spv::Op::OpISub, intType, signedRefBytes[byteCount], signedSrcByte);
  6197. const uint32_t absSub = theBuilder.createExtInst(
  6198. intType, glsl, GLSLstd450::GLSLstd450SAbs, {sub});
  6199. const uint32_t diff = theBuilder.createSelect(
  6200. uintType, isRefByteZero[byteCount], uint0,
  6201. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub));
  6202. // As pointed out by the DXIL reference above, it is *not* required to
  6203. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  6204. // also allowed. For simplicity, we will wrap around at this point.
  6205. accums[msadNum] = theBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  6206. accums[msadNum], diff);
  6207. }
  6208. }
  6209. return theBuilder.createCompositeConstruct(uint4Type, accums);
  6210. }
  6211. uint32_t SPIRVEmitter::processWaveQuery(const CallExpr *callExpr,
  6212. spv::Op opcode) {
  6213. // Signatures:
  6214. // bool WaveIsFirstLane()
  6215. // uint WaveGetLaneCount()
  6216. // uint WaveGetLaneIndex()
  6217. assert(callExpr->getNumArgs() == 0);
  6218. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6219. callExpr->getExprLoc());
  6220. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6221. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6222. const uint32_t retType =
  6223. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6224. return theBuilder.createGroupNonUniformOp(opcode, retType, subgroupScope);
  6225. }
  6226. uint32_t SPIRVEmitter::processWaveVote(const CallExpr *callExpr,
  6227. spv::Op opcode) {
  6228. // Signatures:
  6229. // bool WaveActiveAnyTrue( bool expr )
  6230. // bool WaveActiveAllTrue( bool expr )
  6231. // bool uint4 WaveActiveBallot( bool expr )
  6232. assert(callExpr->getNumArgs() == 1);
  6233. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6234. callExpr->getExprLoc());
  6235. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6236. const uint32_t predicate = doExpr(callExpr->getArg(0));
  6237. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6238. const uint32_t retType =
  6239. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6240. return theBuilder.createGroupNonUniformUnaryOp(opcode, retType, subgroupScope,
  6241. predicate);
  6242. }
  6243. spv::Op SPIRVEmitter::translateWaveOp(hlsl::IntrinsicOp op, QualType type,
  6244. SourceLocation srcLoc) {
  6245. const bool isSintType = isSintOrVecMatOfSintType(type);
  6246. const bool isUintType = isUintOrVecMatOfUintType(type);
  6247. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  6248. #define WAVE_OP_CASE_INT(kind, intWaveOp) \
  6249. \
  6250. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6251. if (isSintType || isUintType) { \
  6252. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6253. } \
  6254. } break
  6255. #define WAVE_OP_CASE_INT_FLOAT(kind, intWaveOp, floatWaveOp) \
  6256. \
  6257. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6258. if (isSintType || isUintType) { \
  6259. return spv::Op::OpGroupNonUniform##intWaveOp; \
  6260. } \
  6261. if (isFloatType) { \
  6262. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6263. } \
  6264. } break
  6265. #define WAVE_OP_CASE_SINT_UINT_FLOAT(kind, sintWaveOp, uintWaveOp, \
  6266. floatWaveOp) \
  6267. \
  6268. case hlsl::IntrinsicOp::IOP_Wave##kind: { \
  6269. if (isSintType) { \
  6270. return spv::Op::OpGroupNonUniform##sintWaveOp; \
  6271. } \
  6272. if (isUintType) { \
  6273. return spv::Op::OpGroupNonUniform##uintWaveOp; \
  6274. } \
  6275. if (isFloatType) { \
  6276. return spv::Op::OpGroupNonUniform##floatWaveOp; \
  6277. } \
  6278. } break
  6279. switch (op) {
  6280. WAVE_OP_CASE_INT_FLOAT(ActiveUSum, IAdd, FAdd);
  6281. WAVE_OP_CASE_INT_FLOAT(ActiveSum, IAdd, FAdd);
  6282. WAVE_OP_CASE_INT_FLOAT(ActiveUProduct, IMul, FMul);
  6283. WAVE_OP_CASE_INT_FLOAT(ActiveProduct, IMul, FMul);
  6284. WAVE_OP_CASE_INT_FLOAT(PrefixUSum, IAdd, FAdd);
  6285. WAVE_OP_CASE_INT_FLOAT(PrefixSum, IAdd, FAdd);
  6286. WAVE_OP_CASE_INT_FLOAT(PrefixUProduct, IMul, FMul);
  6287. WAVE_OP_CASE_INT_FLOAT(PrefixProduct, IMul, FMul);
  6288. WAVE_OP_CASE_INT(ActiveBitAnd, BitwiseAnd);
  6289. WAVE_OP_CASE_INT(ActiveBitOr, BitwiseOr);
  6290. WAVE_OP_CASE_INT(ActiveBitXor, BitwiseXor);
  6291. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMax, SMax, UMax, FMax);
  6292. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMax, SMax, UMax, FMax);
  6293. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveUMin, SMin, UMin, FMin);
  6294. WAVE_OP_CASE_SINT_UINT_FLOAT(ActiveMin, SMin, UMin, FMin);
  6295. default:
  6296. // Only Simple Wave Ops are handled here.
  6297. break;
  6298. }
  6299. #undef WAVE_OP_CASE_INT_FLOAT
  6300. #undef WAVE_OP_CASE_INT
  6301. #undef WAVE_OP_CASE_SINT_UINT_FLOAT
  6302. emitError("translating wave operator '%0' unimplemented", srcLoc)
  6303. << static_cast<uint32_t>(op);
  6304. return spv::Op::OpNop;
  6305. }
  6306. uint32_t SPIRVEmitter::processWaveReductionOrPrefix(
  6307. const CallExpr *callExpr, spv::Op opcode, spv::GroupOperation groupOp) {
  6308. // Signatures:
  6309. // bool WaveActiveAllEqual( <type> expr )
  6310. // uint WaveActiveCountBits( bool bBit )
  6311. // <type> WaveActiveSum( <type> expr )
  6312. // <type> WaveActiveProduct( <type> expr )
  6313. // <int_type> WaveActiveBitAnd( <int_type> expr )
  6314. // <int_type> WaveActiveBitOr( <int_type> expr )
  6315. // <int_type> WaveActiveBitXor( <int_type> expr )
  6316. // <type> WaveActiveMin( <type> expr)
  6317. // <type> WaveActiveMax( <type> expr)
  6318. //
  6319. // uint WavePrefixCountBits(Bool bBit)
  6320. // <type> WavePrefixProduct(<type> value)
  6321. // <type> WavePrefixSum(<type> value)
  6322. assert(callExpr->getNumArgs() == 1);
  6323. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6324. callExpr->getExprLoc());
  6325. theBuilder.requireCapability(getCapabilityForGroupNonUniform(opcode));
  6326. const uint32_t predicate = doExpr(callExpr->getArg(0));
  6327. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6328. const uint32_t retType =
  6329. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6330. return theBuilder.createGroupNonUniformUnaryOp(
  6331. opcode, retType, subgroupScope, predicate,
  6332. llvm::Optional<spv::GroupOperation>(groupOp));
  6333. }
  6334. uint32_t SPIRVEmitter::processWaveBroadcast(const CallExpr *callExpr) {
  6335. // Signatures:
  6336. // <type> WaveReadLaneFirst(<type> expr)
  6337. // <type> WaveReadLaneAt(<type> expr, uint laneIndex)
  6338. const auto numArgs = callExpr->getNumArgs();
  6339. assert(numArgs == 1 || numArgs == 2);
  6340. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6341. callExpr->getExprLoc());
  6342. theBuilder.requireCapability(spv::Capability::GroupNonUniformBallot);
  6343. const uint32_t value = doExpr(callExpr->getArg(0));
  6344. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6345. const uint32_t retType =
  6346. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6347. if (numArgs == 2)
  6348. return theBuilder.createGroupNonUniformBinaryOp(
  6349. spv::Op::OpGroupNonUniformBroadcast, retType, subgroupScope, value,
  6350. doExpr(callExpr->getArg(1)));
  6351. else
  6352. return theBuilder.createGroupNonUniformUnaryOp(
  6353. spv::Op::OpGroupNonUniformBroadcastFirst, retType, subgroupScope,
  6354. value);
  6355. }
  6356. uint32_t SPIRVEmitter::processWaveQuadWideShuffle(const CallExpr *callExpr,
  6357. hlsl::IntrinsicOp op) {
  6358. // Signatures:
  6359. // <type> QuadReadAcrossX(<type> localValue)
  6360. // <type> QuadReadAcrossY(<type> localValue)
  6361. // <type> QuadReadAcrossDiagonal(<type> localValue)
  6362. // <type> QuadReadLaneAt(<type> sourceValue, uint quadLaneID)
  6363. assert(callExpr->getNumArgs() == 1 || callExpr->getNumArgs() == 2);
  6364. featureManager.requestTargetEnv(SPV_ENV_VULKAN_1_1, "Wave Operation",
  6365. callExpr->getExprLoc());
  6366. theBuilder.requireCapability(spv::Capability::GroupNonUniformQuad);
  6367. const uint32_t value = doExpr(callExpr->getArg(0));
  6368. const uint32_t subgroupScope = theBuilder.getConstantInt32(3);
  6369. const uint32_t retType =
  6370. typeTranslator.translateType(callExpr->getCallReturnType(astContext));
  6371. uint32_t target = 0;
  6372. spv::Op opcode = spv::Op::OpGroupNonUniformQuadSwap;
  6373. switch (op) {
  6374. case hlsl::IntrinsicOp::IOP_QuadReadAcrossX:
  6375. target = theBuilder.getConstantUint32(0);
  6376. break;
  6377. case hlsl::IntrinsicOp::IOP_QuadReadAcrossY:
  6378. target = theBuilder.getConstantUint32(1);
  6379. break;
  6380. case hlsl::IntrinsicOp::IOP_QuadReadAcrossDiagonal:
  6381. target = theBuilder.getConstantUint32(2);
  6382. break;
  6383. case hlsl::IntrinsicOp::IOP_QuadReadLaneAt:
  6384. target = doExpr(callExpr->getArg(1));
  6385. opcode = spv::Op::OpGroupNonUniformQuadBroadcast;
  6386. break;
  6387. default:
  6388. llvm_unreachable("case should not appear here");
  6389. }
  6390. return theBuilder.createGroupNonUniformBinaryOp(opcode, retType,
  6391. subgroupScope, value, target);
  6392. }
  6393. uint32_t SPIRVEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  6394. // Signature is: ret modf(x, ip)
  6395. // [in] x: the input floating-point value.
  6396. // [out] ip: the integer portion of x.
  6397. // [out] ret: the fractional portion of x.
  6398. // All of the above must be a scalar, vector, or matrix with the same
  6399. // component types. Component types can be float or int.
  6400. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  6401. // fractional part and the second member is the integer portion.
  6402. // ModfStruct {
  6403. // <scalar or vector of float> frac;
  6404. // <scalar or vector of float> ip;
  6405. // }
  6406. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  6407. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  6408. // argument is not treated the same way. Therefore, in such cases we'll have
  6409. // to manually convert the float result into int.
  6410. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6411. const Expr *arg = callExpr->getArg(0);
  6412. const Expr *ipArg = callExpr->getArg(1);
  6413. const auto argType = arg->getType();
  6414. const auto ipType = ipArg->getType();
  6415. const auto returnType = callExpr->getType();
  6416. const auto returnTypeId = typeTranslator.translateType(returnType);
  6417. const uint32_t argId = doExpr(arg);
  6418. const uint32_t ipId = doExpr(ipArg);
  6419. // For scalar and vector argument types.
  6420. {
  6421. if (TypeTranslator::isScalarType(argType) ||
  6422. TypeTranslator::isVectorType(argType)) {
  6423. const auto argTypeId = typeTranslator.translateType(argType);
  6424. // The struct members *must* have the same type.
  6425. const auto modfStructTypeId = theBuilder.getStructType(
  6426. {argTypeId, argTypeId}, "ModfStructType", {"frac", "ip"});
  6427. const auto modf =
  6428. theBuilder.createExtInst(modfStructTypeId, glslInstSetId,
  6429. GLSLstd450::GLSLstd450ModfStruct, {argId});
  6430. auto ip = theBuilder.createCompositeExtract(argTypeId, modf, {1});
  6431. // This will do nothing if the input number (x) and the ip are both of the
  6432. // same type. Otherwise, it will convert the ip into int as necessary.
  6433. ip = castToInt(ip, argType, ipType, arg->getExprLoc());
  6434. theBuilder.createStore(ipId, ip);
  6435. return theBuilder.createCompositeExtract(argTypeId, modf, {0});
  6436. }
  6437. }
  6438. // For matrix argument types.
  6439. {
  6440. uint32_t rowCount = 0, colCount = 0;
  6441. QualType elemType = {};
  6442. if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  6443. const auto elemTypeId = typeTranslator.translateType(elemType);
  6444. const auto colTypeId = theBuilder.getVecType(elemTypeId, colCount);
  6445. const auto modfStructTypeId = theBuilder.getStructType(
  6446. {colTypeId, colTypeId}, "ModfStructType", {"frac", "ip"});
  6447. llvm::SmallVector<uint32_t, 4> fracs;
  6448. llvm::SmallVector<uint32_t, 4> ips;
  6449. for (uint32_t i = 0; i < rowCount; ++i) {
  6450. const auto curRow =
  6451. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  6452. const auto modf = theBuilder.createExtInst(
  6453. modfStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450ModfStruct,
  6454. {curRow});
  6455. auto ip = theBuilder.createCompositeExtract(colTypeId, modf, {1});
  6456. ips.push_back(ip);
  6457. fracs.push_back(
  6458. theBuilder.createCompositeExtract(colTypeId, modf, {0}));
  6459. }
  6460. uint32_t ip = theBuilder.createCompositeConstruct(
  6461. typeTranslator.translateType(argType), ips);
  6462. // If the 'ip' is not a float type, the AST will not contain a CastExpr
  6463. // because this is internal to the intrinsic function. So, in such a
  6464. // case we need to cast manually.
  6465. if (!hlsl::GetHLSLMatElementType(ipType)->isFloatingType())
  6466. ip = castToInt(ip, argType, ipType, ipArg->getExprLoc());
  6467. theBuilder.createStore(ipId, ip);
  6468. return theBuilder.createCompositeConstruct(returnTypeId, fracs);
  6469. }
  6470. }
  6471. emitError("invalid argument type passed to Modf intrinsic function",
  6472. callExpr->getExprLoc());
  6473. return 0;
  6474. }
  6475. uint32_t SPIRVEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  6476. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  6477. //
  6478. // This function returns a lighting coefficient vector
  6479. // (ambient, diffuse, specular, 1) where:
  6480. // ambient = 1.
  6481. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  6482. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  6483. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6484. const uint32_t nDotL = doExpr(callExpr->getArg(0));
  6485. const uint32_t nDotH = doExpr(callExpr->getArg(1));
  6486. const uint32_t m = doExpr(callExpr->getArg(2));
  6487. const uint32_t floatType = theBuilder.getFloat32Type();
  6488. const uint32_t boolType = theBuilder.getBoolType();
  6489. const uint32_t floatZero = theBuilder.getConstantFloat32(0);
  6490. const uint32_t floatOne = theBuilder.getConstantFloat32(1);
  6491. const uint32_t retType = typeTranslator.translateType(callExpr->getType());
  6492. const uint32_t diffuse = theBuilder.createExtInst(
  6493. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL});
  6494. const uint32_t min = theBuilder.createExtInst(
  6495. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH});
  6496. const uint32_t isNeg = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6497. boolType, min, floatZero);
  6498. const uint32_t mul =
  6499. theBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m);
  6500. const uint32_t specular =
  6501. theBuilder.createSelect(floatType, isNeg, floatZero, mul);
  6502. return theBuilder.createCompositeConstruct(
  6503. retType, {floatOne, diffuse, specular, floatOne});
  6504. }
  6505. uint32_t SPIRVEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  6506. // Signature is: ret frexp(x, exp)
  6507. // [in] x: the input floating-point value.
  6508. // [out] exp: the calculated exponent.
  6509. // [out] ret: the calculated mantissa.
  6510. // All of the above must be a scalar, vector, or matrix of *float* type.
  6511. // The FrexpStruct SPIR-V instruction returns a struct. The first
  6512. // member is the significand (mantissa) and must be of the same type as the
  6513. // input parameter, and the second member is the exponent and must always be a
  6514. // scalar or vector of 32-bit *integer* type.
  6515. // FrexpStruct {
  6516. // <scalar or vector of int/float> mantissa;
  6517. // <scalar or vector of integers> exponent;
  6518. // }
  6519. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6520. const Expr *arg = callExpr->getArg(0);
  6521. const auto argType = arg->getType();
  6522. const auto intId = theBuilder.getInt32Type();
  6523. const auto returnTypeId = typeTranslator.translateType(callExpr->getType());
  6524. const uint32_t argId = doExpr(arg);
  6525. const uint32_t expId = doExpr(callExpr->getArg(1));
  6526. // For scalar and vector argument types.
  6527. {
  6528. uint32_t elemCount = 1;
  6529. if (TypeTranslator::isScalarType(argType) ||
  6530. TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  6531. const auto argTypeId = typeTranslator.translateType(argType);
  6532. const auto expTypeId =
  6533. elemCount == 1 ? intId : theBuilder.getVecType(intId, elemCount);
  6534. const auto frexpStructTypeId = theBuilder.getStructType(
  6535. {argTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  6536. const auto frexp =
  6537. theBuilder.createExtInst(frexpStructTypeId, glslInstSetId,
  6538. GLSLstd450::GLSLstd450FrexpStruct, {argId});
  6539. const auto exponentInt =
  6540. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  6541. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  6542. // expects a float, an conversion must take place before writing the
  6543. // results.
  6544. const auto exponentFloat = theBuilder.createUnaryOp(
  6545. spv::Op::OpConvertSToF, returnTypeId, exponentInt);
  6546. theBuilder.createStore(expId, exponentFloat);
  6547. return theBuilder.createCompositeExtract(argTypeId, frexp, {0});
  6548. }
  6549. }
  6550. // For matrix argument types.
  6551. {
  6552. uint32_t rowCount = 0, colCount = 0;
  6553. if (TypeTranslator::isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  6554. const auto floatId = theBuilder.getFloat32Type();
  6555. const auto expTypeId = theBuilder.getVecType(intId, colCount);
  6556. const auto colTypeId = theBuilder.getVecType(floatId, colCount);
  6557. const auto frexpStructTypeId = theBuilder.getStructType(
  6558. {colTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  6559. llvm::SmallVector<uint32_t, 4> exponents;
  6560. llvm::SmallVector<uint32_t, 4> mantissas;
  6561. for (uint32_t i = 0; i < rowCount; ++i) {
  6562. const auto curRow =
  6563. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  6564. const auto frexp = theBuilder.createExtInst(
  6565. frexpStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450FrexpStruct,
  6566. {curRow});
  6567. const auto exponentInt =
  6568. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  6569. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  6570. // expects a float, an conversion must take place before writing the
  6571. // results.
  6572. const auto exponentFloat = theBuilder.createUnaryOp(
  6573. spv::Op::OpConvertSToF, colTypeId, exponentInt);
  6574. exponents.push_back(exponentFloat);
  6575. mantissas.push_back(
  6576. theBuilder.createCompositeExtract(colTypeId, frexp, {0}));
  6577. }
  6578. const auto exponentsResultId =
  6579. theBuilder.createCompositeConstruct(returnTypeId, exponents);
  6580. theBuilder.createStore(expId, exponentsResultId);
  6581. return theBuilder.createCompositeConstruct(returnTypeId, mantissas);
  6582. }
  6583. }
  6584. emitError("invalid argument type passed to Frexp intrinsic function",
  6585. callExpr->getExprLoc());
  6586. return 0;
  6587. }
  6588. uint32_t SPIRVEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  6589. // Signature: ret ldexp(x, exp)
  6590. // This function uses the following formula: x * 2^exp.
  6591. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  6592. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  6593. // exponent. So we must calculate the result manually.
  6594. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  6595. const Expr *x = callExpr->getArg(0);
  6596. const auto paramType = x->getType();
  6597. const uint32_t xId = doExpr(x);
  6598. const uint32_t expId = doExpr(callExpr->getArg(1));
  6599. // For scalar and vector argument types.
  6600. if (TypeTranslator::isScalarType(paramType) ||
  6601. TypeTranslator::isVectorType(paramType)) {
  6602. const auto paramTypeId = typeTranslator.translateType(paramType);
  6603. const auto twoExp = theBuilder.createExtInst(
  6604. paramTypeId, glsl, GLSLstd450::GLSLstd450Exp2, {expId});
  6605. return theBuilder.createBinaryOp(spv::Op::OpFMul, paramTypeId, xId, twoExp);
  6606. }
  6607. // For matrix argument types.
  6608. {
  6609. uint32_t rowCount = 0, colCount = 0;
  6610. if (TypeTranslator::isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  6611. const auto actOnEachVec = [this, glsl, expId](uint32_t index,
  6612. uint32_t vecType,
  6613. uint32_t xRowId) {
  6614. const auto expRowId =
  6615. theBuilder.createCompositeExtract(vecType, expId, {index});
  6616. const auto twoExp = theBuilder.createExtInst(
  6617. vecType, glsl, GLSLstd450::GLSLstd450Exp2, {expRowId});
  6618. return theBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowId,
  6619. twoExp);
  6620. };
  6621. return processEachVectorInMatrix(x, xId, actOnEachVec);
  6622. }
  6623. }
  6624. emitError("invalid argument type passed to ldexp intrinsic function",
  6625. callExpr->getExprLoc());
  6626. return 0;
  6627. }
  6628. uint32_t SPIRVEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  6629. // Signature is float4 dst(float4 src0, float4 src1)
  6630. // result.x = 1;
  6631. // result.y = src0.y * src1.y;
  6632. // result.z = src0.z;
  6633. // result.w = src1.w;
  6634. const auto floatId = theBuilder.getFloat32Type();
  6635. const auto arg0Id = doExpr(callExpr->getArg(0));
  6636. const auto arg1Id = doExpr(callExpr->getArg(1));
  6637. const auto arg0y = theBuilder.createCompositeExtract(floatId, arg0Id, {1});
  6638. const auto arg1y = theBuilder.createCompositeExtract(floatId, arg1Id, {1});
  6639. const auto arg0z = theBuilder.createCompositeExtract(floatId, arg0Id, {2});
  6640. const auto arg1w = theBuilder.createCompositeExtract(floatId, arg1Id, {3});
  6641. const auto arg0yMularg1y =
  6642. theBuilder.createBinaryOp(spv::Op::OpFMul, floatId, arg0y, arg1y);
  6643. return theBuilder.createCompositeConstruct(
  6644. typeTranslator.translateType(callExpr->getType()),
  6645. {theBuilder.getConstantFloat32(1.0), arg0yMularg1y, arg0z, arg1w});
  6646. }
  6647. uint32_t SPIRVEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  6648. // Discards the current pixel if the specified value is less than zero.
  6649. // TODO: If the argument can be const folded and evaluated, we could
  6650. // potentially avoid creating a branch. This would be a bit challenging for
  6651. // matrix/vector arguments.
  6652. assert(callExpr->getNumArgs() == 1u);
  6653. const Expr *arg = callExpr->getArg(0);
  6654. const auto argType = arg->getType();
  6655. const auto boolType = theBuilder.getBoolType();
  6656. uint32_t condition = 0;
  6657. // Could not determine the argument as a constant. We need to branch based on
  6658. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  6659. // element of the vector/matrix is less than zero.
  6660. const uint32_t argId = doExpr(arg);
  6661. QualType elemType = {};
  6662. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  6663. if (TypeTranslator::isScalarType(argType)) {
  6664. const auto zero = getValueZero(argType);
  6665. condition = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  6666. argId, zero);
  6667. } else if (TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  6668. const auto zero = getValueZero(argType);
  6669. const auto boolVecType = theBuilder.getVecType(boolType, elemCount);
  6670. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6671. boolVecType, argId, zero);
  6672. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  6673. } else if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount,
  6674. &colCount)) {
  6675. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  6676. const uint32_t floatVecType = theBuilder.getVecType(elemTypeId, colCount);
  6677. const uint32_t elemZeroId = getValueZero(elemType);
  6678. llvm::SmallVector<uint32_t, 4> elements(size_t(colCount), elemZeroId);
  6679. const auto zero = theBuilder.getConstantComposite(floatVecType, elements);
  6680. llvm::SmallVector<uint32_t, 4> cmpResults;
  6681. for (uint32_t i = 0; i < rowCount; ++i) {
  6682. const uint32_t lhsVec =
  6683. theBuilder.createCompositeExtract(floatVecType, argId, {i});
  6684. const auto boolColType = theBuilder.getVecType(boolType, colCount);
  6685. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  6686. boolColType, lhsVec, zero);
  6687. const auto any = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  6688. cmpResults.push_back(any);
  6689. }
  6690. const auto boolRowType = theBuilder.getVecType(boolType, rowCount);
  6691. const auto results =
  6692. theBuilder.createCompositeConstruct(boolRowType, cmpResults);
  6693. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, results);
  6694. } else {
  6695. emitError("invalid argument type passed to clip intrinsic function",
  6696. callExpr->getExprLoc());
  6697. return 0;
  6698. }
  6699. // Then we need to emit the instruction for the conditional branch.
  6700. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  6701. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  6702. // Create the branch instruction. This will end the current basic block.
  6703. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  6704. theBuilder.addSuccessor(thenBB);
  6705. theBuilder.addSuccessor(mergeBB);
  6706. theBuilder.setMergeTarget(mergeBB);
  6707. // Handle the then branch
  6708. theBuilder.setInsertPoint(thenBB);
  6709. theBuilder.createKill();
  6710. theBuilder.addSuccessor(mergeBB);
  6711. // From now on, we'll emit instructions into the merge block.
  6712. theBuilder.setInsertPoint(mergeBB);
  6713. return 0;
  6714. }
  6715. uint32_t SPIRVEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  6716. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  6717. // one may be int, uint, or float.
  6718. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6719. const QualType returnType = callExpr->getType();
  6720. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6721. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  6722. if (isFloatOrVecMatOfFloatType(returnType))
  6723. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  6724. else if (isSintOrVecMatOfSintType(returnType))
  6725. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  6726. // Get the function parameters. Expect 3 parameters.
  6727. assert(callExpr->getNumArgs() == 3u);
  6728. const Expr *argX = callExpr->getArg(0);
  6729. const Expr *argMin = callExpr->getArg(1);
  6730. const Expr *argMax = callExpr->getArg(2);
  6731. const uint32_t argXId = doExpr(argX);
  6732. const uint32_t argMinId = doExpr(argMin);
  6733. const uint32_t argMaxId = doExpr(argMax);
  6734. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  6735. // the operation on each vector of the matrix.
  6736. if (TypeTranslator::isMxNMatrix(argX->getType())) {
  6737. const auto actOnEachVec = [this, glslInstSetId, glslOpcode, argMinId,
  6738. argMaxId](uint32_t index, uint32_t vecType,
  6739. uint32_t curRowId) {
  6740. const auto minRowId =
  6741. theBuilder.createCompositeExtract(vecType, argMinId, {index});
  6742. const auto maxRowId =
  6743. theBuilder.createCompositeExtract(vecType, argMaxId, {index});
  6744. return theBuilder.createExtInst(vecType, glslInstSetId, glslOpcode,
  6745. {curRowId, minRowId, maxRowId});
  6746. };
  6747. return processEachVectorInMatrix(argX, argXId, actOnEachVec);
  6748. }
  6749. return theBuilder.createExtInst(returnTypeId, glslInstSetId, glslOpcode,
  6750. {argXId, argMinId, argMaxId});
  6751. }
  6752. uint32_t SPIRVEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  6753. bool isDevice,
  6754. bool groupSync,
  6755. bool isAllBarrier) {
  6756. // * DeviceMemoryBarrier =
  6757. // OpMemoryBarrier (memScope=Device,
  6758. // sem=Image|Uniform|AcquireRelease)
  6759. //
  6760. // * DeviceMemoryBarrierWithGroupSync =
  6761. // OpControlBarrier(execScope = Workgroup,
  6762. // memScope=Device,
  6763. // sem=Image|Uniform|AcquireRelease)
  6764. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  6765. spv::MemorySemanticsMask::ImageMemory |
  6766. spv::MemorySemanticsMask::UniformMemory |
  6767. spv::MemorySemanticsMask::AcquireRelease;
  6768. // * GroupMemoryBarrier =
  6769. // OpMemoryBarrier (memScope=Workgroup,
  6770. // sem = Workgroup|AcquireRelease)
  6771. //
  6772. // * GroupMemoryBarrierWithGroupSync =
  6773. // OpControlBarrier (execScope = Workgroup,
  6774. // memScope = Workgroup,
  6775. // sem = Workgroup|AcquireRelease)
  6776. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  6777. spv::MemorySemanticsMask::WorkgroupMemory |
  6778. spv::MemorySemanticsMask::AcquireRelease;
  6779. // * AllMemoryBarrier =
  6780. // OpMemoryBarrier(memScope = Device,
  6781. // sem = Image|Uniform|Workgroup|AcquireRelease)
  6782. //
  6783. // * AllMemoryBarrierWithGroupSync =
  6784. // OpControlBarrier(execScope = Workgroup,
  6785. // memScope = Device,
  6786. // sem = Image|Uniform|Workgroup|AcquireRelease)
  6787. const spv::MemorySemanticsMask allMemoryBarrierSema =
  6788. spv::MemorySemanticsMask::ImageMemory |
  6789. spv::MemorySemanticsMask::UniformMemory |
  6790. spv::MemorySemanticsMask::WorkgroupMemory |
  6791. spv::MemorySemanticsMask::AtomicCounterMemory |
  6792. spv::MemorySemanticsMask::AcquireRelease;
  6793. // Get <result-id> for execution scope.
  6794. // If present, execution scope is always Workgroup!
  6795. const uint32_t execScopeId =
  6796. groupSync ? theBuilder.getConstantUint32(
  6797. static_cast<uint32_t>(spv::Scope::Workgroup))
  6798. : 0;
  6799. // Get <result-id> for memory scope
  6800. const spv::Scope memScope =
  6801. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  6802. const uint32_t memScopeId =
  6803. theBuilder.getConstantUint32(static_cast<uint32_t>(memScope));
  6804. // Get <result-id> for memory semantics
  6805. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  6806. : isDevice ? deviceMemoryBarrierSema
  6807. : groupMemoryBarrierSema;
  6808. const uint32_t memSema =
  6809. theBuilder.getConstantUint32(static_cast<uint32_t>(memSemaMask));
  6810. theBuilder.createBarrier(execScopeId, memScopeId, memSema);
  6811. return 0;
  6812. }
  6813. uint32_t SPIRVEmitter::processNonFpMatrixTranspose(QualType matType,
  6814. uint32_t matId) {
  6815. // Simplest way is to flatten the matrix construct a new matrix from the
  6816. // flattened elements. (for a mat4x4).
  6817. QualType elemType = {};
  6818. uint32_t numRows = 0, numCols = 0;
  6819. const bool isMat =
  6820. TypeTranslator::isMxNMatrix(matType, &elemType, &numRows, &numCols);
  6821. assert(isMat && !elemType->isFloatingType());
  6822. (void)isMat;
  6823. const auto colQualType = astContext.getExtVectorType(elemType, numRows);
  6824. const uint32_t colTypeId = typeTranslator.translateType(colQualType);
  6825. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  6826. // You cannot perform a composite construct of an array using a few vectors.
  6827. // The number of constutients passed to OpCompositeConstruct must be equal to
  6828. // the number of array elements.
  6829. llvm::SmallVector<uint32_t, 4> elems;
  6830. for (uint32_t i = 0; i < numRows; ++i)
  6831. for (uint32_t j = 0; j < numCols; ++j)
  6832. elems.push_back(
  6833. theBuilder.createCompositeExtract(elemTypeId, matId, {i, j}));
  6834. llvm::SmallVector<uint32_t, 4> cols;
  6835. for (uint32_t i = 0; i < numCols; ++i) {
  6836. // The elements in the ith vector of the "transposed" array are at offset i,
  6837. // i + <original-vector-size>, ...
  6838. llvm::SmallVector<uint32_t, 4> indexes;
  6839. for (uint32_t j = 0; j < numRows; ++j)
  6840. indexes.push_back(elems[i + (j * numCols)]);
  6841. cols.push_back(theBuilder.createCompositeConstruct(colTypeId, indexes));
  6842. }
  6843. const auto transposeTypeId =
  6844. theBuilder.getArrayType(colTypeId, theBuilder.getConstantUint32(numCols));
  6845. return theBuilder.createCompositeConstruct(transposeTypeId, cols);
  6846. }
  6847. uint32_t SPIRVEmitter::processNonFpDot(uint32_t vec1Id, uint32_t vec2Id,
  6848. uint32_t vecSize, QualType elemType) {
  6849. const auto elemTypeId = typeTranslator.translateType(elemType);
  6850. llvm::SmallVector<uint32_t, 4> muls;
  6851. for (uint32_t i = 0; i < vecSize; ++i) {
  6852. const auto elem1 =
  6853. theBuilder.createCompositeExtract(elemTypeId, vec1Id, {i});
  6854. const auto elem2 =
  6855. theBuilder.createCompositeExtract(elemTypeId, vec2Id, {i});
  6856. muls.push_back(theBuilder.createBinaryOp(translateOp(BO_Mul, elemType),
  6857. elemTypeId, elem1, elem2));
  6858. }
  6859. uint32_t sum = muls[0];
  6860. for (uint32_t i = 1; i < vecSize; ++i) {
  6861. sum = theBuilder.createBinaryOp(translateOp(BO_Add, elemType), elemTypeId,
  6862. sum, muls[i]);
  6863. }
  6864. return sum;
  6865. }
  6866. uint32_t SPIRVEmitter::processNonFpScalarTimesMatrix(QualType scalarType,
  6867. uint32_t scalarId,
  6868. QualType matrixType,
  6869. uint32_t matrixId) {
  6870. assert(TypeTranslator::isScalarType(scalarType));
  6871. QualType elemType = {};
  6872. uint32_t numRows = 0, numCols = 0;
  6873. const bool isMat =
  6874. TypeTranslator::isMxNMatrix(matrixType, &elemType, &numRows, &numCols);
  6875. assert(isMat);
  6876. assert(typeTranslator.isSameType(scalarType, elemType));
  6877. (void)isMat;
  6878. // We need to multiply the scalar by each vector of the matrix.
  6879. // The front-end guarantees that the scalar and matrix element type are
  6880. // the same. For example, if the scalar is a float, the matrix is casted
  6881. // to a float matrix before being passed to mul(). It is also guaranteed
  6882. // that types such as bool are casted to float or int before being
  6883. // passed to mul().
  6884. const auto rowType = astContext.getExtVectorType(elemType, numCols);
  6885. const auto rowTypeId = typeTranslator.translateType(rowType);
  6886. llvm::SmallVector<uint32_t, 4> splat(size_t(numCols), scalarId);
  6887. const auto scalarSplat =
  6888. theBuilder.createCompositeConstruct(rowTypeId, splat);
  6889. llvm::SmallVector<uint32_t, 4> mulRows;
  6890. for (uint32_t row = 0; row < numRows; ++row) {
  6891. const auto rowId =
  6892. theBuilder.createCompositeExtract(rowTypeId, matrixId, {row});
  6893. mulRows.push_back(theBuilder.createBinaryOp(translateOp(BO_Mul, scalarType),
  6894. rowTypeId, rowId, scalarSplat));
  6895. }
  6896. return theBuilder.createCompositeConstruct(
  6897. typeTranslator.translateType(matrixType), mulRows);
  6898. }
  6899. uint32_t SPIRVEmitter::processNonFpVectorTimesMatrix(QualType vecType,
  6900. uint32_t vecId,
  6901. QualType matType,
  6902. uint32_t matId,
  6903. uint32_t matTransposeId) {
  6904. // This function assumes that the vector element type and matrix elemet type
  6905. // are the same.
  6906. QualType vecElemType = {}, matElemType = {};
  6907. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  6908. const bool isVec =
  6909. TypeTranslator::isVectorType(vecType, &vecElemType, &vecSize);
  6910. const bool isMat =
  6911. TypeTranslator::isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  6912. assert(typeTranslator.isSameType(vecElemType, matElemType));
  6913. assert(isVec);
  6914. assert(isMat);
  6915. assert(vecSize == numRows);
  6916. (void)isVec;
  6917. (void)isMat;
  6918. // When processing vector times matrix, the vector is a row vector, and it
  6919. // should be multiplied by the matrix *columns*. The most efficient way to
  6920. // handle this in SPIR-V would be to first transpose the matrix, and then use
  6921. // OpAccessChain.
  6922. if (!matTransposeId)
  6923. matTransposeId = processNonFpMatrixTranspose(matType, matId);
  6924. const auto vecTypeId = typeTranslator.translateType(vecType);
  6925. llvm::SmallVector<uint32_t, 4> resultElems;
  6926. for (uint32_t col = 0; col < numCols; ++col) {
  6927. const auto colId =
  6928. theBuilder.createCompositeExtract(vecTypeId, matTransposeId, {col});
  6929. resultElems.push_back(processNonFpDot(vecId, colId, vecSize, vecElemType));
  6930. }
  6931. return theBuilder.createCompositeConstruct(
  6932. typeTranslator.translateType(
  6933. astContext.getExtVectorType(vecElemType, numCols)),
  6934. resultElems);
  6935. }
  6936. uint32_t SPIRVEmitter::processNonFpMatrixTimesVector(QualType matType,
  6937. uint32_t matId,
  6938. QualType vecType,
  6939. uint32_t vecId) {
  6940. // This function assumes that the vector element type and matrix elemet type
  6941. // are the same.
  6942. QualType vecElemType = {}, matElemType = {};
  6943. uint32_t vecSize = 0, numRows = 0, numCols = 0;
  6944. const bool isVec =
  6945. TypeTranslator::isVectorType(vecType, &vecElemType, &vecSize);
  6946. const bool isMat =
  6947. TypeTranslator::isMxNMatrix(matType, &matElemType, &numRows, &numCols);
  6948. assert(typeTranslator.isSameType(vecElemType, matElemType));
  6949. assert(isVec);
  6950. assert(isMat);
  6951. assert(vecSize == numCols);
  6952. (void)isVec;
  6953. (void)isMat;
  6954. // When processing matrix times vector, the vector is a column vector. So we
  6955. // simply get each row of the matrix and perform a dot product with the
  6956. // vector.
  6957. const auto vecTypeId = typeTranslator.translateType(vecType);
  6958. llvm::SmallVector<uint32_t, 4> resultElems;
  6959. for (uint32_t row = 0; row < numRows; ++row) {
  6960. const auto rowId =
  6961. theBuilder.createCompositeExtract(vecTypeId, matId, {row});
  6962. resultElems.push_back(processNonFpDot(rowId, vecId, vecSize, vecElemType));
  6963. }
  6964. return theBuilder.createCompositeConstruct(
  6965. typeTranslator.translateType(
  6966. astContext.getExtVectorType(vecElemType, numRows)),
  6967. resultElems);
  6968. }
  6969. uint32_t SPIRVEmitter::processNonFpMatrixTimesMatrix(QualType lhsType,
  6970. uint32_t lhsId,
  6971. QualType rhsType,
  6972. uint32_t rhsId) {
  6973. // This function assumes that the vector element type and matrix elemet type
  6974. // are the same.
  6975. QualType lhsElemType = {}, rhsElemType = {};
  6976. uint32_t lhsNumRows = 0, lhsNumCols = 0;
  6977. uint32_t rhsNumRows = 0, rhsNumCols = 0;
  6978. const bool lhsIsMat = TypeTranslator::isMxNMatrix(lhsType, &lhsElemType,
  6979. &lhsNumRows, &lhsNumCols);
  6980. const bool rhsIsMat = TypeTranslator::isMxNMatrix(rhsType, &rhsElemType,
  6981. &rhsNumRows, &rhsNumCols);
  6982. assert(typeTranslator.isSameType(lhsElemType, rhsElemType));
  6983. assert(lhsIsMat && rhsIsMat);
  6984. assert(lhsNumCols == rhsNumRows);
  6985. (void)rhsIsMat;
  6986. (void)lhsIsMat;
  6987. const uint32_t rhsTranspose = processNonFpMatrixTranspose(rhsType, rhsId);
  6988. const auto vecType = astContext.getExtVectorType(lhsElemType, lhsNumCols);
  6989. const auto vecTypeId = typeTranslator.translateType(vecType);
  6990. llvm::SmallVector<uint32_t, 4> resultRows;
  6991. for (uint32_t row = 0; row < lhsNumRows; ++row) {
  6992. const auto rowId =
  6993. theBuilder.createCompositeExtract(vecTypeId, lhsId, {row});
  6994. resultRows.push_back(processNonFpVectorTimesMatrix(vecType, rowId, rhsType,
  6995. rhsId, rhsTranspose));
  6996. }
  6997. // The resulting matrix will have 'lhsNumRows' rows and 'rhsNumCols' columns.
  6998. const auto elemTypeId = typeTranslator.translateType(lhsElemType);
  6999. const auto resultNumRows = theBuilder.getConstantUint32(lhsNumRows);
  7000. const auto resultColType = theBuilder.getVecType(elemTypeId, rhsNumCols);
  7001. const auto resultType = theBuilder.getArrayType(resultColType, resultNumRows);
  7002. return theBuilder.createCompositeConstruct(resultType, resultRows);
  7003. }
  7004. uint32_t SPIRVEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  7005. const uint32_t returnTypeId =
  7006. typeTranslator.translateType(callExpr->getType());
  7007. // Get the function parameters. Expect 2 parameters.
  7008. assert(callExpr->getNumArgs() == 2u);
  7009. const Expr *arg0 = callExpr->getArg(0);
  7010. const Expr *arg1 = callExpr->getArg(1);
  7011. const QualType arg0Type = arg0->getType();
  7012. const QualType arg1Type = arg1->getType();
  7013. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  7014. // vector, or matrix. The frontend ensures that the two arguments have the
  7015. // same component type. The only allowed component types are int and float.
  7016. // mul(scalar, vector)
  7017. {
  7018. uint32_t elemCount = 0;
  7019. if (TypeTranslator::isScalarType(arg0Type) &&
  7020. TypeTranslator::isVectorType(arg1Type, nullptr, &elemCount)) {
  7021. const uint32_t arg1Id = doExpr(arg1);
  7022. // We can use OpVectorTimesScalar if arguments are floats.
  7023. if (arg0Type->isFloatingType())
  7024. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  7025. returnTypeId, arg1Id, doExpr(arg0));
  7026. // Use OpIMul for integers
  7027. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId,
  7028. createVectorSplat(arg0, elemCount),
  7029. arg1Id);
  7030. }
  7031. }
  7032. // mul(vector, scalar)
  7033. {
  7034. uint32_t elemCount = 0;
  7035. if (TypeTranslator::isVectorType(arg0Type, nullptr, &elemCount) &&
  7036. TypeTranslator::isScalarType(arg1Type)) {
  7037. const uint32_t arg0Id = doExpr(arg0);
  7038. // We can use OpVectorTimesScalar if arguments are floats.
  7039. if (arg1Type->isFloatingType())
  7040. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  7041. returnTypeId, arg0Id, doExpr(arg1));
  7042. // Use OpIMul for integers
  7043. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId, arg0Id,
  7044. createVectorSplat(arg1, elemCount));
  7045. }
  7046. }
  7047. // mul(vector, vector)
  7048. if (TypeTranslator::isVectorType(arg0Type) &&
  7049. TypeTranslator::isVectorType(arg1Type))
  7050. return processIntrinsicDot(callExpr);
  7051. // All the following cases require handling arg0 and arg1 expressions first.
  7052. const uint32_t arg0Id = doExpr(arg0);
  7053. const uint32_t arg1Id = doExpr(arg1);
  7054. // mul(scalar, scalar)
  7055. if (TypeTranslator::isScalarType(arg0Type) &&
  7056. TypeTranslator::isScalarType(arg1Type))
  7057. return theBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type),
  7058. returnTypeId, arg0Id, arg1Id);
  7059. // mul(scalar, matrix)
  7060. {
  7061. QualType elemType = {};
  7062. if (TypeTranslator::isScalarType(arg0Type) &&
  7063. TypeTranslator::isMxNMatrix(arg1Type, &elemType)) {
  7064. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  7065. // and the scalar type are float.
  7066. if (arg0Type->isFloatingType() && elemType->isFloatingType())
  7067. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  7068. returnTypeId, arg1Id, arg0Id);
  7069. else
  7070. return processNonFpScalarTimesMatrix(arg0Type, arg0Id, arg1Type,
  7071. arg1Id);
  7072. }
  7073. }
  7074. // mul(matrix, scalar)
  7075. {
  7076. QualType elemType = {};
  7077. if (TypeTranslator::isScalarType(arg1Type) &&
  7078. TypeTranslator::isMxNMatrix(arg0Type, &elemType)) {
  7079. // OpMatrixTimesScalar can only be used if *both* the matrix element type
  7080. // and the scalar type are float.
  7081. if (arg1Type->isFloatingType() && elemType->isFloatingType())
  7082. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  7083. returnTypeId, arg0Id, arg1Id);
  7084. else
  7085. return processNonFpScalarTimesMatrix(arg1Type, arg1Id, arg0Type,
  7086. arg0Id);
  7087. }
  7088. }
  7089. // mul(vector, matrix)
  7090. {
  7091. QualType vecElemType = {}, matElemType = {};
  7092. uint32_t elemCount = 0, numRows = 0;
  7093. if (TypeTranslator::isVectorType(arg0Type, &vecElemType, &elemCount) &&
  7094. TypeTranslator::isMxNMatrix(arg1Type, &matElemType, &numRows)) {
  7095. assert(elemCount == numRows);
  7096. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  7097. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  7098. returnTypeId, arg1Id, arg0Id);
  7099. else
  7100. return processNonFpVectorTimesMatrix(arg0Type, arg0Id, arg1Type,
  7101. arg1Id);
  7102. }
  7103. }
  7104. // mul(matrix, vector)
  7105. {
  7106. QualType vecElemType = {}, matElemType = {};
  7107. uint32_t elemCount = 0, numCols = 0;
  7108. if (TypeTranslator::isMxNMatrix(arg0Type, &matElemType, nullptr,
  7109. &numCols) &&
  7110. TypeTranslator::isVectorType(arg1Type, &vecElemType, &elemCount)) {
  7111. assert(elemCount == numCols);
  7112. if (vecElemType->isFloatingType() && matElemType->isFloatingType())
  7113. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  7114. returnTypeId, arg1Id, arg0Id);
  7115. else
  7116. return processNonFpMatrixTimesVector(arg0Type, arg0Id, arg1Type,
  7117. arg1Id);
  7118. }
  7119. }
  7120. // mul(matrix, matrix)
  7121. {
  7122. // The front-end ensures that the two matrix element types match.
  7123. QualType elemType = {};
  7124. uint32_t lhsCols = 0, rhsRows = 0;
  7125. if (TypeTranslator::isMxNMatrix(arg0Type, &elemType, nullptr, &lhsCols) &&
  7126. TypeTranslator::isMxNMatrix(arg1Type, nullptr, &rhsRows, nullptr)) {
  7127. assert(lhsCols == rhsRows);
  7128. if (elemType->isFloatingType())
  7129. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  7130. returnTypeId, arg1Id, arg0Id);
  7131. else
  7132. return processNonFpMatrixTimesMatrix(arg0Type, arg0Id, arg1Type,
  7133. arg1Id);
  7134. }
  7135. }
  7136. emitError("invalid argument type passed to mul intrinsic function",
  7137. callExpr->getExprLoc());
  7138. return 0;
  7139. }
  7140. uint32_t SPIRVEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  7141. const QualType returnType = callExpr->getType();
  7142. const uint32_t returnTypeId =
  7143. typeTranslator.translateType(callExpr->getType());
  7144. // Get the function parameters. Expect 2 vectors as parameters.
  7145. assert(callExpr->getNumArgs() == 2u);
  7146. const Expr *arg0 = callExpr->getArg(0);
  7147. const Expr *arg1 = callExpr->getArg(1);
  7148. const uint32_t arg0Id = doExpr(arg0);
  7149. const uint32_t arg1Id = doExpr(arg1);
  7150. QualType arg0Type = arg0->getType();
  7151. QualType arg1Type = arg1->getType();
  7152. const size_t vec0Size = hlsl::GetHLSLVecSize(arg0Type);
  7153. const size_t vec1Size = hlsl::GetHLSLVecSize(arg1Type);
  7154. const QualType vec0ComponentType = hlsl::GetHLSLVecElementType(arg0Type);
  7155. const QualType vec1ComponentType = hlsl::GetHLSLVecElementType(arg1Type);
  7156. assert(returnType == vec1ComponentType);
  7157. assert(vec0ComponentType == vec1ComponentType);
  7158. assert(vec0Size == vec1Size);
  7159. assert(vec0Size >= 1 && vec0Size <= 4);
  7160. (void)vec0ComponentType;
  7161. (void)vec1ComponentType;
  7162. (void)vec1Size;
  7163. // According to HLSL reference, the dot function only works on integers
  7164. // and floats.
  7165. assert(returnType->isFloatingType() || returnType->isIntegerType());
  7166. // Special case: dot product of two vectors, each of size 1. That is
  7167. // basically the same as regular multiplication of 2 scalars.
  7168. if (vec0Size == 1) {
  7169. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  7170. return theBuilder.createBinaryOp(spvOp, returnTypeId, arg0Id, arg1Id);
  7171. }
  7172. // If the vectors are of type Float, we can use OpDot.
  7173. if (returnType->isFloatingType()) {
  7174. return theBuilder.createBinaryOp(spv::Op::OpDot, returnTypeId, arg0Id,
  7175. arg1Id);
  7176. }
  7177. // Vector component type is Integer (signed or unsigned).
  7178. // Create all instructions necessary to perform a dot product on
  7179. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  7180. // Therefore, we use other SPIR-V instructions (addition and
  7181. // multiplication).
  7182. else {
  7183. uint32_t result = 0;
  7184. llvm::SmallVector<uint32_t, 4> multIds;
  7185. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  7186. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  7187. // Extract members from the two vectors and multiply them.
  7188. for (unsigned int i = 0; i < vec0Size; ++i) {
  7189. const uint32_t vec0member =
  7190. theBuilder.createCompositeExtract(returnTypeId, arg0Id, {i});
  7191. const uint32_t vec1member =
  7192. theBuilder.createCompositeExtract(returnTypeId, arg1Id, {i});
  7193. const uint32_t multId = theBuilder.createBinaryOp(multSpvOp, returnTypeId,
  7194. vec0member, vec1member);
  7195. multIds.push_back(multId);
  7196. }
  7197. // Add all the multiplications.
  7198. result = multIds[0];
  7199. for (unsigned int i = 1; i < vec0Size; ++i) {
  7200. const uint32_t additionId =
  7201. theBuilder.createBinaryOp(addSpvOp, returnTypeId, result, multIds[i]);
  7202. result = additionId;
  7203. }
  7204. return result;
  7205. }
  7206. }
  7207. uint32_t SPIRVEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  7208. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  7209. // float or double.
  7210. assert(callExpr->getNumArgs() == 1u);
  7211. const QualType returnType = callExpr->getType();
  7212. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  7213. const Expr *arg = callExpr->getArg(0);
  7214. const uint32_t argId = doExpr(arg);
  7215. const QualType argType = arg->getType();
  7216. // For cases with matrix argument.
  7217. QualType elemType = {};
  7218. uint32_t numRows = 0, numCols = 0;
  7219. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  7220. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  7221. const auto actOnEachVec = [this, vecOne](uint32_t /*index*/,
  7222. uint32_t vecType,
  7223. uint32_t curRowId) {
  7224. return theBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne,
  7225. curRowId);
  7226. };
  7227. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7228. }
  7229. // For cases with scalar or vector arguments.
  7230. return theBuilder.createBinaryOp(spv::Op::OpFDiv, returnTypeId,
  7231. getValueOne(argType), argId);
  7232. }
  7233. uint32_t SPIRVEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  7234. spv::Op spvOp) {
  7235. // 'all' and 'any' take only 1 parameter.
  7236. assert(callExpr->getNumArgs() == 1u);
  7237. const QualType returnType = callExpr->getType();
  7238. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  7239. const Expr *arg = callExpr->getArg(0);
  7240. const QualType argType = arg->getType();
  7241. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  7242. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  7243. {
  7244. QualType scalarType = {};
  7245. if (TypeTranslator::isScalarType(argType, &scalarType) &&
  7246. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  7247. scalarType->isIntegerType()))
  7248. return castToBool(doExpr(arg), argType, returnType);
  7249. }
  7250. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  7251. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  7252. {
  7253. QualType elemType = {};
  7254. uint32_t size = 0;
  7255. if (TypeTranslator::isVectorType(argType, &elemType, &size)) {
  7256. const QualType castToBoolType =
  7257. astContext.getExtVectorType(returnType, size);
  7258. uint32_t castedToBoolId =
  7259. castToBool(doExpr(arg), argType, castToBoolType);
  7260. return theBuilder.createUnaryOp(spvOp, returnTypeId, castedToBoolId);
  7261. }
  7262. }
  7263. // Handle MxN matrices as arguments.
  7264. {
  7265. QualType elemType = {};
  7266. uint32_t matRowCount = 0, matColCount = 0;
  7267. if (TypeTranslator::isMxNMatrix(argType, &elemType, &matRowCount,
  7268. &matColCount)) {
  7269. uint32_t matrixId = doExpr(arg);
  7270. const uint32_t vecType = typeTranslator.getComponentVectorType(argType);
  7271. llvm::SmallVector<uint32_t, 4> rowResults;
  7272. for (uint32_t i = 0; i < matRowCount; ++i) {
  7273. // Extract the row which is a float vector of size matColCount.
  7274. const uint32_t rowFloatVec =
  7275. theBuilder.createCompositeExtract(vecType, matrixId, {i});
  7276. // Cast the float vector to boolean vector.
  7277. const auto rowFloatQualType =
  7278. astContext.getExtVectorType(elemType, matColCount);
  7279. const auto rowBoolQualType =
  7280. astContext.getExtVectorType(returnType, matColCount);
  7281. const uint32_t rowBoolVec =
  7282. castToBool(rowFloatVec, rowFloatQualType, rowBoolQualType);
  7283. // Perform OpAny/OpAll on the boolean vector.
  7284. rowResults.push_back(
  7285. theBuilder.createUnaryOp(spvOp, returnTypeId, rowBoolVec));
  7286. }
  7287. // Create a new vector that is the concatenation of results of all rows.
  7288. uint32_t boolId = theBuilder.getBoolType();
  7289. uint32_t vecOfBoolsId = theBuilder.getVecType(boolId, matRowCount);
  7290. const uint32_t rowResultsId =
  7291. theBuilder.createCompositeConstruct(vecOfBoolsId, rowResults);
  7292. // Run OpAny/OpAll on the newly-created vector.
  7293. return theBuilder.createUnaryOp(spvOp, returnTypeId, rowResultsId);
  7294. }
  7295. }
  7296. // All types should be handled already.
  7297. llvm_unreachable("Unknown argument type passed to all()/any().");
  7298. return 0;
  7299. }
  7300. uint32_t SPIRVEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  7301. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  7302. // Method 1: ret asint(arg)
  7303. // arg component type = {float, uint}
  7304. // arg template type = {scalar, vector, matrix}
  7305. // ret template type = same as arg template type.
  7306. // ret component type = int
  7307. // Method 2: ret asuint(arg)
  7308. // arg component type = {float, int}
  7309. // arg template type = {scalar, vector, matrix}
  7310. // ret template type = same as arg template type.
  7311. // ret component type = uint
  7312. // Method 3: ret asfloat(arg)
  7313. // arg component type = {float, uint, int}
  7314. // arg template type = {scalar, vector, matrix}
  7315. // ret template type = same as arg template type.
  7316. // ret component type = float
  7317. // Method 4: double asdouble(uint lowbits, uint highbits)
  7318. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  7319. // Method 6:
  7320. // void asuint(
  7321. // in double value,
  7322. // out uint lowbits,
  7323. // out uint highbits
  7324. // );
  7325. const QualType returnType = callExpr->getType();
  7326. const uint32_t numArgs = callExpr->getNumArgs();
  7327. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  7328. const Expr *arg0 = callExpr->getArg(0);
  7329. const QualType argType = arg0->getType();
  7330. // Method 3 return type may be the same as arg type, so it would be a no-op.
  7331. if (typeTranslator.isSameType(returnType, argType))
  7332. return doExpr(arg0);
  7333. switch (numArgs) {
  7334. case 1: {
  7335. // Handling Method 1, 2, and 3.
  7336. const auto argId = doExpr(arg0);
  7337. QualType fromElemType = {};
  7338. uint32_t numRows = 0, numCols = 0;
  7339. // For non-matrix arguments (scalar or vector), just do an OpBitCast.
  7340. if (!TypeTranslator::isMxNMatrix(argType, &fromElemType, &numRows,
  7341. &numCols)) {
  7342. return theBuilder.createUnaryOp(spv::Op::OpBitcast, returnTypeId, argId);
  7343. }
  7344. // Input or output type is a matrix.
  7345. const QualType toElemType = hlsl::GetHLSLMatElementType(returnType);
  7346. llvm::SmallVector<uint32_t, 4> castedRows;
  7347. const auto fromVecQualType =
  7348. astContext.getExtVectorType(fromElemType, numCols);
  7349. const auto toVecQualType = astContext.getExtVectorType(toElemType, numCols);
  7350. const auto fromVecTypeId = typeTranslator.translateType(fromVecQualType);
  7351. const auto toVecTypeId = typeTranslator.translateType(toVecQualType);
  7352. for (uint32_t row = 0; row < numRows; ++row) {
  7353. const auto rowId =
  7354. theBuilder.createCompositeExtract(fromVecTypeId, argId, {row});
  7355. castedRows.push_back(
  7356. theBuilder.createUnaryOp(spv::Op::OpBitcast, toVecTypeId, rowId));
  7357. }
  7358. return theBuilder.createCompositeConstruct(returnTypeId, castedRows);
  7359. }
  7360. case 2: {
  7361. const uint32_t lowbits = doExpr(arg0);
  7362. const uint32_t highbits = doExpr(callExpr->getArg(1));
  7363. const uint32_t uintType = theBuilder.getUint32Type();
  7364. const uint32_t doubleType = theBuilder.getFloat64Type();
  7365. // Handling Method 4
  7366. if (argType->isUnsignedIntegerType()) {
  7367. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  7368. const uint32_t operand = theBuilder.createCompositeConstruct(
  7369. uintVec2Type, {lowbits, highbits});
  7370. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand);
  7371. }
  7372. // Handling Method 5
  7373. else {
  7374. const uint32_t uintVec4Type = theBuilder.getVecType(uintType, 4);
  7375. const uint32_t doubleVec2Type = theBuilder.getVecType(doubleType, 2);
  7376. const uint32_t operand = theBuilder.createVectorShuffle(
  7377. uintVec4Type, lowbits, highbits, {0, 2, 1, 3});
  7378. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  7379. operand);
  7380. }
  7381. }
  7382. case 3: {
  7383. // Handling Method 6.
  7384. const uint32_t value = doExpr(arg0);
  7385. const uint32_t lowbits = doExpr(callExpr->getArg(1));
  7386. const uint32_t highbits = doExpr(callExpr->getArg(2));
  7387. const uint32_t uintType = theBuilder.getUint32Type();
  7388. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  7389. const uint32_t vecResult =
  7390. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value);
  7391. theBuilder.createStore(
  7392. lowbits, theBuilder.createCompositeExtract(uintType, vecResult, {0}));
  7393. theBuilder.createStore(
  7394. highbits, theBuilder.createCompositeExtract(uintType, vecResult, {1}));
  7395. return 0;
  7396. }
  7397. default:
  7398. emitError("unrecognized signature for %0 intrinsic function",
  7399. callExpr->getExprLoc())
  7400. << callExpr->getDirectCallee()->getName();
  7401. return 0;
  7402. }
  7403. }
  7404. uint32_t SPIRVEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  7405. // Should take a float4 and return an int4 by doing:
  7406. // int4 result = input.zyxw * 255.001953;
  7407. // Maximum float precision makes the scaling factor 255.002.
  7408. const auto arg = callExpr->getArg(0);
  7409. const auto argId = doExpr(arg);
  7410. const auto argTypeId = typeTranslator.translateType(arg->getType());
  7411. const auto swizzle =
  7412. theBuilder.createVectorShuffle(argTypeId, argId, argId, {2, 1, 0, 3});
  7413. const auto scaled = theBuilder.createBinaryOp(
  7414. spv::Op::OpVectorTimesScalar, argTypeId, swizzle,
  7415. theBuilder.getConstantFloat32(255.002f));
  7416. return castToInt(scaled, arg->getType(), callExpr->getType(),
  7417. callExpr->getExprLoc());
  7418. }
  7419. uint32_t SPIRVEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  7420. // Since OpIsFinite needs the Kernel capability, translation is instead done
  7421. // using OpIsNan and OpIsInf:
  7422. // isFinite = !(isNan || isInf)
  7423. const auto arg = doExpr(callExpr->getArg(0));
  7424. const auto returnType = typeTranslator.translateType(callExpr->getType());
  7425. const auto isNan =
  7426. theBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg);
  7427. const auto isInf =
  7428. theBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg);
  7429. const auto isNanOrInf =
  7430. theBuilder.createBinaryOp(spv::Op::OpLogicalOr, returnType, isNan, isInf);
  7431. return theBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType,
  7432. isNanOrInf);
  7433. }
  7434. uint32_t SPIRVEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  7435. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  7436. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  7437. CallExpr *sincosExpr =
  7438. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  7439. sincosExpr->setType(callExpr->getArg(0)->getType());
  7440. sincosExpr->setNumArgs(astContext, 1);
  7441. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  7442. // Perform Sin and store results in argument 1.
  7443. const uint32_t sin =
  7444. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  7445. /*actPerRowForMatrices*/ true);
  7446. theBuilder.createStore(doExpr(callExpr->getArg(1)), sin);
  7447. // Perform Cos and store results in argument 2.
  7448. const uint32_t cos =
  7449. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  7450. /*actPerRowForMatrices*/ true);
  7451. theBuilder.createStore(doExpr(callExpr->getArg(2)), cos);
  7452. return 0;
  7453. }
  7454. uint32_t SPIRVEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  7455. const auto *arg = callExpr->getArg(0);
  7456. const auto argId = doExpr(arg);
  7457. const auto argType = arg->getType();
  7458. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7459. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7460. if (argType->isFloatingType()) {
  7461. const uint32_t floatZero = getValueZero(argType);
  7462. const uint32_t floatOne = getValueOne(argType);
  7463. return theBuilder.createExtInst(returnType, glslInstSetId,
  7464. GLSLstd450::GLSLstd450FClamp,
  7465. {argId, floatZero, floatOne});
  7466. }
  7467. QualType elemType = {};
  7468. uint32_t vecSize = 0;
  7469. if (TypeTranslator::isVectorType(argType, &elemType, &vecSize)) {
  7470. const uint32_t vecZero = getVecValueZero(elemType, vecSize);
  7471. const uint32_t vecOne = getVecValueOne(elemType, vecSize);
  7472. return theBuilder.createExtInst(returnType, glslInstSetId,
  7473. GLSLstd450::GLSLstd450FClamp,
  7474. {argId, vecZero, vecOne});
  7475. }
  7476. uint32_t numRows = 0, numCols = 0;
  7477. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  7478. const uint32_t vecZero = getVecValueZero(elemType, numCols);
  7479. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  7480. const auto actOnEachVec = [this, vecZero, vecOne, glslInstSetId](
  7481. uint32_t /*index*/, uint32_t vecType,
  7482. uint32_t curRowId) {
  7483. return theBuilder.createExtInst(vecType, glslInstSetId,
  7484. GLSLstd450::GLSLstd450FClamp,
  7485. {curRowId, vecZero, vecOne});
  7486. };
  7487. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7488. }
  7489. emitError("invalid argument type passed to saturate intrinsic function",
  7490. callExpr->getExprLoc());
  7491. return 0;
  7492. }
  7493. uint32_t SPIRVEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  7494. // Import the GLSL.std.450 extended instruction set.
  7495. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7496. const Expr *arg = callExpr->getArg(0);
  7497. const QualType returnType = callExpr->getType();
  7498. const QualType argType = arg->getType();
  7499. assert(isFloatOrVecMatOfFloatType(argType));
  7500. const uint32_t argTypeId = typeTranslator.translateType(argType);
  7501. const uint32_t argId = doExpr(arg);
  7502. uint32_t floatSignResultId = 0;
  7503. // For matrices, we can perform the instruction on each vector of the matrix.
  7504. if (TypeTranslator::isMxNMatrix(argType)) {
  7505. const auto actOnEachVec = [this, glslInstSetId](uint32_t /*index*/,
  7506. uint32_t vecType,
  7507. uint32_t curRowId) {
  7508. return theBuilder.createExtInst(vecType, glslInstSetId,
  7509. GLSLstd450::GLSLstd450FSign, {curRowId});
  7510. };
  7511. floatSignResultId = processEachVectorInMatrix(arg, argId, actOnEachVec);
  7512. } else {
  7513. floatSignResultId = theBuilder.createExtInst(
  7514. argTypeId, glslInstSetId, GLSLstd450::GLSLstd450FSign, {argId});
  7515. }
  7516. return castToInt(floatSignResultId, arg->getType(), returnType,
  7517. arg->getExprLoc());
  7518. }
  7519. uint32_t SPIRVEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  7520. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  7521. // The frontend should guarantee that by inserting implicit casts.
  7522. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  7523. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  7524. const uint32_t u32TypeId = theBuilder.getUint32Type();
  7525. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  7526. const auto *arg = callExpr->getArg(0);
  7527. const uint32_t argId = doExpr(arg);
  7528. uint32_t elemCount = {};
  7529. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  7530. // The input is a vector. We need to handle each element separately.
  7531. llvm::SmallVector<uint32_t, 4> elements;
  7532. for (uint32_t i = 0; i < elemCount; ++i) {
  7533. const uint32_t srcElem =
  7534. theBuilder.createCompositeExtract(u32TypeId, argId, {i});
  7535. const uint32_t convert = theBuilder.createExtInst(
  7536. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem);
  7537. elements.push_back(
  7538. theBuilder.createCompositeExtract(f32TypeId, convert, {0}));
  7539. }
  7540. return theBuilder.createCompositeConstruct(
  7541. theBuilder.getVecType(f32TypeId, elemCount), elements);
  7542. }
  7543. const uint32_t convert = theBuilder.createExtInst(
  7544. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, argId);
  7545. // f16tof32() converts the float16 stored in the low-half of the uint to
  7546. // a float. So just need to return the first component.
  7547. return theBuilder.createCompositeExtract(f32TypeId, convert, {0});
  7548. }
  7549. uint32_t SPIRVEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  7550. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  7551. // The frontend should guarantee that by inserting implicit casts.
  7552. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  7553. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  7554. const uint32_t u32TypeId = theBuilder.getUint32Type();
  7555. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  7556. const uint32_t zero = theBuilder.getConstantFloat32(0);
  7557. const auto *arg = callExpr->getArg(0);
  7558. const uint32_t argId = doExpr(arg);
  7559. uint32_t elemCount = {};
  7560. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  7561. // The input is a vector. We need to handle each element separately.
  7562. llvm::SmallVector<uint32_t, 4> elements;
  7563. for (uint32_t i = 0; i < elemCount; ++i) {
  7564. const uint32_t srcElem =
  7565. theBuilder.createCompositeExtract(f32TypeId, argId, {i});
  7566. const uint32_t srcVec =
  7567. theBuilder.createCompositeConstruct(v2f32TypeId, {srcElem, zero});
  7568. elements.push_back(theBuilder.createExtInst(
  7569. u32TypeId, glsl, GLSLstd450::GLSLstd450PackHalf2x16, srcVec));
  7570. }
  7571. return theBuilder.createCompositeConstruct(
  7572. theBuilder.getVecType(u32TypeId, elemCount), elements);
  7573. }
  7574. // f16tof32() stores the float into the low-half of the uint. So we need
  7575. // to supply another zero to take the other half.
  7576. const uint32_t srcVec =
  7577. theBuilder.createCompositeConstruct(v2f32TypeId, {argId, zero});
  7578. return theBuilder.createExtInst(u32TypeId, glsl,
  7579. GLSLstd450::GLSLstd450PackHalf2x16, srcVec);
  7580. }
  7581. uint32_t SPIRVEmitter::processIntrinsicUsingSpirvInst(
  7582. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  7583. // Certain opcodes are only allowed in pixel shader
  7584. if (!shaderModel.IsPS())
  7585. switch (opcode) {
  7586. case spv::Op::OpDPdx:
  7587. case spv::Op::OpDPdy:
  7588. case spv::Op::OpDPdxFine:
  7589. case spv::Op::OpDPdyFine:
  7590. case spv::Op::OpDPdxCoarse:
  7591. case spv::Op::OpDPdyCoarse:
  7592. case spv::Op::OpFwidth:
  7593. case spv::Op::OpFwidthFine:
  7594. case spv::Op::OpFwidthCoarse:
  7595. needsLegalization = true;
  7596. break;
  7597. default:
  7598. // Only the given opcodes need legalization. Anything else should preserve
  7599. // previous.
  7600. break;
  7601. }
  7602. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7603. if (callExpr->getNumArgs() == 1u) {
  7604. const Expr *arg = callExpr->getArg(0);
  7605. const uint32_t argId = doExpr(arg);
  7606. // If the instruction does not operate on matrices, we can perform the
  7607. // instruction on each vector of the matrix.
  7608. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg->getType())) {
  7609. const auto actOnEachVec = [this, opcode](uint32_t /*index*/,
  7610. uint32_t vecType,
  7611. uint32_t curRowId) {
  7612. return theBuilder.createUnaryOp(opcode, vecType, curRowId);
  7613. };
  7614. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7615. }
  7616. return theBuilder.createUnaryOp(opcode, returnType, argId);
  7617. } else if (callExpr->getNumArgs() == 2u) {
  7618. const Expr *arg0 = callExpr->getArg(0);
  7619. const uint32_t arg0Id = doExpr(arg0);
  7620. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7621. // If the instruction does not operate on matrices, we can perform the
  7622. // instruction on each vector of the matrix.
  7623. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7624. const auto actOnEachVec = [this, opcode, arg1Id](uint32_t index,
  7625. uint32_t vecType,
  7626. uint32_t arg0RowId) {
  7627. const uint32_t arg1RowId =
  7628. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7629. return theBuilder.createBinaryOp(opcode, vecType, arg0RowId, arg1RowId);
  7630. };
  7631. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7632. }
  7633. return theBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id);
  7634. }
  7635. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  7636. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  7637. return 0;
  7638. }
  7639. uint32_t SPIRVEmitter::processIntrinsicUsingGLSLInst(
  7640. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices) {
  7641. // Import the GLSL.std.450 extended instruction set.
  7642. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  7643. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  7644. if (callExpr->getNumArgs() == 1u) {
  7645. const Expr *arg = callExpr->getArg(0);
  7646. const uint32_t argId = doExpr(arg);
  7647. // If the instruction does not operate on matrices, we can perform the
  7648. // instruction on each vector of the matrix.
  7649. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg->getType())) {
  7650. const auto actOnEachVec = [this, glslInstSetId,
  7651. opcode](uint32_t /*index*/, uint32_t vecType,
  7652. uint32_t curRowId) {
  7653. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7654. {curRowId});
  7655. };
  7656. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  7657. }
  7658. return theBuilder.createExtInst(returnType, glslInstSetId, opcode, {argId});
  7659. } else if (callExpr->getNumArgs() == 2u) {
  7660. const Expr *arg0 = callExpr->getArg(0);
  7661. const uint32_t arg0Id = doExpr(arg0);
  7662. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7663. // If the instruction does not operate on matrices, we can perform the
  7664. // instruction on each vector of the matrix.
  7665. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7666. const auto actOnEachVec = [this, glslInstSetId, opcode,
  7667. arg1Id](uint32_t index, uint32_t vecType,
  7668. uint32_t arg0RowId) {
  7669. const uint32_t arg1RowId =
  7670. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7671. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7672. {arg0RowId, arg1RowId});
  7673. };
  7674. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7675. }
  7676. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  7677. {arg0Id, arg1Id});
  7678. } else if (callExpr->getNumArgs() == 3u) {
  7679. const Expr *arg0 = callExpr->getArg(0);
  7680. const uint32_t arg0Id = doExpr(arg0);
  7681. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  7682. const uint32_t arg2Id = doExpr(callExpr->getArg(2));
  7683. // If the instruction does not operate on matrices, we can perform the
  7684. // instruction on each vector of the matrix.
  7685. if (actPerRowForMatrices && TypeTranslator::isMxNMatrix(arg0->getType())) {
  7686. const auto actOnEachVec = [this, glslInstSetId, opcode, arg1Id,
  7687. arg2Id](uint32_t index, uint32_t vecType,
  7688. uint32_t arg0RowId) {
  7689. const uint32_t arg1RowId =
  7690. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  7691. const uint32_t arg2RowId =
  7692. theBuilder.createCompositeExtract(vecType, arg2Id, {index});
  7693. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  7694. {arg0RowId, arg1RowId, arg2RowId});
  7695. };
  7696. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  7697. }
  7698. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  7699. {arg0Id, arg1Id, arg2Id});
  7700. }
  7701. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  7702. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  7703. return 0;
  7704. }
  7705. uint32_t SPIRVEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  7706. // Since there is no log10 instruction in SPIR-V, we can use:
  7707. // log10(x) = log2(x) * ( 1 / log2(10) )
  7708. // 1 / log2(10) = 0.30103
  7709. const auto scale = theBuilder.getConstantFloat32(0.30103f);
  7710. const auto log2 =
  7711. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450Log2, true);
  7712. const auto returnType = callExpr->getType();
  7713. const auto returnTypeId = typeTranslator.translateType(returnType);
  7714. spv::Op scaleOp = TypeTranslator::isScalarType(returnType)
  7715. ? spv::Op::OpFMul
  7716. : TypeTranslator::isVectorType(returnType)
  7717. ? spv::Op::OpVectorTimesScalar
  7718. : spv::Op::OpMatrixTimesScalar;
  7719. return theBuilder.createBinaryOp(scaleOp, returnTypeId, log2, scale);
  7720. }
  7721. uint32_t SPIRVEmitter::getValueZero(QualType type) {
  7722. {
  7723. QualType scalarType = {};
  7724. if (TypeTranslator::isScalarType(type, &scalarType)) {
  7725. if (scalarType->isSignedIntegerType()) {
  7726. return theBuilder.getConstantInt32(0);
  7727. }
  7728. if (scalarType->isUnsignedIntegerType()) {
  7729. return theBuilder.getConstantUint32(0);
  7730. }
  7731. if (scalarType->isFloatingType()) {
  7732. return theBuilder.getConstantFloat32(0.0);
  7733. }
  7734. }
  7735. }
  7736. {
  7737. QualType elemType = {};
  7738. uint32_t size = {};
  7739. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  7740. return getVecValueZero(elemType, size);
  7741. }
  7742. }
  7743. {
  7744. QualType elemType = {};
  7745. uint32_t rowCount = 0, colCount = 0;
  7746. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  7747. const auto row = getVecValueZero(elemType, colCount);
  7748. llvm::SmallVector<uint32_t, 4> rows((size_t)rowCount, row);
  7749. return theBuilder.createCompositeConstruct(
  7750. typeTranslator.translateType(type), rows);
  7751. }
  7752. }
  7753. emitError("getting value 0 for type %0 unimplemented", {})
  7754. << type.getAsString();
  7755. return 0;
  7756. }
  7757. uint32_t SPIRVEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  7758. const uint32_t elemZeroId = getValueZero(elemType);
  7759. if (size == 1)
  7760. return elemZeroId;
  7761. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemZeroId);
  7762. const uint32_t vecType =
  7763. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  7764. return theBuilder.getConstantComposite(vecType, elements);
  7765. }
  7766. uint32_t SPIRVEmitter::getValueOne(QualType type) {
  7767. {
  7768. QualType scalarType = {};
  7769. if (TypeTranslator::isScalarType(type, &scalarType)) {
  7770. // TODO: Support other types such as short, half, etc.
  7771. if (scalarType->isSignedIntegerType()) {
  7772. return theBuilder.getConstantInt32(1);
  7773. }
  7774. if (scalarType->isUnsignedIntegerType()) {
  7775. return theBuilder.getConstantUint32(1);
  7776. }
  7777. if (scalarType->isSpecificBuiltinType(BuiltinType::LitFloat))
  7778. scalarType = typeTranslator.getIntendedLiteralType(scalarType);
  7779. if (const auto *builtinType = scalarType->getAs<BuiltinType>()) {
  7780. // TODO: Add support for other types that are not covered yet.
  7781. switch (builtinType->getKind()) {
  7782. case BuiltinType::Double:
  7783. return theBuilder.getConstantFloat64(1.0);
  7784. case BuiltinType::Float:
  7785. return theBuilder.getConstantFloat32(1.0);
  7786. }
  7787. }
  7788. }
  7789. }
  7790. {
  7791. QualType elemType = {};
  7792. uint32_t size = {};
  7793. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  7794. return getVecValueOne(elemType, size);
  7795. }
  7796. }
  7797. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  7798. return 0;
  7799. }
  7800. uint32_t SPIRVEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  7801. const uint32_t elemOneId = getValueOne(elemType);
  7802. if (size == 1)
  7803. return elemOneId;
  7804. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemOneId);
  7805. const uint32_t vecType =
  7806. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  7807. return theBuilder.getConstantComposite(vecType, elements);
  7808. }
  7809. uint32_t SPIRVEmitter::getMatElemValueOne(QualType type) {
  7810. assert(hlsl::IsHLSLMatType(type));
  7811. const auto elemType = hlsl::GetHLSLMatElementType(type);
  7812. uint32_t rowCount = 0, colCount = 0;
  7813. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  7814. if (rowCount == 1 && colCount == 1)
  7815. return getValueOne(elemType);
  7816. if (colCount == 1)
  7817. return getVecValueOne(elemType, rowCount);
  7818. return getVecValueOne(elemType, colCount);
  7819. }
  7820. uint32_t SPIRVEmitter::getMaskForBitwidthValue(QualType type) {
  7821. QualType elemType = {};
  7822. uint32_t count = 1;
  7823. if (TypeTranslator::isScalarType(type, &elemType) ||
  7824. TypeTranslator::isVectorType(type, &elemType, &count)) {
  7825. const auto bitwidth = typeTranslator.getElementSpirvBitwidth(elemType);
  7826. uint32_t mask = 0;
  7827. uint32_t elemTypeId = 0;
  7828. switch (bitwidth) {
  7829. case 16:
  7830. mask = theBuilder.getConstantUint16(bitwidth - 1);
  7831. elemTypeId = theBuilder.getUint16Type();
  7832. break;
  7833. case 32:
  7834. mask = theBuilder.getConstantUint32(bitwidth - 1);
  7835. elemTypeId = theBuilder.getUint32Type();
  7836. break;
  7837. case 64:
  7838. mask = theBuilder.getConstantUint64(bitwidth - 1);
  7839. elemTypeId = theBuilder.getUint64Type();
  7840. break;
  7841. default:
  7842. assert(false && "this method only supports 16-, 32-, and 64-bit types");
  7843. }
  7844. if (count == 1)
  7845. return mask;
  7846. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count);
  7847. llvm::SmallVector<uint32_t, 4> elements(size_t(count), mask);
  7848. return theBuilder.getConstantComposite(typeId, elements);
  7849. }
  7850. assert(false && "this method only supports scalars and vectors");
  7851. return 0;
  7852. }
  7853. uint32_t SPIRVEmitter::translateAPValue(const APValue &value,
  7854. const QualType targetType) {
  7855. uint32_t result = 0;
  7856. // Provide a hint to the typeTranslator that if a literal is discovered, its
  7857. // intended usage is targetType.
  7858. TypeTranslator::LiteralTypeHint hint(typeTranslator, targetType);
  7859. if (targetType->isBooleanType()) {
  7860. result = theBuilder.getConstantBool(value.getInt().getBoolValue(),
  7861. isSpecConstantMode);
  7862. } else if (targetType->isIntegerType()) {
  7863. result = translateAPInt(value.getInt(), targetType);
  7864. } else if (targetType->isFloatingType()) {
  7865. result = translateAPFloat(value.getFloat(), targetType);
  7866. } else if (hlsl::IsHLSLVecType(targetType)) {
  7867. const uint32_t vecType = typeTranslator.translateType(targetType);
  7868. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  7869. const auto numElements = value.getVectorLength();
  7870. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  7871. // size so we need to translate it to scalar values.
  7872. if (numElements == 1) {
  7873. result = translateAPValue(value.getVectorElt(0), elemType);
  7874. } else {
  7875. llvm::SmallVector<uint32_t, 4> elements;
  7876. for (uint32_t i = 0; i < numElements; ++i) {
  7877. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  7878. }
  7879. result = theBuilder.getConstantComposite(vecType, elements);
  7880. }
  7881. }
  7882. if (result)
  7883. return result;
  7884. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  7885. value.dump();
  7886. return 0;
  7887. }
  7888. uint32_t SPIRVEmitter::translateAPInt(const llvm::APInt &intValue,
  7889. QualType targetType) {
  7890. targetType = typeTranslator.getIntendedLiteralType(targetType);
  7891. const auto targetTypeBitWidth = astContext.getTypeSize(targetType);
  7892. const bool isSigned = targetType->isSignedIntegerType();
  7893. switch (targetTypeBitWidth) {
  7894. case 16: {
  7895. if (spirvOptions.enable16BitTypes) {
  7896. if (isSigned) {
  7897. return theBuilder.getConstantInt16(
  7898. static_cast<int16_t>(intValue.getSExtValue()));
  7899. } else {
  7900. return theBuilder.getConstantUint16(
  7901. static_cast<uint16_t>(intValue.getZExtValue()));
  7902. }
  7903. } else {
  7904. // If enable16BitTypes option is not true, treat as 32-bit integer.
  7905. if (isSigned)
  7906. return theBuilder.getConstantInt32(
  7907. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  7908. else
  7909. return theBuilder.getConstantUint32(
  7910. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  7911. }
  7912. }
  7913. case 32: {
  7914. if (isSigned) {
  7915. if (!intValue.isSignedIntN(32)) {
  7916. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  7917. "inforamtion",
  7918. {})
  7919. << std::to_string(intValue.getSExtValue());
  7920. return 0;
  7921. }
  7922. return theBuilder.getConstantInt32(
  7923. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  7924. } else {
  7925. if (!intValue.isIntN(32)) {
  7926. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  7927. "inforamtion",
  7928. {})
  7929. << std::to_string(intValue.getZExtValue());
  7930. return 0;
  7931. }
  7932. return theBuilder.getConstantUint32(
  7933. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  7934. }
  7935. }
  7936. case 64: {
  7937. if (isSigned)
  7938. return theBuilder.getConstantInt64(intValue.getSExtValue());
  7939. else
  7940. return theBuilder.getConstantUint64(intValue.getZExtValue());
  7941. }
  7942. }
  7943. emitError("APInt for target bitwidth %0 unimplemented", {})
  7944. << astContext.getIntWidth(targetType);
  7945. return 0;
  7946. }
  7947. bool SPIRVEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  7948. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  7949. const bool isSigned = expr->getType()->isSignedIntegerType();
  7950. const llvm::APInt &value = intLiteral->getValue();
  7951. return (isSigned && !value.isSignedIntN(32)) ||
  7952. (!isSigned && !value.isIntN(32));
  7953. }
  7954. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  7955. llvm::APFloat value = floatLiteral->getValue();
  7956. const auto &semantics = value.getSemantics();
  7957. // regular 'half' and 'float' can be represented in 32 bits.
  7958. if (&semantics == &llvm::APFloat::IEEEsingle ||
  7959. &semantics == &llvm::APFloat::IEEEhalf)
  7960. return true;
  7961. // See if 'double' value can be represented in 32 bits without losing info.
  7962. bool losesInfo = false;
  7963. const auto convertStatus =
  7964. value.convert(llvm::APFloat::IEEEsingle,
  7965. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  7966. if (convertStatus != llvm::APFloat::opOK &&
  7967. convertStatus != llvm::APFloat::opInexact)
  7968. return true;
  7969. }
  7970. return false;
  7971. }
  7972. uint32_t SPIRVEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  7973. bool isSigned) {
  7974. if (isSigned && intValue.isSignedIntN(32)) {
  7975. return theBuilder.getConstantInt32(
  7976. static_cast<int32_t>(intValue.getSExtValue()));
  7977. }
  7978. if (!isSigned && intValue.isIntN(32)) {
  7979. return theBuilder.getConstantUint32(
  7980. static_cast<uint32_t>(intValue.getZExtValue()));
  7981. }
  7982. // Couldn't evaluate as a 32-bit int without losing information.
  7983. return 0;
  7984. }
  7985. uint32_t SPIRVEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  7986. const auto &semantics = floatValue.getSemantics();
  7987. // If the given value is already a 32-bit float, there is no need to convert.
  7988. if (&semantics == &llvm::APFloat::IEEEsingle) {
  7989. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  7990. isSpecConstantMode);
  7991. }
  7992. // Try to see if this literal float can be represented in 32-bit.
  7993. // Since the convert function below may modify the fp value, we call it on a
  7994. // temporary copy.
  7995. llvm::APFloat eval = floatValue;
  7996. bool losesInfo = false;
  7997. const auto convertStatus =
  7998. eval.convert(llvm::APFloat::IEEEsingle,
  7999. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  8000. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  8001. return theBuilder.getConstantFloat32(eval.convertToFloat());
  8002. // Couldn't evaluate as a 32-bit float without losing information.
  8003. return 0;
  8004. }
  8005. uint32_t SPIRVEmitter::translateAPFloat(llvm::APFloat floatValue,
  8006. QualType targetType) {
  8007. using llvm::APFloat;
  8008. const auto originalValue = floatValue;
  8009. const auto valueBitwidth = APFloat::getSizeInBits(floatValue.getSemantics());
  8010. // Find out the target bitwidth.
  8011. targetType = typeTranslator.getIntendedLiteralType(targetType);
  8012. auto targetBitwidth =
  8013. APFloat::getSizeInBits(astContext.getFloatTypeSemantics(targetType));
  8014. // If 16-bit types are not enabled, treat them as 32-bit float.
  8015. if (targetBitwidth == 16 && !spirvOptions.enable16BitTypes)
  8016. targetBitwidth = 32;
  8017. if (targetBitwidth != valueBitwidth) {
  8018. bool losesInfo = false;
  8019. const llvm::fltSemantics &targetSemantics =
  8020. targetBitwidth == 16
  8021. ? APFloat::IEEEhalf
  8022. : targetBitwidth == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble;
  8023. const auto status = floatValue.convert(
  8024. targetSemantics, APFloat::roundingMode::rmTowardZero, &losesInfo);
  8025. if (status != APFloat::opStatus::opOK &&
  8026. status != APFloat::opStatus::opInexact) {
  8027. emitError(
  8028. "evaluating float literal %0 at a lower bitwidth loses information",
  8029. {})
  8030. // Converting from 16bit to 32/64-bit won't lose information.
  8031. // So only 32/64-bit values can reach here.
  8032. << std::to_string(valueBitwidth == 32
  8033. ? originalValue.convertToFloat()
  8034. : originalValue.convertToDouble());
  8035. return 0;
  8036. }
  8037. }
  8038. switch (targetBitwidth) {
  8039. case 16:
  8040. return theBuilder.getConstantFloat16(
  8041. static_cast<uint16_t>(floatValue.bitcastToAPInt().getZExtValue()));
  8042. case 32:
  8043. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  8044. isSpecConstantMode);
  8045. case 64:
  8046. return theBuilder.getConstantFloat64(floatValue.convertToDouble());
  8047. default:
  8048. break;
  8049. }
  8050. emitError("APFloat for target bitwidth %0 unimplemented", {})
  8051. << targetBitwidth;
  8052. return 0;
  8053. }
  8054. uint32_t SPIRVEmitter::tryToEvaluateAsConst(const Expr *expr) {
  8055. Expr::EvalResult evalResult;
  8056. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  8057. !evalResult.HasSideEffects) {
  8058. return translateAPValue(evalResult.Val, expr->getType());
  8059. }
  8060. return 0;
  8061. }
  8062. spv::ExecutionModel
  8063. SPIRVEmitter::getSpirvShaderStage(const hlsl::ShaderModel &model) {
  8064. // DXIL Models are:
  8065. // Profile (DXIL Model) : HLSL Shader Kind : SPIR-V Shader Stage
  8066. // vs_<version> : Vertex Shader : Vertex Shader
  8067. // hs_<version> : Hull Shader : Tassellation Control Shader
  8068. // ds_<version> : Domain Shader : Tessellation Evaluation Shader
  8069. // gs_<version> : Geometry Shader : Geometry Shader
  8070. // ps_<version> : Pixel Shader : Fragment Shader
  8071. // cs_<version> : Compute Shader : Compute Shader
  8072. switch (model.GetKind()) {
  8073. case hlsl::ShaderModel::Kind::Vertex:
  8074. return spv::ExecutionModel::Vertex;
  8075. case hlsl::ShaderModel::Kind::Hull:
  8076. return spv::ExecutionModel::TessellationControl;
  8077. case hlsl::ShaderModel::Kind::Domain:
  8078. return spv::ExecutionModel::TessellationEvaluation;
  8079. case hlsl::ShaderModel::Kind::Geometry:
  8080. return spv::ExecutionModel::Geometry;
  8081. case hlsl::ShaderModel::Kind::Pixel:
  8082. return spv::ExecutionModel::Fragment;
  8083. case hlsl::ShaderModel::Kind::Compute:
  8084. return spv::ExecutionModel::GLCompute;
  8085. default:
  8086. break;
  8087. }
  8088. llvm_unreachable("unknown shader model");
  8089. }
  8090. void SPIRVEmitter::AddRequiredCapabilitiesForShaderModel() {
  8091. if (shaderModel.IsHS() || shaderModel.IsDS()) {
  8092. theBuilder.requireCapability(spv::Capability::Tessellation);
  8093. } else if (shaderModel.IsGS()) {
  8094. theBuilder.requireCapability(spv::Capability::Geometry);
  8095. } else {
  8096. theBuilder.requireCapability(spv::Capability::Shader);
  8097. }
  8098. }
  8099. bool SPIRVEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  8100. uint32_t *arraySize) {
  8101. bool success = true;
  8102. assert(shaderModel.IsGS());
  8103. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  8104. theBuilder.addExecutionMode(entryFunctionId,
  8105. spv::ExecutionMode::OutputVertices,
  8106. {static_cast<uint32_t>(vcAttr->getCount())});
  8107. }
  8108. uint32_t invocations = 1;
  8109. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  8110. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  8111. }
  8112. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::Invocations,
  8113. {invocations});
  8114. // Only one primitive type is permitted for the geometry shader.
  8115. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  8116. inLine = false, inTriangle = false, inLineAdj = false,
  8117. inTriangleAdj = false;
  8118. for (const auto *param : decl->params()) {
  8119. // Add an execution mode based on the output stream type. Do not an
  8120. // execution mode more than once.
  8121. if (param->hasAttr<HLSLInOutAttr>()) {
  8122. const auto paramType = param->getType();
  8123. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  8124. theBuilder.addExecutionMode(
  8125. entryFunctionId, spv::ExecutionMode::OutputTriangleStrip, {});
  8126. outTriangle = true;
  8127. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  8128. theBuilder.addExecutionMode(entryFunctionId,
  8129. spv::ExecutionMode::OutputLineStrip, {});
  8130. outLine = true;
  8131. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  8132. theBuilder.addExecutionMode(entryFunctionId,
  8133. spv::ExecutionMode::OutputPoints, {});
  8134. outPoint = true;
  8135. }
  8136. // An output stream parameter will not have the input primitive type
  8137. // attributes, so we can continue to the next parameter.
  8138. continue;
  8139. }
  8140. // Add an execution mode based on the input primitive type. Do not add an
  8141. // execution mode more than once.
  8142. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  8143. theBuilder.addExecutionMode(entryFunctionId,
  8144. spv::ExecutionMode::InputPoints, {});
  8145. *arraySize = 1;
  8146. inPoint = true;
  8147. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  8148. theBuilder.addExecutionMode(entryFunctionId,
  8149. spv::ExecutionMode::InputLines, {});
  8150. *arraySize = 2;
  8151. inLine = true;
  8152. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  8153. theBuilder.addExecutionMode(entryFunctionId,
  8154. spv::ExecutionMode::Triangles, {});
  8155. *arraySize = 3;
  8156. inTriangle = true;
  8157. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  8158. theBuilder.addExecutionMode(entryFunctionId,
  8159. spv::ExecutionMode::InputLinesAdjacency, {});
  8160. *arraySize = 4;
  8161. inLineAdj = true;
  8162. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  8163. theBuilder.addExecutionMode(
  8164. entryFunctionId, spv::ExecutionMode::InputTrianglesAdjacency, {});
  8165. *arraySize = 6;
  8166. inTriangleAdj = true;
  8167. }
  8168. }
  8169. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  8170. emitError("only one input primitive type can be specified in the geometry "
  8171. "shader",
  8172. {});
  8173. success = false;
  8174. }
  8175. if (outPoint + outTriangle + outLine > 1) {
  8176. emitError("only one output primitive type can be specified in the geometry "
  8177. "shader",
  8178. {});
  8179. success = false;
  8180. }
  8181. return success;
  8182. }
  8183. void SPIRVEmitter::processPixelShaderAttributes(const FunctionDecl *decl) {
  8184. theBuilder.addExecutionMode(entryFunctionId,
  8185. spv::ExecutionMode::OriginUpperLeft, {});
  8186. if (decl->getAttr<HLSLEarlyDepthStencilAttr>()) {
  8187. theBuilder.addExecutionMode(entryFunctionId,
  8188. spv::ExecutionMode::EarlyFragmentTests, {});
  8189. }
  8190. }
  8191. void SPIRVEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  8192. // If not explicitly specified, x, y, and z should be defaulted to 1.
  8193. uint32_t x = 1, y = 1, z = 1;
  8194. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  8195. x = static_cast<uint32_t>(numThreadsAttr->getX());
  8196. y = static_cast<uint32_t>(numThreadsAttr->getY());
  8197. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  8198. }
  8199. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::LocalSize,
  8200. {x, y, z});
  8201. }
  8202. bool SPIRVEmitter::processTessellationShaderAttributes(
  8203. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  8204. assert(shaderModel.IsHS() || shaderModel.IsDS());
  8205. using namespace spv;
  8206. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  8207. const auto domainType = domain->getDomainType().lower();
  8208. const ExecutionMode hsExecMode =
  8209. llvm::StringSwitch<ExecutionMode>(domainType)
  8210. .Case("tri", ExecutionMode::Triangles)
  8211. .Case("quad", ExecutionMode::Quads)
  8212. .Case("isoline", ExecutionMode::Isolines)
  8213. .Default(ExecutionMode::Max);
  8214. if (hsExecMode == ExecutionMode::Max) {
  8215. emitError("unknown domain type specified for entry function",
  8216. domain->getLocation());
  8217. return false;
  8218. }
  8219. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  8220. }
  8221. // Early return for domain shaders as domain shaders only takes the 'domain'
  8222. // attribute.
  8223. if (shaderModel.IsDS())
  8224. return true;
  8225. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  8226. const auto scheme = partitioning->getScheme().lower();
  8227. if (scheme == "pow2") {
  8228. emitError("pow2 partitioning scheme is not supported since there is no "
  8229. "equivalent in Vulkan",
  8230. partitioning->getLocation());
  8231. return false;
  8232. }
  8233. const ExecutionMode hsExecMode =
  8234. llvm::StringSwitch<ExecutionMode>(scheme)
  8235. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  8236. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  8237. .Case("integer", ExecutionMode::SpacingEqual)
  8238. .Default(ExecutionMode::Max);
  8239. if (hsExecMode == ExecutionMode::Max) {
  8240. emitError("unknown partitioning scheme in hull shader",
  8241. partitioning->getLocation());
  8242. return false;
  8243. }
  8244. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  8245. }
  8246. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  8247. const auto topology = outputTopology->getTopology().lower();
  8248. const ExecutionMode hsExecMode =
  8249. llvm::StringSwitch<ExecutionMode>(topology)
  8250. .Case("point", ExecutionMode::PointMode)
  8251. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  8252. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  8253. .Default(ExecutionMode::Max);
  8254. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  8255. // default?
  8256. if (topology != "line") {
  8257. if (hsExecMode != spv::ExecutionMode::Max) {
  8258. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  8259. } else {
  8260. emitError("unknown output topology in hull shader",
  8261. outputTopology->getLocation());
  8262. return false;
  8263. }
  8264. }
  8265. }
  8266. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  8267. *numOutputControlPoints = controlPoints->getCount();
  8268. theBuilder.addExecutionMode(entryFunctionId,
  8269. spv::ExecutionMode::OutputVertices,
  8270. {*numOutputControlPoints});
  8271. }
  8272. if (auto *pcf = decl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8273. llvm::StringRef pcf_name = pcf->getFunctionName();
  8274. for (auto *decl : astContext.getTranslationUnitDecl()->decls())
  8275. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl))
  8276. if (astContext.IsPatchConstantFunctionDecl(funcDecl) &&
  8277. funcDecl->getName() == pcf_name)
  8278. patchConstFunc = funcDecl;
  8279. }
  8280. return true;
  8281. }
  8282. bool SPIRVEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  8283. const uint32_t entryFuncId) {
  8284. // HS specific attributes
  8285. uint32_t numOutputControlPoints = 0;
  8286. uint32_t outputControlPointIdVal = 0; // SV_OutputControlPointID value
  8287. uint32_t primitiveIdVar = 0; // SV_PrimitiveID variable
  8288. uint32_t viewIdVar = 0; // SV_ViewID variable
  8289. uint32_t hullMainInputPatchParam = 0; // Temporary parameter for InputPatch<>
  8290. // The array size of per-vertex input/output variables
  8291. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  8292. uint32_t inputArraySize = 0;
  8293. uint32_t outputArraySize = 0;
  8294. // Construct the wrapper function signature.
  8295. const uint32_t voidType = theBuilder.getVoidType();
  8296. const uint32_t funcType = theBuilder.getFunctionType(voidType, {});
  8297. // The wrapper entry function surely does not have pre-assigned <result-id>
  8298. // for it like other functions that got added to the work queue following
  8299. // function calls. And the wrapper is the entry function.
  8300. entryFunctionId =
  8301. theBuilder.beginFunction(funcType, voidType, decl->getName());
  8302. // Note this should happen before using declIdMapper for other tasks.
  8303. declIdMapper.setEntryFunctionId(entryFunctionId);
  8304. // Handle attributes specific to each shader stage
  8305. if (shaderModel.IsPS()) {
  8306. processPixelShaderAttributes(decl);
  8307. } else if (shaderModel.IsCS()) {
  8308. processComputeShaderAttributes(decl);
  8309. } else if (shaderModel.IsHS()) {
  8310. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  8311. return false;
  8312. // The input array size for HS is specified in the InputPatch parameter.
  8313. for (const auto *param : decl->params())
  8314. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  8315. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  8316. break;
  8317. }
  8318. outputArraySize = numOutputControlPoints;
  8319. } else if (shaderModel.IsDS()) {
  8320. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  8321. return false;
  8322. // The input array size for HS is specified in the OutputPatch parameter.
  8323. for (const auto *param : decl->params())
  8324. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  8325. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  8326. break;
  8327. }
  8328. // The per-vertex output of DS is not an array.
  8329. } else if (shaderModel.IsGS()) {
  8330. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  8331. return false;
  8332. // The per-vertex output of GS is not an array.
  8333. }
  8334. // Go through all parameters and record the declaration of SV_ClipDistance
  8335. // and SV_CullDistance. We need to do this extra step because in HLSL we
  8336. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  8337. // or vector of float types, but we can only have one single float array
  8338. // for the ClipDistance/CullDistance builtin. So we need to group all
  8339. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  8340. // need to calculate the total size of the array and the offset of each
  8341. // variable within that array.
  8342. // Also go through all parameters to record the semantic strings provided for
  8343. // the builtins in gl_PerVertex.
  8344. for (const auto *param : decl->params()) {
  8345. if (canActAsInParmVar(param))
  8346. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, true))
  8347. return false;
  8348. if (canActAsOutParmVar(param))
  8349. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(param, false))
  8350. return false;
  8351. }
  8352. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  8353. if (!declIdMapper.glPerVertex.recordGlPerVertexDeclFacts(decl, false))
  8354. return false;
  8355. // Calculate the total size of the ClipDistance/CullDistance array and the
  8356. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  8357. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  8358. if (!shaderModel.IsCS()) {
  8359. // Generate stand-alone builtins of Position, ClipDistance, and
  8360. // CullDistance, which belongs to gl_PerVertex.
  8361. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  8362. }
  8363. // Require the ClipDistance/CullDistance capability if necessary.
  8364. // It is legal to just use the ClipDistance/CullDistance builtin without
  8365. // requiring the ClipDistance/CullDistance capability, as long as we don't
  8366. // read or write the builtin variable.
  8367. // For our CodeGen, that corresponds to not seeing SV_ClipDistance or
  8368. // SV_CullDistance at all. If we see them, we will generate code to read
  8369. // them to initialize temporary variable for calling the source code entry
  8370. // function or write to them after calling the source code entry function.
  8371. declIdMapper.glPerVertex.requireCapabilityIfNecessary();
  8372. // The entry basic block.
  8373. const uint32_t entryLabel = theBuilder.createBasicBlock();
  8374. theBuilder.setInsertPoint(entryLabel);
  8375. // Initialize all global variables at the beginning of the wrapper
  8376. for (const VarDecl *varDecl : toInitGloalVars) {
  8377. const auto varInfo = declIdMapper.getDeclEvalInfo(varDecl);
  8378. if (const auto *init = varDecl->getInit()) {
  8379. storeValue(varInfo, doExpr(init), varDecl->getType());
  8380. // Update counter variable associated with global variables
  8381. tryToAssignCounterVar(varDecl, init);
  8382. }
  8383. // If not explicitly initialized, initialize with their zero values if not
  8384. // resource objects
  8385. else if (!hlsl::IsHLSLResourceType(varDecl->getType())) {
  8386. const auto typeId = typeTranslator.translateType(varDecl->getType());
  8387. theBuilder.createStore(varInfo, theBuilder.getConstantNull(typeId));
  8388. }
  8389. }
  8390. // Create temporary variables for holding function call arguments
  8391. llvm::SmallVector<uint32_t, 4> params;
  8392. for (const auto *param : decl->params()) {
  8393. const auto paramType = param->getType();
  8394. const uint32_t typeId = typeTranslator.translateType(paramType);
  8395. std::string tempVarName = "param.var." + param->getNameAsString();
  8396. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  8397. params.push_back(tempVar);
  8398. // Create the stage input variable for parameter not marked as pure out and
  8399. // initialize the corresponding temporary variable
  8400. // Also do not create input variables for output stream objects of geometry
  8401. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  8402. if (canActAsInParmVar(param)) {
  8403. if (shaderModel.IsHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  8404. // Record the temporary variable holding InputPatch. It may be used
  8405. // later in the patch constant function.
  8406. hullMainInputPatchParam = tempVar;
  8407. }
  8408. uint32_t loadedValue = 0;
  8409. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  8410. return false;
  8411. // Only initialize the temporary variable if the parameter is indeed used.
  8412. if (param->isUsed()) {
  8413. theBuilder.createStore(tempVar, loadedValue);
  8414. }
  8415. // Record the temporary variable holding SV_OutputControlPointID,
  8416. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  8417. // constant function.
  8418. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  8419. outputControlPointIdVal = loadedValue;
  8420. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  8421. primitiveIdVar = tempVar;
  8422. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  8423. viewIdVar = tempVar;
  8424. }
  8425. }
  8426. // Call the original entry function
  8427. const uint32_t retType = typeTranslator.translateType(decl->getReturnType());
  8428. const uint32_t retVal =
  8429. theBuilder.createFunctionCall(retType, entryFuncId, params);
  8430. // Create and write stage output variables for return value. Special case for
  8431. // Hull shaders since they operate differently in 2 ways:
  8432. // 1- Their return value is in fact an array and each invocation should write
  8433. // to the proper offset in the array.
  8434. // 2- The patch constant function must be called *once* after all invocations
  8435. // of the main entry point function is done.
  8436. if (shaderModel.IsHS()) {
  8437. // Create stage output variables out of the return type.
  8438. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  8439. outputControlPointIdVal, retVal))
  8440. return false;
  8441. if (!processHSEntryPointOutputAndPCF(
  8442. decl, retType, retVal, numOutputControlPoints,
  8443. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  8444. hullMainInputPatchParam))
  8445. return false;
  8446. } else {
  8447. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  8448. return false;
  8449. }
  8450. // Create and write stage output variables for parameters marked as
  8451. // out/inout
  8452. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  8453. const auto *param = decl->getParamDecl(i);
  8454. if (canActAsOutParmVar(param)) {
  8455. // Load the value from the parameter after function call
  8456. const uint32_t typeId = typeTranslator.translateType(param->getType());
  8457. uint32_t loadedParam = 0;
  8458. // No need to write back the value if the parameter is not used at all in
  8459. // the original entry function.
  8460. //
  8461. // Write back of stage output variables in GS is manually controlled by
  8462. // .Append() intrinsic method. No need to load the parameter since we
  8463. // won't need to write back here.
  8464. if (param->isUsed() && !shaderModel.IsGS())
  8465. loadedParam = theBuilder.createLoad(typeId, params[i]);
  8466. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  8467. return false;
  8468. }
  8469. }
  8470. theBuilder.createReturn();
  8471. theBuilder.endFunction();
  8472. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  8473. // We should invoke a translation of the PCF manually.
  8474. if (shaderModel.IsHS())
  8475. doDecl(patchConstFunc);
  8476. return true;
  8477. }
  8478. bool SPIRVEmitter::processHSEntryPointOutputAndPCF(
  8479. const FunctionDecl *hullMainFuncDecl, uint32_t retType, uint32_t retVal,
  8480. uint32_t numOutputControlPoints, uint32_t outputControlPointId,
  8481. uint32_t primitiveId, uint32_t viewId, uint32_t hullMainInputPatch) {
  8482. // This method may only be called for Hull shaders.
  8483. assert(shaderModel.IsHS());
  8484. // For Hull shaders, the real output is an array of size
  8485. // numOutputControlPoints. The results of the main should be written to the
  8486. // correct offset in the array (based on InvocationID).
  8487. if (!numOutputControlPoints) {
  8488. emitError("number of output control points cannot be zero",
  8489. hullMainFuncDecl->getLocation());
  8490. return false;
  8491. }
  8492. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  8493. // is not provided.
  8494. if (!outputControlPointId) {
  8495. emitError(
  8496. "SV_OutputControlPointID semantic must be provided in hull shader",
  8497. hullMainFuncDecl->getLocation());
  8498. return false;
  8499. }
  8500. if (!patchConstFunc) {
  8501. emitError("patch constant function not defined in hull shader",
  8502. hullMainFuncDecl->getLocation());
  8503. return false;
  8504. }
  8505. uint32_t hullMainOutputPatch = 0;
  8506. // If the patch constant function (PCF) takes the result of the Hull main
  8507. // entry point, create a temporary function-scope variable and write the
  8508. // results to it, so it can be passed to the PCF.
  8509. if (patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  8510. const uint32_t hullMainRetType = theBuilder.getArrayType(
  8511. retType, theBuilder.getConstantUint32(numOutputControlPoints));
  8512. hullMainOutputPatch =
  8513. theBuilder.addFnVar(hullMainRetType, "temp.var.hullMainRetVal");
  8514. const auto tempLocation = theBuilder.createAccessChain(
  8515. theBuilder.getPointerType(retType, spv::StorageClass::Function),
  8516. hullMainOutputPatch, {outputControlPointId});
  8517. theBuilder.createStore(tempLocation, retVal);
  8518. }
  8519. // Now create a barrier before calling the Patch Constant Function (PCF).
  8520. // Flags are:
  8521. // Execution Barrier scope = Workgroup (2)
  8522. // Memory Barrier scope = Invocation (4)
  8523. // Memory Semantics Barrier scope = None (0)
  8524. const auto constZero = theBuilder.getConstantUint32(0);
  8525. const auto constFour = theBuilder.getConstantUint32(4);
  8526. const auto constTwo = theBuilder.getConstantUint32(2);
  8527. theBuilder.createBarrier(constTwo, constFour, constZero);
  8528. // The PCF should be called only once. Therefore, we check the invocationID,
  8529. // and we only allow ID 0 to call the PCF.
  8530. const uint32_t condition = theBuilder.createBinaryOp(
  8531. spv::Op::OpIEqual, theBuilder.getBoolType(), outputControlPointId,
  8532. theBuilder.getConstantUint32(0));
  8533. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  8534. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  8535. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  8536. theBuilder.addSuccessor(thenBB);
  8537. theBuilder.addSuccessor(mergeBB);
  8538. theBuilder.setMergeTarget(mergeBB);
  8539. theBuilder.setInsertPoint(thenBB);
  8540. // Call the PCF. Since the function is not explicitly called, we must first
  8541. // register an ID for it.
  8542. const uint32_t pcfId = declIdMapper.getOrRegisterFnResultId(patchConstFunc);
  8543. const uint32_t pcfRetType =
  8544. typeTranslator.translateType(patchConstFunc->getReturnType());
  8545. std::vector<uint32_t> pcfParams;
  8546. // A lambda for creating a stage input variable and its associated temporary
  8547. // variable for function call. Also initializes the temporary variable using
  8548. // the contents loaded from the stage input variable. Returns the <result-id>
  8549. // of the temporary variable.
  8550. const auto createParmVarAndInitFromStageInputVar =
  8551. [this](const ParmVarDecl *param) {
  8552. const uint32_t typeId = typeTranslator.translateType(param->getType());
  8553. std::string tempVarName = "param.var." + param->getNameAsString();
  8554. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  8555. uint32_t loadedValue = 0;
  8556. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  8557. theBuilder.createStore(tempVar, loadedValue);
  8558. return tempVar;
  8559. };
  8560. for (const auto *param : patchConstFunc->parameters()) {
  8561. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  8562. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  8563. // necessarily mean that they are present. There is also no requirement
  8564. // for the order of parameters passed to PCF.
  8565. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  8566. pcfParams.push_back(hullMainInputPatch);
  8567. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  8568. pcfParams.push_back(hullMainOutputPatch);
  8569. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  8570. if (!primitiveId) {
  8571. primitiveId = createParmVarAndInitFromStageInputVar(param);
  8572. }
  8573. pcfParams.push_back(primitiveId);
  8574. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  8575. if (!viewId) {
  8576. viewId = createParmVarAndInitFromStageInputVar(param);
  8577. }
  8578. pcfParams.push_back(viewId);
  8579. } else {
  8580. emitError("patch constant function parameter '%0' unknown",
  8581. param->getLocation())
  8582. << param->getName();
  8583. }
  8584. }
  8585. const uint32_t pcfResultId =
  8586. theBuilder.createFunctionCall(pcfRetType, pcfId, {pcfParams});
  8587. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  8588. /*forPCF*/ true))
  8589. return false;
  8590. theBuilder.createBranch(mergeBB);
  8591. theBuilder.addSuccessor(mergeBB);
  8592. theBuilder.setInsertPoint(mergeBB);
  8593. return true;
  8594. }
  8595. bool SPIRVEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  8596. if (!root)
  8597. return false;
  8598. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8599. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8600. if (!caseStmt && !compoundStmt)
  8601. return true;
  8602. if (caseStmt) {
  8603. const Expr *caseExpr = caseStmt->getLHS();
  8604. return caseExpr && caseExpr->isEvaluatable(astContext);
  8605. }
  8606. // Recurse down if facing a compound statement.
  8607. for (auto *st : compoundStmt->body())
  8608. if (!allSwitchCasesAreIntegerLiterals(st))
  8609. return false;
  8610. return true;
  8611. }
  8612. void SPIRVEmitter::discoverAllCaseStmtInSwitchStmt(
  8613. const Stmt *root, uint32_t *defaultBB,
  8614. std::vector<std::pair<uint32_t, uint32_t>> *targets) {
  8615. if (!root)
  8616. return;
  8617. // A switch case can only appear in DefaultStmt, CaseStmt, or
  8618. // CompoundStmt. For the rest, we can just return.
  8619. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  8620. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8621. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8622. if (!defaultStmt && !caseStmt && !compoundStmt)
  8623. return;
  8624. // Recurse down if facing a compound statement.
  8625. if (compoundStmt) {
  8626. for (auto *st : compoundStmt->body())
  8627. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  8628. return;
  8629. }
  8630. std::string caseLabel;
  8631. uint32_t caseValue = 0;
  8632. if (defaultStmt) {
  8633. // This is the default branch.
  8634. caseLabel = "switch.default";
  8635. } else if (caseStmt) {
  8636. // This is a non-default case.
  8637. // When using OpSwitch, we only allow integer literal cases. e.g:
  8638. // case <literal_integer>: {...; break;}
  8639. const Expr *caseExpr = caseStmt->getLHS();
  8640. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  8641. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  8642. if (bitWidth != 32)
  8643. emitError(
  8644. "non-32bit integer case value in switch statement unimplemented",
  8645. caseExpr->getExprLoc());
  8646. Expr::EvalResult evalResult;
  8647. caseExpr->EvaluateAsRValue(evalResult, astContext);
  8648. const int64_t value = evalResult.Val.getInt().getSExtValue();
  8649. caseValue = static_cast<uint32_t>(value);
  8650. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  8651. llvm::itostr(std::abs(value));
  8652. }
  8653. const uint32_t caseBB = theBuilder.createBasicBlock(caseLabel);
  8654. theBuilder.addSuccessor(caseBB);
  8655. stmtBasicBlock[root] = caseBB;
  8656. // Add all cases to the 'targets' vector.
  8657. if (caseStmt)
  8658. targets->emplace_back(caseValue, caseBB);
  8659. // The default label is not part of the 'targets' vector that is passed
  8660. // to the OpSwitch instruction.
  8661. // If default statement was discovered, return its label via defaultBB.
  8662. if (defaultStmt)
  8663. *defaultBB = caseBB;
  8664. // Process cases nested in other cases. It happens when we have fall through
  8665. // cases. For example:
  8666. // case 1: case 2: ...; break;
  8667. // will result in the CaseSmt for case 2 nested in the one for case 1.
  8668. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  8669. : defaultStmt->getSubStmt(),
  8670. defaultBB, targets);
  8671. }
  8672. void SPIRVEmitter::flattenSwitchStmtAST(const Stmt *root,
  8673. std::vector<const Stmt *> *flatSwitch) {
  8674. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  8675. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  8676. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  8677. if (!compoundStmt) {
  8678. flatSwitch->push_back(root);
  8679. }
  8680. if (compoundStmt) {
  8681. for (const auto *st : compoundStmt->body())
  8682. flattenSwitchStmtAST(st, flatSwitch);
  8683. } else if (caseStmt) {
  8684. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  8685. } else if (defaultStmt) {
  8686. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  8687. }
  8688. }
  8689. void SPIRVEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  8690. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  8691. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  8692. assert(caseStmt || defaultStmt);
  8693. uint32_t caseBB = stmtBasicBlock[stmt];
  8694. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  8695. // We are about to handle the case passed in as parameter. If the current
  8696. // basic block is not terminated, it means the previous case is a fall
  8697. // through case. We need to link it to the case to be processed.
  8698. theBuilder.createBranch(caseBB);
  8699. theBuilder.addSuccessor(caseBB);
  8700. }
  8701. theBuilder.setInsertPoint(caseBB);
  8702. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  8703. }
  8704. void SPIRVEmitter::processSwitchStmtUsingSpirvOpSwitch(
  8705. const SwitchStmt *switchStmt) {
  8706. // First handle the condition variable DeclStmt if one exists.
  8707. // For example: handle 'int a = b' in the following:
  8708. // switch (int a = b) {...}
  8709. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  8710. doDeclStmt(condVarDeclStmt);
  8711. const uint32_t selector = doExpr(switchStmt->getCond());
  8712. // We need a merge block regardless of the number of switch cases.
  8713. // Since OpSwitch always requires a default label, if the switch statement
  8714. // does not have a default branch, we use the merge block as the default
  8715. // target.
  8716. const uint32_t mergeBB = theBuilder.createBasicBlock("switch.merge");
  8717. theBuilder.setMergeTarget(mergeBB);
  8718. breakStack.push(mergeBB);
  8719. uint32_t defaultBB = mergeBB;
  8720. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  8721. std::vector<std::pair<uint32_t, uint32_t>> targets;
  8722. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  8723. // Create the OpSelectionMerge and OpSwitch.
  8724. theBuilder.createSwitch(mergeBB, selector, defaultBB, targets);
  8725. // Handle the switch body.
  8726. doStmt(switchStmt->getBody());
  8727. if (!theBuilder.isCurrentBasicBlockTerminated())
  8728. theBuilder.createBranch(mergeBB);
  8729. theBuilder.setInsertPoint(mergeBB);
  8730. breakStack.pop();
  8731. }
  8732. void SPIRVEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  8733. std::vector<const Stmt *> flatSwitch;
  8734. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  8735. // First handle the condition variable DeclStmt if one exists.
  8736. // For example: handle 'int a = b' in the following:
  8737. // switch (int a = b) {...}
  8738. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  8739. doDeclStmt(condVarDeclStmt);
  8740. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  8741. // the flattened switch AST.
  8742. // For instance, for the following flat vector:
  8743. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  8744. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  8745. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  8746. // The indexes are: {0, 2, 5, 6, 9}
  8747. std::vector<uint32_t> caseStmtLocs;
  8748. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  8749. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  8750. caseStmtLocs.push_back(i);
  8751. IfStmt *prevIfStmt = nullptr;
  8752. IfStmt *rootIfStmt = nullptr;
  8753. CompoundStmt *defaultBody = nullptr;
  8754. // For each case, start at its index in the vector, and go forward
  8755. // accumulating statements until BreakStmt or end of vector is reached.
  8756. for (auto curCaseIndex : caseStmtLocs) {
  8757. const Stmt *curCase = flatSwitch[curCaseIndex];
  8758. // CompoundStmt to hold all statements for this case.
  8759. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  8760. // Accumulate all non-case/default/break statements as the body for the
  8761. // current case.
  8762. std::vector<Stmt *> statements;
  8763. for (unsigned i = curCaseIndex + 1;
  8764. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  8765. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  8766. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  8767. }
  8768. if (!statements.empty())
  8769. cs->setStmts(astContext, statements.data(), statements.size());
  8770. // For non-default cases, generate the IfStmt that compares the switch
  8771. // value to the case value.
  8772. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  8773. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  8774. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  8775. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  8776. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  8777. bo->setOpcode(BO_EQ);
  8778. bo->setType(astContext.getLogicalOperationType());
  8779. curIf->setCond(bo);
  8780. curIf->setThen(cs);
  8781. // No conditional variable associated with this faux if statement.
  8782. curIf->setConditionVariable(astContext, nullptr);
  8783. // Each If statement is the "else" of the previous if statement.
  8784. if (prevIfStmt)
  8785. prevIfStmt->setElse(curIf);
  8786. else
  8787. rootIfStmt = curIf;
  8788. prevIfStmt = curIf;
  8789. } else {
  8790. // Record the DefaultStmt body as it will be used as the body of the
  8791. // "else" block in the if-elseif-...-else pattern.
  8792. defaultBody = cs;
  8793. }
  8794. }
  8795. // If a default case exists, it is the "else" of the last if statement.
  8796. if (prevIfStmt)
  8797. prevIfStmt->setElse(defaultBody);
  8798. // Since all else-if and else statements are the child nodes of the first
  8799. // IfStmt, we only need to call doStmt for the first IfStmt.
  8800. if (rootIfStmt)
  8801. doStmt(rootIfStmt);
  8802. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  8803. // no if statements. The switch in that case only executes the body of the
  8804. // default case.
  8805. else if (defaultBody)
  8806. doStmt(defaultBody);
  8807. }
  8808. uint32_t SPIRVEmitter::extractVecFromVec4(uint32_t fromId,
  8809. uint32_t targetVecSize,
  8810. uint32_t targetElemTypeId) {
  8811. assert(targetVecSize > 0 && targetVecSize < 5);
  8812. const uint32_t retType =
  8813. targetVecSize == 1
  8814. ? targetElemTypeId
  8815. : theBuilder.getVecType(targetElemTypeId, targetVecSize);
  8816. switch (targetVecSize) {
  8817. case 1:
  8818. return theBuilder.createCompositeExtract(retType, fromId, {0});
  8819. break;
  8820. case 2:
  8821. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1});
  8822. break;
  8823. case 3:
  8824. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1, 2});
  8825. break;
  8826. case 4:
  8827. return fromId;
  8828. default:
  8829. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  8830. }
  8831. }
  8832. } // end namespace spirv
  8833. } // end namespace clang