SPIRVEmitter.cpp 335 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483
  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 the type of the given decl. If the given decl is a FunctionDecl,
  22. /// returns its result type.
  23. inline QualType getTypeOrFnRetType(const ValueDecl *decl) {
  24. if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  25. return funcDecl->getReturnType();
  26. }
  27. return decl->getType();
  28. }
  29. // Returns true if the given decl has the given semantic.
  30. bool hasSemantic(const DeclaratorDecl *decl,
  31. hlsl::DXIL::SemanticKind semanticKind) {
  32. using namespace hlsl;
  33. for (auto *annotation : decl->getUnusualAnnotations()) {
  34. if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
  35. llvm::StringRef semanticName;
  36. uint32_t semanticIndex = 0;
  37. Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
  38. &semanticIndex);
  39. const auto *semantic = Semantic::GetByName(semanticName);
  40. if (semantic->GetKind() == semanticKind)
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. bool patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
  47. for (const auto *param : pcf->parameters())
  48. if (hlsl::IsHLSLOutputPatchType(param->getType()))
  49. return true;
  50. return false;
  51. }
  52. // TODO: Maybe we should move these type probing functions to TypeTranslator.
  53. /// Returns true if the two types are the same scalar or vector type.
  54. bool isSameScalarOrVecType(QualType type1, QualType type2) {
  55. // Consider cases such as 'const bool' and 'bool' to be the same type.
  56. type1.removeLocalConst();
  57. type2.removeLocalConst();
  58. {
  59. QualType scalarType1 = {}, scalarType2 = {};
  60. if (TypeTranslator::isScalarType(type1, &scalarType1) &&
  61. TypeTranslator::isScalarType(type2, &scalarType2))
  62. return scalarType1.getCanonicalType() == scalarType2.getCanonicalType();
  63. }
  64. {
  65. QualType elemType1 = {}, elemType2 = {};
  66. uint32_t count1 = {}, count2 = {};
  67. if (TypeTranslator::isVectorType(type1, &elemType1, &count1) &&
  68. TypeTranslator::isVectorType(type2, &elemType2, &count2))
  69. return count1 == count2 &&
  70. elemType1.getCanonicalType() == elemType2.getCanonicalType();
  71. }
  72. return false;
  73. }
  74. /// Returns true if the given type is a bool or vector of bool type.
  75. bool isBoolOrVecOfBoolType(QualType type) {
  76. QualType elemType = {};
  77. return (TypeTranslator::isScalarType(type, &elemType) ||
  78. TypeTranslator::isVectorType(type, &elemType)) &&
  79. elemType->isBooleanType();
  80. }
  81. /// Returns true if the given type is a signed integer or vector of signed
  82. /// integer type.
  83. bool isSintOrVecOfSintType(QualType type) {
  84. QualType elemType = {};
  85. return (TypeTranslator::isScalarType(type, &elemType) ||
  86. TypeTranslator::isVectorType(type, &elemType)) &&
  87. elemType->isSignedIntegerType();
  88. }
  89. /// Returns true if the given type is an unsigned integer or vector of unsigned
  90. /// integer type.
  91. bool isUintOrVecOfUintType(QualType type) {
  92. QualType elemType = {};
  93. return (TypeTranslator::isScalarType(type, &elemType) ||
  94. TypeTranslator::isVectorType(type, &elemType)) &&
  95. elemType->isUnsignedIntegerType();
  96. }
  97. /// Returns true if the given type is a float or vector of float type.
  98. bool isFloatOrVecOfFloatType(QualType type) {
  99. QualType elemType = {};
  100. return (TypeTranslator::isScalarType(type, &elemType) ||
  101. TypeTranslator::isVectorType(type, &elemType)) &&
  102. elemType->isFloatingType();
  103. }
  104. /// Returns true if the given type is a bool or vector/matrix of bool type.
  105. bool isBoolOrVecMatOfBoolType(QualType type) {
  106. return isBoolOrVecOfBoolType(type) ||
  107. (hlsl::IsHLSLMatType(type) &&
  108. hlsl::GetHLSLMatElementType(type)->isBooleanType());
  109. }
  110. /// Returns true if the given type is a signed integer or vector/matrix of
  111. /// signed integer type.
  112. bool isSintOrVecMatOfSintType(QualType type) {
  113. return isSintOrVecOfSintType(type) ||
  114. (hlsl::IsHLSLMatType(type) &&
  115. hlsl::GetHLSLMatElementType(type)->isSignedIntegerType());
  116. }
  117. /// Returns true if the given type is an unsigned integer or vector/matrix of
  118. /// unsigned integer type.
  119. bool isUintOrVecMatOfUintType(QualType type) {
  120. return isUintOrVecOfUintType(type) ||
  121. (hlsl::IsHLSLMatType(type) &&
  122. hlsl::GetHLSLMatElementType(type)->isUnsignedIntegerType());
  123. }
  124. /// Returns true if the given type is a float or vector/matrix of float type.
  125. bool isFloatOrVecMatOfFloatType(QualType type) {
  126. return isFloatOrVecOfFloatType(type) ||
  127. (hlsl::IsHLSLMatType(type) &&
  128. hlsl::GetHLSLMatElementType(type)->isFloatingType());
  129. }
  130. inline bool isSpirvMatrixOp(spv::Op opcode) {
  131. return opcode == spv::Op::OpMatrixTimesMatrix ||
  132. opcode == spv::Op::OpMatrixTimesVector ||
  133. opcode == spv::Op::OpMatrixTimesScalar;
  134. }
  135. /// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
  136. /// index. Otherwiser, returns false.
  137. // TODO: The following doesn't handle Load(int, int) yet. And it is basically a
  138. // duplicate of doCXXMemberCallExpr.
  139. const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
  140. using namespace hlsl;
  141. if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
  142. const auto *callee = indexing->getDirectCallee();
  143. uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
  144. llvm::StringRef group;
  145. if (GetIntrinsicOp(callee, opcode, group)) {
  146. if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
  147. const auto *object = indexing->getImplicitObjectArgument();
  148. if (TypeTranslator::isStructuredBuffer(object->getType())) {
  149. *index = indexing->getArg(0);
  150. return indexing->getImplicitObjectArgument();
  151. }
  152. }
  153. }
  154. }
  155. return nullptr;
  156. }
  157. /// Returns true if the given VarDecl will be translated into a SPIR-V variable
  158. /// not in the Private or Function storage class.
  159. inline bool isExternalVar(const VarDecl *var) {
  160. return var->isExternallyVisible() && !var->isStaticDataMember();
  161. }
  162. /// Returns the referenced variable's DeclContext if the given expr is
  163. /// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
  164. /// returns nullptr.
  165. const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
  166. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
  167. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  168. if (const auto *bufferDecl =
  169. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  170. // Make sure we are not returning true for VarDecls inside
  171. // cbuffer/tbuffer.
  172. if (bufferDecl->isConstantBufferView())
  173. return varDecl->getType()->getAs<RecordType>()->getDecl();
  174. return nullptr;
  175. }
  176. /// Returns true if
  177. /// * the given expr is an DeclRefExpr referencing a kind of structured or byte
  178. /// buffer and it is non-alias one, or
  179. /// * the given expr is an CallExpr returning a kind of structured or byte
  180. /// buffer.
  181. ///
  182. /// Note: legalization specific code
  183. bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
  184. expr = expr->IgnoreParenCasts();
  185. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  186. if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
  187. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(varDecl->getType()))
  188. return isExternalVar(varDecl);
  189. } else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  190. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(callExpr->getType()))
  191. return true;
  192. }
  193. return false;
  194. }
  195. bool spirvToolsLegalize(std::vector<uint32_t> *module, std::string *messages) {
  196. spvtools::Optimizer optimizer(SPV_ENV_VULKAN_1_0);
  197. optimizer.SetMessageConsumer(
  198. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  199. const spv_position_t & /*position*/,
  200. const char *message) { *messages += message; });
  201. optimizer.RegisterLegalizationPasses();
  202. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  203. return optimizer.Run(module->data(), module->size(), module);
  204. }
  205. bool spirvToolsOptimize(std::vector<uint32_t> *module, std::string *messages) {
  206. spvtools::Optimizer optimizer(SPV_ENV_VULKAN_1_0);
  207. optimizer.SetMessageConsumer(
  208. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  209. const spv_position_t & /*position*/,
  210. const char *message) { *messages += message; });
  211. optimizer.RegisterPerformancePasses();
  212. optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
  213. return optimizer.Run(module->data(), module->size(), module);
  214. }
  215. bool spirvToolsValidate(std::vector<uint32_t> *module, std::string *messages,
  216. bool relaxLogicalPointer) {
  217. spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
  218. tools.SetMessageConsumer(
  219. [messages](spv_message_level_t /*level*/, const char * /*source*/,
  220. const spv_position_t & /*position*/,
  221. const char *message) { *messages += message; });
  222. spvtools::ValidatorOptions options;
  223. options.SetRelaxLogicalPointer(relaxLogicalPointer);
  224. return tools.Validate(module->data(), module->size(), options);
  225. }
  226. /// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
  227. spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
  228. using namespace hlsl;
  229. using namespace spv;
  230. switch (opcode) {
  231. case IntrinsicOp::IOP_InterlockedAdd:
  232. case IntrinsicOp::MOP_InterlockedAdd:
  233. return Op::OpAtomicIAdd;
  234. case IntrinsicOp::IOP_InterlockedAnd:
  235. case IntrinsicOp::MOP_InterlockedAnd:
  236. return Op::OpAtomicAnd;
  237. case IntrinsicOp::IOP_InterlockedOr:
  238. case IntrinsicOp::MOP_InterlockedOr:
  239. return Op::OpAtomicOr;
  240. case IntrinsicOp::IOP_InterlockedXor:
  241. case IntrinsicOp::MOP_InterlockedXor:
  242. return Op::OpAtomicXor;
  243. case IntrinsicOp::IOP_InterlockedUMax:
  244. case IntrinsicOp::MOP_InterlockedUMax:
  245. return Op::OpAtomicUMax;
  246. case IntrinsicOp::IOP_InterlockedUMin:
  247. case IntrinsicOp::MOP_InterlockedUMin:
  248. return Op::OpAtomicUMin;
  249. case IntrinsicOp::IOP_InterlockedMax:
  250. case IntrinsicOp::MOP_InterlockedMax:
  251. return Op::OpAtomicSMax;
  252. case IntrinsicOp::IOP_InterlockedMin:
  253. case IntrinsicOp::MOP_InterlockedMin:
  254. return Op::OpAtomicSMin;
  255. case IntrinsicOp::IOP_InterlockedExchange:
  256. case IntrinsicOp::MOP_InterlockedExchange:
  257. return Op::OpAtomicExchange;
  258. }
  259. assert(false && "unimplemented hlsl intrinsic opcode");
  260. return Op::Max;
  261. }
  262. // Returns true if the given opcode is an accepted binary opcode in
  263. // OpSpecConstantOp.
  264. bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
  265. switch (op) {
  266. case spv::Op::OpIAdd:
  267. case spv::Op::OpISub:
  268. case spv::Op::OpIMul:
  269. case spv::Op::OpUDiv:
  270. case spv::Op::OpSDiv:
  271. case spv::Op::OpUMod:
  272. case spv::Op::OpSRem:
  273. case spv::Op::OpSMod:
  274. case spv::Op::OpShiftRightLogical:
  275. case spv::Op::OpShiftRightArithmetic:
  276. case spv::Op::OpShiftLeftLogical:
  277. case spv::Op::OpBitwiseOr:
  278. case spv::Op::OpBitwiseXor:
  279. case spv::Op::OpBitwiseAnd:
  280. case spv::Op::OpVectorShuffle:
  281. case spv::Op::OpCompositeExtract:
  282. case spv::Op::OpCompositeInsert:
  283. case spv::Op::OpLogicalOr:
  284. case spv::Op::OpLogicalAnd:
  285. case spv::Op::OpLogicalNot:
  286. case spv::Op::OpLogicalEqual:
  287. case spv::Op::OpLogicalNotEqual:
  288. case spv::Op::OpIEqual:
  289. case spv::Op::OpINotEqual:
  290. case spv::Op::OpULessThan:
  291. case spv::Op::OpSLessThan:
  292. case spv::Op::OpUGreaterThan:
  293. case spv::Op::OpSGreaterThan:
  294. case spv::Op::OpULessThanEqual:
  295. case spv::Op::OpSLessThanEqual:
  296. case spv::Op::OpUGreaterThanEqual:
  297. case spv::Op::OpSGreaterThanEqual:
  298. return true;
  299. }
  300. return false;
  301. }
  302. /// Returns true if the given expression is an accepted initializer for a spec
  303. /// constant.
  304. bool isAcceptedSpecConstantInit(const Expr *init) {
  305. // Allow numeric casts
  306. init = init->IgnoreParenCasts();
  307. if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
  308. isa<FloatingLiteral>(init))
  309. return true;
  310. // Allow the minus operator which is used to specify negative values
  311. if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
  312. return unaryOp->getOpcode() == UO_Minus &&
  313. isAcceptedSpecConstantInit(unaryOp->getSubExpr());
  314. return false;
  315. }
  316. /// Returns true if the given function parameter can act as shader stage
  317. /// input parameter.
  318. inline bool canActAsInParmVar(const ParmVarDecl *param) {
  319. // If the parameter has no in/out/inout attribute, it is defaulted to
  320. // an in parameter.
  321. return !param->hasAttr<HLSLOutAttr>() &&
  322. // GS output streams are marked as inout, but it should not be
  323. // used as in parameter.
  324. !hlsl::IsHLSLStreamOutputType(param->getType());
  325. }
  326. /// Returns true if the given function parameter can act as shader stage
  327. /// output parameter.
  328. inline bool canActAsOutParmVar(const ParmVarDecl *param) {
  329. return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>();
  330. }
  331. /// Returns true if the given expression is of builtin type and can be evaluated
  332. /// to a constant zero. Returns false otherwise.
  333. inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
  334. const auto type = expr->getType();
  335. if (!type->isBuiltinType())
  336. return false;
  337. Expr::EvalResult evalResult;
  338. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  339. !evalResult.HasSideEffects) {
  340. const auto &val = evalResult.Val;
  341. return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
  342. (type->isIntegerType() && !val.getInt().getBoolValue()) ||
  343. (type->isFloatingType() && val.getFloat().isZero()));
  344. }
  345. return false;
  346. }
  347. /// Returns the HLSLBufferDecl if the given VarDecl is inside a cbuffer/tbuffer.
  348. /// Returns nullptr otherwise, including varDecl is a ConstantBuffer or
  349. /// TextureBuffer itself.
  350. inline const HLSLBufferDecl *getCTBufferContext(const VarDecl *varDecl) {
  351. if (const auto *bufferDecl =
  352. dyn_cast<HLSLBufferDecl>(varDecl->getDeclContext()))
  353. // Filter ConstantBuffer/TextureBuffer
  354. if (!bufferDecl->isConstantBufferView())
  355. return bufferDecl;
  356. return nullptr;
  357. }
  358. /// Returns the real definition of the callee of the given CallExpr.
  359. ///
  360. /// If we are calling a forward-declared function, callee will be the
  361. /// FunctionDecl for the foward-declared function, not the actual
  362. /// definition. The foward-delcaration and defintion are two completely
  363. /// different AST nodes.
  364. inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
  365. const auto *callee = expr->getDirectCallee();
  366. if (callee->isThisDeclarationADefinition())
  367. return callee;
  368. // We need to update callee to the actual definition here
  369. if (!callee->isDefined(callee))
  370. return nullptr;
  371. return callee;
  372. }
  373. /// Returns the referenced definition. The given expr is expected to be a
  374. /// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
  375. const DeclaratorDecl *getReferencedDef(const Expr *expr) {
  376. if (!expr)
  377. return nullptr;
  378. expr = expr->IgnoreParenCasts();
  379. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  380. return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
  381. }
  382. if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
  383. return getCalleeDefinition(callExpr);
  384. }
  385. return nullptr;
  386. }
  387. } // namespace
  388. SPIRVEmitter::SPIRVEmitter(CompilerInstance &ci,
  389. const EmitSPIRVOptions &options)
  390. : theCompilerInstance(ci), astContext(ci.getASTContext()),
  391. diags(ci.getDiagnostics()), spirvOptions(options),
  392. entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction),
  393. shaderModel(*hlsl::ShaderModel::GetByName(
  394. ci.getCodeGenOpts().HLSLProfile.c_str())),
  395. theContext(), theBuilder(&theContext),
  396. declIdMapper(shaderModel, astContext, theBuilder, spirvOptions),
  397. typeTranslator(astContext, theBuilder, diags, options),
  398. entryFunctionId(0), curFunction(nullptr), curThis(0),
  399. seenPushConstantAt(), isSpecConstantMode(false),
  400. needsLegalization(false) {
  401. if (shaderModel.GetKind() == hlsl::ShaderModel::Kind::Invalid)
  402. emitError("unknown shader module: %0", {}) << shaderModel.GetName();
  403. if (options.invertY && !shaderModel.IsVS() && !shaderModel.IsDS() &&
  404. !shaderModel.IsGS())
  405. emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
  406. }
  407. void SPIRVEmitter::HandleTranslationUnit(ASTContext &context) {
  408. // Stop translating if there are errors in previous compilation stages.
  409. if (context.getDiagnostics().hasErrorOccurred())
  410. return;
  411. TranslationUnitDecl *tu = context.getTranslationUnitDecl();
  412. // The entry function is the seed of the queue.
  413. for (auto *decl : tu->decls()) {
  414. if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  415. if (funcDecl->getName() == entryFunctionName) {
  416. workQueue.insert(funcDecl);
  417. }
  418. if (context.IsPatchConstantFunctionDecl(funcDecl)) {
  419. patchConstFunc = funcDecl;
  420. }
  421. } else {
  422. // If ignoring unused resources, defer Decl handling inside
  423. // TranslationUnit to the time of first referencing.
  424. if (!spirvOptions.ignoreUnusedResources) {
  425. doDecl(decl);
  426. }
  427. }
  428. }
  429. // Translate all functions reachable from the entry function.
  430. // The queue can grow in the meanwhile; so need to keep evaluating
  431. // workQueue.size().
  432. for (uint32_t i = 0; i < workQueue.size(); ++i) {
  433. doDecl(workQueue[i]);
  434. }
  435. if (context.getDiagnostics().hasErrorOccurred())
  436. return;
  437. AddRequiredCapabilitiesForShaderModel();
  438. // Addressing and memory model are required in a valid SPIR-V module.
  439. theBuilder.setAddressingModel(spv::AddressingModel::Logical);
  440. theBuilder.setMemoryModel(spv::MemoryModel::GLSL450);
  441. theBuilder.addEntryPoint(getSpirvShaderStage(shaderModel), entryFunctionId,
  442. entryFunctionName, declIdMapper.collectStageVars());
  443. AddExecutionModeForEntryPoint(entryFunctionId);
  444. // Add Location decorations to stage input/output variables.
  445. if (!declIdMapper.decorateStageIOLocations())
  446. return;
  447. // Add descriptor set and binding decorations to resource variables.
  448. if (!declIdMapper.decorateResourceBindings())
  449. return;
  450. // Output the constructed module.
  451. std::vector<uint32_t> m = theBuilder.takeModule();
  452. if (!spirvOptions.codeGenHighLevel) {
  453. // Run legalization passes
  454. if (needsLegalization || declIdMapper.requiresLegalization()) {
  455. std::string messages;
  456. if (!spirvToolsLegalize(&m, &messages)) {
  457. emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
  458. emitNote("please file a bug report on "
  459. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  460. "with source code if possible",
  461. {});
  462. return;
  463. }
  464. }
  465. // Run optimization passes
  466. if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
  467. std::string messages;
  468. if (!spirvToolsOptimize(&m, &messages)) {
  469. emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
  470. emitNote("please file a bug report on "
  471. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  472. "with source code if possible",
  473. {});
  474. return;
  475. }
  476. }
  477. }
  478. // Validate the generated SPIR-V code
  479. if (!spirvOptions.disableValidation) {
  480. std::string messages;
  481. if (!spirvToolsValidate(&m, &messages,
  482. declIdMapper.requiresLegalization())) {
  483. emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
  484. emitNote("please file a bug report on "
  485. "https://github.com/Microsoft/DirectXShaderCompiler/issues "
  486. "with source code if possible",
  487. {});
  488. return;
  489. }
  490. }
  491. theCompilerInstance.getOutStream()->write(
  492. reinterpret_cast<const char *>(m.data()), m.size() * 4);
  493. }
  494. void SPIRVEmitter::doDecl(const Decl *decl) {
  495. if (decl->isImplicit() || isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
  496. return;
  497. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  498. // We can have VarDecls inside cbuffer/tbuffer. For those VarDecls, we need
  499. // to emit their cbuffer/tbuffer as a whole and access each individual one
  500. // using access chains.
  501. if (const auto *bufferDecl = getCTBufferContext(varDecl)) {
  502. doHLSLBufferDecl(bufferDecl);
  503. } else {
  504. doVarDecl(varDecl);
  505. }
  506. } else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  507. doFunctionDecl(funcDecl);
  508. } else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
  509. doHLSLBufferDecl(bufferDecl);
  510. } else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
  511. doRecordDecl(recordDecl);
  512. } else {
  513. emitError("decl type %0 unimplemented", decl->getLocation())
  514. << decl->getDeclKindName();
  515. }
  516. }
  517. void SPIRVEmitter::doStmt(const Stmt *stmt,
  518. llvm::ArrayRef<const Attr *> attrs) {
  519. if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
  520. for (auto *st : compoundStmt->body())
  521. doStmt(st);
  522. } else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
  523. doReturnStmt(retStmt);
  524. } else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
  525. doDeclStmt(declStmt);
  526. } else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
  527. doIfStmt(ifStmt);
  528. } else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
  529. doSwitchStmt(switchStmt, attrs);
  530. } else if (const auto *caseStmt = dyn_cast<CaseStmt>(stmt)) {
  531. processCaseStmtOrDefaultStmt(stmt);
  532. } else if (const auto *defaultStmt = dyn_cast<DefaultStmt>(stmt)) {
  533. processCaseStmtOrDefaultStmt(stmt);
  534. } else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
  535. doBreakStmt(breakStmt);
  536. } else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
  537. doDoStmt(theDoStmt, attrs);
  538. } else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
  539. doDiscardStmt(discardStmt);
  540. } else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
  541. doContinueStmt(continueStmt);
  542. } else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
  543. doWhileStmt(whileStmt, attrs);
  544. } else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
  545. doForStmt(forStmt, attrs);
  546. } else if (const auto *nullStmt = dyn_cast<NullStmt>(stmt)) {
  547. // For the null statement ";". We don't need to do anything.
  548. } else if (const auto *expr = dyn_cast<Expr>(stmt)) {
  549. // All cases for expressions used as statements
  550. doExpr(expr);
  551. } else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
  552. doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
  553. } else {
  554. emitError("statement class '%0' unimplemented", stmt->getLocStart())
  555. << stmt->getStmtClassName() << stmt->getSourceRange();
  556. }
  557. }
  558. SpirvEvalInfo SPIRVEmitter::doDeclRefExpr(const DeclRefExpr *expr) {
  559. const auto *decl = expr->getDecl();
  560. auto id = declIdMapper.getDeclEvalInfo(decl, false);
  561. if (spirvOptions.ignoreUnusedResources && !id) {
  562. // First time referencing a Decl inside TranslationUnit. Register
  563. // into DeclResultIdMapper and emit SPIR-V for it and then query
  564. // again.
  565. doDecl(decl);
  566. id = declIdMapper.getDeclEvalInfo(decl);
  567. }
  568. return id;
  569. }
  570. SpirvEvalInfo SPIRVEmitter::doExpr(const Expr *expr) {
  571. SpirvEvalInfo result(/*id*/ 0);
  572. // Provide a hint to the typeTranslator that if a literal is discovered, its
  573. // intended usage is as this expression type.
  574. TypeTranslator::LiteralTypeHint hint(typeTranslator, expr->getType());
  575. expr = expr->IgnoreParens();
  576. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
  577. result = doDeclRefExpr(declRefExpr);
  578. } else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
  579. result = doMemberExpr(memberExpr);
  580. } else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
  581. result = doCastExpr(castExpr);
  582. } else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
  583. result = doInitListExpr(initListExpr);
  584. } else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
  585. const auto value =
  586. theBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
  587. result = SpirvEvalInfo(value).setConstant().setRValue();
  588. } else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  589. const auto value = translateAPInt(intLiteral->getValue(), expr->getType());
  590. result = SpirvEvalInfo(value).setConstant().setRValue();
  591. } else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  592. const auto value =
  593. translateAPFloat(floatLiteral->getValue(), expr->getType());
  594. result = SpirvEvalInfo(value).setConstant().setRValue();
  595. } else if (const auto *compoundAssignOp =
  596. dyn_cast<CompoundAssignOperator>(expr)) {
  597. // CompoundAssignOperator is a subclass of BinaryOperator. It should be
  598. // checked before BinaryOperator.
  599. result = doCompoundAssignOperator(compoundAssignOp);
  600. } else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
  601. result = doBinaryOperator(binOp);
  602. } else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
  603. result = doUnaryOperator(unaryOp);
  604. } else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  605. result = doHLSLVectorElementExpr(vecElemExpr);
  606. } else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
  607. result = doExtMatrixElementExpr(matElemExpr);
  608. } else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
  609. result = doCallExpr(funcCall);
  610. } else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
  611. result = doArraySubscriptExpr(subscriptExpr);
  612. } else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
  613. result = doConditionalOperator(condExpr);
  614. } else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
  615. result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
  616. } else if (isa<CXXThisExpr>(expr)) {
  617. assert(curThis);
  618. result = curThis;
  619. } else {
  620. emitError("expression class '%0' unimplemented", expr->getExprLoc())
  621. << expr->getStmtClassName() << expr->getSourceRange();
  622. }
  623. return result;
  624. }
  625. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr) {
  626. // We are trying to load the value here, which is what an LValueToRValue
  627. // implicit cast is intended to do. We can ignore the cast if exists.
  628. expr = expr->IgnoreParenLValueCasts();
  629. return loadIfGLValue(expr, doExpr(expr));
  630. }
  631. SpirvEvalInfo SPIRVEmitter::loadIfGLValue(const Expr *expr,
  632. SpirvEvalInfo info) {
  633. // Do nothing if this is already rvalue
  634. if (info.isRValue())
  635. return info;
  636. // Check whether we are trying to load an externally visible structured/byte
  637. // buffer as a whole. If true, it means we are creating alias for it. Avoid
  638. // the load and write the pointer directly to the alias variable then.
  639. //
  640. // Also for the case of alias function returns. If we are trying to load an
  641. // alias function return as a whole, it means we are assigning it to another
  642. // alias variable. Avoid the load and write the pointer directly.
  643. //
  644. // Note: legalization specific code
  645. if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
  646. return info.setRValue();
  647. }
  648. if (loadIfAliasVarRef(expr, info)) {
  649. // We are loading an alias variable as a whole here. This is likely for
  650. // wholesale assignments or function returns. Need to load the pointer.
  651. //
  652. // Note: legalization specific code
  653. return info;
  654. }
  655. uint32_t valType = 0;
  656. // TODO: Ouch. Very hacky. We need special path to get the value type if
  657. // we are loading a whole ConstantBuffer/TextureBuffer since the normal
  658. // type translation path won't work.
  659. if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
  660. valType = declIdMapper.getCTBufferPushConstantTypeId(declContext);
  661. } else {
  662. valType =
  663. typeTranslator.translateType(expr->getType(), info.getLayoutRule());
  664. }
  665. return info.setResultId(theBuilder.createLoad(valType, info)).setRValue();
  666. }
  667. SpirvEvalInfo SPIRVEmitter::loadIfAliasVarRef(const Expr *expr) {
  668. auto info = doExpr(expr);
  669. loadIfAliasVarRef(expr, info);
  670. return info;
  671. }
  672. bool SPIRVEmitter::loadIfAliasVarRef(const Expr *varExpr, SpirvEvalInfo &info) {
  673. if (info.containsAliasComponent() &&
  674. TypeTranslator::isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
  675. // Aliased-to variables are all in the Uniform storage class with GLSL
  676. // std430 layout rules.
  677. const auto ptrType = typeTranslator.translateType(varExpr->getType());
  678. // Load the pointer of the aliased-to-variable if the expression has a
  679. // pointer to pointer type. That is, the expression itself is a lvalue.
  680. // (Note that we translate alias function return values as pointer types,
  681. // not pointer to pointer types.)
  682. if (varExpr->isGLValue())
  683. info.setResultId(theBuilder.createLoad(ptrType, info));
  684. info.setStorageClass(spv::StorageClass::Uniform)
  685. .setLayoutRule(LayoutRule::GLSLStd430)
  686. // Now it is a pointer to the global resource, which is lvalue.
  687. .setRValue(false)
  688. // Set to false to indicate that we've performed dereference over the
  689. // pointer-to-pointer and now should fallback to the normal path
  690. .setContainsAliasComponent(false);
  691. return true;
  692. }
  693. return false;
  694. }
  695. uint32_t SPIRVEmitter::castToType(uint32_t value, QualType fromType,
  696. QualType toType, SourceLocation srcLoc) {
  697. if (isFloatOrVecOfFloatType(toType))
  698. return castToFloat(value, fromType, toType, srcLoc);
  699. // Order matters here. Bool (vector) values will also be considered as uint
  700. // (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
  701. // will also return true. We need to check bool before uint. The opposite is
  702. // not true.
  703. if (isBoolOrVecOfBoolType(toType))
  704. return castToBool(value, fromType, toType);
  705. if (isSintOrVecOfSintType(toType) || isUintOrVecOfUintType(toType))
  706. return castToInt(value, fromType, toType, srcLoc);
  707. emitError("casting to type %0 unimplemented", {}) << toType;
  708. return 0;
  709. }
  710. void SPIRVEmitter::doFunctionDecl(const FunctionDecl *decl) {
  711. assert(decl->isThisDeclarationADefinition());
  712. // A RAII class for maintaining the current function under traversal.
  713. class FnEnvRAII {
  714. public:
  715. // Creates a new instance which sets fnEnv to the newFn on creation,
  716. // and resets fnEnv to its original value on destruction.
  717. FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
  718. : oldFn(*fnEnv), fnSlot(fnEnv) {
  719. *fnEnv = newFn;
  720. }
  721. ~FnEnvRAII() { *fnSlot = oldFn; }
  722. private:
  723. const FunctionDecl *oldFn;
  724. const FunctionDecl **fnSlot;
  725. };
  726. FnEnvRAII fnEnvRAII(&curFunction, decl);
  727. // We are about to start translation for a new function. Clear the break stack
  728. // and the continue stack.
  729. breakStack = std::stack<uint32_t>();
  730. continueStack = std::stack<uint32_t>();
  731. std::string funcName = decl->getName();
  732. uint32_t funcId = 0;
  733. if (funcName == entryFunctionName) {
  734. // The entry function surely does not have pre-assigned <result-id> for
  735. // it like other functions that got added to the work queue following
  736. // function calls.
  737. funcId = theContext.takeNextId();
  738. funcName = "src." + funcName;
  739. // Create wrapper for the entry function
  740. if (!emitEntryFunctionWrapper(decl, funcId))
  741. return;
  742. } else {
  743. // Non-entry functions are added to the work queue following function
  744. // calls. We have already assigned <result-id>s for it when translating
  745. // its call site. Query it here.
  746. funcId = declIdMapper.getDeclEvalInfo(decl);
  747. }
  748. const uint32_t retType =
  749. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(decl);
  750. // Construct the function signature.
  751. llvm::SmallVector<uint32_t, 4> paramTypes;
  752. bool isNonStaticMemberFn = false;
  753. if (const auto *memberFn = dyn_cast<CXXMethodDecl>(decl)) {
  754. isNonStaticMemberFn = !memberFn->isStatic();
  755. if (isNonStaticMemberFn) {
  756. // For non-static member function, the first parameter should be the
  757. // object on which we are invoking this method.
  758. const uint32_t valueType = typeTranslator.translateType(
  759. memberFn->getThisType(astContext)->getPointeeType());
  760. const uint32_t ptrType =
  761. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  762. paramTypes.push_back(ptrType);
  763. }
  764. // Prefix the function name with the struct name
  765. if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
  766. funcName = st->getName().str() + "." + funcName;
  767. }
  768. for (const auto *param : decl->params()) {
  769. const uint32_t valueType =
  770. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  771. const uint32_t ptrType =
  772. theBuilder.getPointerType(valueType, spv::StorageClass::Function);
  773. paramTypes.push_back(ptrType);
  774. }
  775. const uint32_t funcType = theBuilder.getFunctionType(retType, paramTypes);
  776. theBuilder.beginFunction(funcType, retType, funcName, funcId);
  777. if (isNonStaticMemberFn) {
  778. // Remember the parameter for the this object so later we can handle
  779. // CXXThisExpr correctly.
  780. curThis = theBuilder.addFnParam(paramTypes[0], "param.this");
  781. }
  782. // Create all parameters.
  783. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  784. const ParmVarDecl *paramDecl = decl->getParamDecl(i);
  785. (void)declIdMapper.createFnParam(paramDecl);
  786. }
  787. if (decl->hasBody()) {
  788. // The entry basic block.
  789. const uint32_t entryLabel = theBuilder.createBasicBlock("bb.entry");
  790. theBuilder.setInsertPoint(entryLabel);
  791. // Process all statments in the body.
  792. doStmt(decl->getBody());
  793. // We have processed all Stmts in this function and now in the last
  794. // basic block. Make sure we have a termination instruction.
  795. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  796. const auto retType = decl->getReturnType();
  797. if (retType->isVoidType()) {
  798. theBuilder.createReturn();
  799. } else {
  800. // If the source code does not provide a proper return value for some
  801. // control flow path, it's undefined behavior. We just return null
  802. // value here.
  803. theBuilder.createReturnValue(
  804. theBuilder.getConstantNull(typeTranslator.translateType(retType)));
  805. }
  806. }
  807. }
  808. theBuilder.endFunction();
  809. }
  810. bool SPIRVEmitter::validateVKAttributes(const NamedDecl *decl) {
  811. bool success = true;
  812. if (decl->hasAttr<HLSLRowMajorAttr>()) {
  813. emitWarning("row_major attribute for stand-alone matrix is not supported",
  814. decl->getAttr<HLSLRowMajorAttr>()->getLocation());
  815. }
  816. if (decl->hasAttr<HLSLColumnMajorAttr>()) {
  817. emitWarning(
  818. "column_major attribute for stand-alone matrix is not supported",
  819. decl->getAttr<HLSLColumnMajorAttr>()->getLocation());
  820. }
  821. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  822. const auto varType = varDecl->getType();
  823. if ((TypeTranslator::isSubpassInput(varType) ||
  824. TypeTranslator::isSubpassInputMS(varType)) &&
  825. !varDecl->hasAttr<VKInputAttachmentIndexAttr>()) {
  826. emitError("missing vk::input_attachment_index attribute",
  827. varDecl->getLocation());
  828. success = false;
  829. }
  830. }
  831. if (const auto *iaiAttr = decl->getAttr<VKInputAttachmentIndexAttr>()) {
  832. if (!shaderModel.IsPS()) {
  833. emitError("SubpassInput(MS) only allowed in pixel shader",
  834. decl->getLocation());
  835. success = false;
  836. }
  837. if (!decl->isExternallyVisible()) {
  838. emitError("SubpassInput(MS) must be externally visible",
  839. decl->getLocation());
  840. success = false;
  841. }
  842. // We only allow VKInputAttachmentIndexAttr to be attached to global
  843. // variables. So it should be fine to cast here.
  844. const auto elementType =
  845. hlsl::GetHLSLResourceResultType(cast<VarDecl>(decl)->getType());
  846. if (!TypeTranslator::isScalarType(elementType) &&
  847. !TypeTranslator::isVectorType(elementType)) {
  848. emitError(
  849. "only scalar/vector types allowed as SubpassInput(MS) parameter type",
  850. decl->getLocation());
  851. // Return directly to avoid further type processing, which will hit
  852. // asserts in TypeTranslator.
  853. return false;
  854. }
  855. }
  856. // The frontend will make sure that
  857. // * vk::push_constant applies to global variables of struct type
  858. // * vk::binding applies to global variables or cbuffers/tbuffers
  859. // * vk::counter_binding applies to global variables of RW/Append/Consume
  860. // StructuredBuffer
  861. // * vk::location applies to function parameters/returns and struct fields
  862. // So the only case we need to check co-existence is vk::push_constant and
  863. // vk::binding.
  864. if (const auto *pcAttr = decl->getAttr<VKPushConstantAttr>()) {
  865. const auto loc = pcAttr->getLocation();
  866. if (seenPushConstantAt.isInvalid()) {
  867. seenPushConstantAt = loc;
  868. } else {
  869. // TODO: Actually this is slightly incorrect. The Vulkan spec says:
  870. // There must be no more than one push constant block statically used
  871. // per shader entry point.
  872. // But we are checking whether there are more than one push constant
  873. // blocks defined. Tracking usage requires more work.
  874. emitError("cannot have more than one push constant block", loc);
  875. emitNote("push constant block previously defined here",
  876. seenPushConstantAt);
  877. success = false;
  878. }
  879. if (decl->hasAttr<VKBindingAttr>()) {
  880. emitError("vk::push_constant attribute cannot be used together with "
  881. "vk::binding attribute",
  882. loc);
  883. success = false;
  884. }
  885. }
  886. return success;
  887. }
  888. void SPIRVEmitter::doHLSLBufferDecl(const HLSLBufferDecl *bufferDecl) {
  889. // This is a cbuffer/tbuffer decl.
  890. // Check and emit warnings for member intializers which are not
  891. // supported in Vulkan
  892. for (const auto *member : bufferDecl->decls()) {
  893. if (const auto *varMember = dyn_cast<VarDecl>(member)) {
  894. if (const auto *init = varMember->getInit())
  895. emitWarning("%select{tbuffer|cbuffer}0 member initializer "
  896. "ignored since no equivalent in Vulkan",
  897. init->getExprLoc())
  898. << bufferDecl->isCBuffer() << init->getSourceRange();
  899. for (const auto *annotation : varMember->getUnusualAnnotations())
  900. if (const auto *packing = dyn_cast<hlsl::ConstantPacking>(annotation))
  901. emitWarning("packoffset ignored since not supported", packing->Loc);
  902. }
  903. }
  904. if (!validateVKAttributes(bufferDecl))
  905. return;
  906. (void)declIdMapper.createCTBuffer(bufferDecl);
  907. }
  908. void SPIRVEmitter::doRecordDecl(const RecordDecl *recordDecl) {
  909. // Ignore implict records
  910. // Somehow we'll have implicit records with:
  911. // static const int Length = count;
  912. // that can mess up with the normal CodeGen.
  913. if (recordDecl->isImplicit())
  914. return;
  915. // Handle each static member with inline initializer.
  916. // Each static member has a corresponding VarDecl inside the
  917. // RecordDecl. For those defined in the translation unit,
  918. // their VarDecls do not have initializer.
  919. for (auto *subDecl : recordDecl->decls())
  920. if (auto *varDecl = dyn_cast<VarDecl>(subDecl))
  921. if (varDecl->isStaticDataMember() && varDecl->hasInit())
  922. doVarDecl(varDecl);
  923. }
  924. void SPIRVEmitter::doVarDecl(const VarDecl *decl) {
  925. if (!validateVKAttributes(decl))
  926. return;
  927. if (decl->hasAttr<VKConstantIdAttr>()) {
  928. // This is a VarDecl for specialization constant.
  929. createSpecConstant(decl);
  930. return;
  931. }
  932. if (decl->hasAttr<VKPushConstantAttr>()) {
  933. // This is a VarDecl for PushConstant block.
  934. (void)declIdMapper.createPushConstant(decl);
  935. return;
  936. }
  937. if (isa<HLSLBufferDecl>(decl->getDeclContext())) {
  938. // This is a VarDecl of a ConstantBuffer/TextureBuffer type.
  939. (void)declIdMapper.createCTBuffer(decl);
  940. return;
  941. }
  942. uint32_t varId = 0;
  943. // The contents in externally visible variables can be updated via the
  944. // pipeline. They should be handled differently from file and function scope
  945. // variables.
  946. // File scope variables (static "global" and "local" variables) belongs to
  947. // the Private storage class, while function scope variables (normal "local"
  948. // variables) belongs to the Function storage class.
  949. if (isExternalVar(decl)) {
  950. varId = declIdMapper.createExternVar(decl);
  951. } else {
  952. // We already know the variable is not externally visible here. If it does
  953. // not have local storage, it should be file scope variable.
  954. const bool isFileScopeVar = !decl->hasLocalStorage();
  955. if (isFileScopeVar)
  956. varId = declIdMapper.createFileVar(decl, llvm::None);
  957. else
  958. varId = declIdMapper.createFnVar(decl, llvm::None);
  959. // Emit OpStore to initialize the variable
  960. // TODO: revert back to use OpVariable initializer
  961. // We should only evaluate the initializer once for a static variable.
  962. if (isFileScopeVar) {
  963. if (decl->isStaticLocal()) {
  964. initOnce(decl->getType(), decl->getName(), varId, decl->getInit());
  965. } else {
  966. // Defer to initialize these global variables at the beginning of the
  967. // entry function.
  968. toInitGloalVars.push_back(decl);
  969. }
  970. }
  971. // Function local variables. Just emit OpStore at the current insert point.
  972. else if (const Expr *init = decl->getInit()) {
  973. if (const auto constId = tryToEvaluateAsConst(init))
  974. theBuilder.createStore(varId, constId);
  975. else
  976. storeValue(varId, loadIfGLValue(init), decl->getType());
  977. // Update counter variable associated with local variables
  978. tryToAssignCounterVar(decl, init);
  979. }
  980. // Variables that are not externally visible and of opaque types should
  981. // request legalization.
  982. if (!needsLegalization && TypeTranslator::isOpaqueType(decl->getType()))
  983. needsLegalization = true;
  984. }
  985. if (TypeTranslator::isRelaxedPrecisionType(decl->getType(), spirvOptions)) {
  986. theBuilder.decorate(varId, spv::Decoration::RelaxedPrecision);
  987. }
  988. // All variables that are of opaque struct types should request legalization.
  989. if (!needsLegalization && TypeTranslator::isOpaqueStructType(decl->getType()))
  990. needsLegalization = true;
  991. }
  992. spv::LoopControlMask SPIRVEmitter::translateLoopAttribute(const Stmt *stmt,
  993. const Attr &attr) {
  994. switch (attr.getKind()) {
  995. case attr::HLSLLoop:
  996. case attr::HLSLFastOpt:
  997. return spv::LoopControlMask::DontUnroll;
  998. case attr::HLSLUnroll:
  999. return spv::LoopControlMask::Unroll;
  1000. case attr::HLSLAllowUAVCondition:
  1001. emitWarning("unsupported allow_uav_condition attribute ignored",
  1002. stmt->getLocStart());
  1003. break;
  1004. default:
  1005. llvm_unreachable("found unknown loop attribute");
  1006. }
  1007. return spv::LoopControlMask::MaskNone;
  1008. }
  1009. void SPIRVEmitter::doDiscardStmt(const DiscardStmt *discardStmt) {
  1010. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1011. theBuilder.createKill();
  1012. // Some statements that alter the control flow (break, continue, return, and
  1013. // discard), require creation of a new basic block to hold any statement that
  1014. // may follow them.
  1015. const uint32_t newBB = theBuilder.createBasicBlock();
  1016. theBuilder.setInsertPoint(newBB);
  1017. }
  1018. void SPIRVEmitter::doDoStmt(const DoStmt *theDoStmt,
  1019. llvm::ArrayRef<const Attr *> attrs) {
  1020. // do-while loops are composed of:
  1021. //
  1022. // do {
  1023. // <body>
  1024. // } while(<check>);
  1025. //
  1026. // SPIR-V requires loops to have a merge basic block as well as a continue
  1027. // basic block. Even though do-while loops do not have an explicit continue
  1028. // block as in for-loops, we still do need to create a continue block.
  1029. //
  1030. // Since SPIR-V requires structured control flow, we need two more basic
  1031. // blocks, <header> and <merge>. <header> is the block before control flow
  1032. // diverges, and <merge> is the block where control flow subsequently
  1033. // converges. The <check> can be performed in the <continue> basic block.
  1034. // The final CFG should normally be like the following. Exceptions
  1035. // will occur with non-local exits like loop breaks or early returns.
  1036. //
  1037. // +----------+
  1038. // | header | <-----------------------------------+
  1039. // +----------+ |
  1040. // | | (true)
  1041. // v |
  1042. // +------+ +--------------------+ |
  1043. // | body | ----> | continue (<check>) |-----------+
  1044. // +------+ +--------------------+
  1045. // |
  1046. // | (false)
  1047. // +-------+ |
  1048. // | merge | <-------------+
  1049. // +-------+
  1050. //
  1051. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1052. const spv::LoopControlMask loopControl =
  1053. attrs.empty() ? spv::LoopControlMask::MaskNone
  1054. : translateLoopAttribute(theDoStmt, *attrs.front());
  1055. // Create basic blocks
  1056. const uint32_t headerBB = theBuilder.createBasicBlock("do_while.header");
  1057. const uint32_t bodyBB = theBuilder.createBasicBlock("do_while.body");
  1058. const uint32_t continueBB = theBuilder.createBasicBlock("do_while.continue");
  1059. const uint32_t mergeBB = theBuilder.createBasicBlock("do_while.merge");
  1060. // Make sure any continue statements branch to the continue block, and any
  1061. // break statements branch to the merge block.
  1062. continueStack.push(continueBB);
  1063. breakStack.push(mergeBB);
  1064. // Branch from the current insert point to the header block.
  1065. theBuilder.createBranch(headerBB);
  1066. theBuilder.addSuccessor(headerBB);
  1067. // Process the <header> block
  1068. // The header block must always branch to the body.
  1069. theBuilder.setInsertPoint(headerBB);
  1070. theBuilder.createBranch(bodyBB, mergeBB, continueBB, loopControl);
  1071. theBuilder.addSuccessor(bodyBB);
  1072. // The current basic block has OpLoopMerge instruction. We need to set its
  1073. // continue and merge target.
  1074. theBuilder.setContinueTarget(continueBB);
  1075. theBuilder.setMergeTarget(mergeBB);
  1076. // Process the <body> block
  1077. theBuilder.setInsertPoint(bodyBB);
  1078. if (const Stmt *body = theDoStmt->getBody()) {
  1079. doStmt(body);
  1080. }
  1081. if (!theBuilder.isCurrentBasicBlockTerminated())
  1082. theBuilder.createBranch(continueBB);
  1083. theBuilder.addSuccessor(continueBB);
  1084. // Process the <continue> block. The check for whether the loop should
  1085. // continue lies in the continue block.
  1086. // *NOTE*: There's a SPIR-V rule that when a conditional branch is to occur in
  1087. // a continue block of a loop, there should be no OpSelectionMerge. Only an
  1088. // OpBranchConditional must be specified.
  1089. theBuilder.setInsertPoint(continueBB);
  1090. uint32_t condition = 0;
  1091. if (const Expr *check = theDoStmt->getCond()) {
  1092. condition = doExpr(check);
  1093. } else {
  1094. condition = theBuilder.getConstantBool(true);
  1095. }
  1096. theBuilder.createConditionalBranch(condition, headerBB, mergeBB);
  1097. theBuilder.addSuccessor(headerBB);
  1098. theBuilder.addSuccessor(mergeBB);
  1099. // Set insertion point to the <merge> block for subsequent statements
  1100. theBuilder.setInsertPoint(mergeBB);
  1101. // Done with the current scope's continue block and merge block.
  1102. continueStack.pop();
  1103. breakStack.pop();
  1104. }
  1105. void SPIRVEmitter::doContinueStmt(const ContinueStmt *continueStmt) {
  1106. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1107. const uint32_t continueTargetBB = continueStack.top();
  1108. theBuilder.createBranch(continueTargetBB);
  1109. theBuilder.addSuccessor(continueTargetBB);
  1110. // Some statements that alter the control flow (break, continue, return, and
  1111. // discard), require creation of a new basic block to hold any statement that
  1112. // may follow them. For example: StmtB and StmtC below are put inside a new
  1113. // basic block which is unreachable.
  1114. //
  1115. // while (true) {
  1116. // StmtA;
  1117. // continue;
  1118. // StmtB;
  1119. // StmtC;
  1120. // }
  1121. const uint32_t newBB = theBuilder.createBasicBlock();
  1122. theBuilder.setInsertPoint(newBB);
  1123. }
  1124. void SPIRVEmitter::doWhileStmt(const WhileStmt *whileStmt,
  1125. llvm::ArrayRef<const Attr *> attrs) {
  1126. // While loops are composed of:
  1127. // while (<check>) { <body> }
  1128. //
  1129. // SPIR-V requires loops to have a merge basic block as well as a continue
  1130. // basic block. Even though while loops do not have an explicit continue
  1131. // block as in for-loops, we still do need to create a continue block.
  1132. //
  1133. // Since SPIR-V requires structured control flow, we need two more basic
  1134. // blocks, <header> and <merge>. <header> is the block before control flow
  1135. // diverges, and <merge> is the block where control flow subsequently
  1136. // converges. The <check> block can take the responsibility of the <header>
  1137. // block. The final CFG should normally be like the following. Exceptions
  1138. // will occur with non-local exits like loop breaks or early returns.
  1139. //
  1140. // +----------+
  1141. // | header | <------------------+
  1142. // | (check) | |
  1143. // +----------+ |
  1144. // | |
  1145. // +-------+-------+ |
  1146. // | false | true |
  1147. // | v |
  1148. // | +------+ +------------------+
  1149. // | | body | --> | continue (no-op) |
  1150. // v +------+ +------------------+
  1151. // +-------+
  1152. // | merge |
  1153. // +-------+
  1154. //
  1155. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1156. const spv::LoopControlMask loopControl =
  1157. attrs.empty() ? spv::LoopControlMask::MaskNone
  1158. : translateLoopAttribute(whileStmt, *attrs.front());
  1159. // Create basic blocks
  1160. const uint32_t checkBB = theBuilder.createBasicBlock("while.check");
  1161. const uint32_t bodyBB = theBuilder.createBasicBlock("while.body");
  1162. const uint32_t continueBB = theBuilder.createBasicBlock("while.continue");
  1163. const uint32_t mergeBB = theBuilder.createBasicBlock("while.merge");
  1164. // Make sure any continue statements branch to the continue block, and any
  1165. // break statements branch to the merge block.
  1166. continueStack.push(continueBB);
  1167. breakStack.push(mergeBB);
  1168. // Process the <check> block
  1169. theBuilder.createBranch(checkBB);
  1170. theBuilder.addSuccessor(checkBB);
  1171. theBuilder.setInsertPoint(checkBB);
  1172. // If we have:
  1173. // while (int a = foo()) {...}
  1174. // we should evaluate 'a' by calling 'foo()' every single time the check has
  1175. // to occur.
  1176. if (const auto *condVarDecl = whileStmt->getConditionVariableDeclStmt())
  1177. doStmt(condVarDecl);
  1178. uint32_t condition = 0;
  1179. if (const Expr *check = whileStmt->getCond()) {
  1180. condition = doExpr(check);
  1181. } else {
  1182. condition = theBuilder.getConstantBool(true);
  1183. }
  1184. theBuilder.createConditionalBranch(condition, bodyBB,
  1185. /*false branch*/ mergeBB,
  1186. /*merge*/ mergeBB, continueBB,
  1187. spv::SelectionControlMask::MaskNone,
  1188. loopControl);
  1189. theBuilder.addSuccessor(bodyBB);
  1190. theBuilder.addSuccessor(mergeBB);
  1191. // The current basic block has OpLoopMerge instruction. We need to set its
  1192. // continue and merge target.
  1193. theBuilder.setContinueTarget(continueBB);
  1194. theBuilder.setMergeTarget(mergeBB);
  1195. // Process the <body> block
  1196. theBuilder.setInsertPoint(bodyBB);
  1197. if (const Stmt *body = whileStmt->getBody()) {
  1198. doStmt(body);
  1199. }
  1200. if (!theBuilder.isCurrentBasicBlockTerminated())
  1201. theBuilder.createBranch(continueBB);
  1202. theBuilder.addSuccessor(continueBB);
  1203. // Process the <continue> block. While loops do not have an explicit
  1204. // continue block. The continue block just branches to the <check> block.
  1205. theBuilder.setInsertPoint(continueBB);
  1206. theBuilder.createBranch(checkBB);
  1207. theBuilder.addSuccessor(checkBB);
  1208. // Set insertion point to the <merge> block for subsequent statements
  1209. theBuilder.setInsertPoint(mergeBB);
  1210. // Done with the current scope's continue and merge blocks.
  1211. continueStack.pop();
  1212. breakStack.pop();
  1213. }
  1214. void SPIRVEmitter::doForStmt(const ForStmt *forStmt,
  1215. llvm::ArrayRef<const Attr *> attrs) {
  1216. // for loops are composed of:
  1217. // for (<init>; <check>; <continue>) <body>
  1218. //
  1219. // To translate a for loop, we'll need to emit all <init> statements
  1220. // in the current basic block, and then have separate basic blocks for
  1221. // <check>, <continue>, and <body>. Besides, since SPIR-V requires
  1222. // structured control flow, we need two more basic blocks, <header>
  1223. // and <merge>. <header> is the block before control flow diverges,
  1224. // while <merge> is the block where control flow subsequently converges.
  1225. // The <check> block can take the responsibility of the <header> block.
  1226. // The final CFG should normally be like the following. Exceptions will
  1227. // occur with non-local exits like loop breaks or early returns.
  1228. // +--------+
  1229. // | init |
  1230. // +--------+
  1231. // |
  1232. // v
  1233. // +----------+
  1234. // | header | <---------------+
  1235. // | (check) | |
  1236. // +----------+ |
  1237. // | |
  1238. // +-------+-------+ |
  1239. // | false | true |
  1240. // | v |
  1241. // | +------+ +----------+
  1242. // | | body | --> | continue |
  1243. // v +------+ +----------+
  1244. // +-------+
  1245. // | merge |
  1246. // +-------+
  1247. //
  1248. // For more details, see "2.11. Structured Control Flow" in the SPIR-V spec.
  1249. const spv::LoopControlMask loopControl =
  1250. attrs.empty() ? spv::LoopControlMask::MaskNone
  1251. : translateLoopAttribute(forStmt, *attrs.front());
  1252. // Create basic blocks
  1253. const uint32_t checkBB = theBuilder.createBasicBlock("for.check");
  1254. const uint32_t bodyBB = theBuilder.createBasicBlock("for.body");
  1255. const uint32_t continueBB = theBuilder.createBasicBlock("for.continue");
  1256. const uint32_t mergeBB = theBuilder.createBasicBlock("for.merge");
  1257. // Make sure any continue statements branch to the continue block, and any
  1258. // break statements branch to the merge block.
  1259. continueStack.push(continueBB);
  1260. breakStack.push(mergeBB);
  1261. // Process the <init> block
  1262. if (const Stmt *initStmt = forStmt->getInit()) {
  1263. doStmt(initStmt);
  1264. }
  1265. theBuilder.createBranch(checkBB);
  1266. theBuilder.addSuccessor(checkBB);
  1267. // Process the <check> block
  1268. theBuilder.setInsertPoint(checkBB);
  1269. uint32_t condition;
  1270. if (const Expr *check = forStmt->getCond()) {
  1271. condition = doExpr(check);
  1272. } else {
  1273. condition = theBuilder.getConstantBool(true);
  1274. }
  1275. theBuilder.createConditionalBranch(condition, bodyBB,
  1276. /*false branch*/ mergeBB,
  1277. /*merge*/ mergeBB, continueBB,
  1278. spv::SelectionControlMask::MaskNone,
  1279. loopControl);
  1280. theBuilder.addSuccessor(bodyBB);
  1281. theBuilder.addSuccessor(mergeBB);
  1282. // The current basic block has OpLoopMerge instruction. We need to set its
  1283. // continue and merge target.
  1284. theBuilder.setContinueTarget(continueBB);
  1285. theBuilder.setMergeTarget(mergeBB);
  1286. // Process the <body> block
  1287. theBuilder.setInsertPoint(bodyBB);
  1288. if (const Stmt *body = forStmt->getBody()) {
  1289. doStmt(body);
  1290. }
  1291. if (!theBuilder.isCurrentBasicBlockTerminated())
  1292. theBuilder.createBranch(continueBB);
  1293. theBuilder.addSuccessor(continueBB);
  1294. // Process the <continue> block
  1295. theBuilder.setInsertPoint(continueBB);
  1296. if (const Expr *cont = forStmt->getInc()) {
  1297. doExpr(cont);
  1298. }
  1299. theBuilder.createBranch(checkBB); // <continue> should jump back to header
  1300. theBuilder.addSuccessor(checkBB);
  1301. // Set insertion point to the <merge> block for subsequent statements
  1302. theBuilder.setInsertPoint(mergeBB);
  1303. // Done with the current scope's continue block and merge block.
  1304. continueStack.pop();
  1305. breakStack.pop();
  1306. }
  1307. void SPIRVEmitter::doIfStmt(const IfStmt *ifStmt) {
  1308. // if statements are composed of:
  1309. // if (<check>) { <then> } else { <else> }
  1310. //
  1311. // To translate if statements, we'll need to emit the <check> expressions
  1312. // in the current basic block, and then create separate basic blocks for
  1313. // <then> and <else>. Additionally, we'll need a <merge> block as per
  1314. // SPIR-V's structured control flow requirements. Depending whether there
  1315. // exists the else branch, the final CFG should normally be like the
  1316. // following. Exceptions will occur with non-local exits like loop breaks
  1317. // or early returns.
  1318. // +-------+ +-------+
  1319. // | check | | check |
  1320. // +-------+ +-------+
  1321. // | |
  1322. // +-------+-------+ +-----+-----+
  1323. // | true | false | true | false
  1324. // v v or v |
  1325. // +------+ +------+ +------+ |
  1326. // | then | | else | | then | |
  1327. // +------+ +------+ +------+ |
  1328. // | | | v
  1329. // | +-------+ | | +-------+
  1330. // +-> | merge | <-+ +---> | merge |
  1331. // +-------+ +-------+
  1332. { // Try to see if we can const-eval the condition
  1333. bool condition = false;
  1334. if (ifStmt->getCond()->EvaluateAsBooleanCondition(condition, astContext)) {
  1335. if (condition) {
  1336. doStmt(ifStmt->getThen());
  1337. } else if (ifStmt->getElse()) {
  1338. doStmt(ifStmt->getElse());
  1339. }
  1340. return;
  1341. }
  1342. }
  1343. if (const auto *declStmt = ifStmt->getConditionVariableDeclStmt())
  1344. doDeclStmt(declStmt);
  1345. // First emit the instruction for evaluating the condition.
  1346. const uint32_t condition = doExpr(ifStmt->getCond());
  1347. // Then we need to emit the instruction for the conditional branch.
  1348. // We'll need the <label-id> for the then/else/merge block to do so.
  1349. const bool hasElse = ifStmt->getElse() != nullptr;
  1350. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  1351. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  1352. const uint32_t elseBB =
  1353. hasElse ? theBuilder.createBasicBlock("if.false") : mergeBB;
  1354. // Create the branch instruction. This will end the current basic block.
  1355. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB);
  1356. theBuilder.addSuccessor(thenBB);
  1357. theBuilder.addSuccessor(elseBB);
  1358. // The current basic block has the OpSelectionMerge instruction. We need
  1359. // to record its merge target.
  1360. theBuilder.setMergeTarget(mergeBB);
  1361. // Handle the then branch
  1362. theBuilder.setInsertPoint(thenBB);
  1363. doStmt(ifStmt->getThen());
  1364. if (!theBuilder.isCurrentBasicBlockTerminated())
  1365. theBuilder.createBranch(mergeBB);
  1366. theBuilder.addSuccessor(mergeBB);
  1367. // Handle the else branch (if exists)
  1368. if (hasElse) {
  1369. theBuilder.setInsertPoint(elseBB);
  1370. doStmt(ifStmt->getElse());
  1371. if (!theBuilder.isCurrentBasicBlockTerminated())
  1372. theBuilder.createBranch(mergeBB);
  1373. theBuilder.addSuccessor(mergeBB);
  1374. }
  1375. // From now on, we'll emit instructions into the merge block.
  1376. theBuilder.setInsertPoint(mergeBB);
  1377. }
  1378. void SPIRVEmitter::doReturnStmt(const ReturnStmt *stmt) {
  1379. if (const auto *retVal = stmt->getRetValue()) {
  1380. // Update counter variable associated with function returns
  1381. tryToAssignCounterVar(curFunction, retVal);
  1382. const auto retInfo = loadIfGLValue(retVal);
  1383. const auto retType = retVal->getType();
  1384. if (retInfo.getStorageClass() != spv::StorageClass::Function &&
  1385. retType->isStructureType()) {
  1386. // We are returning some value from a non-Function storage class. Need to
  1387. // create a temporary variable to "convert" the value to Function storage
  1388. // class and then return.
  1389. const uint32_t valType = typeTranslator.translateType(retType);
  1390. const uint32_t tempVar = theBuilder.addFnVar(valType, "temp.var.ret");
  1391. storeValue(tempVar, retInfo, retType);
  1392. theBuilder.createReturnValue(theBuilder.createLoad(valType, tempVar));
  1393. } else {
  1394. theBuilder.createReturnValue(retInfo);
  1395. }
  1396. } else {
  1397. theBuilder.createReturn();
  1398. }
  1399. // We are translating a ReturnStmt, we should be in some function's body.
  1400. assert(curFunction->hasBody());
  1401. // If this return statement is the last statement in the function, then
  1402. // whe have no more work to do.
  1403. if (cast<CompoundStmt>(curFunction->getBody())->body_back() == stmt)
  1404. return;
  1405. // Some statements that alter the control flow (break, continue, return, and
  1406. // discard), require creation of a new basic block to hold any statement that
  1407. // may follow them. In this case, the newly created basic block will contain
  1408. // any statement that may come after an early return.
  1409. const uint32_t newBB = theBuilder.createBasicBlock();
  1410. theBuilder.setInsertPoint(newBB);
  1411. }
  1412. void SPIRVEmitter::doBreakStmt(const BreakStmt *breakStmt) {
  1413. assert(!theBuilder.isCurrentBasicBlockTerminated());
  1414. uint32_t breakTargetBB = breakStack.top();
  1415. theBuilder.addSuccessor(breakTargetBB);
  1416. theBuilder.createBranch(breakTargetBB);
  1417. // Some statements that alter the control flow (break, continue, return, and
  1418. // discard), require creation of a new basic block to hold any statement that
  1419. // may follow them. For example: StmtB and StmtC below are put inside a new
  1420. // basic block which is unreachable.
  1421. //
  1422. // while (true) {
  1423. // StmtA;
  1424. // break;
  1425. // StmtB;
  1426. // StmtC;
  1427. // }
  1428. const uint32_t newBB = theBuilder.createBasicBlock();
  1429. theBuilder.setInsertPoint(newBB);
  1430. }
  1431. void SPIRVEmitter::doSwitchStmt(const SwitchStmt *switchStmt,
  1432. llvm::ArrayRef<const Attr *> attrs) {
  1433. // Switch statements are composed of:
  1434. // switch (<condition variable>) {
  1435. // <CaseStmt>
  1436. // <CaseStmt>
  1437. // <CaseStmt>
  1438. // <DefaultStmt> (optional)
  1439. // }
  1440. //
  1441. // +-------+
  1442. // | check |
  1443. // +-------+
  1444. // |
  1445. // +-------+-------+----------------+---------------+
  1446. // | 1 | 2 | 3 | (others)
  1447. // v v v v
  1448. // +-------+ +-------------+ +-------+ +------------+
  1449. // | case1 | | case2 | | case3 | ... | default |
  1450. // | | |(fallthrough)|---->| | | (optional) |
  1451. // +-------+ |+------------+ +-------+ +------------+
  1452. // | | |
  1453. // | | |
  1454. // | +-------+ | |
  1455. // | | | <--------------------+ |
  1456. // +-> | merge | |
  1457. // | | <-------------------------------------+
  1458. // +-------+
  1459. // If no attributes are given, or if "forcecase" attribute was provided,
  1460. // we'll do our best to use OpSwitch if possible.
  1461. // If any of the cases compares to a variable (rather than an integer
  1462. // literal), we cannot use OpSwitch because OpSwitch expects literal
  1463. // numbers as parameters.
  1464. const bool isAttrForceCase =
  1465. !attrs.empty() && attrs.front()->getKind() == attr::HLSLForceCase;
  1466. const bool canUseSpirvOpSwitch =
  1467. (attrs.empty() || isAttrForceCase) &&
  1468. allSwitchCasesAreIntegerLiterals(switchStmt->getBody());
  1469. if (isAttrForceCase && !canUseSpirvOpSwitch)
  1470. emitWarning("ignored 'forcecase' attribute for the switch statement "
  1471. "since one or more case values are not integer literals",
  1472. switchStmt->getLocStart());
  1473. if (canUseSpirvOpSwitch)
  1474. processSwitchStmtUsingSpirvOpSwitch(switchStmt);
  1475. else
  1476. processSwitchStmtUsingIfStmts(switchStmt);
  1477. }
  1478. SpirvEvalInfo
  1479. SPIRVEmitter::doArraySubscriptExpr(const ArraySubscriptExpr *expr) {
  1480. llvm::SmallVector<uint32_t, 4> indices;
  1481. auto info = loadIfAliasVarRef(collectArrayStructIndices(expr, &indices));
  1482. if (!indices.empty()) {
  1483. (void)turnIntoElementPtr(info, expr->getType(), indices);
  1484. }
  1485. return info;
  1486. }
  1487. SpirvEvalInfo SPIRVEmitter::doBinaryOperator(const BinaryOperator *expr) {
  1488. const auto opcode = expr->getOpcode();
  1489. // Handle assignment first since we need to evaluate rhs before lhs.
  1490. // For other binary operations, we need to evaluate lhs before rhs.
  1491. if (opcode == BO_Assign) {
  1492. // Update counter variable associated with lhs of assignments
  1493. tryToAssignCounterVar(expr->getLHS(), expr->getRHS());
  1494. return processAssignment(expr->getLHS(), loadIfGLValue(expr->getRHS()),
  1495. /*isCompoundAssignment=*/false);
  1496. }
  1497. // Try to optimize floatMxN * float and floatN * float case
  1498. if (opcode == BO_Mul) {
  1499. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  1500. return result;
  1501. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  1502. return result;
  1503. }
  1504. return processBinaryOp(expr->getLHS(), expr->getRHS(), opcode,
  1505. expr->getType(), expr->getSourceRange());
  1506. }
  1507. SpirvEvalInfo SPIRVEmitter::doCallExpr(const CallExpr *callExpr) {
  1508. if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(callExpr))
  1509. return doCXXOperatorCallExpr(operatorCall);
  1510. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr))
  1511. return doCXXMemberCallExpr(memberCall);
  1512. // Intrinsic functions such as 'dot' or 'mul'
  1513. if (hlsl::IsIntrinsicOp(callExpr->getDirectCallee())) {
  1514. return processIntrinsicCallExpr(callExpr);
  1515. }
  1516. // Normal standalone functions
  1517. return processCall(callExpr);
  1518. }
  1519. SpirvEvalInfo SPIRVEmitter::processCall(const CallExpr *callExpr) {
  1520. const FunctionDecl *callee = getCalleeDefinition(callExpr);
  1521. // Note that we always want the defintion because Stmts/Exprs in the
  1522. // function body references the parameters in the definition.
  1523. if (!callee) {
  1524. emitError("found undefined function", callExpr->getExprLoc());
  1525. return 0;
  1526. }
  1527. const auto numParams = callee->getNumParams();
  1528. bool isNonStaticMemberCall = false;
  1529. QualType objectType = {}; // Type of the object (if exists)
  1530. SpirvEvalInfo objectEvalInfo = 0; // EvalInfo for the object (if exists)
  1531. bool objectNeedsTempVar = false; // Temporary variable for lvalue object
  1532. llvm::SmallVector<uint32_t, 4> params; // Temporary variables
  1533. llvm::SmallVector<SpirvEvalInfo, 4> args; // Evaluated arguments
  1534. if (const auto *memberCall = dyn_cast<CXXMemberCallExpr>(callExpr)) {
  1535. const auto *memberFn = cast<CXXMethodDecl>(memberCall->getCalleeDecl());
  1536. isNonStaticMemberCall = !memberFn->isStatic();
  1537. if (isNonStaticMemberCall) {
  1538. // For non-static member calls, evaluate the object and pass it as the
  1539. // first argument.
  1540. const auto *object = memberCall->getImplicitObjectArgument();
  1541. object = object->IgnoreParenNoopCasts(astContext);
  1542. // Update counter variable associated with the implicit object
  1543. tryToAssignCounterVar(getOrCreateDeclForMethodObject(memberFn), object);
  1544. objectType = object->getType();
  1545. objectEvalInfo = doExpr(object);
  1546. uint32_t objectId = objectEvalInfo;
  1547. // If not already a variable, we need to create a temporary variable and
  1548. // pass the object pointer to the function. Example:
  1549. // getObject().objectMethod();
  1550. bool needsTempVar = objectEvalInfo.isRValue();
  1551. // Try to see if we are calling methods on a global variable, which is put
  1552. // in the Private storage class. We also need to create temporary variable
  1553. // for it since the function signature expects all arguments in the
  1554. // Function storage class.
  1555. if (!needsTempVar)
  1556. if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(object))
  1557. if (const auto *refDecl = declRefExpr->getFoundDecl())
  1558. if (const auto *varDecl = dyn_cast<VarDecl>(refDecl))
  1559. needsTempVar = objectNeedsTempVar = varDecl->hasGlobalStorage();
  1560. if (needsTempVar) {
  1561. objectId =
  1562. createTemporaryVar(objectType, TypeTranslator::getName(objectType),
  1563. // May need to load to use as initializer
  1564. loadIfGLValue(object, objectEvalInfo));
  1565. }
  1566. args.push_back(objectId);
  1567. // We do not need to create a new temporary variable for the this
  1568. // object. Use the evaluated argument.
  1569. params.push_back(args.back());
  1570. }
  1571. }
  1572. // Evaluate parameters
  1573. for (uint32_t i = 0; i < numParams; ++i) {
  1574. // We want the argument variable here so that we can write back to it
  1575. // later. We will do the OpLoad of this argument manually. So ingore
  1576. // the LValueToRValue implicit cast here.
  1577. auto *arg = callExpr->getArg(i)->IgnoreParenLValueCasts();
  1578. const auto *param = callee->getParamDecl(i);
  1579. // We need to create variables for holding the values to be used as
  1580. // arguments. The variables themselves are of pointer types.
  1581. const uint32_t varType =
  1582. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(param);
  1583. const std::string varName = "param.var." + param->getNameAsString();
  1584. const uint32_t tempVarId = theBuilder.addFnVar(varType, varName);
  1585. params.push_back(tempVarId);
  1586. args.push_back(doExpr(arg));
  1587. // Update counter variable associated with function parameters
  1588. tryToAssignCounterVar(param, arg);
  1589. // Manually load the argument here
  1590. const auto rhsVal = loadIfGLValue(arg, args.back());
  1591. // Initialize the temporary variables using the contents of the arguments
  1592. storeValue(tempVarId, rhsVal, param->getType());
  1593. }
  1594. // Push the callee into the work queue if it is not there.
  1595. if (!workQueue.count(callee)) {
  1596. workQueue.insert(callee);
  1597. }
  1598. const uint32_t retType =
  1599. declIdMapper.getTypeAndCreateCounterForPotentialAliasVar(callee);
  1600. // Get or forward declare the function <result-id>
  1601. const uint32_t funcId = declIdMapper.getOrRegisterFnResultId(callee);
  1602. const uint32_t retVal =
  1603. theBuilder.createFunctionCall(retType, funcId, params);
  1604. // If we created a temporary variable for the object this method is invoked
  1605. // upon, we need to copy the contents in the temporary variable back to the
  1606. // original object's variable in case there are side effects.
  1607. if (objectNeedsTempVar) {
  1608. const uint32_t typeId = typeTranslator.translateType(objectType);
  1609. const uint32_t value = theBuilder.createLoad(typeId, params.front());
  1610. storeValue(objectEvalInfo, value, objectType);
  1611. }
  1612. // Go through all parameters and write those marked as out/inout
  1613. for (uint32_t i = 0; i < numParams; ++i) {
  1614. const auto *param = callee->getParamDecl(i);
  1615. if (canActAsOutParmVar(param)) {
  1616. const auto *arg = callExpr->getArg(i);
  1617. const uint32_t index = i + isNonStaticMemberCall;
  1618. const uint32_t typeId = typeTranslator.translateType(param->getType());
  1619. const uint32_t value = theBuilder.createLoad(typeId, params[index]);
  1620. processAssignment(arg, value, false, args[index]);
  1621. }
  1622. }
  1623. // Inherit the SpirvEvalInfo from the function definition
  1624. return declIdMapper.getDeclEvalInfo(callee).setResultId(retVal);
  1625. }
  1626. SpirvEvalInfo SPIRVEmitter::doCastExpr(const CastExpr *expr) {
  1627. const Expr *subExpr = expr->getSubExpr();
  1628. const QualType subExprType = subExpr->getType();
  1629. const QualType toType = expr->getType();
  1630. switch (expr->getCastKind()) {
  1631. case CastKind::CK_LValueToRValue:
  1632. return loadIfGLValue(subExpr);
  1633. case CastKind::CK_NoOp:
  1634. return doExpr(subExpr);
  1635. case CastKind::CK_IntegralCast:
  1636. case CastKind::CK_FloatingToIntegral:
  1637. case CastKind::CK_HLSLCC_IntegralCast:
  1638. case CastKind::CK_HLSLCC_FloatingToIntegral: {
  1639. // Integer literals in the AST are represented using 64bit APInt
  1640. // themselves and then implicitly casted into the expected bitwidth.
  1641. // We need special treatment of integer literals here because generating
  1642. // a 64bit constant and then explicit casting in SPIR-V requires Int64
  1643. // capability. We should avoid introducing unnecessary capabilities to
  1644. // our best.
  1645. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1646. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1647. const auto valueId =
  1648. castToInt(doExpr(subExpr), subExprType, toType, subExpr->getExprLoc());
  1649. return SpirvEvalInfo(valueId).setRValue();
  1650. }
  1651. case CastKind::CK_FloatingCast:
  1652. case CastKind::CK_IntegralToFloating:
  1653. case CastKind::CK_HLSLCC_FloatingCast:
  1654. case CastKind::CK_HLSLCC_IntegralToFloating: {
  1655. // First try to see if we can do constant folding for floating point
  1656. // numbers like what we are doing for integers in the above.
  1657. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1658. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1659. const auto valueId = castToFloat(doExpr(subExpr), subExprType, toType,
  1660. subExpr->getExprLoc());
  1661. return SpirvEvalInfo(valueId).setRValue();
  1662. }
  1663. case CastKind::CK_IntegralToBoolean:
  1664. case CastKind::CK_FloatingToBoolean:
  1665. case CastKind::CK_HLSLCC_IntegralToBoolean:
  1666. case CastKind::CK_HLSLCC_FloatingToBoolean: {
  1667. // First try to see if we can do constant folding.
  1668. if (const uint32_t valueId = tryToEvaluateAsConst(expr))
  1669. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1670. const auto valueId = castToBool(doExpr(subExpr), subExprType, toType);
  1671. return SpirvEvalInfo(valueId).setRValue();
  1672. }
  1673. case CastKind::CK_HLSLVectorSplat: {
  1674. const size_t size = hlsl::GetHLSLVecSize(expr->getType());
  1675. return createVectorSplat(subExpr, size);
  1676. }
  1677. case CastKind::CK_HLSLVectorTruncationCast: {
  1678. const uint32_t toVecTypeId = typeTranslator.translateType(toType);
  1679. const uint32_t elemTypeId =
  1680. typeTranslator.translateType(hlsl::GetHLSLVecElementType(toType));
  1681. const auto toSize = hlsl::GetHLSLVecSize(toType);
  1682. const uint32_t composite = doExpr(subExpr);
  1683. llvm::SmallVector<uint32_t, 4> elements;
  1684. for (uint32_t i = 0; i < toSize; ++i) {
  1685. elements.push_back(
  1686. theBuilder.createCompositeExtract(elemTypeId, composite, {i}));
  1687. }
  1688. auto valueId = elements.front();
  1689. if (toSize > 1)
  1690. valueId = theBuilder.createCompositeConstruct(toVecTypeId, elements);
  1691. return SpirvEvalInfo(valueId).setRValue();
  1692. }
  1693. case CastKind::CK_HLSLVectorToScalarCast: {
  1694. // The underlying should already be a vector of size 1.
  1695. assert(hlsl::GetHLSLVecSize(subExprType) == 1);
  1696. return doExpr(subExpr);
  1697. }
  1698. case CastKind::CK_HLSLVectorToMatrixCast: {
  1699. // If target type is already an 1xN matrix type, we just return the
  1700. // underlying vector.
  1701. if (TypeTranslator::is1xNMatrix(toType))
  1702. return doExpr(subExpr);
  1703. // A vector can have no more than 4 elements. The only remaining case
  1704. // is casting from size-4 vector to size-2-by-2 matrix.
  1705. const auto vec = loadIfGLValue(subExpr);
  1706. QualType elemType = {};
  1707. uint32_t rowCount = 0, colCount = 0;
  1708. const bool isMat =
  1709. TypeTranslator::isMxNMatrix(toType, &elemType, &rowCount, &colCount);
  1710. assert(isMat && rowCount == 2 && colCount == 2);
  1711. uint32_t vec2Type =
  1712. theBuilder.getVecType(typeTranslator.translateType(elemType), 2);
  1713. const auto subVec1 =
  1714. theBuilder.createVectorShuffle(vec2Type, vec, vec, {0, 1});
  1715. const auto subVec2 =
  1716. theBuilder.createVectorShuffle(vec2Type, vec, vec, {2, 3});
  1717. const auto mat = theBuilder.createCompositeConstruct(
  1718. theBuilder.getMatType(vec2Type, 2), {subVec1, subVec2});
  1719. return SpirvEvalInfo(mat).setRValue();
  1720. }
  1721. case CastKind::CK_HLSLMatrixSplat: {
  1722. // From scalar to matrix
  1723. uint32_t rowCount = 0, colCount = 0;
  1724. hlsl::GetHLSLMatRowColCount(toType, rowCount, colCount);
  1725. // Handle degenerated cases first
  1726. if (rowCount == 1 && colCount == 1)
  1727. return doExpr(subExpr);
  1728. if (colCount == 1)
  1729. return createVectorSplat(subExpr, rowCount);
  1730. const auto vecSplat = createVectorSplat(subExpr, colCount);
  1731. if (rowCount == 1)
  1732. return vecSplat;
  1733. const uint32_t matType = typeTranslator.translateType(toType);
  1734. llvm::SmallVector<uint32_t, 4> vectors(size_t(rowCount), vecSplat);
  1735. if (vecSplat.isConstant()) {
  1736. const auto valueId = theBuilder.getConstantComposite(matType, vectors);
  1737. return SpirvEvalInfo(valueId).setConstant().setRValue();
  1738. } else {
  1739. const auto valueId =
  1740. theBuilder.createCompositeConstruct(matType, vectors);
  1741. return SpirvEvalInfo(valueId).setRValue();
  1742. }
  1743. }
  1744. case CastKind::CK_HLSLMatrixTruncationCast: {
  1745. const QualType srcType = subExprType;
  1746. const uint32_t srcId = doExpr(subExpr);
  1747. const QualType elemType = hlsl::GetHLSLMatElementType(srcType);
  1748. const uint32_t dstTypeId = typeTranslator.translateType(toType);
  1749. llvm::SmallVector<uint32_t, 4> indexes;
  1750. // It is possible that the source matrix is in fact a vector.
  1751. // For example: Truncate float1x3 --> float1x2.
  1752. // The front-end disallows float1x3 --> float2x1.
  1753. {
  1754. uint32_t srcVecSize = 0, dstVecSize = 0;
  1755. if (TypeTranslator::isVectorType(srcType, nullptr, &srcVecSize) &&
  1756. TypeTranslator::isVectorType(toType, nullptr, &dstVecSize)) {
  1757. for (uint32_t i = 0; i < dstVecSize; ++i)
  1758. indexes.push_back(i);
  1759. const auto valId =
  1760. theBuilder.createVectorShuffle(dstTypeId, srcId, srcId, indexes);
  1761. return SpirvEvalInfo(valId).setRValue();
  1762. }
  1763. }
  1764. uint32_t srcRows = 0, srcCols = 0, dstRows = 0, dstCols = 0;
  1765. hlsl::GetHLSLMatRowColCount(srcType, srcRows, srcCols);
  1766. hlsl::GetHLSLMatRowColCount(toType, dstRows, dstCols);
  1767. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  1768. const uint32_t srcRowType = theBuilder.getVecType(elemTypeId, srcCols);
  1769. // Indexes to pass to OpVectorShuffle
  1770. for (uint32_t i = 0; i < dstCols; ++i)
  1771. indexes.push_back(i);
  1772. llvm::SmallVector<uint32_t, 4> extractedVecs;
  1773. for (uint32_t row = 0; row < dstRows; ++row) {
  1774. // Extract a row
  1775. uint32_t rowId =
  1776. theBuilder.createCompositeExtract(srcRowType, srcId, {row});
  1777. // Extract the necessary columns from that row.
  1778. // The front-end ensures dstCols <= srcCols.
  1779. // If dstCols equals srcCols, we can use the whole row directly.
  1780. if (dstCols == 1) {
  1781. rowId = theBuilder.createCompositeExtract(elemTypeId, rowId, {0});
  1782. } else if (dstCols < srcCols) {
  1783. rowId = theBuilder.createVectorShuffle(
  1784. theBuilder.getVecType(elemTypeId, dstCols), rowId, rowId, indexes);
  1785. }
  1786. extractedVecs.push_back(rowId);
  1787. }
  1788. uint32_t valId = extractedVecs.front();
  1789. if (extractedVecs.size() > 1) {
  1790. valId = theBuilder.createCompositeConstruct(
  1791. typeTranslator.translateType(toType), extractedVecs);
  1792. }
  1793. return SpirvEvalInfo(valId).setRValue();
  1794. }
  1795. case CastKind::CK_HLSLMatrixToScalarCast: {
  1796. // The underlying should already be a matrix of 1x1.
  1797. assert(TypeTranslator::is1x1Matrix(subExprType));
  1798. return doExpr(subExpr);
  1799. }
  1800. case CastKind::CK_HLSLMatrixToVectorCast: {
  1801. // The underlying should already be a matrix of 1xN.
  1802. assert(TypeTranslator::is1xNMatrix(subExprType) ||
  1803. TypeTranslator::isMx1Matrix(subExprType));
  1804. return doExpr(subExpr);
  1805. }
  1806. case CastKind::CK_FunctionToPointerDecay:
  1807. // Just need to return the function id
  1808. return doExpr(subExpr);
  1809. case CastKind::CK_FlatConversion: {
  1810. uint32_t subExprId = 0;
  1811. QualType evalType = subExprType;
  1812. // Optimization: we can use OpConstantNull for cases where we want to
  1813. // initialize an entire data structure to zeros.
  1814. if (evaluatesToConstZero(subExpr, astContext)) {
  1815. subExprId =
  1816. theBuilder.getConstantNull(typeTranslator.translateType(toType));
  1817. return SpirvEvalInfo(subExprId).setRValue().setConstant();
  1818. }
  1819. // Try to evaluate 'literal float' as float rather than double.
  1820. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(subExpr)) {
  1821. subExprId = tryToEvaluateAsFloat32(floatLiteral->getValue());
  1822. if (subExprId)
  1823. evalType = astContext.FloatTy;
  1824. }
  1825. // Try to evaluate 'literal int' as 32-bit int rather than 64-bit int.
  1826. else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(subExpr)) {
  1827. const bool isSigned = subExprType->isSignedIntegerType();
  1828. subExprId = tryToEvaluateAsInt32(intLiteral->getValue(), isSigned);
  1829. if (subExprId)
  1830. evalType = isSigned ? astContext.IntTy : astContext.UnsignedIntTy;
  1831. }
  1832. if (!subExprId)
  1833. subExprId = doExpr(subExpr);
  1834. const auto valId =
  1835. processFlatConversion(toType, evalType, subExprId, expr->getExprLoc());
  1836. return SpirvEvalInfo(valId).setRValue();
  1837. }
  1838. default:
  1839. emitError("implicit cast kind '%0' unimplemented", expr->getExprLoc())
  1840. << expr->getCastKindName() << expr->getSourceRange();
  1841. expr->dump();
  1842. return 0;
  1843. }
  1844. }
  1845. uint32_t SPIRVEmitter::processFlatConversion(const QualType type,
  1846. const QualType initType,
  1847. const uint32_t initId,
  1848. SourceLocation srcLoc) {
  1849. // Try to translate the canonical type first
  1850. const auto canonicalType = type.getCanonicalType();
  1851. if (canonicalType != type)
  1852. return processFlatConversion(canonicalType, initType, initId, srcLoc);
  1853. // Primitive types
  1854. {
  1855. QualType ty = {};
  1856. if (TypeTranslator::isScalarType(type, &ty)) {
  1857. if (const auto *builtinType = ty->getAs<BuiltinType>()) {
  1858. switch (builtinType->getKind()) {
  1859. case BuiltinType::Void: {
  1860. emitError("cannot create a constant of void type", srcLoc);
  1861. return 0;
  1862. }
  1863. case BuiltinType::Bool:
  1864. return castToBool(initId, initType, ty);
  1865. // Target type is an integer variant.
  1866. // TODO: Add long and ulong.
  1867. case BuiltinType::Int:
  1868. case BuiltinType::Short:
  1869. case BuiltinType::Min12Int:
  1870. case BuiltinType::UShort:
  1871. case BuiltinType::UInt:
  1872. return castToInt(initId, initType, ty, srcLoc);
  1873. // Target type is a float variant.
  1874. // TODO: Add double.
  1875. case BuiltinType::Float:
  1876. case BuiltinType::Half:
  1877. case BuiltinType::Min10Float:
  1878. return castToFloat(initId, initType, ty, srcLoc);
  1879. default:
  1880. emitError("flat conversion of type %0 unimplemented", srcLoc)
  1881. << builtinType->getTypeClassName();
  1882. return 0;
  1883. }
  1884. }
  1885. }
  1886. }
  1887. // Vector types
  1888. {
  1889. QualType elemType = {};
  1890. uint32_t elemCount = {};
  1891. if (TypeTranslator::isVectorType(type, &elemType, &elemCount)) {
  1892. const uint32_t elemId =
  1893. processFlatConversion(elemType, initType, initId, srcLoc);
  1894. llvm::SmallVector<uint32_t, 4> constituents(size_t(elemCount), elemId);
  1895. return theBuilder.createCompositeConstruct(
  1896. typeTranslator.translateType(type), constituents);
  1897. }
  1898. }
  1899. // Matrix types
  1900. {
  1901. QualType elemType = {};
  1902. uint32_t rowCount = 0, colCount = 0;
  1903. if (TypeTranslator::isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
  1904. if (!elemType->isFloatingType()) {
  1905. emitError("non-floating-point matrix type unimplemented", {});
  1906. return 0;
  1907. }
  1908. // By default HLSL matrices are row major, while SPIR-V matrices are
  1909. // column major. We are mapping what HLSL semantically mean a row into a
  1910. // column here.
  1911. const uint32_t vecType = theBuilder.getVecType(
  1912. typeTranslator.translateType(elemType), colCount);
  1913. const uint32_t elemId =
  1914. processFlatConversion(elemType, initType, initId, srcLoc);
  1915. const llvm::SmallVector<uint32_t, 4> constituents(size_t(colCount),
  1916. elemId);
  1917. const uint32_t colId =
  1918. theBuilder.createCompositeConstruct(vecType, constituents);
  1919. const llvm::SmallVector<uint32_t, 4> rows(size_t(rowCount), colId);
  1920. return theBuilder.createCompositeConstruct(
  1921. typeTranslator.translateType(type), rows);
  1922. }
  1923. }
  1924. // Struct type
  1925. if (const auto *structType = type->getAs<RecordType>()) {
  1926. const auto *decl = structType->getDecl();
  1927. llvm::SmallVector<uint32_t, 4> fields;
  1928. for (const auto *field : decl->fields()) {
  1929. // There is a special case for FlatConversion. If T is a struct with only
  1930. // one member, S, then (T)<an-instance-of-S> is allowed, which essentially
  1931. // constructs a new T instance using the instance of S as its only member.
  1932. // Check whether we are handling that case here first.
  1933. if (field->getType().getCanonicalType() == initType.getCanonicalType()) {
  1934. fields.push_back(initId);
  1935. } else {
  1936. fields.push_back(
  1937. processFlatConversion(field->getType(), initType, initId, srcLoc));
  1938. }
  1939. }
  1940. return theBuilder.createCompositeConstruct(
  1941. typeTranslator.translateType(type), fields);
  1942. }
  1943. // Array type
  1944. if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
  1945. const auto size =
  1946. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  1947. const uint32_t elemId = processFlatConversion(arrayType->getElementType(),
  1948. initType, initId, srcLoc);
  1949. llvm::SmallVector<uint32_t, 4> constituents(size_t(size), elemId);
  1950. return theBuilder.createCompositeConstruct(
  1951. typeTranslator.translateType(type), constituents);
  1952. }
  1953. emitError("flat conversion of type %0 unimplemented", {})
  1954. << type->getTypeClassName();
  1955. type->dump();
  1956. return 0;
  1957. }
  1958. SpirvEvalInfo
  1959. SPIRVEmitter::doCompoundAssignOperator(const CompoundAssignOperator *expr) {
  1960. const auto opcode = expr->getOpcode();
  1961. // Try to optimize floatMxN *= float and floatN *= float case
  1962. if (opcode == BO_MulAssign) {
  1963. if (SpirvEvalInfo result = tryToGenFloatMatrixScale(expr))
  1964. return result;
  1965. if (SpirvEvalInfo result = tryToGenFloatVectorScale(expr))
  1966. return result;
  1967. }
  1968. const auto *rhs = expr->getRHS();
  1969. const auto *lhs = expr->getLHS();
  1970. SpirvEvalInfo lhsPtr = 0;
  1971. const auto result = processBinaryOp(lhs, rhs, opcode, expr->getType(),
  1972. expr->getSourceRange(), &lhsPtr);
  1973. return processAssignment(lhs, result, true, lhsPtr);
  1974. }
  1975. SpirvEvalInfo
  1976. SPIRVEmitter::doConditionalOperator(const ConditionalOperator *expr) {
  1977. const auto type = expr->getType();
  1978. // Enhancement for special case when the ConditionalOperator return type is a
  1979. // literal type. For example:
  1980. //
  1981. // float a = cond ? 1 : 2;
  1982. // int b = cond ? 1.5 : 2.5;
  1983. //
  1984. // There will be no indications about whether '1' and '2' should be used as
  1985. // 32-bit or 64-bit integers. Similarly, there will be no indication about
  1986. // whether '1.5' and '2.5' should be used as 32-bit or 64-bit floats.
  1987. //
  1988. // We want to avoid using 64-bit int and 64-bit float as much as possible.
  1989. //
  1990. // Note that if the literal is in fact large enough that it can't be
  1991. // represented in 32 bits (e.g. integer larger than 3e+9), we should *not*
  1992. // provide a hint.
  1993. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  1994. const bool isLitInt = type->isSpecificBuiltinType(BuiltinType::LitInt);
  1995. const bool isLitFloat = type->isSpecificBuiltinType(BuiltinType::LitFloat);
  1996. // Return type of ConditionalOperator is a 'literal int' or 'literal float'
  1997. if (isLitInt || isLitFloat) {
  1998. // There is no hint about the intended usage of the literal type.
  1999. if (typeTranslator.getIntendedLiteralType(type) == type) {
  2000. // If either branch is a literal that is larger than 32-bits, do not
  2001. // provide a hint.
  2002. if (!isLiteralLargerThan32Bits(expr->getTrueExpr()) &&
  2003. !isLiteralLargerThan32Bits(expr->getFalseExpr())) {
  2004. if (isLitInt)
  2005. hint.setHint(astContext.IntTy);
  2006. else if (isLitFloat)
  2007. hint.setHint(astContext.FloatTy);
  2008. }
  2009. }
  2010. }
  2011. // According to HLSL doc, all sides of the ?: expression are always
  2012. // evaluated.
  2013. const uint32_t typeId = typeTranslator.translateType(type);
  2014. // If we are selecting between two SampleState objects, none of the three
  2015. // operands has a LValueToRValue implicit cast.
  2016. uint32_t condition = loadIfGLValue(expr->getCond());
  2017. const auto trueBranch = loadIfGLValue(expr->getTrueExpr());
  2018. const auto falseBranch = loadIfGLValue(expr->getFalseExpr());
  2019. // For cases where the return type is a scalar or a vector, we can use
  2020. // OpSelect to choose between the two. OpSelect's return type must be either
  2021. // scalar or vector.
  2022. if (TypeTranslator::isScalarType(type) ||
  2023. TypeTranslator::isVectorType(type)) {
  2024. // The SPIR-V OpSelect instruction must have a selection argument that is
  2025. // the same size as the return type. If the return type is a vector, the
  2026. // selection must be a vector of booleans (one per output component).
  2027. uint32_t count = 0;
  2028. if (TypeTranslator::isVectorType(expr->getType(), nullptr, &count) &&
  2029. !TypeTranslator::isVectorType(expr->getCond()->getType())) {
  2030. const uint32_t condVecType =
  2031. theBuilder.getVecType(theBuilder.getBoolType(), count);
  2032. const llvm::SmallVector<uint32_t, 4> components(size_t(count), condition);
  2033. condition = theBuilder.createCompositeConstruct(condVecType, components);
  2034. }
  2035. auto valueId =
  2036. theBuilder.createSelect(typeId, condition, trueBranch, falseBranch);
  2037. return SpirvEvalInfo(valueId).setRValue();
  2038. }
  2039. // If we can't use OpSelect, we need to create if-else control flow.
  2040. const uint32_t tempVar = theBuilder.addFnVar(typeId, "temp.var.ternary");
  2041. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  2042. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  2043. const uint32_t elseBB = theBuilder.createBasicBlock("if.false");
  2044. // Create the branch instruction. This will end the current basic block.
  2045. theBuilder.createConditionalBranch(condition, thenBB, elseBB, mergeBB);
  2046. theBuilder.addSuccessor(thenBB);
  2047. theBuilder.addSuccessor(elseBB);
  2048. theBuilder.setMergeTarget(mergeBB);
  2049. // Handle the then branch
  2050. theBuilder.setInsertPoint(thenBB);
  2051. theBuilder.createStore(tempVar, trueBranch);
  2052. theBuilder.createBranch(mergeBB);
  2053. theBuilder.addSuccessor(mergeBB);
  2054. // Handle the else branch
  2055. theBuilder.setInsertPoint(elseBB);
  2056. theBuilder.createStore(tempVar, falseBranch);
  2057. theBuilder.createBranch(mergeBB);
  2058. theBuilder.addSuccessor(mergeBB);
  2059. // From now on, emit instructions into the merge block.
  2060. theBuilder.setInsertPoint(mergeBB);
  2061. return SpirvEvalInfo(theBuilder.createLoad(typeId, tempVar)).setRValue();
  2062. }
  2063. uint32_t SPIRVEmitter::processByteAddressBufferStructuredBufferGetDimensions(
  2064. const CXXMemberCallExpr *expr) {
  2065. const auto *object = expr->getImplicitObjectArgument();
  2066. const auto objectId = loadIfAliasVarRef(object);
  2067. const auto type = object->getType();
  2068. const bool isByteAddressBuffer = TypeTranslator::isByteAddressBuffer(type) ||
  2069. TypeTranslator::isRWByteAddressBuffer(type);
  2070. const bool isStructuredBuffer =
  2071. TypeTranslator::isStructuredBuffer(type) ||
  2072. TypeTranslator::isAppendStructuredBuffer(type) ||
  2073. TypeTranslator::isConsumeStructuredBuffer(type);
  2074. assert(isByteAddressBuffer || isStructuredBuffer);
  2075. // (RW)ByteAddressBuffers/(RW)StructuredBuffers are represented as a structure
  2076. // with only one member that is a runtime array. We need to perform
  2077. // OpArrayLength on member 0.
  2078. const auto uintType = theBuilder.getUint32Type();
  2079. uint32_t length =
  2080. theBuilder.createBinaryOp(spv::Op::OpArrayLength, uintType, objectId, 0);
  2081. // For (RW)ByteAddressBuffers, GetDimensions() must return the array length
  2082. // in bytes, but OpArrayLength returns the number of uints in the runtime
  2083. // array. Therefore we must multiply the results by 4.
  2084. if (isByteAddressBuffer) {
  2085. length = theBuilder.createBinaryOp(spv::Op::OpIMul, uintType, length,
  2086. theBuilder.getConstantUint32(4u));
  2087. }
  2088. theBuilder.createStore(doExpr(expr->getArg(0)), length);
  2089. if (isStructuredBuffer) {
  2090. // For (RW)StructuredBuffer, the stride of the runtime array (which is the
  2091. // size of the struct) must also be written to the second argument.
  2092. uint32_t size = 0, stride = 0;
  2093. std::tie(std::ignore, size) = typeTranslator.getAlignmentAndSize(
  2094. type, LayoutRule::GLSLStd430, /*isRowMajor*/ false, &stride);
  2095. const auto sizeId = theBuilder.getConstantUint32(size);
  2096. theBuilder.createStore(doExpr(expr->getArg(1)), sizeId);
  2097. }
  2098. return 0;
  2099. }
  2100. uint32_t SPIRVEmitter::processRWByteAddressBufferAtomicMethods(
  2101. hlsl::IntrinsicOp opcode, const CXXMemberCallExpr *expr) {
  2102. // The signature of RWByteAddressBuffer atomic methods are largely:
  2103. // void Interlocked*(in UINT dest, in UINT value);
  2104. // void Interlocked*(in UINT dest, in UINT value, out UINT original_value);
  2105. const auto *object = expr->getImplicitObjectArgument();
  2106. const auto objectInfo = loadIfAliasVarRef(object);
  2107. const auto uintType = theBuilder.getUint32Type();
  2108. const uint32_t zero = theBuilder.getConstantUint32(0);
  2109. const uint32_t offset = doExpr(expr->getArg(0));
  2110. // Right shift by 2 to convert the byte offset to uint32_t offset
  2111. const uint32_t address =
  2112. theBuilder.createBinaryOp(spv::Op::OpShiftRightLogical, uintType, offset,
  2113. theBuilder.getConstantUint32(2));
  2114. const auto ptrType =
  2115. theBuilder.getPointerType(uintType, objectInfo.getStorageClass());
  2116. const uint32_t ptr =
  2117. theBuilder.createAccessChain(ptrType, objectInfo, {zero, address});
  2118. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  2119. const bool isCompareExchange =
  2120. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareExchange;
  2121. const bool isCompareStore =
  2122. opcode == hlsl::IntrinsicOp::MOP_InterlockedCompareStore;
  2123. if (isCompareExchange || isCompareStore) {
  2124. const uint32_t comparator = doExpr(expr->getArg(1));
  2125. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  2126. uintType, ptr, scope, zero, zero, doExpr(expr->getArg(2)), comparator);
  2127. if (isCompareExchange)
  2128. theBuilder.createStore(doExpr(expr->getArg(3)), originalVal);
  2129. } else {
  2130. const uint32_t value = doExpr(expr->getArg(1));
  2131. const uint32_t originalVal = theBuilder.createAtomicOp(
  2132. translateAtomicHlslOpcodeToSpirvOpcode(opcode), uintType, ptr, scope,
  2133. zero, value);
  2134. if (expr->getNumArgs() > 2)
  2135. theBuilder.createStore(doExpr(expr->getArg(2)), originalVal);
  2136. }
  2137. return 0;
  2138. }
  2139. uint32_t SPIRVEmitter::processGetSamplePosition(const CXXMemberCallExpr *expr) {
  2140. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2141. const auto sampleCount = theBuilder.createUnaryOp(
  2142. spv::Op::OpImageQuerySamples, theBuilder.getUint32Type(),
  2143. loadIfGLValue(object));
  2144. emitWarning(
  2145. "GetSamplePosition only supports standard sample settings with 1, 2, 4, "
  2146. "8, or 16 samples and will return float2(0, 0) for other cases",
  2147. expr->getCallee()->getExprLoc());
  2148. return emitGetSamplePosition(sampleCount, doExpr(expr->getArg(0)));
  2149. }
  2150. SpirvEvalInfo SPIRVEmitter::processSubpassLoad(const CXXMemberCallExpr *expr) {
  2151. const auto *object = expr->getImplicitObjectArgument()->IgnoreParens();
  2152. const uint32_t sample = expr->getNumArgs() == 1 ? doExpr(expr->getArg(0)) : 0;
  2153. const uint32_t zero = theBuilder.getConstantInt32(0);
  2154. const uint32_t location = theBuilder.getConstantComposite(
  2155. theBuilder.getVecType(theBuilder.getInt32Type(), 2), {zero, zero});
  2156. return processBufferTextureLoad(object, location, /*constOffset*/ 0,
  2157. /*varOffset*/ 0, /*lod*/ sample,
  2158. /*residencyCode*/ 0);
  2159. }
  2160. uint32_t
  2161. SPIRVEmitter::processBufferTextureGetDimensions(const CXXMemberCallExpr *expr) {
  2162. const auto *object = expr->getImplicitObjectArgument();
  2163. const auto objectId = loadIfGLValue(object);
  2164. const auto type = object->getType();
  2165. const auto *recType = type->getAs<RecordType>();
  2166. assert(recType);
  2167. const auto typeName = recType->getDecl()->getName();
  2168. const auto numArgs = expr->getNumArgs();
  2169. const Expr *mipLevel = nullptr, *numLevels = nullptr, *numSamples = nullptr;
  2170. assert(TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2171. TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type));
  2172. // For Texture1D, arguments are either:
  2173. // a) width
  2174. // b) MipLevel, width, NumLevels
  2175. // For Texture1DArray, arguments are either:
  2176. // a) width, elements
  2177. // b) MipLevel, width, elements, NumLevels
  2178. // For Texture2D, arguments are either:
  2179. // a) width, height
  2180. // b) MipLevel, width, height, NumLevels
  2181. // For Texture2DArray, arguments are either:
  2182. // a) width, height, elements
  2183. // b) MipLevel, width, height, elements, NumLevels
  2184. // For Texture3D, arguments are either:
  2185. // a) width, height, depth
  2186. // b) MipLevel, width, height, depth, NumLevels
  2187. // For Texture2DMS, arguments are: width, height, NumSamples
  2188. // For Texture2DMSArray, arguments are: width, height, elements, NumSamples
  2189. // For TextureCube, arguments are either:
  2190. // a) width, height
  2191. // b) MipLevel, width, height, NumLevels
  2192. // For TextureCubeArray, arguments are either:
  2193. // a) width, height, elements
  2194. // b) MipLevel, width, height, elements, NumLevels
  2195. // Note: SPIR-V Spec requires return type of OpImageQuerySize(Lod) to be a
  2196. // scalar/vector of integers. SPIR-V Spec also requires return type of
  2197. // OpImageQueryLevels and OpImageQuerySamples to be scalar integers.
  2198. // The HLSL methods, however, have overloaded functions which have float
  2199. // output arguments. Since the AST naturally won't have casting AST nodes for
  2200. // such cases, we'll have to perform the cast ourselves.
  2201. const auto storeToOutputArg = [this](const Expr *outputArg,
  2202. uint32_t toStoreId) {
  2203. const auto outputArgType = outputArg->getType();
  2204. // Perform cast to float if necessary.
  2205. if (isFloatOrVecMatOfFloatType(outputArgType)) {
  2206. toStoreId = theBuilder.createUnaryOp(
  2207. spv::Op::OpConvertUToF, typeTranslator.translateType(outputArgType),
  2208. toStoreId);
  2209. }
  2210. theBuilder.createStore(doExpr(outputArg), toStoreId);
  2211. };
  2212. if ((typeName == "Texture1D" && numArgs > 1) ||
  2213. (typeName == "Texture2D" && numArgs > 2) ||
  2214. (typeName == "TextureCube" && numArgs > 2) ||
  2215. (typeName == "Texture3D" && numArgs > 3) ||
  2216. (typeName == "Texture1DArray" && numArgs > 2) ||
  2217. (typeName == "TextureCubeArray" && numArgs > 3) ||
  2218. (typeName == "Texture2DArray" && numArgs > 3)) {
  2219. mipLevel = expr->getArg(0);
  2220. numLevels = expr->getArg(numArgs - 1);
  2221. }
  2222. if (TypeTranslator::isTextureMS(type)) {
  2223. numSamples = expr->getArg(numArgs - 1);
  2224. }
  2225. uint32_t querySize = numArgs;
  2226. // If numLevels arg is present, mipLevel must also be present. These are not
  2227. // queried via ImageQuerySizeLod.
  2228. if (numLevels)
  2229. querySize -= 2;
  2230. // If numLevels arg is present, mipLevel must also be present.
  2231. else if (numSamples)
  2232. querySize -= 1;
  2233. const uint32_t uintId = theBuilder.getUint32Type();
  2234. const uint32_t resultTypeId =
  2235. querySize == 1 ? uintId : theBuilder.getVecType(uintId, querySize);
  2236. // Only Texture types use ImageQuerySizeLod.
  2237. // TextureMS, RWTexture, Buffers, RWBuffers use ImageQuerySize.
  2238. uint32_t lod = 0;
  2239. if (TypeTranslator::isTexture(type) && !numSamples) {
  2240. if (mipLevel) {
  2241. // For Texture types when mipLevel argument is present.
  2242. lod = doExpr(mipLevel);
  2243. } else {
  2244. // For Texture types when mipLevel argument is omitted.
  2245. lod = theBuilder.getConstantInt32(0);
  2246. }
  2247. }
  2248. const uint32_t query =
  2249. lod ? theBuilder.createBinaryOp(spv::Op::OpImageQuerySizeLod,
  2250. resultTypeId, objectId, lod)
  2251. : theBuilder.createUnaryOp(spv::Op::OpImageQuerySize, resultTypeId,
  2252. objectId);
  2253. if (querySize == 1) {
  2254. const uint32_t argIndex = mipLevel ? 1 : 0;
  2255. storeToOutputArg(expr->getArg(argIndex), query);
  2256. } else {
  2257. for (uint32_t i = 0; i < querySize; ++i) {
  2258. const uint32_t component =
  2259. theBuilder.createCompositeExtract(uintId, query, {i});
  2260. // If the first arg is the mipmap level, we must write the results
  2261. // starting from Arg(i+1), not Arg(i).
  2262. const uint32_t argIndex = mipLevel ? i + 1 : i;
  2263. storeToOutputArg(expr->getArg(argIndex), component);
  2264. }
  2265. }
  2266. if (numLevels || numSamples) {
  2267. const Expr *numLevelsSamplesArg = numLevels ? numLevels : numSamples;
  2268. const spv::Op opcode =
  2269. numLevels ? spv::Op::OpImageQueryLevels : spv::Op::OpImageQuerySamples;
  2270. const uint32_t numLevelsSamplesQuery =
  2271. theBuilder.createUnaryOp(opcode, uintId, objectId);
  2272. storeToOutputArg(numLevelsSamplesArg, numLevelsSamplesQuery);
  2273. }
  2274. return 0;
  2275. }
  2276. uint32_t
  2277. SPIRVEmitter::processTextureLevelOfDetail(const CXXMemberCallExpr *expr) {
  2278. // Possible signatures are as follows:
  2279. // Texture1D(Array).CalculateLevelOfDetail(SamplerState S, float x);
  2280. // Texture2D(Array).CalculateLevelOfDetail(SamplerState S, float2 xy);
  2281. // TextureCube(Array).CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2282. // Texture3D.CalculateLevelOfDetail(SamplerState S, float3 xyz);
  2283. // Return type is always a single float (LOD).
  2284. assert(expr->getNumArgs() == 2u);
  2285. const auto *object = expr->getImplicitObjectArgument();
  2286. const uint32_t objectId = loadIfGLValue(object);
  2287. const uint32_t samplerState = doExpr(expr->getArg(0));
  2288. const uint32_t coordinate = doExpr(expr->getArg(1));
  2289. const uint32_t sampledImageType = theBuilder.getSampledImageType(
  2290. typeTranslator.translateType(object->getType()));
  2291. const uint32_t sampledImage = theBuilder.createBinaryOp(
  2292. spv::Op::OpSampledImage, sampledImageType, objectId, samplerState);
  2293. // The result type of OpImageQueryLod must be a float2.
  2294. const uint32_t queryResultType =
  2295. theBuilder.getVecType(theBuilder.getFloat32Type(), 2u);
  2296. const uint32_t query = theBuilder.createBinaryOp(
  2297. spv::Op::OpImageQueryLod, queryResultType, sampledImage, coordinate);
  2298. // The first component of the float2 contains the mipmap array layer.
  2299. return theBuilder.createCompositeExtract(theBuilder.getFloat32Type(), query,
  2300. {0});
  2301. }
  2302. uint32_t SPIRVEmitter::processTextureGatherRGBACmpRGBA(
  2303. const CXXMemberCallExpr *expr, const bool isCmp, const uint32_t component) {
  2304. // Parameters for .Gather{Red|Green|Blue|Alpha}() are one of the following
  2305. // two sets:
  2306. // * SamplerState s, float2 location, int2 offset
  2307. // * SamplerState s, float2 location, int2 offset0, int2 offset1,
  2308. // int offset2, int2 offset3
  2309. //
  2310. // An additional 'out uint status' parameter can appear in both of the above.
  2311. //
  2312. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() are one of the following
  2313. // two sets:
  2314. // * SamplerState s, float2 location, float compare_value, int2 offset
  2315. // * SamplerState s, float2 location, float compare_value, int2 offset1,
  2316. // int2 offset2, int2 offset3, int2 offset4
  2317. //
  2318. // An additional 'out uint status' parameter can appear in both of the above.
  2319. //
  2320. // TextureCube's signature is somewhat different from the rest.
  2321. // Parameters for .Gather{Red|Green|Blue|Alpha}() for TextureCube are:
  2322. // * SamplerState s, float2 location, out uint status
  2323. // Parameters for .GatherCmp{Red|Green|Blue|Alpha}() for TextureCube are:
  2324. // * SamplerState s, float2 location, float compare_value, out uint status
  2325. //
  2326. // Return type is always a 4-component vector.
  2327. const FunctionDecl *callee = expr->getDirectCallee();
  2328. const auto numArgs = expr->getNumArgs();
  2329. const auto *imageExpr = expr->getImplicitObjectArgument();
  2330. const QualType imageType = imageExpr->getType();
  2331. const auto imageTypeId = typeTranslator.translateType(imageType);
  2332. const auto retTypeId = typeTranslator.translateType(callee->getReturnType());
  2333. // If the last arg is an unsigned integer, it must be the status.
  2334. const bool hasStatusArg =
  2335. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2336. // Subtract 1 for status arg (if it exists), subtract 1 for compare_value (if
  2337. // it exists), and subtract 2 for SamplerState and location.
  2338. const auto numOffsetArgs = numArgs - hasStatusArg - isCmp - 2;
  2339. // No offset args for TextureCube, 1 or 4 offset args for the rest.
  2340. assert(numOffsetArgs == 0 || numOffsetArgs == 1 || numOffsetArgs == 4);
  2341. const uint32_t image = loadIfGLValue(imageExpr);
  2342. const uint32_t sampler = doExpr(expr->getArg(0));
  2343. const uint32_t coordinate = doExpr(expr->getArg(1));
  2344. const uint32_t compareVal = isCmp ? doExpr(expr->getArg(2)) : 0;
  2345. // Handle offsets (if any).
  2346. uint32_t constOffset = 0, varOffset = 0, constOffsets = 0;
  2347. if (numOffsetArgs == 1) {
  2348. // The offset arg is not optional.
  2349. handleOffsetInMethodCall(expr, 2 + isCmp, &constOffset, &varOffset);
  2350. } else if (numOffsetArgs == 4) {
  2351. const auto offset0 = tryToEvaluateAsConst(expr->getArg(2 + isCmp));
  2352. const auto offset1 = tryToEvaluateAsConst(expr->getArg(3 + isCmp));
  2353. const auto offset2 = tryToEvaluateAsConst(expr->getArg(4 + isCmp));
  2354. const auto offset3 = tryToEvaluateAsConst(expr->getArg(5 + isCmp));
  2355. // Make sure we can generate the ConstOffsets image operands in SPIR-V.
  2356. if (!offset0 || !offset1 || !offset2 || !offset3) {
  2357. emitError("all offset parameters to '%0' method call must be constants",
  2358. expr->getExprLoc())
  2359. << callee->getName() << expr->getSourceRange();
  2360. return 0;
  2361. }
  2362. const uint32_t v2i32 = theBuilder.getVecType(theBuilder.getInt32Type(), 2);
  2363. const uint32_t offsetType =
  2364. theBuilder.getArrayType(v2i32, theBuilder.getConstantUint32(4));
  2365. constOffsets = theBuilder.getConstantComposite(
  2366. offsetType, {offset0, offset1, offset2, offset3});
  2367. }
  2368. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  2369. return theBuilder.createImageGather(
  2370. retTypeId, imageTypeId, image, sampler, coordinate,
  2371. theBuilder.getConstantInt32(component), compareVal, constOffset,
  2372. varOffset, constOffsets, /*sampleNumber*/ 0, status);
  2373. }
  2374. uint32_t SPIRVEmitter::processTextureGatherCmp(const CXXMemberCallExpr *expr) {
  2375. // Signature for Texture2D/Texture2DArray:
  2376. //
  2377. // float4 GatherCmp(
  2378. // in SamplerComparisonState s,
  2379. // in float2 location,
  2380. // in float compare_value
  2381. // [,in int2 offset]
  2382. // [,out uint Status]
  2383. // );
  2384. //
  2385. // Signature for TextureCube/TextureCubeArray:
  2386. //
  2387. // float4 GatherCmp(
  2388. // in SamplerComparisonState s,
  2389. // in float2 location,
  2390. // in float compare_value,
  2391. // out uint Status
  2392. // );
  2393. //
  2394. // Other Texture types do not have the GatherCmp method.
  2395. const FunctionDecl *callee = expr->getDirectCallee();
  2396. const auto numArgs = expr->getNumArgs();
  2397. const bool hasStatusArg =
  2398. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  2399. const bool hasOffsetArg = (numArgs == 5) || (numArgs == 4 && !hasStatusArg);
  2400. const auto *imageExpr = expr->getImplicitObjectArgument();
  2401. const uint32_t image = loadIfGLValue(imageExpr);
  2402. const uint32_t sampler = doExpr(expr->getArg(0));
  2403. const uint32_t coordinate = doExpr(expr->getArg(1));
  2404. const uint32_t comparator = doExpr(expr->getArg(2));
  2405. uint32_t constOffset = 0, varOffset = 0;
  2406. if (hasOffsetArg)
  2407. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  2408. const auto retType = typeTranslator.translateType(callee->getReturnType());
  2409. const auto imageType = typeTranslator.translateType(imageExpr->getType());
  2410. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  2411. return theBuilder.createImageGather(
  2412. retType, imageType, image, sampler, coordinate, /*component*/ 0,
  2413. comparator, constOffset, varOffset, /*constOffsets*/ 0,
  2414. /*sampleNumber*/ 0, status);
  2415. }
  2416. SpirvEvalInfo SPIRVEmitter::processBufferTextureLoad(
  2417. const Expr *object, const uint32_t locationId, uint32_t constOffset,
  2418. uint32_t varOffset, uint32_t lod, uint32_t residencyCode) {
  2419. // Loading for Buffer and RWBuffer translates to an OpImageFetch.
  2420. // The result type of an OpImageFetch must be a vec4 of float or int.
  2421. const auto type = object->getType();
  2422. assert(TypeTranslator::isBuffer(type) || TypeTranslator::isRWBuffer(type) ||
  2423. TypeTranslator::isTexture(type) || TypeTranslator::isRWTexture(type) ||
  2424. TypeTranslator::isSubpassInput(type) ||
  2425. TypeTranslator::isSubpassInputMS(type));
  2426. const bool doFetch =
  2427. TypeTranslator::isBuffer(type) || TypeTranslator::isTexture(type);
  2428. const uint32_t objectId = loadIfGLValue(object);
  2429. // For Texture2DMS and Texture2DMSArray, Sample must be used rather than Lod.
  2430. uint32_t sampleNumber = 0;
  2431. if (TypeTranslator::isTextureMS(type) ||
  2432. TypeTranslator::isSubpassInputMS(type)) {
  2433. sampleNumber = lod;
  2434. lod = 0;
  2435. }
  2436. const auto sampledType = hlsl::GetHLSLResourceResultType(type);
  2437. QualType elemType = sampledType;
  2438. uint32_t elemCount = 1;
  2439. uint32_t elemTypeId = 0;
  2440. (void)TypeTranslator::isVectorType(sampledType, &elemType, &elemCount);
  2441. if (elemType->isFloatingType()) {
  2442. elemTypeId = theBuilder.getFloat32Type();
  2443. } else if (elemType->isSignedIntegerType()) {
  2444. elemTypeId = theBuilder.getInt32Type();
  2445. } else if (elemType->isUnsignedIntegerType()) {
  2446. elemTypeId = theBuilder.getUint32Type();
  2447. } else {
  2448. emitError("buffer/texture type unimplemented", object->getExprLoc());
  2449. return 0;
  2450. }
  2451. // OpImageFetch and OpImageRead can only fetch a vector of 4 elements.
  2452. const uint32_t texelTypeId = theBuilder.getVecType(elemTypeId, 4u);
  2453. const uint32_t texel = theBuilder.createImageFetchOrRead(
  2454. doFetch, texelTypeId, type, objectId, locationId, lod, constOffset,
  2455. varOffset, /*constOffsets*/ 0, sampleNumber, residencyCode);
  2456. // If the result type is a vec1, vec2, or vec3, some extra processing
  2457. // (extraction) is required.
  2458. uint32_t retVal = extractVecFromVec4(texel, elemCount, elemTypeId);
  2459. return SpirvEvalInfo(retVal).setRValue();
  2460. }
  2461. SpirvEvalInfo SPIRVEmitter::processByteAddressBufferLoadStore(
  2462. const CXXMemberCallExpr *expr, uint32_t numWords, bool doStore) {
  2463. uint32_t resultId = 0;
  2464. const auto object = expr->getImplicitObjectArgument();
  2465. const auto type = object->getType();
  2466. const auto objectInfo = loadIfAliasVarRef(object);
  2467. assert(numWords >= 1 && numWords <= 4);
  2468. if (doStore) {
  2469. assert(typeTranslator.isRWByteAddressBuffer(type));
  2470. assert(expr->getNumArgs() == 2);
  2471. } else {
  2472. assert(typeTranslator.isRWByteAddressBuffer(type) ||
  2473. typeTranslator.isByteAddressBuffer(type));
  2474. if (expr->getNumArgs() == 2) {
  2475. emitError(
  2476. "(RW)ByteAddressBuffer::Load(in address, out status) not supported",
  2477. expr->getExprLoc());
  2478. return 0;
  2479. }
  2480. }
  2481. const Expr *addressExpr = expr->getArg(0);
  2482. const uint32_t byteAddress = doExpr(addressExpr);
  2483. const uint32_t addressTypeId =
  2484. typeTranslator.translateType(addressExpr->getType());
  2485. // Do a OpShiftRightLogical by 2 (divide by 4 to get aligned memory
  2486. // access). The AST always casts the address to unsinged integer, so shift
  2487. // by unsinged integer 2.
  2488. const uint32_t constUint2 = theBuilder.getConstantUint32(2);
  2489. const uint32_t address = theBuilder.createBinaryOp(
  2490. spv::Op::OpShiftRightLogical, addressTypeId, byteAddress, constUint2);
  2491. // Perform access chain into the RWByteAddressBuffer.
  2492. // First index must be zero (member 0 of the struct is a
  2493. // runtimeArray). The second index passed to OpAccessChain should be
  2494. // the address.
  2495. const uint32_t uintTypeId = theBuilder.getUint32Type();
  2496. const uint32_t ptrType =
  2497. theBuilder.getPointerType(uintTypeId, objectInfo.getStorageClass());
  2498. const uint32_t constUint0 = theBuilder.getConstantUint32(0);
  2499. if (doStore) {
  2500. const uint32_t valuesId = doExpr(expr->getArg(1));
  2501. uint32_t curStoreAddress = address;
  2502. for (uint32_t wordCounter = 0; wordCounter < numWords; ++wordCounter) {
  2503. // Extract a 32-bit word from the input.
  2504. const uint32_t curValue = numWords == 1
  2505. ? valuesId
  2506. : theBuilder.createCompositeExtract(
  2507. uintTypeId, valuesId, {wordCounter});
  2508. // Update the output address if necessary.
  2509. if (wordCounter > 0) {
  2510. const uint32_t offset = theBuilder.getConstantUint32(wordCounter);
  2511. curStoreAddress = theBuilder.createBinaryOp(
  2512. spv::Op::OpIAdd, addressTypeId, address, offset);
  2513. }
  2514. // Store the word to the right address at the output.
  2515. const uint32_t storePtr = theBuilder.createAccessChain(
  2516. ptrType, objectInfo, {constUint0, curStoreAddress});
  2517. theBuilder.createStore(storePtr, curValue);
  2518. }
  2519. } else {
  2520. uint32_t loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2521. {constUint0, address});
  2522. resultId = theBuilder.createLoad(uintTypeId, loadPtr);
  2523. if (numWords > 1) {
  2524. // Load word 2, 3, and 4 where necessary. Use OpCompositeConstruct to
  2525. // return a vector result.
  2526. llvm::SmallVector<uint32_t, 4> values;
  2527. values.push_back(resultId);
  2528. for (uint32_t wordCounter = 2; wordCounter <= numWords; ++wordCounter) {
  2529. const uint32_t offset = theBuilder.getConstantUint32(wordCounter - 1);
  2530. const uint32_t newAddress = theBuilder.createBinaryOp(
  2531. spv::Op::OpIAdd, addressTypeId, address, offset);
  2532. loadPtr = theBuilder.createAccessChain(ptrType, objectInfo,
  2533. {constUint0, newAddress});
  2534. values.push_back(theBuilder.createLoad(uintTypeId, loadPtr));
  2535. }
  2536. const uint32_t resultType =
  2537. theBuilder.getVecType(addressTypeId, numWords);
  2538. resultId = theBuilder.createCompositeConstruct(resultType, values);
  2539. }
  2540. }
  2541. return SpirvEvalInfo(resultId).setRValue();
  2542. }
  2543. SpirvEvalInfo
  2544. SPIRVEmitter::processStructuredBufferLoad(const CXXMemberCallExpr *expr) {
  2545. if (expr->getNumArgs() == 2) {
  2546. emitError(
  2547. "(RW)StructuredBuffer::Load(in location, out status) not supported",
  2548. expr->getExprLoc());
  2549. return 0;
  2550. }
  2551. const auto *buffer = expr->getImplicitObjectArgument();
  2552. auto info = loadIfAliasVarRef(buffer);
  2553. const QualType structType =
  2554. hlsl::GetHLSLResourceResultType(buffer->getType());
  2555. const uint32_t zero = theBuilder.getConstantInt32(0);
  2556. const uint32_t index = doExpr(expr->getArg(0));
  2557. return turnIntoElementPtr(info, structType, {zero, index});
  2558. }
  2559. uint32_t SPIRVEmitter::incDecRWACSBufferCounter(const CXXMemberCallExpr *expr,
  2560. bool isInc, bool loadObject) {
  2561. const uint32_t i32Type = theBuilder.getInt32Type();
  2562. const uint32_t one = theBuilder.getConstantUint32(1); // As scope: Device
  2563. const uint32_t zero = theBuilder.getConstantUint32(0); // As memory sema: None
  2564. const uint32_t sOne = theBuilder.getConstantInt32(1);
  2565. const auto *object =
  2566. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2567. if (loadObject) {
  2568. // We don't need the object's <result-id> here since counter variable is a
  2569. // separate variable. But we still need the side effects of evaluating the
  2570. // object, e.g., if the source code is foo(...).IncrementCounter(), we still
  2571. // want to emit the code for foo(...).
  2572. (void)doExpr(object);
  2573. }
  2574. const auto *counterPair = getFinalACSBufferCounter(object);
  2575. if (!counterPair) {
  2576. emitFatalError("cannot find the associated counter variable",
  2577. object->getExprLoc());
  2578. return 0;
  2579. }
  2580. const uint32_t counterPtrType = theBuilder.getPointerType(
  2581. theBuilder.getInt32Type(), spv::StorageClass::Uniform);
  2582. const uint32_t counterPtr = theBuilder.createAccessChain(
  2583. counterPtrType, counterPair->get(theBuilder, typeTranslator), {zero});
  2584. uint32_t index = 0;
  2585. if (isInc) {
  2586. index = theBuilder.createAtomicOp(spv::Op::OpAtomicIAdd, i32Type,
  2587. counterPtr, one, zero, sOne);
  2588. } else {
  2589. // Note that OpAtomicISub returns the value before the subtraction;
  2590. // so we need to do substraction again with OpAtomicISub's return value.
  2591. const auto prev = theBuilder.createAtomicOp(spv::Op::OpAtomicISub, i32Type,
  2592. counterPtr, one, zero, sOne);
  2593. index = theBuilder.createBinaryOp(spv::Op::OpISub, i32Type, prev, sOne);
  2594. }
  2595. return index;
  2596. }
  2597. bool SPIRVEmitter::tryToAssignCounterVar(const DeclaratorDecl *dstDecl,
  2598. const Expr *srcExpr) {
  2599. // We are handling associated counters here. Casts should not alter which
  2600. // associated counter to manipulate.
  2601. srcExpr = srcExpr->IgnoreParenCasts();
  2602. // For parameters of forward-declared functions. We must make sure the
  2603. // associated counter variable is created. But for forward-declared functions,
  2604. // the translation of the real definition may not be started yet.
  2605. if (const auto *param = dyn_cast<ParmVarDecl>(dstDecl))
  2606. declIdMapper.createFnParamCounterVar(param);
  2607. // For implicit objects of methods. Similar to the above.
  2608. else if (const auto *thisObject = dyn_cast<ImplicitParamDecl>(dstDecl))
  2609. declIdMapper.createFnParamCounterVar(thisObject);
  2610. // Handle AssocCounter#1 (see CounterVarFields comment)
  2611. if (const auto *dstPair = declIdMapper.getCounterIdAliasPair(dstDecl)) {
  2612. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2613. if (!srcPair) {
  2614. emitFatalError("cannot find the associated counter variable",
  2615. srcExpr->getExprLoc());
  2616. return false;
  2617. }
  2618. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2619. return true;
  2620. }
  2621. // Handle AssocCounter#3
  2622. llvm::SmallVector<uint32_t, 4> srcIndices;
  2623. const auto *dstFields = declIdMapper.getCounterVarFields(dstDecl);
  2624. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2625. if (dstFields && srcFields) {
  2626. if (!dstFields->assign(*srcFields, theBuilder, typeTranslator)) {
  2627. emitFatalError("cannot handle associated counter variable assignment",
  2628. srcExpr->getExprLoc());
  2629. return false;
  2630. }
  2631. return true;
  2632. }
  2633. // AssocCounter#2 and AssocCounter#4 for the lhs cannot happen since the lhs
  2634. // is a stand-alone decl in this method.
  2635. return false;
  2636. }
  2637. bool SPIRVEmitter::tryToAssignCounterVar(const Expr *dstExpr,
  2638. const Expr *srcExpr) {
  2639. dstExpr = dstExpr->IgnoreParenCasts();
  2640. srcExpr = srcExpr->IgnoreParenCasts();
  2641. const auto *dstPair = getFinalACSBufferCounter(dstExpr);
  2642. const auto *srcPair = getFinalACSBufferCounter(srcExpr);
  2643. if ((dstPair == nullptr) != (srcPair == nullptr)) {
  2644. emitFatalError("cannot handle associated counter variable assignment",
  2645. srcExpr->getExprLoc());
  2646. return false;
  2647. }
  2648. // Handle AssocCounter#1 & AssocCounter#2
  2649. if (dstPair && srcPair) {
  2650. dstPair->assign(*srcPair, theBuilder, typeTranslator);
  2651. return true;
  2652. }
  2653. // Handle AssocCounter#3 & AssocCounter#4
  2654. llvm::SmallVector<uint32_t, 4> dstIndices;
  2655. llvm::SmallVector<uint32_t, 4> srcIndices;
  2656. const auto *srcFields = getIntermediateACSBufferCounter(srcExpr, &srcIndices);
  2657. const auto *dstFields = getIntermediateACSBufferCounter(dstExpr, &dstIndices);
  2658. if (dstFields && srcFields) {
  2659. return dstFields->assign(*srcFields, dstIndices, srcIndices, theBuilder,
  2660. typeTranslator);
  2661. }
  2662. return false;
  2663. }
  2664. const CounterIdAliasPair *
  2665. SPIRVEmitter::getFinalACSBufferCounter(const Expr *expr) {
  2666. // AssocCounter#1: referencing some stand-alone variable
  2667. if (const auto *decl = getReferencedDef(expr))
  2668. return declIdMapper.getCounterIdAliasPair(decl);
  2669. // AssocCounter#2: referencing some non-struct field
  2670. llvm::SmallVector<uint32_t, 4> indices;
  2671. const auto *base =
  2672. collectArrayStructIndices(expr, &indices, /*rawIndex=*/true);
  2673. const auto *decl =
  2674. (base && isa<CXXThisExpr>(base))
  2675. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  2676. : getReferencedDef(base);
  2677. return declIdMapper.getCounterIdAliasPair(decl, &indices);
  2678. }
  2679. const CounterVarFields *SPIRVEmitter::getIntermediateACSBufferCounter(
  2680. const Expr *expr, llvm::SmallVector<uint32_t, 4> *indices) {
  2681. const auto *base =
  2682. collectArrayStructIndices(expr, indices, /*rawIndex=*/true);
  2683. const auto *decl =
  2684. (base && isa<CXXThisExpr>(base))
  2685. // Use the decl we created to represent the implicit object
  2686. ? getOrCreateDeclForMethodObject(cast<CXXMethodDecl>(curFunction))
  2687. // Find the referenced decl from the original source code
  2688. : getReferencedDef(base);
  2689. return declIdMapper.getCounterVarFields(decl);
  2690. }
  2691. const ImplicitParamDecl *
  2692. SPIRVEmitter::getOrCreateDeclForMethodObject(const CXXMethodDecl *method) {
  2693. const auto found = thisDecls.find(method);
  2694. if (found != thisDecls.end())
  2695. return found->second;
  2696. const std::string name = method->getName().str() + ".this";
  2697. // Create a new identifier to convey the name
  2698. auto &identifier = astContext.Idents.get(name);
  2699. return thisDecls[method] = ImplicitParamDecl::Create(
  2700. astContext, /*DC=*/nullptr, SourceLocation(), &identifier,
  2701. method->getThisType(astContext)->getPointeeType());
  2702. }
  2703. SpirvEvalInfo
  2704. SPIRVEmitter::processACSBufferAppendConsume(const CXXMemberCallExpr *expr) {
  2705. const bool isAppend = expr->getNumArgs() == 1;
  2706. const uint32_t zero = theBuilder.getConstantUint32(0);
  2707. const auto *object =
  2708. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2709. auto bufferInfo = loadIfAliasVarRef(object);
  2710. uint32_t index = incDecRWACSBufferCounter(
  2711. expr, isAppend,
  2712. // We have already translated the object in the above. Avoid duplication.
  2713. /*loadObject=*/false);
  2714. const auto bufferElemTy = hlsl::GetHLSLResourceResultType(object->getType());
  2715. (void)turnIntoElementPtr(bufferInfo, bufferElemTy, {zero, index});
  2716. if (isAppend) {
  2717. // Write out the value
  2718. storeValue(bufferInfo, doExpr(expr->getArg(0)), bufferElemTy);
  2719. return 0;
  2720. } else {
  2721. // Note that we are returning a pointer (lvalue) here inorder to further
  2722. // acess the fields in this element, e.g., buffer.Consume().a.b. So we
  2723. // cannot forcefully set all normal function calls as returning rvalue.
  2724. return bufferInfo;
  2725. }
  2726. }
  2727. uint32_t
  2728. SPIRVEmitter::processStreamOutputAppend(const CXXMemberCallExpr *expr) {
  2729. // TODO: handle multiple stream-output objects
  2730. const auto *object =
  2731. expr->getImplicitObjectArgument()->IgnoreParenNoopCasts(astContext);
  2732. const auto *stream = cast<DeclRefExpr>(object)->getDecl();
  2733. const uint32_t value = doExpr(expr->getArg(0));
  2734. declIdMapper.writeBackOutputStream(stream, value);
  2735. theBuilder.createEmitVertex();
  2736. return 0;
  2737. }
  2738. uint32_t
  2739. SPIRVEmitter::processStreamOutputRestart(const CXXMemberCallExpr *expr) {
  2740. // TODO: handle multiple stream-output objects
  2741. theBuilder.createEndPrimitive();
  2742. return 0;
  2743. }
  2744. uint32_t SPIRVEmitter::emitGetSamplePosition(const uint32_t sampleCount,
  2745. const uint32_t sampleIndex) {
  2746. struct Float2 {
  2747. float x;
  2748. float y;
  2749. };
  2750. static const Float2 pos2[] = {
  2751. {4.0 / 16.0, 4.0 / 16.0},
  2752. {-4.0 / 16.0, -4.0 / 16.0},
  2753. };
  2754. static const Float2 pos4[] = {
  2755. {-2.0 / 16.0, -6.0 / 16.0},
  2756. {6.0 / 16.0, -2.0 / 16.0},
  2757. {-6.0 / 16.0, 2.0 / 16.0},
  2758. {2.0 / 16.0, 6.0 / 16.0},
  2759. };
  2760. static const Float2 pos8[] = {
  2761. {1.0 / 16.0, -3.0 / 16.0}, {-1.0 / 16.0, 3.0 / 16.0},
  2762. {5.0 / 16.0, 1.0 / 16.0}, {-3.0 / 16.0, -5.0 / 16.0},
  2763. {-5.0 / 16.0, 5.0 / 16.0}, {-7.0 / 16.0, -1.0 / 16.0},
  2764. {3.0 / 16.0, 7.0 / 16.0}, {7.0 / 16.0, -7.0 / 16.0},
  2765. };
  2766. static const Float2 pos16[] = {
  2767. {1.0 / 16.0, 1.0 / 16.0}, {-1.0 / 16.0, -3.0 / 16.0},
  2768. {-3.0 / 16.0, 2.0 / 16.0}, {4.0 / 16.0, -1.0 / 16.0},
  2769. {-5.0 / 16.0, -2.0 / 16.0}, {2.0 / 16.0, 5.0 / 16.0},
  2770. {5.0 / 16.0, 3.0 / 16.0}, {3.0 / 16.0, -5.0 / 16.0},
  2771. {-2.0 / 16.0, 6.0 / 16.0}, {0.0 / 16.0, -7.0 / 16.0},
  2772. {-4.0 / 16.0, -6.0 / 16.0}, {-6.0 / 16.0, 4.0 / 16.0},
  2773. {-8.0 / 16.0, 0.0 / 16.0}, {7.0 / 16.0, -4.0 / 16.0},
  2774. {6.0 / 16.0, 7.0 / 16.0}, {-7.0 / 16.0, -8.0 / 16.0},
  2775. };
  2776. // We are emitting the SPIR-V for the following HLSL source code:
  2777. //
  2778. // float2 position;
  2779. //
  2780. // if (count == 2) {
  2781. // position = pos2[index];
  2782. // }
  2783. // else if (count == 4) {
  2784. // position = pos4[index];
  2785. // }
  2786. // else if (count == 8) {
  2787. // position = pos8[index];
  2788. // }
  2789. // else if (count == 16) {
  2790. // position = pos16[index];
  2791. // }
  2792. // else {
  2793. // position = float2(0.0f, 0.0f);
  2794. // }
  2795. const uint32_t boolType = theBuilder.getBoolType();
  2796. const auto v2f32Type = theBuilder.getVecType(theBuilder.getFloat32Type(), 2);
  2797. const uint32_t ptrType =
  2798. theBuilder.getPointerType(v2f32Type, spv::StorageClass::Function);
  2799. // Creates a SPIR-V function scope variable of type float2[len].
  2800. const auto createArray = [this, v2f32Type](const Float2 *ptr, uint32_t len) {
  2801. llvm::SmallVector<uint32_t, 16> components;
  2802. for (uint32_t i = 0; i < len; ++i) {
  2803. const auto x = theBuilder.getConstantFloat32(ptr[i].x);
  2804. const auto y = theBuilder.getConstantFloat32(ptr[i].y);
  2805. components.push_back(theBuilder.getConstantComposite(v2f32Type, {x, y}));
  2806. }
  2807. const auto arrType =
  2808. theBuilder.getArrayType(v2f32Type, theBuilder.getConstantUint32(len));
  2809. const auto val = theBuilder.getConstantComposite(arrType, components);
  2810. const std::string varName =
  2811. "var.GetSamplePosition.data." + std::to_string(len);
  2812. const auto var = theBuilder.addFnVar(arrType, varName);
  2813. theBuilder.createStore(var, val);
  2814. return var;
  2815. };
  2816. const uint32_t pos2Arr = createArray(pos2, 2);
  2817. const uint32_t pos4Arr = createArray(pos4, 4);
  2818. const uint32_t pos8Arr = createArray(pos8, 8);
  2819. const uint32_t pos16Arr = createArray(pos16, 16);
  2820. const uint32_t resultVar =
  2821. theBuilder.addFnVar(v2f32Type, "var.GetSamplePosition.result");
  2822. const uint32_t then2BB =
  2823. theBuilder.createBasicBlock("if.GetSamplePosition.then2");
  2824. const uint32_t then4BB =
  2825. theBuilder.createBasicBlock("if.GetSamplePosition.then4");
  2826. const uint32_t then8BB =
  2827. theBuilder.createBasicBlock("if.GetSamplePosition.then8");
  2828. const uint32_t then16BB =
  2829. theBuilder.createBasicBlock("if.GetSamplePosition.then16");
  2830. const uint32_t else2BB =
  2831. theBuilder.createBasicBlock("if.GetSamplePosition.else2");
  2832. const uint32_t else4BB =
  2833. theBuilder.createBasicBlock("if.GetSamplePosition.else4");
  2834. const uint32_t else8BB =
  2835. theBuilder.createBasicBlock("if.GetSamplePosition.else8");
  2836. const uint32_t else16BB =
  2837. theBuilder.createBasicBlock("if.GetSamplePosition.else16");
  2838. const uint32_t merge2BB =
  2839. theBuilder.createBasicBlock("if.GetSamplePosition.merge2");
  2840. const uint32_t merge4BB =
  2841. theBuilder.createBasicBlock("if.GetSamplePosition.merge4");
  2842. const uint32_t merge8BB =
  2843. theBuilder.createBasicBlock("if.GetSamplePosition.merge8");
  2844. const uint32_t merge16BB =
  2845. theBuilder.createBasicBlock("if.GetSamplePosition.merge16");
  2846. // if (count == 2) {
  2847. const auto check2 =
  2848. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  2849. theBuilder.getConstantUint32(2));
  2850. theBuilder.createConditionalBranch(check2, then2BB, else2BB, merge2BB);
  2851. theBuilder.addSuccessor(then2BB);
  2852. theBuilder.addSuccessor(else2BB);
  2853. theBuilder.setMergeTarget(merge2BB);
  2854. // position = pos2[index];
  2855. // }
  2856. theBuilder.setInsertPoint(then2BB);
  2857. auto ac = theBuilder.createAccessChain(ptrType, pos2Arr, {sampleIndex});
  2858. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  2859. theBuilder.createBranch(merge2BB);
  2860. theBuilder.addSuccessor(merge2BB);
  2861. // else if (count == 4) {
  2862. theBuilder.setInsertPoint(else2BB);
  2863. const auto check4 =
  2864. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  2865. theBuilder.getConstantUint32(4));
  2866. theBuilder.createConditionalBranch(check4, then4BB, else4BB, merge4BB);
  2867. theBuilder.addSuccessor(then4BB);
  2868. theBuilder.addSuccessor(else4BB);
  2869. theBuilder.setMergeTarget(merge4BB);
  2870. // position = pos4[index];
  2871. // }
  2872. theBuilder.setInsertPoint(then4BB);
  2873. ac = theBuilder.createAccessChain(ptrType, pos4Arr, {sampleIndex});
  2874. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  2875. theBuilder.createBranch(merge4BB);
  2876. theBuilder.addSuccessor(merge4BB);
  2877. // else if (count == 8) {
  2878. theBuilder.setInsertPoint(else4BB);
  2879. const auto check8 =
  2880. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  2881. theBuilder.getConstantUint32(8));
  2882. theBuilder.createConditionalBranch(check8, then8BB, else8BB, merge8BB);
  2883. theBuilder.addSuccessor(then8BB);
  2884. theBuilder.addSuccessor(else8BB);
  2885. theBuilder.setMergeTarget(merge8BB);
  2886. // position = pos8[index];
  2887. // }
  2888. theBuilder.setInsertPoint(then8BB);
  2889. ac = theBuilder.createAccessChain(ptrType, pos8Arr, {sampleIndex});
  2890. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  2891. theBuilder.createBranch(merge8BB);
  2892. theBuilder.addSuccessor(merge8BB);
  2893. // else if (count == 16) {
  2894. theBuilder.setInsertPoint(else8BB);
  2895. const auto check16 =
  2896. theBuilder.createBinaryOp(spv::Op::OpIEqual, boolType, sampleCount,
  2897. theBuilder.getConstantUint32(16));
  2898. theBuilder.createConditionalBranch(check16, then16BB, else16BB, merge16BB);
  2899. theBuilder.addSuccessor(then16BB);
  2900. theBuilder.addSuccessor(else16BB);
  2901. theBuilder.setMergeTarget(merge16BB);
  2902. // position = pos16[index];
  2903. // }
  2904. theBuilder.setInsertPoint(then16BB);
  2905. ac = theBuilder.createAccessChain(ptrType, pos16Arr, {sampleIndex});
  2906. theBuilder.createStore(resultVar, theBuilder.createLoad(v2f32Type, ac));
  2907. theBuilder.createBranch(merge16BB);
  2908. theBuilder.addSuccessor(merge16BB);
  2909. // else {
  2910. // position = float2(0.0f, 0.0f);
  2911. // }
  2912. theBuilder.setInsertPoint(else16BB);
  2913. const auto zero = theBuilder.getConstantFloat32(0);
  2914. const auto v2f32Zero =
  2915. theBuilder.getConstantComposite(v2f32Type, {zero, zero});
  2916. theBuilder.createStore(resultVar, v2f32Zero);
  2917. theBuilder.createBranch(merge16BB);
  2918. theBuilder.addSuccessor(merge16BB);
  2919. theBuilder.setInsertPoint(merge16BB);
  2920. theBuilder.createBranch(merge8BB);
  2921. theBuilder.addSuccessor(merge8BB);
  2922. theBuilder.setInsertPoint(merge8BB);
  2923. theBuilder.createBranch(merge4BB);
  2924. theBuilder.addSuccessor(merge4BB);
  2925. theBuilder.setInsertPoint(merge4BB);
  2926. theBuilder.createBranch(merge2BB);
  2927. theBuilder.addSuccessor(merge2BB);
  2928. theBuilder.setInsertPoint(merge2BB);
  2929. return theBuilder.createLoad(v2f32Type, resultVar);
  2930. }
  2931. SpirvEvalInfo SPIRVEmitter::doCXXMemberCallExpr(const CXXMemberCallExpr *expr) {
  2932. const FunctionDecl *callee = expr->getDirectCallee();
  2933. llvm::StringRef group;
  2934. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  2935. if (hlsl::GetIntrinsicOp(callee, opcode, group)) {
  2936. return processIntrinsicMemberCall(expr,
  2937. static_cast<hlsl::IntrinsicOp>(opcode));
  2938. }
  2939. return processCall(expr);
  2940. }
  2941. void SPIRVEmitter::handleOffsetInMethodCall(const CXXMemberCallExpr *expr,
  2942. uint32_t index,
  2943. uint32_t *constOffset,
  2944. uint32_t *varOffset) {
  2945. // Ensure the given arg index is not out-of-range.
  2946. assert(index < expr->getNumArgs());
  2947. *constOffset = *varOffset = 0; // Initialize both first
  2948. if (*constOffset = tryToEvaluateAsConst(expr->getArg(index)))
  2949. return; // Constant offset
  2950. else
  2951. *varOffset = doExpr(expr->getArg(index));
  2952. };
  2953. SpirvEvalInfo
  2954. SPIRVEmitter::processIntrinsicMemberCall(const CXXMemberCallExpr *expr,
  2955. hlsl::IntrinsicOp opcode) {
  2956. using namespace hlsl;
  2957. uint32_t retVal = 0;
  2958. switch (opcode) {
  2959. case IntrinsicOp::MOP_Sample:
  2960. retVal = processTextureSampleGather(expr, /*isSample=*/true);
  2961. break;
  2962. case IntrinsicOp::MOP_Gather:
  2963. retVal = processTextureSampleGather(expr, /*isSample=*/false);
  2964. break;
  2965. case IntrinsicOp::MOP_SampleBias:
  2966. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/true);
  2967. break;
  2968. case IntrinsicOp::MOP_SampleLevel:
  2969. retVal = processTextureSampleBiasLevel(expr, /*isBias=*/false);
  2970. break;
  2971. case IntrinsicOp::MOP_SampleGrad:
  2972. retVal = processTextureSampleGrad(expr);
  2973. break;
  2974. case IntrinsicOp::MOP_SampleCmp:
  2975. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/true);
  2976. break;
  2977. case IntrinsicOp::MOP_SampleCmpLevelZero:
  2978. retVal = processTextureSampleCmpCmpLevelZero(expr, /*isCmp=*/false);
  2979. break;
  2980. case IntrinsicOp::MOP_GatherRed:
  2981. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 0);
  2982. break;
  2983. case IntrinsicOp::MOP_GatherGreen:
  2984. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 1);
  2985. break;
  2986. case IntrinsicOp::MOP_GatherBlue:
  2987. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 2);
  2988. break;
  2989. case IntrinsicOp::MOP_GatherAlpha:
  2990. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/false, 3);
  2991. break;
  2992. case IntrinsicOp::MOP_GatherCmp:
  2993. retVal = processTextureGatherCmp(expr);
  2994. break;
  2995. case IntrinsicOp::MOP_GatherCmpRed:
  2996. retVal = processTextureGatherRGBACmpRGBA(expr, /*isCmp=*/true, 0);
  2997. break;
  2998. case IntrinsicOp::MOP_Load:
  2999. return processBufferTextureLoad(expr);
  3000. case IntrinsicOp::MOP_Load2:
  3001. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ false);
  3002. case IntrinsicOp::MOP_Load3:
  3003. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ false);
  3004. case IntrinsicOp::MOP_Load4:
  3005. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ false);
  3006. case IntrinsicOp::MOP_Store:
  3007. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ true);
  3008. case IntrinsicOp::MOP_Store2:
  3009. return processByteAddressBufferLoadStore(expr, 2, /*doStore*/ true);
  3010. case IntrinsicOp::MOP_Store3:
  3011. return processByteAddressBufferLoadStore(expr, 3, /*doStore*/ true);
  3012. case IntrinsicOp::MOP_Store4:
  3013. return processByteAddressBufferLoadStore(expr, 4, /*doStore*/ true);
  3014. case IntrinsicOp::MOP_GetDimensions:
  3015. retVal = processGetDimensions(expr);
  3016. break;
  3017. case IntrinsicOp::MOP_CalculateLevelOfDetail:
  3018. retVal = processTextureLevelOfDetail(expr);
  3019. break;
  3020. case IntrinsicOp::MOP_IncrementCounter:
  3021. retVal = theBuilder.createUnaryOp(
  3022. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3023. incDecRWACSBufferCounter(expr, /*isInc*/ true));
  3024. break;
  3025. case IntrinsicOp::MOP_DecrementCounter:
  3026. retVal = theBuilder.createUnaryOp(
  3027. spv::Op::OpBitcast, theBuilder.getUint32Type(),
  3028. incDecRWACSBufferCounter(expr, /*isInc*/ false));
  3029. break;
  3030. case IntrinsicOp::MOP_Append:
  3031. if (hlsl::IsHLSLStreamOutputType(
  3032. expr->getImplicitObjectArgument()->getType()))
  3033. return processStreamOutputAppend(expr);
  3034. else
  3035. return processACSBufferAppendConsume(expr);
  3036. case IntrinsicOp::MOP_Consume:
  3037. return processACSBufferAppendConsume(expr);
  3038. case IntrinsicOp::MOP_RestartStrip:
  3039. retVal = processStreamOutputRestart(expr);
  3040. break;
  3041. case IntrinsicOp::MOP_InterlockedAdd:
  3042. case IntrinsicOp::MOP_InterlockedAnd:
  3043. case IntrinsicOp::MOP_InterlockedOr:
  3044. case IntrinsicOp::MOP_InterlockedXor:
  3045. case IntrinsicOp::MOP_InterlockedUMax:
  3046. case IntrinsicOp::MOP_InterlockedUMin:
  3047. case IntrinsicOp::MOP_InterlockedMax:
  3048. case IntrinsicOp::MOP_InterlockedMin:
  3049. case IntrinsicOp::MOP_InterlockedExchange:
  3050. case IntrinsicOp::MOP_InterlockedCompareExchange:
  3051. case IntrinsicOp::MOP_InterlockedCompareStore:
  3052. retVal = processRWByteAddressBufferAtomicMethods(opcode, expr);
  3053. break;
  3054. case IntrinsicOp::MOP_GetSamplePosition:
  3055. retVal = processGetSamplePosition(expr);
  3056. break;
  3057. case IntrinsicOp::MOP_SubpassLoad:
  3058. retVal = processSubpassLoad(expr);
  3059. break;
  3060. case IntrinsicOp::MOP_GatherCmpGreen:
  3061. case IntrinsicOp::MOP_GatherCmpBlue:
  3062. case IntrinsicOp::MOP_GatherCmpAlpha:
  3063. case IntrinsicOp::MOP_CalculateLevelOfDetailUnclamped:
  3064. emitError("no equivalent for %0 intrinsic method in Vulkan",
  3065. expr->getCallee()->getExprLoc())
  3066. << expr->getMethodDecl()->getName();
  3067. return 0;
  3068. default:
  3069. emitError("intrinsic '%0' method unimplemented",
  3070. expr->getCallee()->getExprLoc())
  3071. << expr->getDirectCallee()->getName();
  3072. return 0;
  3073. }
  3074. return SpirvEvalInfo(retVal).setRValue();
  3075. }
  3076. uint32_t SPIRVEmitter::createImageSample(
  3077. QualType retType, uint32_t imageType, uint32_t image, uint32_t sampler,
  3078. uint32_t coordinate, uint32_t compareVal, uint32_t bias, uint32_t lod,
  3079. std::pair<uint32_t, uint32_t> grad, uint32_t constOffset,
  3080. uint32_t varOffset, uint32_t constOffsets, uint32_t sample, uint32_t minLod,
  3081. uint32_t residencyCodeId) {
  3082. const auto retTypeId = typeTranslator.translateType(retType);
  3083. // SampleDref* instructions in SPIR-V always return a scalar.
  3084. // They also have the correct type in HLSL.
  3085. if (compareVal) {
  3086. return theBuilder.createImageSample(retTypeId, imageType, image, sampler,
  3087. coordinate, compareVal, bias, lod, grad,
  3088. constOffset, varOffset, constOffsets,
  3089. sample, minLod, residencyCodeId);
  3090. }
  3091. // Non-Dref Sample instructions in SPIR-V must always return a vec4.
  3092. auto texelTypeId = retTypeId;
  3093. QualType elemType = {};
  3094. uint32_t elemTypeId = 0;
  3095. uint32_t retVecSize = 0;
  3096. if (TypeTranslator::isVectorType(retType, &elemType, &retVecSize) &&
  3097. retVecSize != 4) {
  3098. elemTypeId = typeTranslator.translateType(elemType);
  3099. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3100. } else if (TypeTranslator::isScalarType(retType)) {
  3101. retVecSize = 1;
  3102. elemTypeId = typeTranslator.translateType(retType);
  3103. texelTypeId = theBuilder.getVecType(elemTypeId, 4);
  3104. }
  3105. uint32_t retVal = theBuilder.createImageSample(
  3106. texelTypeId, imageType, image, sampler, coordinate, compareVal, bias, lod,
  3107. grad, constOffset, varOffset, constOffsets, sample, minLod,
  3108. residencyCodeId);
  3109. // Extract smaller vector from the vec4 result if necessary.
  3110. if (texelTypeId != retTypeId) {
  3111. retVal = extractVecFromVec4(retVal, retVecSize, elemTypeId);
  3112. }
  3113. return retVal;
  3114. }
  3115. uint32_t SPIRVEmitter::processTextureSampleGather(const CXXMemberCallExpr *expr,
  3116. const bool isSample) {
  3117. // Signatures:
  3118. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3119. // DXGI_FORMAT Object.Sample(sampler_state S,
  3120. // float Location
  3121. // [, int Offset]
  3122. // [, float Clamp]
  3123. // [, out uint Status]);
  3124. //
  3125. // For TextureCube and TextureCubeArray:
  3126. // DXGI_FORMAT Object.Sample(sampler_state S,
  3127. // float Location
  3128. // [, float Clamp]
  3129. // [, out uint Status]);
  3130. //
  3131. // For Texture2D/Texture2DArray:
  3132. // <Template Type>4 Object.Gather(sampler_state S,
  3133. // float2|3|4 Location,
  3134. // int2 Offset
  3135. // [, uint Status]);
  3136. //
  3137. // For TextureCube/TextureCubeArray:
  3138. // <Template Type>4 Object.Gather(sampler_state S,
  3139. // float2|3|4 Location
  3140. // [, uint Status]);
  3141. //
  3142. // Other Texture types do not have a Gather method.
  3143. const auto numArgs = expr->getNumArgs();
  3144. const bool hasStatusArg =
  3145. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3146. uint32_t clamp = 0;
  3147. if (numArgs > 2 && expr->getArg(2)->getType()->isFloatingType())
  3148. clamp = doExpr(expr->getArg(2));
  3149. else if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3150. clamp = doExpr(expr->getArg(3));
  3151. const bool hasClampArg = (clamp != 0);
  3152. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3153. // Subtract 1 for status (if it exists), subtract 1 for clamp (if it exists),
  3154. // and subtract 2 for sampler_state and location.
  3155. const bool hasOffsetArg = numArgs - hasStatusArg - hasClampArg - 2 > 0;
  3156. const auto *imageExpr = expr->getImplicitObjectArgument();
  3157. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3158. const uint32_t image = loadIfGLValue(imageExpr);
  3159. const uint32_t sampler = doExpr(expr->getArg(0));
  3160. const uint32_t coordinate = doExpr(expr->getArg(1));
  3161. // .Sample()/.Gather() may have a third optional paramter for offset.
  3162. uint32_t constOffset = 0, varOffset = 0;
  3163. if (hasOffsetArg)
  3164. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3165. const auto retType = expr->getDirectCallee()->getReturnType();
  3166. const auto retTypeId = typeTranslator.translateType(retType);
  3167. if (isSample) {
  3168. return createImageSample(
  3169. retType, imageType, image, sampler, coordinate, /*compareVal*/ 0,
  3170. /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0), constOffset, varOffset,
  3171. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3172. } else {
  3173. return theBuilder.createImageGather(
  3174. retTypeId, imageType, image, sampler, coordinate,
  3175. // .Gather() doc says we return four components of red data.
  3176. theBuilder.getConstantInt32(0), /*compareVal*/ 0, constOffset,
  3177. varOffset, /*constOffsets*/ 0, /*sampleNumber*/ 0, status);
  3178. }
  3179. }
  3180. uint32_t
  3181. SPIRVEmitter::processTextureSampleBiasLevel(const CXXMemberCallExpr *expr,
  3182. const bool isBias) {
  3183. // Signatures:
  3184. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3185. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3186. // float Location,
  3187. // float Bias
  3188. // [, int Offset]
  3189. // [, float clamp]
  3190. // [, out uint Status]);
  3191. //
  3192. // For TextureCube and TextureCubeArray:
  3193. // DXGI_FORMAT Object.SampleBias(sampler_state S,
  3194. // float Location,
  3195. // float Bias
  3196. // [, float clamp]
  3197. // [, out uint Status]);
  3198. //
  3199. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3200. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3201. // float Location,
  3202. // float LOD
  3203. // [, int Offset]
  3204. // [, out uint Status]);
  3205. //
  3206. // For TextureCube and TextureCubeArray:
  3207. // DXGI_FORMAT Object.SampleLevel(sampler_state S,
  3208. // float Location,
  3209. // float LOD
  3210. // [, out uint Status]);
  3211. const auto numArgs = expr->getNumArgs();
  3212. const bool hasStatusArg =
  3213. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3214. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3215. uint32_t clamp = 0;
  3216. // The .SampleLevel() methods do not take the clamp argument.
  3217. if (isBias) {
  3218. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3219. clamp = doExpr(expr->getArg(3));
  3220. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3221. clamp = doExpr(expr->getArg(4));
  3222. }
  3223. const bool hasClampArg = clamp != 0;
  3224. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3225. // and 3 for sampler_state, location, and Bias/LOD.
  3226. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3227. const auto *imageExpr = expr->getImplicitObjectArgument();
  3228. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3229. const uint32_t image = loadIfGLValue(imageExpr);
  3230. const uint32_t sampler = doExpr(expr->getArg(0));
  3231. const uint32_t coordinate = doExpr(expr->getArg(1));
  3232. uint32_t lod = 0;
  3233. uint32_t bias = 0;
  3234. if (isBias) {
  3235. bias = doExpr(expr->getArg(2));
  3236. } else {
  3237. lod = doExpr(expr->getArg(2));
  3238. }
  3239. // If offset is present in .Bias()/.SampleLevel(), it is the fourth argument.
  3240. uint32_t constOffset = 0, varOffset = 0;
  3241. if (hasOffsetArg)
  3242. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3243. const auto retType = expr->getDirectCallee()->getReturnType();
  3244. return createImageSample(retType, imageType, image, sampler, coordinate,
  3245. /*compareVal*/ 0, bias, lod, std::make_pair(0, 0),
  3246. constOffset, varOffset, /*constOffsets*/ 0,
  3247. /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3248. }
  3249. uint32_t SPIRVEmitter::processTextureSampleGrad(const CXXMemberCallExpr *expr) {
  3250. // Signature:
  3251. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, and Texture3D:
  3252. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3253. // float Location,
  3254. // float DDX,
  3255. // float DDY
  3256. // [, int Offset]
  3257. // [, float Clamp]
  3258. // [, out uint Status]);
  3259. //
  3260. // For TextureCube and TextureCubeArray:
  3261. // DXGI_FORMAT Object.SampleGrad(sampler_state S,
  3262. // float Location,
  3263. // float DDX,
  3264. // float DDY
  3265. // [, float Clamp]
  3266. // [, out uint Status]);
  3267. const auto numArgs = expr->getNumArgs();
  3268. const bool hasStatusArg =
  3269. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3270. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3271. uint32_t clamp = 0;
  3272. if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3273. clamp = doExpr(expr->getArg(4));
  3274. else if (numArgs > 5 && expr->getArg(5)->getType()->isFloatingType())
  3275. clamp = doExpr(expr->getArg(5));
  3276. const bool hasClampArg = clamp != 0;
  3277. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3278. // and 4 for sampler_state, location, DDX, and DDY;
  3279. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 4 > 0;
  3280. const auto *imageExpr = expr->getImplicitObjectArgument();
  3281. const uint32_t imageType = typeTranslator.translateType(imageExpr->getType());
  3282. const uint32_t image = loadIfGLValue(imageExpr);
  3283. const uint32_t sampler = doExpr(expr->getArg(0));
  3284. const uint32_t coordinate = doExpr(expr->getArg(1));
  3285. const uint32_t ddx = doExpr(expr->getArg(2));
  3286. const uint32_t ddy = doExpr(expr->getArg(3));
  3287. // If offset is present in .SampleGrad(), it is the fifth argument.
  3288. uint32_t constOffset = 0, varOffset = 0;
  3289. if (hasOffsetArg)
  3290. handleOffsetInMethodCall(expr, 4, &constOffset, &varOffset);
  3291. const auto retType = expr->getDirectCallee()->getReturnType();
  3292. return createImageSample(
  3293. retType, imageType, image, sampler, coordinate, /*compareVal*/ 0,
  3294. /*bias*/ 0, /*lod*/ 0, std::make_pair(ddx, ddy), constOffset, varOffset,
  3295. /*constOffsets*/ 0, /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3296. }
  3297. uint32_t
  3298. SPIRVEmitter::processTextureSampleCmpCmpLevelZero(const CXXMemberCallExpr *expr,
  3299. const bool isCmp) {
  3300. // .SampleCmp() Signature:
  3301. //
  3302. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3303. // float Object.SampleCmp(
  3304. // SamplerComparisonState S,
  3305. // float Location,
  3306. // float CompareValue
  3307. // [, int Offset]
  3308. // [, float Clamp]
  3309. // [, out uint Status]
  3310. // );
  3311. //
  3312. // For TextureCube and TextureCubeArray:
  3313. // float Object.SampleCmp(
  3314. // SamplerComparisonState S,
  3315. // float Location,
  3316. // float CompareValue
  3317. // [, float Clamp]
  3318. // [, out uint Status]
  3319. // );
  3320. //
  3321. // .SampleCmpLevelZero() is identical to .SampleCmp() on mipmap level 0 only.
  3322. // It never takes a clamp argument, which is good because lod and clamp may
  3323. // not be used together.
  3324. //
  3325. // .SampleCmpLevelZero() Signature:
  3326. //
  3327. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray:
  3328. // float Object.SampleCmpLevelZero(
  3329. // SamplerComparisonState S,
  3330. // float Location,
  3331. // float CompareValue
  3332. // [, int Offset]
  3333. // [, out uint Status]
  3334. // );
  3335. //
  3336. // For TextureCube and TextureCubeArray:
  3337. // float Object.SampleCmpLevelZero(
  3338. // SamplerComparisonState S,
  3339. // float Location,
  3340. // float CompareValue
  3341. // [, out uint Status]
  3342. // );
  3343. const auto numArgs = expr->getNumArgs();
  3344. const bool hasStatusArg =
  3345. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3346. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3347. uint32_t clamp = 0;
  3348. // The .SampleCmpLevelZero() methods do not take the clamp argument.
  3349. if (isCmp) {
  3350. if (numArgs > 3 && expr->getArg(3)->getType()->isFloatingType())
  3351. clamp = doExpr(expr->getArg(3));
  3352. else if (numArgs > 4 && expr->getArg(4)->getType()->isFloatingType())
  3353. clamp = doExpr(expr->getArg(4));
  3354. }
  3355. const bool hasClampArg = clamp != 0;
  3356. // Subtract 1 for clamp (if it exists), 1 for status (if it exists),
  3357. // and 3 for sampler_state, location, and compare_value.
  3358. const bool hasOffsetArg = numArgs - hasClampArg - hasStatusArg - 3 > 0;
  3359. const auto *imageExpr = expr->getImplicitObjectArgument();
  3360. const uint32_t image = loadIfGLValue(imageExpr);
  3361. const uint32_t sampler = doExpr(expr->getArg(0));
  3362. const uint32_t coordinate = doExpr(expr->getArg(1));
  3363. const uint32_t compareVal = doExpr(expr->getArg(2));
  3364. // If offset is present in .SampleCmp(), it will be the fourth argument.
  3365. uint32_t constOffset = 0, varOffset = 0;
  3366. if (hasOffsetArg)
  3367. handleOffsetInMethodCall(expr, 3, &constOffset, &varOffset);
  3368. const uint32_t lod = isCmp ? 0 : theBuilder.getConstantFloat32(0);
  3369. const auto retType = expr->getDirectCallee()->getReturnType();
  3370. const auto imageType = typeTranslator.translateType(imageExpr->getType());
  3371. return createImageSample(retType, imageType, image, sampler, coordinate,
  3372. compareVal, /*bias*/ 0, lod, std::make_pair(0, 0),
  3373. constOffset, varOffset, /*constOffsets*/ 0,
  3374. /*sampleNumber*/ 0, /*minLod*/ clamp, status);
  3375. }
  3376. SpirvEvalInfo
  3377. SPIRVEmitter::processBufferTextureLoad(const CXXMemberCallExpr *expr) {
  3378. // Signature:
  3379. // For Texture1D, Texture1DArray, Texture2D, Texture2DArray, Texture3D:
  3380. // ret Object.Load(int Location
  3381. // [, int Offset]
  3382. // [, uint status]);
  3383. //
  3384. // For Texture2DMS and Texture2DMSArray, there is one additional argument:
  3385. // ret Object.Load(int Location
  3386. // [, int SampleIndex]
  3387. // [, int Offset]
  3388. // [, uint status]);
  3389. //
  3390. // For (RW)Buffer, RWTexture1D, RWTexture1DArray, RWTexture2D,
  3391. // RWTexture2DArray, RWTexture3D:
  3392. // ret Object.Load (int Location
  3393. // [, uint status]);
  3394. //
  3395. // Note: (RW)ByteAddressBuffer and (RW)StructuredBuffer types also have Load
  3396. // methods that take an additional Status argument. However, since these types
  3397. // are not represented as OpTypeImage in SPIR-V, we don't have a way of
  3398. // figuring out the Residency Code for them. Therefore having the Status
  3399. // argument for these types is not supported.
  3400. //
  3401. // For (RW)ByteAddressBuffer:
  3402. // ret Object.{Load,Load2,Load3,Load4} (int Location
  3403. // [, uint status]);
  3404. //
  3405. // For (RW)StructuredBuffer:
  3406. // ret Object.Load (int Location
  3407. // [, uint status]);
  3408. //
  3409. const auto *object = expr->getImplicitObjectArgument();
  3410. const auto objectType = object->getType();
  3411. if (typeTranslator.isRWByteAddressBuffer(objectType) ||
  3412. typeTranslator.isByteAddressBuffer(objectType))
  3413. return processByteAddressBufferLoadStore(expr, 1, /*doStore*/ false);
  3414. if (TypeTranslator::isStructuredBuffer(objectType))
  3415. return processStructuredBufferLoad(expr);
  3416. const auto numArgs = expr->getNumArgs();
  3417. const auto *location = expr->getArg(0);
  3418. const bool isTextureMS = TypeTranslator::isTextureMS(objectType);
  3419. const bool hasStatusArg =
  3420. expr->getArg(numArgs - 1)->getType()->isUnsignedIntegerType();
  3421. const auto status = hasStatusArg ? doExpr(expr->getArg(numArgs - 1)) : 0;
  3422. if (TypeTranslator::isBuffer(objectType) ||
  3423. TypeTranslator::isRWBuffer(objectType) ||
  3424. TypeTranslator::isRWTexture(objectType))
  3425. return processBufferTextureLoad(object, doExpr(location), /*constOffset*/ 0,
  3426. /*varOffset*/ 0, /*lod*/ 0,
  3427. /*residencyCode*/ status);
  3428. // Subtract 1 for status (if it exists), and 1 for sampleIndex (if it exists),
  3429. // and 1 for location.
  3430. const bool hasOffsetArg = numArgs - hasStatusArg - isTextureMS - 1 > 0;
  3431. if (TypeTranslator::isTexture(objectType)) {
  3432. // .Load() has a second optional paramter for offset.
  3433. const auto locationId = doExpr(location);
  3434. uint32_t constOffset = 0, varOffset = 0;
  3435. uint32_t coordinate = locationId, lod = 0;
  3436. if (isTextureMS) {
  3437. // SampleIndex is only available when the Object is of Texture2DMS or
  3438. // Texture2DMSArray types. Under those cases, Offset will be the third
  3439. // parameter (index 2).
  3440. lod = doExpr(expr->getArg(1));
  3441. if (hasOffsetArg)
  3442. handleOffsetInMethodCall(expr, 2, &constOffset, &varOffset);
  3443. } else {
  3444. // For Texture Load() functions, the location parameter is a vector
  3445. // that consists of both the coordinate and the mipmap level (via the
  3446. // last vector element). We need to split it here since the
  3447. // OpImageFetch SPIR-V instruction encodes them as separate arguments.
  3448. splitVecLastElement(location->getType(), locationId, &coordinate, &lod);
  3449. // For textures other than Texture2DMS(Array), offset should be the
  3450. // second parameter (index 1).
  3451. if (hasOffsetArg)
  3452. handleOffsetInMethodCall(expr, 1, &constOffset, &varOffset);
  3453. }
  3454. return processBufferTextureLoad(object, coordinate, constOffset, varOffset,
  3455. lod, status);
  3456. }
  3457. emitError("Load() of the given object type unimplemented",
  3458. object->getExprLoc());
  3459. return 0;
  3460. }
  3461. uint32_t SPIRVEmitter::processGetDimensions(const CXXMemberCallExpr *expr) {
  3462. const auto objectType = expr->getImplicitObjectArgument()->getType();
  3463. if (TypeTranslator::isTexture(objectType) ||
  3464. TypeTranslator::isRWTexture(objectType) ||
  3465. TypeTranslator::isBuffer(objectType) ||
  3466. TypeTranslator::isRWBuffer(objectType)) {
  3467. return processBufferTextureGetDimensions(expr);
  3468. } else if (TypeTranslator::isByteAddressBuffer(objectType) ||
  3469. TypeTranslator::isRWByteAddressBuffer(objectType) ||
  3470. TypeTranslator::isStructuredBuffer(objectType) ||
  3471. TypeTranslator::isAppendStructuredBuffer(objectType) ||
  3472. TypeTranslator::isConsumeStructuredBuffer(objectType)) {
  3473. return processByteAddressBufferStructuredBufferGetDimensions(expr);
  3474. } else {
  3475. emitError("GetDimensions() of the given object type unimplemented",
  3476. expr->getExprLoc());
  3477. return 0;
  3478. }
  3479. }
  3480. SpirvEvalInfo
  3481. SPIRVEmitter::doCXXOperatorCallExpr(const CXXOperatorCallExpr *expr) {
  3482. { // Handle Buffer/RWBuffer/Texture/RWTexture indexing
  3483. const Expr *baseExpr = nullptr;
  3484. const Expr *indexExpr = nullptr;
  3485. const Expr *lodExpr = nullptr;
  3486. // For Textures, regular indexing (operator[]) uses slice 0.
  3487. if (isBufferTextureIndexing(expr, &baseExpr, &indexExpr)) {
  3488. const uint32_t lod = TypeTranslator::isTexture(baseExpr->getType())
  3489. ? theBuilder.getConstantUint32(0)
  3490. : 0;
  3491. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3492. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3493. /*residencyCode*/ 0);
  3494. }
  3495. // .mips[][] or .sample[][] must use the correct slice.
  3496. if (isTextureMipsSampleIndexing(expr, &baseExpr, &indexExpr, &lodExpr)) {
  3497. const uint32_t lod = doExpr(lodExpr);
  3498. return processBufferTextureLoad(baseExpr, doExpr(indexExpr),
  3499. /*constOffset*/ 0, /*varOffset*/ 0, lod,
  3500. /*residencyCode*/ 0);
  3501. }
  3502. }
  3503. llvm::SmallVector<uint32_t, 4> indices;
  3504. const Expr *baseExpr = collectArrayStructIndices(expr, &indices);
  3505. auto base = loadIfAliasVarRef(baseExpr);
  3506. if (indices.empty())
  3507. return base; // For indexing into size-1 vectors and 1xN matrices
  3508. // If we are indexing into a rvalue, to use OpAccessChain, we first need
  3509. // to create a local variable to hold the rvalue.
  3510. //
  3511. // TODO: We can optimize the codegen by emitting OpCompositeExtract if
  3512. // all indices are contant integers.
  3513. if (base.isRValue()) {
  3514. base = createTemporaryVar(baseExpr->getType(), "vector", base);
  3515. }
  3516. return turnIntoElementPtr(base, expr->getType(), indices);
  3517. }
  3518. SpirvEvalInfo
  3519. SPIRVEmitter::doExtMatrixElementExpr(const ExtMatrixElementExpr *expr) {
  3520. const Expr *baseExpr = expr->getBase();
  3521. const auto baseInfo = doExpr(baseExpr);
  3522. const auto accessor = expr->getEncodedElementAccess();
  3523. const uint32_t elemType = typeTranslator.translateType(
  3524. hlsl::GetHLSLMatElementType(baseExpr->getType()));
  3525. uint32_t rowCount = 0, colCount = 0;
  3526. hlsl::GetHLSLMatRowColCount(baseExpr->getType(), rowCount, colCount);
  3527. // Construct a temporary vector out of all elements accessed:
  3528. // 1. Create access chain for each element using OpAccessChain
  3529. // 2. Load each element using OpLoad
  3530. // 3. Create the vector using OpCompositeConstruct
  3531. llvm::SmallVector<uint32_t, 4> elements;
  3532. for (uint32_t i = 0; i < accessor.Count; ++i) {
  3533. uint32_t row = 0, col = 0, elem = 0;
  3534. accessor.GetPosition(i, &row, &col);
  3535. llvm::SmallVector<uint32_t, 2> indices;
  3536. // If the matrix only has one row/column, we are indexing into a vector
  3537. // then. Only one index is needed for such cases.
  3538. if (rowCount > 1)
  3539. indices.push_back(row);
  3540. if (colCount > 1)
  3541. indices.push_back(col);
  3542. if (baseExpr->isGLValue()) {
  3543. for (uint32_t i = 0; i < indices.size(); ++i)
  3544. indices[i] = theBuilder.getConstantInt32(indices[i]);
  3545. const uint32_t ptrType =
  3546. theBuilder.getPointerType(elemType, baseInfo.getStorageClass());
  3547. if (!indices.empty()) {
  3548. assert(!baseInfo.isRValue());
  3549. // Load the element via access chain
  3550. elem = theBuilder.createAccessChain(ptrType, baseInfo, indices);
  3551. } else {
  3552. // The matrix is of size 1x1. No need to use access chain, base should
  3553. // be the source pointer.
  3554. elem = baseInfo;
  3555. }
  3556. elem = theBuilder.createLoad(elemType, elem);
  3557. } else { // e.g., (mat1 + mat2)._m11
  3558. elem = theBuilder.createCompositeExtract(elemType, baseInfo, indices);
  3559. }
  3560. elements.push_back(elem);
  3561. }
  3562. auto valueId = elements.front();
  3563. if (elements.size() > 1) {
  3564. const uint32_t vecType = theBuilder.getVecType(elemType, elements.size());
  3565. valueId = theBuilder.createCompositeConstruct(vecType, elements);
  3566. }
  3567. return SpirvEvalInfo(valueId).setRValue();
  3568. }
  3569. SpirvEvalInfo
  3570. SPIRVEmitter::doHLSLVectorElementExpr(const HLSLVectorElementExpr *expr) {
  3571. const Expr *baseExpr = nullptr;
  3572. hlsl::VectorMemberAccessPositions accessor;
  3573. condenseVectorElementExpr(expr, &baseExpr, &accessor);
  3574. const QualType baseType = baseExpr->getType();
  3575. assert(hlsl::IsHLSLVecType(baseType));
  3576. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  3577. const uint32_t type = typeTranslator.translateType(expr->getType());
  3578. const auto accessorSize = static_cast<size_t>(accessor.Count);
  3579. // Depending on the number of elements selected, we emit different
  3580. // instructions.
  3581. // For vectors of size greater than 1, if we are only selecting one element,
  3582. // typical access chain or composite extraction should be fine. But if we
  3583. // are selecting more than one elements, we must resolve to vector specific
  3584. // operations.
  3585. // For size-1 vectors, if we are selecting their single elements multiple
  3586. // times, we need composite construct instructions.
  3587. if (accessorSize == 1) {
  3588. auto baseInfo = doExpr(baseExpr);
  3589. if (baseSize == 1) {
  3590. // Selecting one element from a size-1 vector. The underlying vector is
  3591. // already treated as a scalar.
  3592. return baseInfo;
  3593. }
  3594. // If the base is an lvalue, we should emit an access chain instruction
  3595. // so that we can load/store the specified element. For rvalue base,
  3596. // we should use composite extraction. We should check the immediate base
  3597. // instead of the original base here since we can have something like
  3598. // v.xyyz to turn a lvalue v into rvalue.
  3599. if (!baseInfo.isRValue()) { // E.g., v.x;
  3600. const uint32_t ptrType =
  3601. theBuilder.getPointerType(type, baseInfo.getStorageClass());
  3602. const uint32_t index = theBuilder.getConstantInt32(accessor.Swz0);
  3603. // We need a lvalue here. Do not try to load.
  3604. return theBuilder.createAccessChain(ptrType, baseInfo, {index});
  3605. } else { // E.g., (v + w).x;
  3606. // The original base vector may not be a rvalue. Need to load it if
  3607. // it is lvalue since ImplicitCastExpr (LValueToRValue) will be missing
  3608. // for that case.
  3609. return baseInfo.setResultId(
  3610. theBuilder.createCompositeExtract(type, baseInfo, {accessor.Swz0}));
  3611. }
  3612. }
  3613. if (baseSize == 1) {
  3614. // Selecting more than one element from a size-1 vector, for example,
  3615. // <scalar>.xx. Construct the vector.
  3616. auto info = loadIfGLValue(baseExpr);
  3617. llvm::SmallVector<uint32_t, 4> components(accessorSize, info);
  3618. return info
  3619. .setResultId(theBuilder.createCompositeConstruct(type, components))
  3620. .setRValue();
  3621. }
  3622. llvm::SmallVector<uint32_t, 4> selectors;
  3623. selectors.resize(accessorSize);
  3624. // Whether we are selecting elements in the original order
  3625. bool originalOrder = baseSize == accessorSize;
  3626. for (uint32_t i = 0; i < accessorSize; ++i) {
  3627. accessor.GetPosition(i, &selectors[i]);
  3628. // We can select more elements than the vector provides. This handles
  3629. // that case too.
  3630. originalOrder &= selectors[i] == i;
  3631. }
  3632. if (originalOrder)
  3633. return doExpr(baseExpr);
  3634. auto info = loadIfGLValue(baseExpr);
  3635. // Use base for both vectors. But we are only selecting values from the
  3636. // first one.
  3637. return info.setResultId(
  3638. theBuilder.createVectorShuffle(type, info, info, selectors));
  3639. }
  3640. SpirvEvalInfo SPIRVEmitter::doInitListExpr(const InitListExpr *expr) {
  3641. if (const uint32_t id = tryToEvaluateAsConst(expr))
  3642. return SpirvEvalInfo(id).setRValue();
  3643. return SpirvEvalInfo(InitListHandler(*this).process(expr)).setRValue();
  3644. }
  3645. SpirvEvalInfo SPIRVEmitter::doMemberExpr(const MemberExpr *expr) {
  3646. llvm::SmallVector<uint32_t, 4> indices;
  3647. const Expr *base = collectArrayStructIndices(expr, &indices);
  3648. auto info = loadIfAliasVarRef(base);
  3649. if (!indices.empty()) {
  3650. // Sometime we are accessing the member of a rvalue, e.g.,
  3651. // <some-function-returing-a-struct>().<some-field>
  3652. // Create a temporary variable to hold the rvalue so that we can use access
  3653. // chain to index into it.
  3654. if (info.isRValue()) {
  3655. SpirvEvalInfo tempVar = createTemporaryVar(
  3656. base->getType(), TypeTranslator::getName(base->getType()), info);
  3657. (void)turnIntoElementPtr(tempVar, expr->getType(), indices);
  3658. info.setResultId(theBuilder.createLoad(
  3659. typeTranslator.translateType(expr->getType()), tempVar));
  3660. } else {
  3661. (void)turnIntoElementPtr(info, expr->getType(), indices);
  3662. }
  3663. }
  3664. return info;
  3665. }
  3666. uint32_t SPIRVEmitter::createTemporaryVar(QualType type, llvm::StringRef name,
  3667. const SpirvEvalInfo &init) {
  3668. const uint32_t varType =
  3669. typeTranslator.translateType(type, init.getLayoutRule());
  3670. const std::string varName = "temp.var." + name.str();
  3671. const uint32_t varId = theBuilder.addFnVar(varType, varName);
  3672. theBuilder.createStore(varId, init);
  3673. return varId;
  3674. }
  3675. SpirvEvalInfo SPIRVEmitter::doUnaryOperator(const UnaryOperator *expr) {
  3676. const auto opcode = expr->getOpcode();
  3677. const auto *subExpr = expr->getSubExpr();
  3678. const auto subType = subExpr->getType();
  3679. auto subValue = doExpr(subExpr);
  3680. const auto subTypeId = typeTranslator.translateType(subType);
  3681. switch (opcode) {
  3682. case UO_PreInc:
  3683. case UO_PreDec:
  3684. case UO_PostInc:
  3685. case UO_PostDec: {
  3686. const bool isPre = opcode == UO_PreInc || opcode == UO_PreDec;
  3687. const bool isInc = opcode == UO_PreInc || opcode == UO_PostInc;
  3688. const spv::Op spvOp = translateOp(isInc ? BO_Add : BO_Sub, subType);
  3689. const uint32_t originValue = theBuilder.createLoad(subTypeId, subValue);
  3690. const uint32_t one = hlsl::IsHLSLMatType(subType)
  3691. ? getMatElemValueOne(subType)
  3692. : getValueOne(subType);
  3693. uint32_t incValue = 0;
  3694. if (TypeTranslator::isSpirvAcceptableMatrixType(subType)) {
  3695. // For matrices, we can only increment/decrement each vector of it.
  3696. const auto actOnEachVec = [this, spvOp, one](uint32_t /*index*/,
  3697. uint32_t vecType,
  3698. uint32_t lhsVec) {
  3699. const auto valId =
  3700. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, one);
  3701. return SpirvEvalInfo(valId).setRValue();
  3702. };
  3703. incValue = processEachVectorInMatrix(subExpr, originValue, actOnEachVec);
  3704. } else {
  3705. incValue = theBuilder.createBinaryOp(spvOp, subTypeId, originValue, one);
  3706. }
  3707. theBuilder.createStore(subValue, incValue);
  3708. // Prefix increment/decrement operator returns a lvalue, while postfix
  3709. // increment/decrement returns a rvalue.
  3710. return isPre ? subValue : SpirvEvalInfo(originValue).setRValue();
  3711. }
  3712. case UO_Not: {
  3713. const auto valId =
  3714. theBuilder.createUnaryOp(spv::Op::OpNot, subTypeId, subValue);
  3715. return SpirvEvalInfo(valId).setRValue();
  3716. }
  3717. case UO_LNot: {
  3718. // Parsing will do the necessary casting to make sure we are applying the
  3719. // ! operator on boolean values.
  3720. const auto valId =
  3721. theBuilder.createUnaryOp(spv::Op::OpLogicalNot, subTypeId, subValue);
  3722. return SpirvEvalInfo(valId).setRValue();
  3723. }
  3724. case UO_Plus:
  3725. // No need to do anything for the prefix + operator.
  3726. return subValue;
  3727. case UO_Minus: {
  3728. // SPIR-V have two opcodes for negating values: OpSNegate and OpFNegate.
  3729. const spv::Op spvOp = isFloatOrVecOfFloatType(subType) ? spv::Op::OpFNegate
  3730. : spv::Op::OpSNegate;
  3731. const auto valId = theBuilder.createUnaryOp(spvOp, subTypeId, subValue);
  3732. return SpirvEvalInfo(valId).setRValue();
  3733. }
  3734. default:
  3735. break;
  3736. }
  3737. emitError("unary operator '%0' unimplemented", expr->getExprLoc())
  3738. << expr->getOpcodeStr(opcode);
  3739. expr->dump();
  3740. return 0;
  3741. }
  3742. spv::Op SPIRVEmitter::translateOp(BinaryOperator::Opcode op, QualType type) {
  3743. const bool isSintType = isSintOrVecMatOfSintType(type);
  3744. const bool isUintType = isUintOrVecMatOfUintType(type);
  3745. const bool isFloatType = isFloatOrVecMatOfFloatType(type);
  3746. #define BIN_OP_CASE_INT_FLOAT(kind, intBinOp, floatBinOp) \
  3747. \
  3748. case BO_##kind: { \
  3749. if (isSintType || isUintType) { \
  3750. return spv::Op::Op##intBinOp; \
  3751. } \
  3752. if (isFloatType) { \
  3753. return spv::Op::Op##floatBinOp; \
  3754. } \
  3755. } break
  3756. #define BIN_OP_CASE_SINT_UINT_FLOAT(kind, sintBinOp, uintBinOp, floatBinOp) \
  3757. \
  3758. case BO_##kind: { \
  3759. if (isSintType) { \
  3760. return spv::Op::Op##sintBinOp; \
  3761. } \
  3762. if (isUintType) { \
  3763. return spv::Op::Op##uintBinOp; \
  3764. } \
  3765. if (isFloatType) { \
  3766. return spv::Op::Op##floatBinOp; \
  3767. } \
  3768. } break
  3769. #define BIN_OP_CASE_SINT_UINT(kind, sintBinOp, uintBinOp) \
  3770. \
  3771. case BO_##kind: { \
  3772. if (isSintType) { \
  3773. return spv::Op::Op##sintBinOp; \
  3774. } \
  3775. if (isUintType) { \
  3776. return spv::Op::Op##uintBinOp; \
  3777. } \
  3778. } break
  3779. switch (op) {
  3780. case BO_EQ: {
  3781. if (isBoolOrVecMatOfBoolType(type))
  3782. return spv::Op::OpLogicalEqual;
  3783. if (isSintType || isUintType)
  3784. return spv::Op::OpIEqual;
  3785. if (isFloatType)
  3786. return spv::Op::OpFOrdEqual;
  3787. } break;
  3788. case BO_NE: {
  3789. if (isBoolOrVecMatOfBoolType(type))
  3790. return spv::Op::OpLogicalNotEqual;
  3791. if (isSintType || isUintType)
  3792. return spv::Op::OpINotEqual;
  3793. if (isFloatType)
  3794. return spv::Op::OpFOrdNotEqual;
  3795. } break;
  3796. // According to HLSL doc, all sides of the && and || expression are always
  3797. // evaluated.
  3798. case BO_LAnd:
  3799. return spv::Op::OpLogicalAnd;
  3800. case BO_LOr:
  3801. return spv::Op::OpLogicalOr;
  3802. BIN_OP_CASE_INT_FLOAT(Add, IAdd, FAdd);
  3803. BIN_OP_CASE_INT_FLOAT(AddAssign, IAdd, FAdd);
  3804. BIN_OP_CASE_INT_FLOAT(Sub, ISub, FSub);
  3805. BIN_OP_CASE_INT_FLOAT(SubAssign, ISub, FSub);
  3806. BIN_OP_CASE_INT_FLOAT(Mul, IMul, FMul);
  3807. BIN_OP_CASE_INT_FLOAT(MulAssign, IMul, FMul);
  3808. BIN_OP_CASE_SINT_UINT_FLOAT(Div, SDiv, UDiv, FDiv);
  3809. BIN_OP_CASE_SINT_UINT_FLOAT(DivAssign, SDiv, UDiv, FDiv);
  3810. // According to HLSL spec, "the modulus operator returns the remainder of
  3811. // a division." "The % operator is defined only in cases where either both
  3812. // sides are positive or both sides are negative."
  3813. //
  3814. // In SPIR-V, there are two reminder operations: Op*Rem and Op*Mod. With
  3815. // the former, the sign of a non-0 result comes from Operand 1, while
  3816. // with the latter, from Operand 2.
  3817. //
  3818. // For operands with different signs, technically we can map % to either
  3819. // Op*Rem or Op*Mod since it's undefined behavior. But it is more
  3820. // consistent with C (HLSL starts as a C derivative) and Clang frontend
  3821. // const expression evaluation if we map % to Op*Rem.
  3822. //
  3823. // Note there is no OpURem in SPIR-V.
  3824. BIN_OP_CASE_SINT_UINT_FLOAT(Rem, SRem, UMod, FRem);
  3825. BIN_OP_CASE_SINT_UINT_FLOAT(RemAssign, SRem, UMod, FRem);
  3826. BIN_OP_CASE_SINT_UINT_FLOAT(LT, SLessThan, ULessThan, FOrdLessThan);
  3827. BIN_OP_CASE_SINT_UINT_FLOAT(LE, SLessThanEqual, ULessThanEqual,
  3828. FOrdLessThanEqual);
  3829. BIN_OP_CASE_SINT_UINT_FLOAT(GT, SGreaterThan, UGreaterThan,
  3830. FOrdGreaterThan);
  3831. BIN_OP_CASE_SINT_UINT_FLOAT(GE, SGreaterThanEqual, UGreaterThanEqual,
  3832. FOrdGreaterThanEqual);
  3833. BIN_OP_CASE_SINT_UINT(And, BitwiseAnd, BitwiseAnd);
  3834. BIN_OP_CASE_SINT_UINT(AndAssign, BitwiseAnd, BitwiseAnd);
  3835. BIN_OP_CASE_SINT_UINT(Or, BitwiseOr, BitwiseOr);
  3836. BIN_OP_CASE_SINT_UINT(OrAssign, BitwiseOr, BitwiseOr);
  3837. BIN_OP_CASE_SINT_UINT(Xor, BitwiseXor, BitwiseXor);
  3838. BIN_OP_CASE_SINT_UINT(XorAssign, BitwiseXor, BitwiseXor);
  3839. BIN_OP_CASE_SINT_UINT(Shl, ShiftLeftLogical, ShiftLeftLogical);
  3840. BIN_OP_CASE_SINT_UINT(ShlAssign, ShiftLeftLogical, ShiftLeftLogical);
  3841. BIN_OP_CASE_SINT_UINT(Shr, ShiftRightArithmetic, ShiftRightLogical);
  3842. BIN_OP_CASE_SINT_UINT(ShrAssign, ShiftRightArithmetic, ShiftRightLogical);
  3843. default:
  3844. break;
  3845. }
  3846. #undef BIN_OP_CASE_INT_FLOAT
  3847. #undef BIN_OP_CASE_SINT_UINT_FLOAT
  3848. #undef BIN_OP_CASE_SINT_UINT
  3849. emitError("translating binary operator '%0' unimplemented", {})
  3850. << BinaryOperator::getOpcodeStr(op);
  3851. return spv::Op::OpNop;
  3852. }
  3853. SpirvEvalInfo SPIRVEmitter::processAssignment(const Expr *lhs,
  3854. const SpirvEvalInfo &rhs,
  3855. const bool isCompoundAssignment,
  3856. SpirvEvalInfo lhsPtr) {
  3857. // Assigning to vector swizzling should be handled differently.
  3858. if (SpirvEvalInfo result = tryToAssignToVectorElements(lhs, rhs))
  3859. return result;
  3860. // Assigning to matrix swizzling should be handled differently.
  3861. if (SpirvEvalInfo result = tryToAssignToMatrixElements(lhs, rhs))
  3862. return result;
  3863. // Assigning to a RWBuffer/RWTexture should be handled differently.
  3864. if (SpirvEvalInfo result = tryToAssignToRWBufferRWTexture(lhs, rhs))
  3865. return result;
  3866. // Normal assignment procedure
  3867. if (!lhsPtr)
  3868. lhsPtr = doExpr(lhs);
  3869. storeValue(lhsPtr, rhs, lhs->getType());
  3870. // Plain assignment returns a rvalue, while compound assignment returns
  3871. // lvalue.
  3872. return isCompoundAssignment ? lhsPtr : rhs;
  3873. }
  3874. void SPIRVEmitter::storeValue(const SpirvEvalInfo &lhsPtr,
  3875. const SpirvEvalInfo &rhsVal,
  3876. const QualType lhsValType) {
  3877. if (typeTranslator.isScalarType(lhsValType) ||
  3878. typeTranslator.isVectorType(lhsValType) ||
  3879. typeTranslator.isMxNMatrix(lhsValType)) {
  3880. theBuilder.createStore(lhsPtr, rhsVal);
  3881. } else if (TypeTranslator::isOpaqueType(lhsValType)) {
  3882. // Resource types are represented using RecordType in the AST.
  3883. // Handle them before the general RecordType.
  3884. //
  3885. // HLSL allows to put resource types that translating into SPIR-V opaque
  3886. // types in structs, or assign to variables of resource types. These can all
  3887. // result in illegal SPIR-V for Vulkan. We just translate here literally and
  3888. // let SPIRV-Tools opt to do the legalization work.
  3889. //
  3890. // Note: legalization specific code
  3891. theBuilder.createStore(lhsPtr, rhsVal);
  3892. needsLegalization = true;
  3893. } else if (TypeTranslator::isAKindOfStructuredOrByteBuffer(lhsValType)) {
  3894. // The rhs should be a pointer and the lhs should be a pointer-to-pointer.
  3895. // Directly store the pointer here and let SPIRV-Tools opt to do the clean
  3896. // up.
  3897. //
  3898. // Note: legalization specific code
  3899. theBuilder.createStore(lhsPtr, rhsVal);
  3900. needsLegalization = true;
  3901. // For ConstantBuffers/TextureBuffers, we decompose and assign each field
  3902. // recursively like normal structs using the following logic.
  3903. //
  3904. // The frontend forbids declaring ConstantBuffer<T> or TextureBuffer<T>
  3905. // variables as function parameters/returns/variables, but happily accepts
  3906. // assignments/returns from ConstantBuffer<T>/TextureBuffer<T> to function
  3907. // parameters/returns/variables of type T. And ConstantBuffer<T> is not
  3908. // represented differently as struct T.
  3909. } else if (lhsPtr.getLayoutRule() == rhsVal.getLayoutRule()) {
  3910. // If lhs and rhs has the same memory layout, we should be safe to load
  3911. // from rhs and directly store into lhs and avoid decomposing rhs.
  3912. // Note: this check should happen after those setting needsLegalization.
  3913. // TODO: is this optimization always correct?
  3914. theBuilder.createStore(lhsPtr, rhsVal);
  3915. } else if (const auto *recordType = lhsValType->getAs<RecordType>()) {
  3916. uint32_t index = 0;
  3917. for (const auto *field : recordType->getDecl()->fields()) {
  3918. const auto subRhsValType = typeTranslator.translateType(
  3919. field->getType(), rhsVal.getLayoutRule());
  3920. const auto subRhsVal =
  3921. theBuilder.createCompositeExtract(subRhsValType, rhsVal, {index});
  3922. const auto subLhsPtrType = theBuilder.getPointerType(
  3923. typeTranslator.translateType(field->getType(),
  3924. lhsPtr.getLayoutRule()),
  3925. lhsPtr.getStorageClass());
  3926. const auto subLhsPtr = theBuilder.createAccessChain(
  3927. subLhsPtrType, lhsPtr, {theBuilder.getConstantUint32(index)});
  3928. storeValue(lhsPtr.substResultId(subLhsPtr),
  3929. rhsVal.substResultId(subRhsVal), field->getType());
  3930. ++index;
  3931. }
  3932. } else if (const auto *arrayType =
  3933. astContext.getAsConstantArrayType(lhsValType)) {
  3934. const auto elemType = arrayType->getElementType();
  3935. // TODO: handle extra large array size?
  3936. const auto size =
  3937. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  3938. for (uint32_t i = 0; i < size; ++i) {
  3939. const auto subRhsValType =
  3940. typeTranslator.translateType(elemType, rhsVal.getLayoutRule());
  3941. const auto subRhsVal =
  3942. theBuilder.createCompositeExtract(subRhsValType, rhsVal, {i});
  3943. const auto subLhsPtrType = theBuilder.getPointerType(
  3944. typeTranslator.translateType(elemType, lhsPtr.getLayoutRule()),
  3945. lhsPtr.getStorageClass());
  3946. const auto subLhsPtr = theBuilder.createAccessChain(
  3947. subLhsPtrType, lhsPtr, {theBuilder.getConstantUint32(i)});
  3948. storeValue(lhsPtr.substResultId(subLhsPtr),
  3949. rhsVal.substResultId(subRhsVal), elemType);
  3950. }
  3951. } else {
  3952. emitError("storing value of type %0 unimplemented", {}) << lhsValType;
  3953. }
  3954. }
  3955. SpirvEvalInfo SPIRVEmitter::processBinaryOp(const Expr *lhs, const Expr *rhs,
  3956. const BinaryOperatorKind opcode,
  3957. const QualType resultType,
  3958. SourceRange sourceRange,
  3959. SpirvEvalInfo *lhsInfo,
  3960. const spv::Op mandateGenOpcode) {
  3961. const uint32_t resultTypeId = typeTranslator.translateType(resultType);
  3962. // Binary logical operations (such as ==, !=, etc) that return a boolean type
  3963. // may get a literal (e.g. 0, 1, etc.) as lhs or rhs args. Since only
  3964. // non-zero-ness of these literals matter, they can be translated as 32-bits.
  3965. TypeTranslator::LiteralTypeHint hint(typeTranslator);
  3966. if (resultType->isBooleanType()) {
  3967. if (lhs->getType()->isSpecificBuiltinType(BuiltinType::LitInt) ||
  3968. rhs->getType()->isSpecificBuiltinType(BuiltinType::LitInt))
  3969. hint.setHint(astContext.IntTy);
  3970. if (lhs->getType()->isSpecificBuiltinType(BuiltinType::LitFloat) ||
  3971. rhs->getType()->isSpecificBuiltinType(BuiltinType::LitFloat))
  3972. hint.setHint(astContext.FloatTy);
  3973. }
  3974. // If the operands are of matrix type, we need to dispatch the operation
  3975. // onto each element vector iff the operands are not degenerated matrices
  3976. // and we don't have a matrix specific SPIR-V instruction for the operation.
  3977. if (!isSpirvMatrixOp(mandateGenOpcode) &&
  3978. TypeTranslator::isSpirvAcceptableMatrixType(lhs->getType())) {
  3979. return processMatrixBinaryOp(lhs, rhs, opcode, sourceRange);
  3980. }
  3981. // Comma operator works differently from other binary operations as there is
  3982. // no SPIR-V instruction for it. For each comma, we must evaluate lhs and rhs
  3983. // respectively, and return the results of rhs.
  3984. if (opcode == BO_Comma) {
  3985. (void)doExpr(lhs);
  3986. return doExpr(rhs);
  3987. }
  3988. const spv::Op spvOp = (mandateGenOpcode == spv::Op::Max)
  3989. ? translateOp(opcode, lhs->getType())
  3990. : mandateGenOpcode;
  3991. SpirvEvalInfo rhsVal = 0, lhsPtr = 0, lhsVal = 0;
  3992. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  3993. // Evalute rhs before lhs
  3994. rhsVal = loadIfGLValue(rhs);
  3995. lhsVal = lhsPtr = doExpr(lhs);
  3996. // This is a compound assignment. We need to load the lhs value if lhs
  3997. // is not already rvalue and does not generate a vector shuffle.
  3998. if (!lhsPtr.isRValue() && !isVectorShuffle(lhs)) {
  3999. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4000. }
  4001. } else {
  4002. // Evalute lhs before rhs
  4003. lhsPtr = doExpr(lhs);
  4004. lhsVal = loadIfGLValue(lhs, lhsPtr);
  4005. rhsVal = loadIfGLValue(rhs);
  4006. }
  4007. if (lhsInfo)
  4008. *lhsInfo = lhsPtr;
  4009. switch (opcode) {
  4010. case BO_Add:
  4011. case BO_Sub:
  4012. case BO_Mul:
  4013. case BO_Div:
  4014. case BO_Rem:
  4015. case BO_LT:
  4016. case BO_LE:
  4017. case BO_GT:
  4018. case BO_GE:
  4019. case BO_EQ:
  4020. case BO_NE:
  4021. case BO_And:
  4022. case BO_Or:
  4023. case BO_Xor:
  4024. case BO_Shl:
  4025. case BO_Shr:
  4026. case BO_LAnd:
  4027. case BO_LOr:
  4028. case BO_AddAssign:
  4029. case BO_SubAssign:
  4030. case BO_MulAssign:
  4031. case BO_DivAssign:
  4032. case BO_RemAssign:
  4033. case BO_AndAssign:
  4034. case BO_OrAssign:
  4035. case BO_XorAssign:
  4036. case BO_ShlAssign:
  4037. case BO_ShrAssign: {
  4038. // To evaluate this expression as an OpSpecConstantOp, we need to make sure
  4039. // both operands are constant and at least one of them is a spec constant.
  4040. if (lhsVal.isConstant() && rhsVal.isConstant() &&
  4041. (lhsVal.isSpecConstant() || rhsVal.isSpecConstant()) &&
  4042. isAcceptedSpecConstantBinaryOp(spvOp)) {
  4043. const auto valId = theBuilder.createSpecConstantBinaryOp(
  4044. spvOp, resultTypeId, lhsVal, rhsVal);
  4045. return SpirvEvalInfo(valId).setRValue().setSpecConstant();
  4046. }
  4047. // Normal binary operation
  4048. const auto valId =
  4049. theBuilder.createBinaryOp(spvOp, resultTypeId, lhsVal, rhsVal);
  4050. auto result = SpirvEvalInfo(valId).setRValue();
  4051. if (lhsVal.isRelaxedPrecision() || rhsVal.isRelaxedPrecision())
  4052. result.setRelaxedPrecision();
  4053. return result;
  4054. }
  4055. case BO_Assign:
  4056. llvm_unreachable("assignment should not be handled here");
  4057. }
  4058. emitError("binary operator '%0' unimplemented", lhs->getExprLoc())
  4059. << BinaryOperator::getOpcodeStr(opcode) << sourceRange;
  4060. return 0;
  4061. }
  4062. void SPIRVEmitter::initOnce(QualType varType, std::string varName,
  4063. uint32_t varPtr, const Expr *varInit) {
  4064. const uint32_t boolType = theBuilder.getBoolType();
  4065. varName = "init.done." + varName;
  4066. // Create a file/module visible variable to hold the initialization state.
  4067. const uint32_t initDoneVar =
  4068. theBuilder.addModuleVar(boolType, spv::StorageClass::Private, varName,
  4069. theBuilder.getConstantBool(false));
  4070. const uint32_t condition = theBuilder.createLoad(boolType, initDoneVar);
  4071. const uint32_t todoBB = theBuilder.createBasicBlock("if.init.todo");
  4072. const uint32_t doneBB = theBuilder.createBasicBlock("if.init.done");
  4073. // If initDoneVar contains true, we jump to the "done" basic block; otherwise,
  4074. // jump to the "todo" basic block.
  4075. theBuilder.createConditionalBranch(condition, doneBB, todoBB, doneBB);
  4076. theBuilder.addSuccessor(todoBB);
  4077. theBuilder.addSuccessor(doneBB);
  4078. theBuilder.setMergeTarget(doneBB);
  4079. theBuilder.setInsertPoint(todoBB);
  4080. // Do initialization and mark done
  4081. if (varInit) {
  4082. storeValue(
  4083. // Static function variable are of private storage class
  4084. SpirvEvalInfo(varPtr).setStorageClass(spv::StorageClass::Private),
  4085. doExpr(varInit), varInit->getType());
  4086. } else {
  4087. const auto typeId = typeTranslator.translateType(varType);
  4088. theBuilder.createStore(varPtr, theBuilder.getConstantNull(typeId));
  4089. }
  4090. theBuilder.createStore(initDoneVar, theBuilder.getConstantBool(true));
  4091. theBuilder.createBranch(doneBB);
  4092. theBuilder.addSuccessor(doneBB);
  4093. theBuilder.setInsertPoint(doneBB);
  4094. }
  4095. bool SPIRVEmitter::isVectorShuffle(const Expr *expr) {
  4096. // TODO: the following check is essentially duplicated from
  4097. // doHLSLVectorElementExpr. Should unify them.
  4098. if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
  4099. const Expr *base = nullptr;
  4100. hlsl::VectorMemberAccessPositions accessor;
  4101. condenseVectorElementExpr(vecElemExpr, &base, &accessor);
  4102. const auto accessorSize = accessor.Count;
  4103. if (accessorSize == 1) {
  4104. // Selecting only one element. OpAccessChain or OpCompositeExtract for
  4105. // such cases.
  4106. return false;
  4107. }
  4108. const auto baseSize = hlsl::GetHLSLVecSize(base->getType());
  4109. if (accessorSize != baseSize)
  4110. return true;
  4111. for (uint32_t i = 0; i < accessorSize; ++i) {
  4112. uint32_t position;
  4113. accessor.GetPosition(i, &position);
  4114. if (position != i)
  4115. return true;
  4116. }
  4117. // Selecting exactly the original vector. No vector shuffle generated.
  4118. return false;
  4119. }
  4120. return false;
  4121. }
  4122. bool SPIRVEmitter::isTextureMipsSampleIndexing(const CXXOperatorCallExpr *expr,
  4123. const Expr **base,
  4124. const Expr **location,
  4125. const Expr **lod) {
  4126. if (!expr)
  4127. return false;
  4128. // <object>.mips[][] consists of an outer operator[] and an inner operator[]
  4129. const CXXOperatorCallExpr *outerExpr = expr;
  4130. if (outerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4131. return false;
  4132. const Expr *arg0 = outerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4133. const CXXOperatorCallExpr *innerExpr = dyn_cast<CXXOperatorCallExpr>(arg0);
  4134. // Must have an inner operator[]
  4135. if (!innerExpr ||
  4136. innerExpr->getOperator() != OverloadedOperatorKind::OO_Subscript) {
  4137. return false;
  4138. }
  4139. const Expr *innerArg0 =
  4140. innerExpr->getArg(0)->IgnoreParenNoopCasts(astContext);
  4141. const MemberExpr *memberExpr = dyn_cast<MemberExpr>(innerArg0);
  4142. if (!memberExpr)
  4143. return false;
  4144. // Must be accessing the member named "mips" or "sample"
  4145. const auto &memberName =
  4146. memberExpr->getMemberNameInfo().getName().getAsString();
  4147. if (memberName != "mips" && memberName != "sample")
  4148. return false;
  4149. const Expr *object = memberExpr->getBase();
  4150. const auto objectType = object->getType();
  4151. if (!TypeTranslator::isTexture(objectType))
  4152. return false;
  4153. if (base)
  4154. *base = object;
  4155. if (lod)
  4156. *lod = innerExpr->getArg(1);
  4157. if (location)
  4158. *location = outerExpr->getArg(1);
  4159. return true;
  4160. }
  4161. bool SPIRVEmitter::isBufferTextureIndexing(const CXXOperatorCallExpr *indexExpr,
  4162. const Expr **base,
  4163. const Expr **index) {
  4164. if (!indexExpr)
  4165. return false;
  4166. // Must be operator[]
  4167. if (indexExpr->getOperator() != OverloadedOperatorKind::OO_Subscript)
  4168. return false;
  4169. const Expr *object = indexExpr->getArg(0);
  4170. const auto objectType = object->getType();
  4171. if (TypeTranslator::isBuffer(objectType) ||
  4172. TypeTranslator::isRWBuffer(objectType) ||
  4173. TypeTranslator::isTexture(objectType) ||
  4174. TypeTranslator::isRWTexture(objectType)) {
  4175. if (base)
  4176. *base = object;
  4177. if (index)
  4178. *index = indexExpr->getArg(1);
  4179. return true;
  4180. }
  4181. return false;
  4182. }
  4183. void SPIRVEmitter::condenseVectorElementExpr(
  4184. const HLSLVectorElementExpr *expr, const Expr **basePtr,
  4185. hlsl::VectorMemberAccessPositions *flattenedAccessor) {
  4186. llvm::SmallVector<hlsl::VectorMemberAccessPositions, 2> accessors;
  4187. accessors.push_back(expr->getEncodedElementAccess());
  4188. // Recursively descending until we find the true base vector. In the
  4189. // meanwhile, collecting accessors in the reverse order.
  4190. *basePtr = expr->getBase();
  4191. while (const auto *vecElemBase = dyn_cast<HLSLVectorElementExpr>(*basePtr)) {
  4192. accessors.push_back(vecElemBase->getEncodedElementAccess());
  4193. *basePtr = vecElemBase->getBase();
  4194. }
  4195. *flattenedAccessor = accessors.back();
  4196. for (int32_t i = accessors.size() - 2; i >= 0; --i) {
  4197. const auto &currentAccessor = accessors[i];
  4198. // Apply the current level of accessor to the flattened accessor of all
  4199. // previous levels of ones.
  4200. hlsl::VectorMemberAccessPositions combinedAccessor;
  4201. for (uint32_t j = 0; j < currentAccessor.Count; ++j) {
  4202. uint32_t currentPosition = 0;
  4203. currentAccessor.GetPosition(j, &currentPosition);
  4204. uint32_t previousPosition = 0;
  4205. flattenedAccessor->GetPosition(currentPosition, &previousPosition);
  4206. combinedAccessor.SetPosition(j, previousPosition);
  4207. }
  4208. combinedAccessor.Count = currentAccessor.Count;
  4209. combinedAccessor.IsValid =
  4210. flattenedAccessor->IsValid && currentAccessor.IsValid;
  4211. *flattenedAccessor = combinedAccessor;
  4212. }
  4213. }
  4214. SpirvEvalInfo SPIRVEmitter::createVectorSplat(const Expr *scalarExpr,
  4215. uint32_t size) {
  4216. bool isConstVal = false;
  4217. SpirvEvalInfo scalarVal = 0;
  4218. // Try to evaluate the element as constant first. If successful, then we
  4219. // can generate constant instructions for this vector splat.
  4220. if (scalarVal = tryToEvaluateAsConst(scalarExpr)) {
  4221. isConstVal = true;
  4222. } else {
  4223. scalarVal = doExpr(scalarExpr);
  4224. }
  4225. if (size == 1) {
  4226. // Just return the scalar value for vector splat with size 1.
  4227. // Note that can be used as an lvalue, so we need to carry over
  4228. // the lvalueness for non-constant cases.
  4229. return isConstVal ? scalarVal.setConstant().setRValue() : scalarVal;
  4230. }
  4231. const uint32_t vecType = theBuilder.getVecType(
  4232. typeTranslator.translateType(scalarExpr->getType()), size);
  4233. llvm::SmallVector<uint32_t, 4> elements(size_t(size), scalarVal);
  4234. // TODO: we are saying the constant has Function storage class here.
  4235. // Should find a more meaningful one.
  4236. if (isConstVal) {
  4237. const auto valueId = theBuilder.getConstantComposite(vecType, elements);
  4238. return SpirvEvalInfo(valueId).setConstant().setRValue();
  4239. } else {
  4240. const auto valueId = theBuilder.createCompositeConstruct(vecType, elements);
  4241. return SpirvEvalInfo(valueId).setRValue();
  4242. }
  4243. }
  4244. void SPIRVEmitter::splitVecLastElement(QualType vecType, uint32_t vec,
  4245. uint32_t *residual,
  4246. uint32_t *lastElement) {
  4247. assert(hlsl::IsHLSLVecType(vecType));
  4248. const uint32_t count = hlsl::GetHLSLVecSize(vecType);
  4249. assert(count > 1);
  4250. const uint32_t elemTypeId =
  4251. typeTranslator.translateType(hlsl::GetHLSLVecElementType(vecType));
  4252. if (count == 2) {
  4253. *residual = theBuilder.createCompositeExtract(elemTypeId, vec, 0);
  4254. } else {
  4255. llvm::SmallVector<uint32_t, 4> indices;
  4256. for (uint32_t i = 0; i < count - 1; ++i)
  4257. indices.push_back(i);
  4258. const uint32_t typeId = theBuilder.getVecType(elemTypeId, count - 1);
  4259. *residual = theBuilder.createVectorShuffle(typeId, vec, vec, indices);
  4260. }
  4261. *lastElement =
  4262. theBuilder.createCompositeExtract(elemTypeId, vec, {count - 1});
  4263. }
  4264. SpirvEvalInfo
  4265. SPIRVEmitter::tryToGenFloatVectorScale(const BinaryOperator *expr) {
  4266. const QualType type = expr->getType();
  4267. const SourceRange range = expr->getSourceRange();
  4268. // We can only translate floatN * float into OpVectorTimesScalar.
  4269. // So the result type must be floatN.
  4270. if (!hlsl::IsHLSLVecType(type) ||
  4271. !hlsl::GetHLSLVecElementType(type)->isFloatingType())
  4272. return 0;
  4273. const Expr *lhs = expr->getLHS();
  4274. const Expr *rhs = expr->getRHS();
  4275. // Multiplying a float vector with a float scalar will be represented in
  4276. // AST via a binary operation with two float vectors as operands; one of
  4277. // the operand is from an implicit cast with kind CK_HLSLVectorSplat.
  4278. // vector * scalar
  4279. if (hlsl::IsHLSLVecType(lhs->getType())) {
  4280. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4281. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4282. const QualType vecType = expr->getType();
  4283. if (isa<CompoundAssignOperator>(expr)) {
  4284. SpirvEvalInfo lhsPtr = 0;
  4285. const auto result = processBinaryOp(
  4286. lhs, cast->getSubExpr(), expr->getOpcode(), vecType, range,
  4287. &lhsPtr, spv::Op::OpVectorTimesScalar);
  4288. return processAssignment(lhs, result, true, lhsPtr);
  4289. } else {
  4290. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4291. vecType, range, nullptr,
  4292. spv::Op::OpVectorTimesScalar);
  4293. }
  4294. }
  4295. }
  4296. }
  4297. // scalar * vector
  4298. if (hlsl::IsHLSLVecType(rhs->getType())) {
  4299. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4300. if (cast->getCastKind() == CK_HLSLVectorSplat) {
  4301. const QualType vecType = expr->getType();
  4302. // We need to switch the positions of lhs and rhs here because
  4303. // OpVectorTimesScalar requires the first operand to be a vector and
  4304. // the second to be a scalar.
  4305. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4306. vecType, range, nullptr,
  4307. spv::Op::OpVectorTimesScalar);
  4308. }
  4309. }
  4310. }
  4311. return 0;
  4312. }
  4313. SpirvEvalInfo
  4314. SPIRVEmitter::tryToGenFloatMatrixScale(const BinaryOperator *expr) {
  4315. const QualType type = expr->getType();
  4316. const SourceRange range = expr->getSourceRange();
  4317. // We can only translate floatMxN * float into OpMatrixTimesScalar.
  4318. // So the result type must be floatMxN.
  4319. if (!hlsl::IsHLSLMatType(type) ||
  4320. !hlsl::GetHLSLMatElementType(type)->isFloatingType())
  4321. return 0;
  4322. const Expr *lhs = expr->getLHS();
  4323. const Expr *rhs = expr->getRHS();
  4324. const QualType lhsType = lhs->getType();
  4325. const QualType rhsType = rhs->getType();
  4326. const auto selectOpcode = [](const QualType ty) {
  4327. return TypeTranslator::isMx1Matrix(ty) || TypeTranslator::is1xNMatrix(ty)
  4328. ? spv::Op::OpVectorTimesScalar
  4329. : spv::Op::OpMatrixTimesScalar;
  4330. };
  4331. // Multiplying a float matrix with a float scalar will be represented in
  4332. // AST via a binary operation with two float matrices as operands; one of
  4333. // the operand is from an implicit cast with kind CK_HLSLMatrixSplat.
  4334. // matrix * scalar
  4335. if (hlsl::IsHLSLMatType(lhsType)) {
  4336. if (const auto *cast = dyn_cast<ImplicitCastExpr>(rhs)) {
  4337. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4338. const QualType matType = expr->getType();
  4339. const spv::Op opcode = selectOpcode(lhsType);
  4340. if (isa<CompoundAssignOperator>(expr)) {
  4341. SpirvEvalInfo lhsPtr = 0;
  4342. const auto result =
  4343. processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4344. matType, range, &lhsPtr, opcode);
  4345. return processAssignment(lhs, result, true, lhsPtr);
  4346. } else {
  4347. return processBinaryOp(lhs, cast->getSubExpr(), expr->getOpcode(),
  4348. matType, range, nullptr, opcode);
  4349. }
  4350. }
  4351. }
  4352. }
  4353. // scalar * matrix
  4354. if (hlsl::IsHLSLMatType(rhsType)) {
  4355. if (const auto *cast = dyn_cast<ImplicitCastExpr>(lhs)) {
  4356. if (cast->getCastKind() == CK_HLSLMatrixSplat) {
  4357. const QualType matType = expr->getType();
  4358. const spv::Op opcode = selectOpcode(rhsType);
  4359. // We need to switch the positions of lhs and rhs here because
  4360. // OpMatrixTimesScalar requires the first operand to be a matrix and
  4361. // the second to be a scalar.
  4362. return processBinaryOp(rhs, cast->getSubExpr(), expr->getOpcode(),
  4363. matType, range, nullptr, opcode);
  4364. }
  4365. }
  4366. }
  4367. return 0;
  4368. }
  4369. SpirvEvalInfo
  4370. SPIRVEmitter::tryToAssignToVectorElements(const Expr *lhs,
  4371. const SpirvEvalInfo &rhs) {
  4372. // Assigning to a vector swizzling lhs is tricky if we are neither
  4373. // writing to one element nor all elements in their original order.
  4374. // Under such cases, we need to create a new vector swizzling involving
  4375. // both the lhs and rhs vectors and then write the result of this swizzling
  4376. // into the base vector of lhs.
  4377. // For example, for vec4.yz = vec2, we nee to do the following:
  4378. //
  4379. // %vec4Val = OpLoad %v4float %vec4
  4380. // %vec2Val = OpLoad %v2float %vec2
  4381. // %shuffle = OpVectorShuffle %v4float %vec4Val %vec2Val 0 4 5 3
  4382. // OpStore %vec4 %shuffle
  4383. //
  4384. // When doing the vector shuffle, we use the lhs base vector as the first
  4385. // vector and the rhs vector as the second vector. Therefore, all elements
  4386. // in the second vector will be selected into the shuffle result.
  4387. const auto *lhsExpr = dyn_cast<HLSLVectorElementExpr>(lhs);
  4388. if (!lhsExpr)
  4389. return 0;
  4390. // Special case for <scalar-value>.x, which will have an AST of
  4391. // HLSLVectorElementExpr whose base is an ImplicitCastExpr
  4392. // (CK_HLSLVectorSplat). We just need to assign to <scalar-value>
  4393. // for such case.
  4394. if (const auto *baseCast = dyn_cast<CastExpr>(lhsExpr->getBase()))
  4395. if (baseCast->getCastKind() == CastKind::CK_HLSLVectorSplat &&
  4396. hlsl::GetHLSLVecSize(baseCast->getType()) == 1)
  4397. return processAssignment(baseCast->getSubExpr(), rhs, false);
  4398. const Expr *base = nullptr;
  4399. hlsl::VectorMemberAccessPositions accessor;
  4400. condenseVectorElementExpr(lhsExpr, &base, &accessor);
  4401. const QualType baseType = base->getType();
  4402. assert(hlsl::IsHLSLVecType(baseType));
  4403. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  4404. const auto baseSize = hlsl::GetHLSLVecSize(baseType);
  4405. const auto accessorSize = accessor.Count;
  4406. // Whether selecting the whole original vector
  4407. bool isSelectOrigin = accessorSize == baseSize;
  4408. // Assigning to one component
  4409. if (accessorSize == 1) {
  4410. if (isBufferTextureIndexing(dyn_cast_or_null<CXXOperatorCallExpr>(base))) {
  4411. // Assigning to one component of a RWBuffer/RWTexture element
  4412. // We need to use OpImageWrite here.
  4413. // Compose the new vector value first
  4414. const uint32_t oldVec = doExpr(base);
  4415. const uint32_t newVec = theBuilder.createCompositeInsert(
  4416. baseTypeId, oldVec, {accessor.Swz0}, rhs);
  4417. const auto result = tryToAssignToRWBufferRWTexture(base, newVec);
  4418. assert(result); // Definitely RWBuffer/RWTexture assignment
  4419. return rhs; // TODO: incorrect for compound assignments
  4420. } else {
  4421. // Assigning to one normal vector component. Nothing special, just fall
  4422. // back to the normal CodeGen path.
  4423. return 0;
  4424. }
  4425. }
  4426. if (isSelectOrigin) {
  4427. for (uint32_t i = 0; i < accessorSize; ++i) {
  4428. uint32_t position;
  4429. accessor.GetPosition(i, &position);
  4430. if (position != i)
  4431. isSelectOrigin = false;
  4432. }
  4433. }
  4434. // Assigning to the original vector
  4435. if (isSelectOrigin) {
  4436. // Ignore this HLSLVectorElementExpr and dispatch to base
  4437. return processAssignment(base, rhs, false);
  4438. }
  4439. llvm::SmallVector<uint32_t, 4> selectors;
  4440. selectors.resize(baseSize);
  4441. // Assume we are selecting all original elements first.
  4442. for (uint32_t i = 0; i < baseSize; ++i) {
  4443. selectors[i] = i;
  4444. }
  4445. // Now fix up the elements that actually got overwritten by the rhs vector.
  4446. // Since we are using the rhs vector as the second vector, their index
  4447. // should be offset'ed by the size of the lhs base vector.
  4448. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4449. uint32_t position;
  4450. accessor.GetPosition(i, &position);
  4451. selectors[position] = baseSize + i;
  4452. }
  4453. const auto vec1 = doExpr(base);
  4454. const uint32_t vec1Val =
  4455. vec1.isRValue() ? vec1 : theBuilder.createLoad(baseTypeId, vec1);
  4456. const uint32_t shuffle =
  4457. theBuilder.createVectorShuffle(baseTypeId, vec1Val, rhs, selectors);
  4458. if (!tryToAssignToRWBufferRWTexture(base, shuffle))
  4459. theBuilder.createStore(vec1, shuffle);
  4460. // TODO: OK, this return value is incorrect for compound assignments, for
  4461. // which cases we should return lvalues. Should at least emit errors if
  4462. // this return value is used (can be checked via ASTContext.getParents).
  4463. return rhs;
  4464. }
  4465. SpirvEvalInfo
  4466. SPIRVEmitter::tryToAssignToRWBufferRWTexture(const Expr *lhs,
  4467. const SpirvEvalInfo &rhs) {
  4468. const Expr *baseExpr = nullptr;
  4469. const Expr *indexExpr = nullptr;
  4470. const auto lhsExpr = dyn_cast<CXXOperatorCallExpr>(lhs);
  4471. if (isBufferTextureIndexing(lhsExpr, &baseExpr, &indexExpr)) {
  4472. const uint32_t locId = doExpr(indexExpr);
  4473. const QualType imageType = baseExpr->getType();
  4474. const uint32_t imageId = theBuilder.createLoad(
  4475. typeTranslator.translateType(imageType), doExpr(baseExpr));
  4476. theBuilder.createImageWrite(imageType, imageId, locId, rhs);
  4477. return rhs;
  4478. }
  4479. return 0;
  4480. }
  4481. SpirvEvalInfo
  4482. SPIRVEmitter::tryToAssignToMatrixElements(const Expr *lhs,
  4483. const SpirvEvalInfo &rhs) {
  4484. const auto *lhsExpr = dyn_cast<ExtMatrixElementExpr>(lhs);
  4485. if (!lhsExpr)
  4486. return 0;
  4487. const Expr *baseMat = lhsExpr->getBase();
  4488. const auto base = doExpr(baseMat);
  4489. const QualType elemType = hlsl::GetHLSLMatElementType(baseMat->getType());
  4490. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  4491. uint32_t rowCount = 0, colCount = 0;
  4492. hlsl::GetHLSLMatRowColCount(baseMat->getType(), rowCount, colCount);
  4493. // For each lhs element written to:
  4494. // 1. Extract the corresponding rhs element using OpCompositeExtract
  4495. // 2. Create access chain for the lhs element using OpAccessChain
  4496. // 3. Write using OpStore
  4497. const auto accessor = lhsExpr->getEncodedElementAccess();
  4498. for (uint32_t i = 0; i < accessor.Count; ++i) {
  4499. uint32_t row = 0, col = 0;
  4500. accessor.GetPosition(i, &row, &col);
  4501. llvm::SmallVector<uint32_t, 2> indices;
  4502. // If the matrix only have one row/column, we are indexing into a vector
  4503. // then. Only one index is needed for such cases.
  4504. if (rowCount > 1)
  4505. indices.push_back(row);
  4506. if (colCount > 1)
  4507. indices.push_back(col);
  4508. for (uint32_t i = 0; i < indices.size(); ++i)
  4509. indices[i] = theBuilder.getConstantInt32(indices[i]);
  4510. // If we are writing to only one element, the rhs should already be a
  4511. // scalar value.
  4512. uint32_t rhsElem = rhs;
  4513. if (accessor.Count > 1)
  4514. rhsElem = theBuilder.createCompositeExtract(elemTypeId, rhs, {i});
  4515. const uint32_t ptrType =
  4516. theBuilder.getPointerType(elemTypeId, base.getStorageClass());
  4517. // If the lhs is actually a matrix of size 1x1, we don't need the access
  4518. // chain. base is already the dest pointer.
  4519. uint32_t lhsElemPtr = base;
  4520. if (!indices.empty()) {
  4521. assert(!base.isRValue());
  4522. // Load the element via access chain
  4523. lhsElemPtr = theBuilder.createAccessChain(ptrType, lhsElemPtr, indices);
  4524. }
  4525. theBuilder.createStore(lhsElemPtr, rhsElem);
  4526. }
  4527. // TODO: OK, this return value is incorrect for compound assignments, for
  4528. // which cases we should return lvalues. Should at least emit errors if
  4529. // this return value is used (can be checked via ASTContext.getParents).
  4530. return rhs;
  4531. }
  4532. SpirvEvalInfo SPIRVEmitter::processEachVectorInMatrix(
  4533. const Expr *matrix, const uint32_t matrixVal,
  4534. llvm::function_ref<uint32_t(uint32_t, uint32_t, uint32_t)>
  4535. actOnEachVector) {
  4536. const auto matType = matrix->getType();
  4537. assert(TypeTranslator::isSpirvAcceptableMatrixType(matType));
  4538. const uint32_t vecType = typeTranslator.getComponentVectorType(matType);
  4539. uint32_t rowCount = 0, colCount = 0;
  4540. hlsl::GetHLSLMatRowColCount(matType, rowCount, colCount);
  4541. llvm::SmallVector<uint32_t, 4> vectors;
  4542. // Extract each component vector and do operation on it
  4543. for (uint32_t i = 0; i < rowCount; ++i) {
  4544. const uint32_t lhsVec =
  4545. theBuilder.createCompositeExtract(vecType, matrixVal, {i});
  4546. vectors.push_back(actOnEachVector(i, vecType, lhsVec));
  4547. }
  4548. // Construct the result matrix
  4549. const auto valId = theBuilder.createCompositeConstruct(
  4550. typeTranslator.translateType(matType), vectors);
  4551. return SpirvEvalInfo(valId).setRValue();
  4552. }
  4553. void SPIRVEmitter::createSpecConstant(const VarDecl *varDecl) {
  4554. class SpecConstantEnvRAII {
  4555. public:
  4556. // Creates a new instance which sets mode to true on creation,
  4557. // and resets mode to false on destruction.
  4558. SpecConstantEnvRAII(bool *mode) : modeSlot(mode) { *modeSlot = true; }
  4559. ~SpecConstantEnvRAII() { *modeSlot = false; }
  4560. private:
  4561. bool *modeSlot;
  4562. };
  4563. const QualType varType = varDecl->getType();
  4564. bool hasError = false;
  4565. if (!varDecl->isExternallyVisible()) {
  4566. emitError("specialization constant must be externally visible",
  4567. varDecl->getLocation());
  4568. hasError = true;
  4569. }
  4570. if (const auto *builtinType = varType->getAs<BuiltinType>()) {
  4571. switch (builtinType->getKind()) {
  4572. case BuiltinType::Bool:
  4573. case BuiltinType::Int:
  4574. case BuiltinType::UInt:
  4575. case BuiltinType::Float:
  4576. break;
  4577. default:
  4578. emitError("unsupported specialization constant type",
  4579. varDecl->getLocStart());
  4580. hasError = true;
  4581. }
  4582. }
  4583. const auto *init = varDecl->getInit();
  4584. if (!init) {
  4585. emitError("missing default value for specialization constant",
  4586. varDecl->getLocation());
  4587. hasError = true;
  4588. } else if (!isAcceptedSpecConstantInit(init)) {
  4589. emitError("unsupported specialization constant initializer",
  4590. init->getLocStart())
  4591. << init->getSourceRange();
  4592. hasError = true;
  4593. }
  4594. if (hasError)
  4595. return;
  4596. SpecConstantEnvRAII specConstantEnvRAII(&isSpecConstantMode);
  4597. const auto specConstant = doExpr(init);
  4598. // We are not creating a variable to hold the spec constant, instead, we
  4599. // translate the varDecl directly into the spec constant here.
  4600. theBuilder.decorateSpecId(
  4601. specConstant, varDecl->getAttr<VKConstantIdAttr>()->getSpecConstId());
  4602. declIdMapper.registerSpecConstant(varDecl, specConstant);
  4603. }
  4604. SpirvEvalInfo
  4605. SPIRVEmitter::processMatrixBinaryOp(const Expr *lhs, const Expr *rhs,
  4606. const BinaryOperatorKind opcode,
  4607. SourceRange range) {
  4608. // TODO: some code are duplicated from processBinaryOp. Try to unify them.
  4609. const auto lhsType = lhs->getType();
  4610. assert(TypeTranslator::isSpirvAcceptableMatrixType(lhsType));
  4611. const spv::Op spvOp = translateOp(opcode, lhsType);
  4612. uint32_t rhsVal, lhsPtr, lhsVal;
  4613. if (BinaryOperator::isCompoundAssignmentOp(opcode)) {
  4614. // Evalute rhs before lhs
  4615. rhsVal = doExpr(rhs);
  4616. lhsPtr = doExpr(lhs);
  4617. const uint32_t lhsTy = typeTranslator.translateType(lhsType);
  4618. lhsVal = theBuilder.createLoad(lhsTy, lhsPtr);
  4619. } else {
  4620. // Evalute lhs before rhs
  4621. lhsVal = lhsPtr = doExpr(lhs);
  4622. rhsVal = doExpr(rhs);
  4623. }
  4624. switch (opcode) {
  4625. case BO_Add:
  4626. case BO_Sub:
  4627. case BO_Mul:
  4628. case BO_Div:
  4629. case BO_Rem:
  4630. case BO_AddAssign:
  4631. case BO_SubAssign:
  4632. case BO_MulAssign:
  4633. case BO_DivAssign:
  4634. case BO_RemAssign: {
  4635. const uint32_t vecType = typeTranslator.getComponentVectorType(lhsType);
  4636. const auto actOnEachVec = [this, spvOp, rhsVal](uint32_t index,
  4637. uint32_t vecType,
  4638. uint32_t lhsVec) {
  4639. // For each vector of lhs, we need to load the corresponding vector of
  4640. // rhs and do the operation on them.
  4641. const uint32_t rhsVec =
  4642. theBuilder.createCompositeExtract(vecType, rhsVal, {index});
  4643. const auto valId =
  4644. theBuilder.createBinaryOp(spvOp, vecType, lhsVec, rhsVec);
  4645. return SpirvEvalInfo(valId).setRValue();
  4646. };
  4647. return processEachVectorInMatrix(lhs, lhsVal, actOnEachVec);
  4648. }
  4649. case BO_Assign:
  4650. llvm_unreachable("assignment should not be handled here");
  4651. default:
  4652. break;
  4653. }
  4654. emitError("binary operator '%0' over matrix type unimplemented",
  4655. lhs->getExprLoc())
  4656. << BinaryOperator::getOpcodeStr(opcode) << range;
  4657. return 0;
  4658. }
  4659. const Expr *SPIRVEmitter::collectArrayStructIndices(
  4660. const Expr *expr, llvm::SmallVectorImpl<uint32_t> *indices, bool rawIndex) {
  4661. if (const auto *indexing = dyn_cast<MemberExpr>(expr)) {
  4662. // First check whether this is referring to a static member. If it is, we
  4663. // create a DeclRefExpr for it.
  4664. if (auto *varDecl = dyn_cast<VarDecl>(indexing->getMemberDecl()))
  4665. if (varDecl->isStaticDataMember())
  4666. return DeclRefExpr::Create(
  4667. astContext, NestedNameSpecifierLoc(), SourceLocation(), varDecl,
  4668. /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
  4669. varDecl->getType(), VK_LValue);
  4670. const Expr *base = collectArrayStructIndices(
  4671. indexing->getBase()->IgnoreParenNoopCasts(astContext), indices,
  4672. rawIndex);
  4673. // Append the index of the current level
  4674. const auto *fieldDecl = cast<FieldDecl>(indexing->getMemberDecl());
  4675. assert(fieldDecl);
  4676. const uint32_t index = fieldDecl->getFieldIndex();
  4677. indices->push_back(rawIndex ? index : theBuilder.getConstantInt32(index));
  4678. return base;
  4679. }
  4680. // Provide a hint to the TypeTranslator that the integer literal used to
  4681. // index into the following cases should be translated as a 32-bit integer.
  4682. TypeTranslator::LiteralTypeHint hint(typeTranslator, astContext.IntTy);
  4683. if (const auto *indexing = dyn_cast<ArraySubscriptExpr>(expr)) {
  4684. if (rawIndex)
  4685. return nullptr; // TODO: handle constant array index
  4686. // The base of an ArraySubscriptExpr has a wrapping LValueToRValue implicit
  4687. // cast. We need to ingore it to avoid creating OpLoad.
  4688. const Expr *thisBase = indexing->getBase()->IgnoreParenLValueCasts();
  4689. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  4690. indices->push_back(doExpr(indexing->getIdx()));
  4691. return base;
  4692. }
  4693. if (const auto *indexing = dyn_cast<CXXOperatorCallExpr>(expr))
  4694. if (indexing->getOperator() == OverloadedOperatorKind::OO_Subscript) {
  4695. if (rawIndex)
  4696. return nullptr; // TODO: handle constant array index
  4697. const Expr *thisBase =
  4698. indexing->getArg(0)->IgnoreParenNoopCasts(astContext);
  4699. const auto thisBaseType = thisBase->getType();
  4700. const Expr *base = collectArrayStructIndices(thisBase, indices, rawIndex);
  4701. if (thisBaseType != base->getType() &&
  4702. TypeTranslator::isAKindOfStructuredOrByteBuffer(thisBaseType)) {
  4703. // The immediate base is a kind of structured or byte buffer. It should
  4704. // be an alias variable. Break the normal index collecting chain.
  4705. // Return the immediate base as the base so that we can apply other
  4706. // hacks for legalization over it.
  4707. //
  4708. // Note: legalization specific code
  4709. indices->clear();
  4710. base = thisBase;
  4711. }
  4712. // If the base is a StructureType, we need to push an addtional index 0
  4713. // here. This is because we created an additional OpTypeRuntimeArray
  4714. // in the structure.
  4715. if (TypeTranslator::isStructuredBuffer(thisBaseType))
  4716. indices->push_back(theBuilder.getConstantInt32(0));
  4717. if ((hlsl::IsHLSLVecType(thisBaseType) &&
  4718. (hlsl::GetHLSLVecSize(thisBaseType) == 1)) ||
  4719. typeTranslator.is1x1Matrix(thisBaseType) ||
  4720. typeTranslator.is1xNMatrix(thisBaseType)) {
  4721. // If this is a size-1 vector or 1xN matrix, ignore the index.
  4722. } else {
  4723. indices->push_back(doExpr(indexing->getArg(1)));
  4724. }
  4725. return base;
  4726. }
  4727. {
  4728. const Expr *index = nullptr;
  4729. // TODO: the following is duplicating the logic in doCXXMemberCallExpr.
  4730. if (const auto *object = isStructuredBufferLoad(expr, &index)) {
  4731. if (rawIndex)
  4732. return nullptr; // TODO: handle constant array index
  4733. // For object.Load(index), there should be no more indexing into the
  4734. // object.
  4735. indices->push_back(theBuilder.getConstantInt32(0));
  4736. indices->push_back(doExpr(index));
  4737. return object;
  4738. }
  4739. }
  4740. // This the deepest we can go. No more array or struct indexing.
  4741. return expr;
  4742. }
  4743. SpirvEvalInfo &SPIRVEmitter::turnIntoElementPtr(
  4744. SpirvEvalInfo &info, QualType elemType,
  4745. const llvm::SmallVector<uint32_t, 4> &indices) {
  4746. assert(!info.isRValue());
  4747. const uint32_t ptrType = theBuilder.getPointerType(
  4748. typeTranslator.translateType(elemType, info.getLayoutRule()),
  4749. info.getStorageClass());
  4750. return info.setResultId(theBuilder.createAccessChain(ptrType, info, indices));
  4751. }
  4752. uint32_t SPIRVEmitter::castToBool(const uint32_t fromVal, QualType fromType,
  4753. QualType toBoolType) {
  4754. if (isSameScalarOrVecType(fromType, toBoolType))
  4755. return fromVal;
  4756. // Converting to bool means comparing with value zero.
  4757. const spv::Op spvOp = translateOp(BO_NE, fromType);
  4758. const uint32_t boolType = typeTranslator.translateType(toBoolType);
  4759. const uint32_t zeroVal = getValueZero(fromType);
  4760. return theBuilder.createBinaryOp(spvOp, boolType, fromVal, zeroVal);
  4761. }
  4762. uint32_t SPIRVEmitter::castToInt(const uint32_t fromVal, QualType fromType,
  4763. QualType toIntType, SourceLocation srcLoc) {
  4764. if (isSameScalarOrVecType(fromType, toIntType))
  4765. return fromVal;
  4766. uint32_t intType = typeTranslator.translateType(toIntType);
  4767. // AST may include a 'literal int' to 'int' conversion. No-op.
  4768. if (fromType->isSpecificBuiltinType(BuiltinType::LitInt) &&
  4769. toIntType->isIntegerType())
  4770. return fromVal;
  4771. if (isBoolOrVecOfBoolType(fromType)) {
  4772. const uint32_t one = getValueOne(toIntType);
  4773. const uint32_t zero = getValueZero(toIntType);
  4774. return theBuilder.createSelect(intType, fromVal, one, zero);
  4775. }
  4776. if (isSintOrVecOfSintType(fromType) || isUintOrVecOfUintType(fromType)) {
  4777. // TODO: handle different bitwidths
  4778. return theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, fromVal);
  4779. }
  4780. if (isFloatOrVecOfFloatType(fromType)) {
  4781. if (isSintOrVecOfSintType(toIntType)) {
  4782. return theBuilder.createUnaryOp(spv::Op::OpConvertFToS, intType, fromVal);
  4783. } else if (isUintOrVecOfUintType(toIntType)) {
  4784. return theBuilder.createUnaryOp(spv::Op::OpConvertFToU, intType, fromVal);
  4785. } else {
  4786. emitError("casting from floating point to integer unimplemented", srcLoc);
  4787. }
  4788. } else {
  4789. emitError("casting to integer unimplemented", srcLoc);
  4790. }
  4791. return 0;
  4792. }
  4793. uint32_t SPIRVEmitter::castToFloat(const uint32_t fromVal, QualType fromType,
  4794. QualType toFloatType,
  4795. SourceLocation srcLoc) {
  4796. if (isSameScalarOrVecType(fromType, toFloatType))
  4797. return fromVal;
  4798. const uint32_t floatType = typeTranslator.translateType(toFloatType);
  4799. // AST may include a 'literal float' to 'float' conversion. No-op.
  4800. if (fromType->isSpecificBuiltinType(BuiltinType::LitFloat) &&
  4801. toFloatType->isFloatingType())
  4802. return fromVal;
  4803. if (isBoolOrVecOfBoolType(fromType)) {
  4804. const uint32_t one = getValueOne(toFloatType);
  4805. const uint32_t zero = getValueZero(toFloatType);
  4806. return theBuilder.createSelect(floatType, fromVal, one, zero);
  4807. }
  4808. if (isSintOrVecOfSintType(fromType)) {
  4809. return theBuilder.createUnaryOp(spv::Op::OpConvertSToF, floatType, fromVal);
  4810. }
  4811. if (isUintOrVecOfUintType(fromType)) {
  4812. return theBuilder.createUnaryOp(spv::Op::OpConvertUToF, floatType, fromVal);
  4813. }
  4814. if (isFloatOrVecOfFloatType(fromType)) {
  4815. return theBuilder.createUnaryOp(spv::Op::OpFConvert, floatType, fromVal);
  4816. }
  4817. emitError("casting to floating point unimplemented", srcLoc);
  4818. return 0;
  4819. }
  4820. SpirvEvalInfo SPIRVEmitter::processIntrinsicCallExpr(const CallExpr *callExpr) {
  4821. const FunctionDecl *callee = callExpr->getDirectCallee();
  4822. assert(hlsl::IsIntrinsicOp(callee) &&
  4823. "doIntrinsicCallExpr was called for a non-intrinsic function.");
  4824. const bool isFloatType = isFloatOrVecMatOfFloatType(callExpr->getType());
  4825. const bool isSintType = isSintOrVecMatOfSintType(callExpr->getType());
  4826. // Figure out which intrinsic function to translate.
  4827. llvm::StringRef group;
  4828. uint32_t opcode = static_cast<uint32_t>(hlsl::IntrinsicOp::Num_Intrinsics);
  4829. hlsl::GetIntrinsicOp(callee, opcode, group);
  4830. GLSLstd450 glslOpcode = GLSLstd450Bad;
  4831. uint32_t retVal = 0;
  4832. #define INTRINSIC_SPIRV_OP_WITH_CAP_CASE(intrinsicOp, spirvOp, doEachVec, cap) \
  4833. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  4834. theBuilder.requireCapability(cap); \
  4835. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  4836. doEachVec); \
  4837. } break
  4838. #define INTRINSIC_SPIRV_OP_CASE(intrinsicOp, spirvOp, doEachVec) \
  4839. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  4840. retVal = processIntrinsicUsingSpirvInst(callExpr, spv::Op::Op##spirvOp, \
  4841. doEachVec); \
  4842. } break
  4843. #define INTRINSIC_OP_CASE(intrinsicOp, glslOp, doEachVec) \
  4844. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  4845. glslOpcode = GLSLstd450::GLSLstd450##glslOp; \
  4846. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  4847. } break
  4848. #define INTRINSIC_OP_CASE_INT_FLOAT(intrinsicOp, glslIntOp, glslFloatOp, \
  4849. doEachVec) \
  4850. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  4851. glslOpcode = isFloatType ? GLSLstd450::GLSLstd450##glslFloatOp \
  4852. : GLSLstd450::GLSLstd450##glslIntOp; \
  4853. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  4854. } break
  4855. #define INTRINSIC_OP_CASE_SINT_UINT(intrinsicOp, glslSintOp, glslUintOp, \
  4856. doEachVec) \
  4857. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  4858. glslOpcode = isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  4859. : GLSLstd450::GLSLstd450##glslUintOp; \
  4860. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  4861. } break
  4862. #define INTRINSIC_OP_CASE_SINT_UINT_FLOAT(intrinsicOp, glslSintOp, glslUintOp, \
  4863. glslFloatOp, doEachVec) \
  4864. case hlsl::IntrinsicOp::IOP_##intrinsicOp: { \
  4865. glslOpcode = isFloatType \
  4866. ? GLSLstd450::GLSLstd450##glslFloatOp \
  4867. : isSintType ? GLSLstd450::GLSLstd450##glslSintOp \
  4868. : GLSLstd450::GLSLstd450##glslUintOp; \
  4869. retVal = processIntrinsicUsingGLSLInst(callExpr, glslOpcode, doEachVec); \
  4870. } break
  4871. switch (const auto hlslOpcode = static_cast<hlsl::IntrinsicOp>(opcode)) {
  4872. case hlsl::IntrinsicOp::IOP_InterlockedAdd:
  4873. case hlsl::IntrinsicOp::IOP_InterlockedAnd:
  4874. case hlsl::IntrinsicOp::IOP_InterlockedMax:
  4875. case hlsl::IntrinsicOp::IOP_InterlockedUMax:
  4876. case hlsl::IntrinsicOp::IOP_InterlockedMin:
  4877. case hlsl::IntrinsicOp::IOP_InterlockedUMin:
  4878. case hlsl::IntrinsicOp::IOP_InterlockedOr:
  4879. case hlsl::IntrinsicOp::IOP_InterlockedXor:
  4880. case hlsl::IntrinsicOp::IOP_InterlockedExchange:
  4881. case hlsl::IntrinsicOp::IOP_InterlockedCompareStore:
  4882. case hlsl::IntrinsicOp::IOP_InterlockedCompareExchange:
  4883. retVal = processIntrinsicInterlockedMethod(callExpr, hlslOpcode);
  4884. break;
  4885. case hlsl::IntrinsicOp::IOP_tex1D:
  4886. case hlsl::IntrinsicOp::IOP_tex1Dbias:
  4887. case hlsl::IntrinsicOp::IOP_tex1Dgrad:
  4888. case hlsl::IntrinsicOp::IOP_tex1Dlod:
  4889. case hlsl::IntrinsicOp::IOP_tex1Dproj:
  4890. case hlsl::IntrinsicOp::IOP_tex2D:
  4891. case hlsl::IntrinsicOp::IOP_tex2Dbias:
  4892. case hlsl::IntrinsicOp::IOP_tex2Dgrad:
  4893. case hlsl::IntrinsicOp::IOP_tex2Dlod:
  4894. case hlsl::IntrinsicOp::IOP_tex2Dproj:
  4895. case hlsl::IntrinsicOp::IOP_tex3D:
  4896. case hlsl::IntrinsicOp::IOP_tex3Dbias:
  4897. case hlsl::IntrinsicOp::IOP_tex3Dgrad:
  4898. case hlsl::IntrinsicOp::IOP_tex3Dlod:
  4899. case hlsl::IntrinsicOp::IOP_tex3Dproj:
  4900. case hlsl::IntrinsicOp::IOP_texCUBE:
  4901. case hlsl::IntrinsicOp::IOP_texCUBEbias:
  4902. case hlsl::IntrinsicOp::IOP_texCUBEgrad:
  4903. case hlsl::IntrinsicOp::IOP_texCUBElod:
  4904. case hlsl::IntrinsicOp::IOP_texCUBEproj: {
  4905. emitError("deprecated %0 intrinsic function will not be supported",
  4906. callExpr->getExprLoc())
  4907. << callee->getName();
  4908. return 0;
  4909. }
  4910. case hlsl::IntrinsicOp::IOP_dot:
  4911. retVal = processIntrinsicDot(callExpr);
  4912. break;
  4913. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrier:
  4914. retVal = processIntrinsicMemoryBarrier(callExpr,
  4915. /*isDevice*/ false,
  4916. /*groupSync*/ false,
  4917. /*isAllBarrier*/ false);
  4918. break;
  4919. case hlsl::IntrinsicOp::IOP_GroupMemoryBarrierWithGroupSync:
  4920. retVal = processIntrinsicMemoryBarrier(callExpr,
  4921. /*isDevice*/ false,
  4922. /*groupSync*/ true,
  4923. /*isAllBarrier*/ false);
  4924. break;
  4925. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrier:
  4926. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  4927. /*groupSync*/ false,
  4928. /*isAllBarrier*/ false);
  4929. break;
  4930. case hlsl::IntrinsicOp::IOP_DeviceMemoryBarrierWithGroupSync:
  4931. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  4932. /*groupSync*/ true,
  4933. /*isAllBarrier*/ false);
  4934. break;
  4935. case hlsl::IntrinsicOp::IOP_AllMemoryBarrier:
  4936. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  4937. /*groupSync*/ false,
  4938. /*isAllBarrier*/ true);
  4939. break;
  4940. case hlsl::IntrinsicOp::IOP_AllMemoryBarrierWithGroupSync:
  4941. retVal = processIntrinsicMemoryBarrier(callExpr, /*isDevice*/ true,
  4942. /*groupSync*/ true,
  4943. /*isAllBarrier*/ true);
  4944. break;
  4945. case hlsl::IntrinsicOp::IOP_CheckAccessFullyMapped:
  4946. retVal =
  4947. theBuilder.createImageSparseTexelsResident(doExpr(callExpr->getArg(0)));
  4948. break;
  4949. case hlsl::IntrinsicOp::IOP_mul:
  4950. retVal = processIntrinsicMul(callExpr);
  4951. break;
  4952. case hlsl::IntrinsicOp::IOP_all:
  4953. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAll);
  4954. break;
  4955. case hlsl::IntrinsicOp::IOP_any:
  4956. retVal = processIntrinsicAllOrAny(callExpr, spv::Op::OpAny);
  4957. break;
  4958. case hlsl::IntrinsicOp::IOP_asdouble:
  4959. case hlsl::IntrinsicOp::IOP_asfloat:
  4960. case hlsl::IntrinsicOp::IOP_asint:
  4961. case hlsl::IntrinsicOp::IOP_asuint:
  4962. retVal = processIntrinsicAsType(callExpr);
  4963. break;
  4964. case hlsl::IntrinsicOp::IOP_clip:
  4965. retVal = processIntrinsicClip(callExpr);
  4966. break;
  4967. case hlsl::IntrinsicOp::IOP_dst:
  4968. retVal = processIntrinsicDst(callExpr);
  4969. break;
  4970. case hlsl::IntrinsicOp::IOP_clamp:
  4971. case hlsl::IntrinsicOp::IOP_uclamp:
  4972. retVal = processIntrinsicClamp(callExpr);
  4973. break;
  4974. case hlsl::IntrinsicOp::IOP_frexp:
  4975. retVal = processIntrinsicFrexp(callExpr);
  4976. break;
  4977. case hlsl::IntrinsicOp::IOP_ldexp:
  4978. retVal = processIntrinsicLdexp(callExpr);
  4979. break;
  4980. case hlsl::IntrinsicOp::IOP_lit:
  4981. retVal = processIntrinsicLit(callExpr);
  4982. break;
  4983. case hlsl::IntrinsicOp::IOP_modf:
  4984. retVal = processIntrinsicModf(callExpr);
  4985. break;
  4986. case hlsl::IntrinsicOp::IOP_msad4:
  4987. retVal = processIntrinsicMsad4(callExpr);
  4988. break;
  4989. case hlsl::IntrinsicOp::IOP_sign: {
  4990. if (isFloatOrVecMatOfFloatType(callExpr->getArg(0)->getType()))
  4991. retVal = processIntrinsicFloatSign(callExpr);
  4992. else
  4993. retVal =
  4994. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450SSign,
  4995. /*actPerRowForMatrices*/ true);
  4996. } break;
  4997. case hlsl::IntrinsicOp::IOP_D3DCOLORtoUBYTE4:
  4998. retVal = processD3DCOLORtoUBYTE4(callExpr);
  4999. break;
  5000. case hlsl::IntrinsicOp::IOP_isfinite:
  5001. retVal = processIntrinsicIsFinite(callExpr);
  5002. break;
  5003. case hlsl::IntrinsicOp::IOP_sincos:
  5004. retVal = processIntrinsicSinCos(callExpr);
  5005. break;
  5006. case hlsl::IntrinsicOp::IOP_rcp:
  5007. retVal = processIntrinsicRcp(callExpr);
  5008. break;
  5009. case hlsl::IntrinsicOp::IOP_saturate:
  5010. retVal = processIntrinsicSaturate(callExpr);
  5011. break;
  5012. case hlsl::IntrinsicOp::IOP_log10:
  5013. retVal = processIntrinsicLog10(callExpr);
  5014. break;
  5015. case hlsl::IntrinsicOp::IOP_f16tof32:
  5016. retVal = processIntrinsicF16ToF32(callExpr);
  5017. break;
  5018. case hlsl::IntrinsicOp::IOP_f32tof16:
  5019. retVal = processIntrinsicF32ToF16(callExpr);
  5020. break;
  5021. case hlsl::IntrinsicOp::IOP_abort:
  5022. case hlsl::IntrinsicOp::IOP_GetRenderTargetSampleCount:
  5023. case hlsl::IntrinsicOp::IOP_GetRenderTargetSamplePosition: {
  5024. emitError("no equivalent for %0 intrinsic function in Vulkan",
  5025. callExpr->getExprLoc())
  5026. << callee->getName();
  5027. return 0;
  5028. }
  5029. INTRINSIC_SPIRV_OP_CASE(transpose, Transpose, false);
  5030. INTRINSIC_SPIRV_OP_CASE(ddx, DPdx, true);
  5031. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_coarse, DPdxCoarse, false,
  5032. spv::Capability::DerivativeControl);
  5033. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddx_fine, DPdxFine, false,
  5034. spv::Capability::DerivativeControl);
  5035. INTRINSIC_SPIRV_OP_CASE(ddy, DPdy, true);
  5036. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_coarse, DPdyCoarse, false,
  5037. spv::Capability::DerivativeControl);
  5038. INTRINSIC_SPIRV_OP_WITH_CAP_CASE(ddy_fine, DPdyFine, false,
  5039. spv::Capability::DerivativeControl);
  5040. INTRINSIC_SPIRV_OP_CASE(countbits, BitCount, false);
  5041. INTRINSIC_SPIRV_OP_CASE(isinf, IsInf, true);
  5042. INTRINSIC_SPIRV_OP_CASE(isnan, IsNan, true);
  5043. INTRINSIC_SPIRV_OP_CASE(fmod, FMod, true);
  5044. INTRINSIC_SPIRV_OP_CASE(fwidth, Fwidth, true);
  5045. INTRINSIC_SPIRV_OP_CASE(reversebits, BitReverse, false);
  5046. INTRINSIC_OP_CASE(round, Round, true);
  5047. INTRINSIC_OP_CASE_INT_FLOAT(abs, SAbs, FAbs, true);
  5048. INTRINSIC_OP_CASE(acos, Acos, true);
  5049. INTRINSIC_OP_CASE(asin, Asin, true);
  5050. INTRINSIC_OP_CASE(atan, Atan, true);
  5051. INTRINSIC_OP_CASE(atan2, Atan2, true);
  5052. INTRINSIC_OP_CASE(ceil, Ceil, true);
  5053. INTRINSIC_OP_CASE(cos, Cos, true);
  5054. INTRINSIC_OP_CASE(cosh, Cosh, true);
  5055. INTRINSIC_OP_CASE(cross, Cross, false);
  5056. INTRINSIC_OP_CASE(degrees, Degrees, true);
  5057. INTRINSIC_OP_CASE(distance, Distance, false);
  5058. INTRINSIC_OP_CASE(determinant, Determinant, false);
  5059. INTRINSIC_OP_CASE(exp, Exp, true);
  5060. INTRINSIC_OP_CASE(exp2, Exp2, true);
  5061. INTRINSIC_OP_CASE_SINT_UINT(firstbithigh, FindSMsb, FindUMsb, false);
  5062. INTRINSIC_OP_CASE_SINT_UINT(ufirstbithigh, FindSMsb, FindUMsb, false);
  5063. INTRINSIC_OP_CASE(faceforward, FaceForward, false);
  5064. INTRINSIC_OP_CASE(firstbitlow, FindILsb, false);
  5065. INTRINSIC_OP_CASE(floor, Floor, true);
  5066. INTRINSIC_OP_CASE(fma, Fma, true);
  5067. INTRINSIC_OP_CASE(frac, Fract, true);
  5068. INTRINSIC_OP_CASE(length, Length, false);
  5069. INTRINSIC_OP_CASE(lerp, FMix, true);
  5070. INTRINSIC_OP_CASE(log, Log, true);
  5071. INTRINSIC_OP_CASE(log2, Log2, true);
  5072. INTRINSIC_OP_CASE(mad, Fma, true);
  5073. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(max, SMax, UMax, FMax, true);
  5074. INTRINSIC_OP_CASE(umax, UMax, true);
  5075. INTRINSIC_OP_CASE_SINT_UINT_FLOAT(min, SMin, UMin, FMin, true);
  5076. INTRINSIC_OP_CASE(umin, UMin, true);
  5077. INTRINSIC_OP_CASE(normalize, Normalize, false);
  5078. INTRINSIC_OP_CASE(pow, Pow, true);
  5079. INTRINSIC_OP_CASE(radians, Radians, true);
  5080. INTRINSIC_OP_CASE(reflect, Reflect, false);
  5081. INTRINSIC_OP_CASE(refract, Refract, false);
  5082. INTRINSIC_OP_CASE(rsqrt, InverseSqrt, true);
  5083. INTRINSIC_OP_CASE(smoothstep, SmoothStep, true);
  5084. INTRINSIC_OP_CASE(step, Step, true);
  5085. INTRINSIC_OP_CASE(sin, Sin, true);
  5086. INTRINSIC_OP_CASE(sinh, Sinh, true);
  5087. INTRINSIC_OP_CASE(tan, Tan, true);
  5088. INTRINSIC_OP_CASE(tanh, Tanh, true);
  5089. INTRINSIC_OP_CASE(sqrt, Sqrt, true);
  5090. INTRINSIC_OP_CASE(trunc, Trunc, true);
  5091. default:
  5092. emitError("%0 intrinsic function unimplemented", callExpr->getExprLoc())
  5093. << callee->getName();
  5094. return 0;
  5095. }
  5096. #undef INTRINSIC_OP_CASE
  5097. #undef INTRINSIC_OP_CASE_INT_FLOAT
  5098. return SpirvEvalInfo(retVal).setRValue();
  5099. }
  5100. uint32_t
  5101. SPIRVEmitter::processIntrinsicInterlockedMethod(const CallExpr *expr,
  5102. hlsl::IntrinsicOp opcode) {
  5103. // The signature of intrinsic atomic methods are:
  5104. // void Interlocked*(in R dest, in T value);
  5105. // void Interlocked*(in R dest, in T value, out T original_value);
  5106. // Note: ALL Interlocked*() methods are forced to have an unsigned integer
  5107. // 'value'. Meaning, T is forced to be 'unsigned int'. If the provided
  5108. // parameter is not an unsigned integer, the frontend inserts an
  5109. // 'ImplicitCastExpr' to convert it to unsigned integer. OpAtomicIAdd (and
  5110. // other SPIR-V OpAtomic* instructions) require that the pointee in 'dest' to
  5111. // be of the same type as T. This will result in an invalid SPIR-V if 'dest'
  5112. // is a signed integer typed resource such as RWTexture1D<int>. For example,
  5113. // the following OpAtomicIAdd is invalid because the pointee type defined in
  5114. // %1 is a signed integer, while the value passed to atomic add (%3) is an
  5115. // unsigned integer.
  5116. //
  5117. // %_ptr_Image_int = OpTypePointer Image %int
  5118. // %1 = OpImageTexelPointer %_ptr_Image_int %RWTexture1D_int %index %uint_0
  5119. // %2 = OpLoad %int %value
  5120. // %3 = OpBitcast %uint %2 <-------- Inserted by the frontend
  5121. // %4 = OpAtomicIAdd %int %1 %uint_1 %uint_0 %3
  5122. //
  5123. // In such cases, we bypass the forced IntegralCast.
  5124. // Moreover, the frontend does not add a cast AST node to cast uint to int
  5125. // where necessary. To ensure SPIR-V validity, we add that where necessary.
  5126. const uint32_t zero = theBuilder.getConstantUint32(0);
  5127. const uint32_t scope = theBuilder.getConstantUint32(1); // Device
  5128. const auto *dest = expr->getArg(0);
  5129. const auto baseType = dest->getType();
  5130. const uint32_t baseTypeId = typeTranslator.translateType(baseType);
  5131. const auto doArg = [baseType, this](const CallExpr *callExpr,
  5132. uint32_t argIndex) {
  5133. const Expr *valueExpr = callExpr->getArg(argIndex);
  5134. if (const auto *castExpr = dyn_cast<ImplicitCastExpr>(valueExpr))
  5135. if (castExpr->getCastKind() == CK_IntegralCast &&
  5136. castExpr->getSubExpr()->getType() == baseType)
  5137. valueExpr = castExpr->getSubExpr();
  5138. uint32_t argId = doExpr(valueExpr);
  5139. if (valueExpr->getType() != baseType)
  5140. argId = castToInt(argId, valueExpr->getType(), baseType,
  5141. valueExpr->getExprLoc());
  5142. return argId;
  5143. };
  5144. const auto writeToOutputArg = [&baseType, dest, this](
  5145. uint32_t toWrite, const CallExpr *callExpr,
  5146. uint32_t outputArgIndex) {
  5147. const auto outputArg = callExpr->getArg(outputArgIndex);
  5148. const auto outputArgType = outputArg->getType();
  5149. if (baseType != outputArgType)
  5150. toWrite = castToInt(toWrite, baseType, outputArgType, dest->getExprLoc());
  5151. theBuilder.createStore(doExpr(outputArg), toWrite);
  5152. };
  5153. // If the argument is indexing into a texture/buffer, we need to create an
  5154. // OpImageTexelPointer instruction.
  5155. uint32_t ptr = 0;
  5156. if (const auto *callExpr = dyn_cast<CXXOperatorCallExpr>(dest)) {
  5157. const Expr *base = nullptr;
  5158. const Expr *index = nullptr;
  5159. if (isBufferTextureIndexing(callExpr, &base, &index)) {
  5160. const auto ptrType =
  5161. theBuilder.getPointerType(baseTypeId, spv::StorageClass::Image);
  5162. const auto baseId = doExpr(base);
  5163. const auto coordId = doExpr(index);
  5164. ptr = theBuilder.createImageTexelPointer(ptrType, baseId, coordId, zero);
  5165. }
  5166. }
  5167. if (!ptr)
  5168. ptr = doExpr(dest);
  5169. const bool isCompareExchange =
  5170. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareExchange;
  5171. const bool isCompareStore =
  5172. opcode == hlsl::IntrinsicOp::IOP_InterlockedCompareStore;
  5173. if (isCompareExchange || isCompareStore) {
  5174. const uint32_t comparator = doArg(expr, 1);
  5175. const uint32_t valueId = doArg(expr, 2);
  5176. const uint32_t originalVal = theBuilder.createAtomicCompareExchange(
  5177. baseTypeId, ptr, scope, zero, zero, valueId, comparator);
  5178. if (isCompareExchange)
  5179. writeToOutputArg(originalVal, expr, 3);
  5180. } else {
  5181. const uint32_t valueId = doArg(expr, 1);
  5182. // Since these atomic operations write through the provided pointer, the
  5183. // signed vs. unsigned opcode must be decided based on the pointee type
  5184. // of the first argument. However, the frontend decides the opcode based on
  5185. // the second argument (value). Therefore, the HLSL opcode provided by the
  5186. // frontend may be wrong. Therefore we need the following code to make sure
  5187. // we are using the correct SPIR-V opcode.
  5188. spv::Op atomicOp = translateAtomicHlslOpcodeToSpirvOpcode(opcode);
  5189. if (atomicOp == spv::Op::OpAtomicUMax && baseType->isSignedIntegerType())
  5190. atomicOp = spv::Op::OpAtomicSMax;
  5191. if (atomicOp == spv::Op::OpAtomicSMax && baseType->isUnsignedIntegerType())
  5192. atomicOp = spv::Op::OpAtomicUMax;
  5193. if (atomicOp == spv::Op::OpAtomicUMin && baseType->isSignedIntegerType())
  5194. atomicOp = spv::Op::OpAtomicSMin;
  5195. if (atomicOp == spv::Op::OpAtomicSMin && baseType->isUnsignedIntegerType())
  5196. atomicOp = spv::Op::OpAtomicUMin;
  5197. const uint32_t originalVal = theBuilder.createAtomicOp(
  5198. atomicOp, baseTypeId, ptr, scope, zero, valueId);
  5199. if (expr->getNumArgs() > 2)
  5200. writeToOutputArg(originalVal, expr, 2);
  5201. }
  5202. return 0;
  5203. }
  5204. uint32_t SPIRVEmitter::processIntrinsicMsad4(const CallExpr *callExpr) {
  5205. emitWarning("msad4 intrinsic function is emulated using many SPIR-V "
  5206. "instructions due to lack of direct SPIR-V equivalent",
  5207. callExpr->getExprLoc());
  5208. // Compares a 4-byte reference value and an 8-byte source value and
  5209. // accumulates a vector of 4 sums. Each sum corresponds to the masked sum
  5210. // of absolute differences of a different byte alignment between the
  5211. // reference value and the source value.
  5212. // If we have:
  5213. // uint v0; // reference
  5214. // uint2 v1; // source
  5215. // uint4 v2; // accum
  5216. // uint4 o0; // result of msad4
  5217. // uint4 r0, t0; // temporary values
  5218. //
  5219. // Then msad4(v0, v1, v2) translates to the following SM5 assembly according
  5220. // to fxc:
  5221. // Step 1:
  5222. // ushr r0.xyz, v1.xxxx, l(8, 16, 24, 0)
  5223. // Step 2:
  5224. // [result], [ width ], [ offset ], [ insert ], [ base ]
  5225. // bfi t0.yzw, l(0, 8, 16, 24), l(0, 24, 16, 8), v1.yyyy , r0.xxyz
  5226. // mov t0.x, v1.x
  5227. // Step 3:
  5228. // msad o0.xyzw, v0.xxxx, t0.xyzw, v2.xyzw
  5229. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  5230. const auto boolType = theBuilder.getBoolType();
  5231. const auto intType = theBuilder.getInt32Type();
  5232. const auto uintType = theBuilder.getUint32Type();
  5233. const auto uint4Type = theBuilder.getVecType(uintType, 4);
  5234. const uint32_t reference = doExpr(callExpr->getArg(0));
  5235. const uint32_t source = doExpr(callExpr->getArg(1));
  5236. const uint32_t accum = doExpr(callExpr->getArg(2));
  5237. const auto uint0 = theBuilder.getConstantUint32(0);
  5238. const auto uint8 = theBuilder.getConstantUint32(8);
  5239. const auto uint16 = theBuilder.getConstantUint32(16);
  5240. const auto uint24 = theBuilder.getConstantUint32(24);
  5241. // Step 1.
  5242. const uint32_t v1x = theBuilder.createCompositeExtract(uintType, source, {0});
  5243. // r0.x = v1xS8 = v1.x shifted by 8 bits
  5244. uint32_t v1xS8 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5245. uintType, v1x, uint8);
  5246. // r0.y = v1xS16 = v1.x shifted by 16 bits
  5247. uint32_t v1xS16 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5248. uintType, v1x, uint16);
  5249. // r0.z = v1xS24 = v1.x shifted by 24 bits
  5250. uint32_t v1xS24 = theBuilder.createBinaryOp(spv::Op::OpShiftLeftLogical,
  5251. uintType, v1x, uint24);
  5252. // Step 2.
  5253. // Do bfi 3 times. DXIL bfi is equivalent to SPIR-V OpBitFieldInsert.
  5254. const uint32_t v1y = theBuilder.createCompositeExtract(uintType, source, {1});
  5255. // Note that t0.x = v1.x, nothing we need to do for that.
  5256. const uint32_t t0y =
  5257. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS8, /*insert*/ v1y,
  5258. /*offset*/ uint24,
  5259. /*width*/ uint8);
  5260. const uint32_t t0z =
  5261. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS16, /*insert*/ v1y,
  5262. /*offset*/ uint16,
  5263. /*width*/ uint16);
  5264. const uint32_t t0w =
  5265. theBuilder.createBitFieldInsert(uintType, /*base*/ v1xS24, /*insert*/ v1y,
  5266. /*offset*/ uint8,
  5267. /*width*/ uint24);
  5268. // Step 3. MSAD (Masked Sum of Absolute Differences)
  5269. // Now perform MSAD four times.
  5270. // Need to mimic this algorithm in SPIR-V!
  5271. //
  5272. // UINT msad( UINT ref, UINT src, UINT accum )
  5273. // {
  5274. // for (UINT i = 0; i < 4; i++)
  5275. // {
  5276. // BYTE refByte, srcByte, absDiff;
  5277. //
  5278. // refByte = (BYTE)(ref >> (i * 8));
  5279. // if (!refByte)
  5280. // {
  5281. // continue;
  5282. // }
  5283. //
  5284. // srcByte = (BYTE)(src >> (i * 8));
  5285. // if (refByte >= srcByte)
  5286. // {
  5287. // absDiff = refByte - srcByte;
  5288. // }
  5289. // else
  5290. // {
  5291. // absDiff = srcByte - refByte;
  5292. // }
  5293. //
  5294. // // The recommended overflow behavior for MSAD is
  5295. // // to do a 32-bit saturate. This is not
  5296. // // required, however, and wrapping is allowed.
  5297. // // So from an application point of view,
  5298. // // overflow behavior is undefined.
  5299. // if (UINT_MAX - accum < absDiff)
  5300. // {
  5301. // accum = UINT_MAX;
  5302. // break;
  5303. // }
  5304. // accum += absDiff;
  5305. // }
  5306. //
  5307. // return accum;
  5308. // }
  5309. llvm::SmallVector<uint32_t, 4> result;
  5310. const uint32_t accum0 =
  5311. theBuilder.createCompositeExtract(uintType, accum, {0});
  5312. const uint32_t accum1 =
  5313. theBuilder.createCompositeExtract(uintType, accum, {1});
  5314. const uint32_t accum2 =
  5315. theBuilder.createCompositeExtract(uintType, accum, {2});
  5316. const uint32_t accum3 =
  5317. theBuilder.createCompositeExtract(uintType, accum, {3});
  5318. const llvm::SmallVector<uint32_t, 4> sources = {v1x, t0y, t0z, t0w};
  5319. llvm::SmallVector<uint32_t, 4> accums = {accum0, accum1, accum2, accum3};
  5320. llvm::SmallVector<uint32_t, 4> refBytes;
  5321. llvm::SmallVector<uint32_t, 4> signedRefBytes;
  5322. llvm::SmallVector<uint32_t, 4> isRefByteZero;
  5323. for (uint32_t i = 0; i < 4; ++i) {
  5324. refBytes.push_back(theBuilder.createBitFieldExtract(
  5325. uintType, reference, /*offset*/ theBuilder.getConstantUint32(i * 8),
  5326. /*count*/ uint8, /*isSigned*/ false));
  5327. signedRefBytes.push_back(
  5328. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, refBytes.back()));
  5329. isRefByteZero.push_back(theBuilder.createBinaryOp(
  5330. spv::Op::OpIEqual, boolType, refBytes.back(), uint0));
  5331. }
  5332. for (uint32_t msadNum = 0; msadNum < 4; ++msadNum) {
  5333. for (uint32_t byteCount = 0; byteCount < 4; ++byteCount) {
  5334. // 'count' is always 8 because we are extracting 8 bits out of 32.
  5335. const uint32_t srcByte = theBuilder.createBitFieldExtract(
  5336. uintType, sources[msadNum],
  5337. /*offset*/ theBuilder.getConstantUint32(8 * byteCount),
  5338. /*count*/ uint8, /*isSigned*/ false);
  5339. const uint32_t signedSrcByte =
  5340. theBuilder.createUnaryOp(spv::Op::OpBitcast, intType, srcByte);
  5341. const uint32_t sub = theBuilder.createBinaryOp(
  5342. spv::Op::OpISub, intType, signedRefBytes[byteCount], signedSrcByte);
  5343. const uint32_t absSub = theBuilder.createExtInst(
  5344. intType, glsl, GLSLstd450::GLSLstd450SAbs, {sub});
  5345. const uint32_t diff = theBuilder.createSelect(
  5346. uintType, isRefByteZero[byteCount], uint0,
  5347. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintType, absSub));
  5348. // As pointed out by the DXIL reference above, it is *not* required to
  5349. // saturate the output to UINT_MAX in case of overflow. Wrapping around is
  5350. // also allowed. For simplicity, we will wrap around at this point.
  5351. accums[msadNum] = theBuilder.createBinaryOp(spv::Op::OpIAdd, uintType,
  5352. accums[msadNum], diff);
  5353. }
  5354. }
  5355. return theBuilder.createCompositeConstruct(uint4Type, accums);
  5356. }
  5357. uint32_t SPIRVEmitter::processIntrinsicModf(const CallExpr *callExpr) {
  5358. // Signature is: ret modf(x, ip)
  5359. // [in] x: the input floating-point value.
  5360. // [out] ip: the integer portion of x.
  5361. // [out] ret: the fractional portion of x.
  5362. // All of the above must be a scalar, vector, or matrix with the same
  5363. // component types. Component types can be float or int.
  5364. // The ModfStruct SPIR-V instruction returns a struct. The first member is the
  5365. // fractional part and the second member is the integer portion.
  5366. // ModfStruct {
  5367. // <scalar or vector of float> frac;
  5368. // <scalar or vector of float> ip;
  5369. // }
  5370. // Note if the input number (x) is not a float (i.e. 'x' is an int), it is
  5371. // automatically converted to float before modf is invoked. Sadly, the 'ip'
  5372. // argument is not treated the same way. Therefore, in such cases we'll have
  5373. // to manually convert the float result into int.
  5374. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  5375. const Expr *arg = callExpr->getArg(0);
  5376. const Expr *ipArg = callExpr->getArg(1);
  5377. const auto argType = arg->getType();
  5378. const auto ipType = ipArg->getType();
  5379. const auto returnType = callExpr->getType();
  5380. const auto returnTypeId = typeTranslator.translateType(returnType);
  5381. const auto ipTypeId = typeTranslator.translateType(ipType);
  5382. const uint32_t argId = doExpr(arg);
  5383. const uint32_t ipId = doExpr(ipArg);
  5384. // TODO: We currently do not support non-float matrices.
  5385. QualType ipElemType = {};
  5386. if (TypeTranslator::isMxNMatrix(ipType, &ipElemType) &&
  5387. !ipElemType->isFloatingType()) {
  5388. emitError("non-floating-point matrix type unimplemented", {});
  5389. return 0;
  5390. }
  5391. // For scalar and vector argument types.
  5392. {
  5393. if (TypeTranslator::isScalarType(argType) ||
  5394. TypeTranslator::isVectorType(argType)) {
  5395. const auto argTypeId = typeTranslator.translateType(argType);
  5396. // The struct members *must* have the same type.
  5397. const auto modfStructTypeId = theBuilder.getStructType(
  5398. {argTypeId, argTypeId}, "ModfStructType", {"frac", "ip"});
  5399. const auto modf =
  5400. theBuilder.createExtInst(modfStructTypeId, glslInstSetId,
  5401. GLSLstd450::GLSLstd450ModfStruct, {argId});
  5402. auto ip = theBuilder.createCompositeExtract(argTypeId, modf, {1});
  5403. // This will do nothing if the input number (x) and the ip are both of the
  5404. // same type. Otherwise, it will convert the ip into int as necessary.
  5405. ip = castToInt(ip, argType, ipType, arg->getExprLoc());
  5406. theBuilder.createStore(ipId, ip);
  5407. return theBuilder.createCompositeExtract(argTypeId, modf, {0});
  5408. }
  5409. }
  5410. // For matrix argument types.
  5411. {
  5412. uint32_t rowCount = 0, colCount = 0;
  5413. QualType elemType = {};
  5414. if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount, &colCount)) {
  5415. const auto elemTypeId = typeTranslator.translateType(elemType);
  5416. const auto colTypeId = theBuilder.getVecType(elemTypeId, colCount);
  5417. const auto modfStructTypeId = theBuilder.getStructType(
  5418. {colTypeId, colTypeId}, "ModfStructType", {"frac", "ip"});
  5419. llvm::SmallVector<uint32_t, 4> fracs;
  5420. llvm::SmallVector<uint32_t, 4> ips;
  5421. for (uint32_t i = 0; i < rowCount; ++i) {
  5422. const auto curRow =
  5423. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  5424. const auto modf = theBuilder.createExtInst(
  5425. modfStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450ModfStruct,
  5426. {curRow});
  5427. auto ip = theBuilder.createCompositeExtract(colTypeId, modf, {1});
  5428. ips.push_back(ip);
  5429. fracs.push_back(
  5430. theBuilder.createCompositeExtract(colTypeId, modf, {0}));
  5431. }
  5432. theBuilder.createStore(
  5433. ipId, theBuilder.createCompositeConstruct(returnTypeId, ips));
  5434. return theBuilder.createCompositeConstruct(returnTypeId, fracs);
  5435. }
  5436. }
  5437. emitError("invalid argument type passed to Modf intrinsic function",
  5438. callExpr->getExprLoc());
  5439. return 0;
  5440. }
  5441. uint32_t SPIRVEmitter::processIntrinsicLit(const CallExpr *callExpr) {
  5442. // Signature is: float4 lit(float n_dot_l, float n_dot_h, float m)
  5443. //
  5444. // This function returns a lighting coefficient vector
  5445. // (ambient, diffuse, specular, 1) where:
  5446. // ambient = 1.
  5447. // diffuse = (n_dot_l < 0) ? 0 : n_dot_l
  5448. // specular = (n_dot_l < 0 || n_dot_h < 0) ? 0 : ((n_dot_h) * m)
  5449. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  5450. const uint32_t nDotL = doExpr(callExpr->getArg(0));
  5451. const uint32_t nDotH = doExpr(callExpr->getArg(1));
  5452. const uint32_t m = doExpr(callExpr->getArg(2));
  5453. const uint32_t floatType = theBuilder.getFloat32Type();
  5454. const uint32_t boolType = theBuilder.getBoolType();
  5455. const uint32_t floatZero = theBuilder.getConstantFloat32(0);
  5456. const uint32_t floatOne = theBuilder.getConstantFloat32(1);
  5457. const uint32_t retType = typeTranslator.translateType(callExpr->getType());
  5458. const uint32_t diffuse = theBuilder.createExtInst(
  5459. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMax, {floatZero, nDotL});
  5460. const uint32_t min = theBuilder.createExtInst(
  5461. floatType, glslInstSetId, GLSLstd450::GLSLstd450FMin, {nDotL, nDotH});
  5462. const uint32_t isNeg = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  5463. boolType, min, floatZero);
  5464. const uint32_t mul =
  5465. theBuilder.createBinaryOp(spv::Op::OpFMul, floatType, nDotH, m);
  5466. const uint32_t specular =
  5467. theBuilder.createSelect(floatType, isNeg, floatZero, mul);
  5468. return theBuilder.createCompositeConstruct(
  5469. retType, {floatOne, diffuse, specular, floatOne});
  5470. }
  5471. uint32_t SPIRVEmitter::processIntrinsicFrexp(const CallExpr *callExpr) {
  5472. // Signature is: ret frexp(x, exp)
  5473. // [in] x: the input floating-point value.
  5474. // [out] exp: the calculated exponent.
  5475. // [out] ret: the calculated mantissa.
  5476. // All of the above must be a scalar, vector, or matrix of *float* type.
  5477. // The FrexpStruct SPIR-V instruction returns a struct. The first
  5478. // member is the significand (mantissa) and must be of the same type as the
  5479. // input parameter, and the second member is the exponent and must always be a
  5480. // scalar or vector of 32-bit *integer* type.
  5481. // FrexpStruct {
  5482. // <scalar or vector of int/float> mantissa;
  5483. // <scalar or vector of integers> exponent;
  5484. // }
  5485. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  5486. const Expr *arg = callExpr->getArg(0);
  5487. const auto argType = arg->getType();
  5488. const auto intId = theBuilder.getInt32Type();
  5489. const auto returnTypeId = typeTranslator.translateType(callExpr->getType());
  5490. const uint32_t argId = doExpr(arg);
  5491. const uint32_t expId = doExpr(callExpr->getArg(1));
  5492. // For scalar and vector argument types.
  5493. {
  5494. uint32_t elemCount = 1;
  5495. if (TypeTranslator::isScalarType(argType) ||
  5496. TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  5497. const auto argTypeId = typeTranslator.translateType(argType);
  5498. const auto expTypeId =
  5499. elemCount == 1 ? intId : theBuilder.getVecType(intId, elemCount);
  5500. const auto frexpStructTypeId = theBuilder.getStructType(
  5501. {argTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  5502. const auto frexp =
  5503. theBuilder.createExtInst(frexpStructTypeId, glslInstSetId,
  5504. GLSLstd450::GLSLstd450FrexpStruct, {argId});
  5505. const auto exponentInt =
  5506. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  5507. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  5508. // expects a float, an conversion must take place before writing the
  5509. // results.
  5510. const auto exponentFloat = theBuilder.createUnaryOp(
  5511. spv::Op::OpConvertSToF, returnTypeId, exponentInt);
  5512. theBuilder.createStore(expId, exponentFloat);
  5513. return theBuilder.createCompositeExtract(argTypeId, frexp, {0});
  5514. }
  5515. }
  5516. // For matrix argument types.
  5517. {
  5518. uint32_t rowCount = 0, colCount = 0;
  5519. if (TypeTranslator::isMxNMatrix(argType, nullptr, &rowCount, &colCount)) {
  5520. const auto floatId = theBuilder.getFloat32Type();
  5521. const auto expTypeId = theBuilder.getVecType(intId, colCount);
  5522. const auto colTypeId = theBuilder.getVecType(floatId, colCount);
  5523. const auto frexpStructTypeId = theBuilder.getStructType(
  5524. {colTypeId, expTypeId}, "FrexpStructType", {"mantissa", "exponent"});
  5525. llvm::SmallVector<uint32_t, 4> exponents;
  5526. llvm::SmallVector<uint32_t, 4> mantissas;
  5527. for (uint32_t i = 0; i < rowCount; ++i) {
  5528. const auto curRow =
  5529. theBuilder.createCompositeExtract(colTypeId, argId, {i});
  5530. const auto frexp = theBuilder.createExtInst(
  5531. frexpStructTypeId, glslInstSetId, GLSLstd450::GLSLstd450FrexpStruct,
  5532. {curRow});
  5533. const auto exponentInt =
  5534. theBuilder.createCompositeExtract(expTypeId, frexp, {1});
  5535. // Since the SPIR-V instruction returns an int, and the intrinsic HLSL
  5536. // expects a float, an conversion must take place before writing the
  5537. // results.
  5538. const auto exponentFloat = theBuilder.createUnaryOp(
  5539. spv::Op::OpConvertSToF, colTypeId, exponentInt);
  5540. exponents.push_back(exponentFloat);
  5541. mantissas.push_back(
  5542. theBuilder.createCompositeExtract(colTypeId, frexp, {0}));
  5543. }
  5544. const auto exponentsResultId =
  5545. theBuilder.createCompositeConstruct(returnTypeId, exponents);
  5546. theBuilder.createStore(expId, exponentsResultId);
  5547. return theBuilder.createCompositeConstruct(returnTypeId, mantissas);
  5548. }
  5549. }
  5550. emitError("invalid argument type passed to Frexp intrinsic function",
  5551. callExpr->getExprLoc());
  5552. return 0;
  5553. }
  5554. uint32_t SPIRVEmitter::processIntrinsicLdexp(const CallExpr *callExpr) {
  5555. // Signature: ret ldexp(x, exp)
  5556. // This function uses the following formula: x * 2^exp.
  5557. // Note that we cannot use GLSL extended instruction Ldexp since it requires
  5558. // the exponent to be an integer (vector) but HLSL takes an float (vector)
  5559. // exponent. So we must calculate the result manually.
  5560. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  5561. const Expr *x = callExpr->getArg(0);
  5562. const auto paramType = x->getType();
  5563. const uint32_t xId = doExpr(x);
  5564. const uint32_t expId = doExpr(callExpr->getArg(1));
  5565. // For scalar and vector argument types.
  5566. if (TypeTranslator::isScalarType(paramType) ||
  5567. TypeTranslator::isVectorType(paramType)) {
  5568. const auto paramTypeId = typeTranslator.translateType(paramType);
  5569. const auto twoExp = theBuilder.createExtInst(
  5570. paramTypeId, glsl, GLSLstd450::GLSLstd450Exp2, {expId});
  5571. return theBuilder.createBinaryOp(spv::Op::OpFMul, paramTypeId, xId, twoExp);
  5572. }
  5573. // For matrix argument types.
  5574. {
  5575. uint32_t rowCount = 0, colCount = 0;
  5576. if (TypeTranslator::isMxNMatrix(paramType, nullptr, &rowCount, &colCount)) {
  5577. const auto actOnEachVec = [this, glsl, expId](uint32_t index,
  5578. uint32_t vecType,
  5579. uint32_t xRowId) {
  5580. const auto expRowId =
  5581. theBuilder.createCompositeExtract(vecType, expId, {index});
  5582. const auto twoExp = theBuilder.createExtInst(
  5583. vecType, glsl, GLSLstd450::GLSLstd450Exp2, {expRowId});
  5584. return theBuilder.createBinaryOp(spv::Op::OpFMul, vecType, xRowId,
  5585. twoExp);
  5586. };
  5587. return processEachVectorInMatrix(x, xId, actOnEachVec);
  5588. }
  5589. }
  5590. emitError("invalid argument type passed to ldexp intrinsic function",
  5591. callExpr->getExprLoc());
  5592. return 0;
  5593. }
  5594. uint32_t SPIRVEmitter::processIntrinsicDst(const CallExpr *callExpr) {
  5595. // Signature is float4 dst(float4 src0, float4 src1)
  5596. // result.x = 1;
  5597. // result.y = src0.y * src1.y;
  5598. // result.z = src0.z;
  5599. // result.w = src1.w;
  5600. const auto floatId = theBuilder.getFloat32Type();
  5601. const auto arg0Id = doExpr(callExpr->getArg(0));
  5602. const auto arg1Id = doExpr(callExpr->getArg(1));
  5603. const auto arg0y = theBuilder.createCompositeExtract(floatId, arg0Id, {1});
  5604. const auto arg1y = theBuilder.createCompositeExtract(floatId, arg1Id, {1});
  5605. const auto arg0z = theBuilder.createCompositeExtract(floatId, arg0Id, {2});
  5606. const auto arg1w = theBuilder.createCompositeExtract(floatId, arg1Id, {3});
  5607. const auto arg0yMularg1y =
  5608. theBuilder.createBinaryOp(spv::Op::OpFMul, floatId, arg0y, arg1y);
  5609. return theBuilder.createCompositeConstruct(
  5610. typeTranslator.translateType(callExpr->getType()),
  5611. {theBuilder.getConstantFloat32(1.0), arg0yMularg1y, arg0z, arg1w});
  5612. }
  5613. uint32_t SPIRVEmitter::processIntrinsicClip(const CallExpr *callExpr) {
  5614. // Discards the current pixel if the specified value is less than zero.
  5615. // TODO: If the argument can be const folded and evaluated, we could
  5616. // potentially avoid creating a branch. This would be a bit challenging for
  5617. // matrix/vector arguments.
  5618. assert(callExpr->getNumArgs() == 1u);
  5619. const Expr *arg = callExpr->getArg(0);
  5620. const auto argType = arg->getType();
  5621. const auto boolType = theBuilder.getBoolType();
  5622. uint32_t condition = 0;
  5623. // Could not determine the argument as a constant. We need to branch based on
  5624. // the argument. If the argument is a vector/matrix, clipping is done if *any*
  5625. // element of the vector/matrix is less than zero.
  5626. const uint32_t argId = doExpr(arg);
  5627. QualType elemType = {};
  5628. uint32_t elemCount = 0, rowCount = 0, colCount = 0;
  5629. if (TypeTranslator::isScalarType(argType)) {
  5630. const auto zero = getValueZero(argType);
  5631. condition = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan, boolType,
  5632. argId, zero);
  5633. } else if (TypeTranslator::isVectorType(argType, nullptr, &elemCount)) {
  5634. const auto zero = getValueZero(argType);
  5635. const auto boolVecType = theBuilder.getVecType(boolType, elemCount);
  5636. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  5637. boolVecType, argId, zero);
  5638. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  5639. } else if (TypeTranslator::isMxNMatrix(argType, &elemType, &rowCount,
  5640. &colCount)) {
  5641. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  5642. const uint32_t floatVecType = theBuilder.getVecType(elemTypeId, colCount);
  5643. const uint32_t elemZeroId = getValueZero(elemType);
  5644. llvm::SmallVector<uint32_t, 4> elements(size_t(colCount), elemZeroId);
  5645. const auto zero = theBuilder.getConstantComposite(floatVecType, elements);
  5646. llvm::SmallVector<uint32_t, 4> cmpResults;
  5647. for (uint32_t i = 0; i < rowCount; ++i) {
  5648. const uint32_t lhsVec =
  5649. theBuilder.createCompositeExtract(floatVecType, argId, {i});
  5650. const auto boolColType = theBuilder.getVecType(boolType, colCount);
  5651. const auto cmp = theBuilder.createBinaryOp(spv::Op::OpFOrdLessThan,
  5652. boolColType, lhsVec, zero);
  5653. const auto any = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, cmp);
  5654. cmpResults.push_back(any);
  5655. }
  5656. const auto boolRowType = theBuilder.getVecType(boolType, rowCount);
  5657. const auto results =
  5658. theBuilder.createCompositeConstruct(boolRowType, cmpResults);
  5659. condition = theBuilder.createUnaryOp(spv::Op::OpAny, boolType, results);
  5660. } else {
  5661. emitError("invalid argument type passed to clip intrinsic function",
  5662. callExpr->getExprLoc());
  5663. return 0;
  5664. }
  5665. // Then we need to emit the instruction for the conditional branch.
  5666. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  5667. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  5668. // Create the branch instruction. This will end the current basic block.
  5669. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  5670. theBuilder.addSuccessor(thenBB);
  5671. theBuilder.addSuccessor(mergeBB);
  5672. theBuilder.setMergeTarget(mergeBB);
  5673. // Handle the then branch
  5674. theBuilder.setInsertPoint(thenBB);
  5675. theBuilder.createKill();
  5676. theBuilder.addSuccessor(mergeBB);
  5677. // From now on, we'll emit instructions into the merge block.
  5678. theBuilder.setInsertPoint(mergeBB);
  5679. return 0;
  5680. }
  5681. uint32_t SPIRVEmitter::processIntrinsicClamp(const CallExpr *callExpr) {
  5682. // According the HLSL reference: clamp(X, Min, Max) takes 3 arguments. Each
  5683. // one may be int, uint, or float.
  5684. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  5685. const QualType returnType = callExpr->getType();
  5686. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  5687. GLSLstd450 glslOpcode = GLSLstd450::GLSLstd450UClamp;
  5688. if (isFloatOrVecMatOfFloatType(returnType))
  5689. glslOpcode = GLSLstd450::GLSLstd450FClamp;
  5690. else if (isSintOrVecMatOfSintType(returnType))
  5691. glslOpcode = GLSLstd450::GLSLstd450SClamp;
  5692. // Get the function parameters. Expect 3 parameters.
  5693. assert(callExpr->getNumArgs() == 3u);
  5694. const Expr *argX = callExpr->getArg(0);
  5695. const Expr *argMin = callExpr->getArg(1);
  5696. const Expr *argMax = callExpr->getArg(2);
  5697. const uint32_t argXId = doExpr(argX);
  5698. const uint32_t argMinId = doExpr(argMin);
  5699. const uint32_t argMaxId = doExpr(argMax);
  5700. // FClamp, UClamp, and SClamp do not operate on matrices, so we should perform
  5701. // the operation on each vector of the matrix.
  5702. if (TypeTranslator::isSpirvAcceptableMatrixType(argX->getType())) {
  5703. const auto actOnEachVec = [this, glslInstSetId, glslOpcode, argMinId,
  5704. argMaxId](uint32_t index, uint32_t vecType,
  5705. uint32_t curRowId) {
  5706. const auto minRowId =
  5707. theBuilder.createCompositeExtract(vecType, argMinId, {index});
  5708. const auto maxRowId =
  5709. theBuilder.createCompositeExtract(vecType, argMaxId, {index});
  5710. return theBuilder.createExtInst(vecType, glslInstSetId, glslOpcode,
  5711. {curRowId, minRowId, maxRowId});
  5712. };
  5713. return processEachVectorInMatrix(argX, argXId, actOnEachVec);
  5714. }
  5715. return theBuilder.createExtInst(returnTypeId, glslInstSetId, glslOpcode,
  5716. {argXId, argMinId, argMaxId});
  5717. }
  5718. uint32_t SPIRVEmitter::processIntrinsicMemoryBarrier(const CallExpr *callExpr,
  5719. bool isDevice,
  5720. bool groupSync,
  5721. bool isAllBarrier) {
  5722. // * DeviceMemoryBarrier =
  5723. // OpMemoryBarrier (memScope=Device,
  5724. // sem=Image|Uniform|AcquireRelease)
  5725. //
  5726. // * DeviceMemoryBarrierWithGroupSync =
  5727. // OpControlBarrier(execScope = Workgroup,
  5728. // memScope=Device,
  5729. // sem=Image|Uniform|AcquireRelease)
  5730. const spv::MemorySemanticsMask deviceMemoryBarrierSema =
  5731. spv::MemorySemanticsMask::ImageMemory |
  5732. spv::MemorySemanticsMask::UniformMemory |
  5733. spv::MemorySemanticsMask::AcquireRelease;
  5734. // * GroupMemoryBarrier =
  5735. // OpMemoryBarrier (memScope=Workgroup,
  5736. // sem = Workgroup|AcquireRelease)
  5737. //
  5738. // * GroupMemoryBarrierWithGroupSync =
  5739. // OpControlBarrier (execScope = Workgroup,
  5740. // memScope = Workgroup,
  5741. // sem = Workgroup|AcquireRelease)
  5742. const spv::MemorySemanticsMask groupMemoryBarrierSema =
  5743. spv::MemorySemanticsMask::WorkgroupMemory |
  5744. spv::MemorySemanticsMask::AcquireRelease;
  5745. // * AllMemoryBarrier =
  5746. // OpMemoryBarrier(memScope = Device,
  5747. // sem = Image|Uniform|Workgroup|AcquireRelease)
  5748. //
  5749. // * AllMemoryBarrierWithGroupSync =
  5750. // OpControlBarrier(execScope = Workgroup,
  5751. // memScope = Device,
  5752. // sem = Image|Uniform|Workgroup|AcquireRelease)
  5753. const spv::MemorySemanticsMask allMemoryBarrierSema =
  5754. spv::MemorySemanticsMask::ImageMemory |
  5755. spv::MemorySemanticsMask::UniformMemory |
  5756. spv::MemorySemanticsMask::WorkgroupMemory |
  5757. spv::MemorySemanticsMask::AtomicCounterMemory |
  5758. spv::MemorySemanticsMask::AcquireRelease;
  5759. // Get <result-id> for execution scope.
  5760. // If present, execution scope is always Workgroup!
  5761. const uint32_t execScopeId =
  5762. groupSync ? theBuilder.getConstantUint32(
  5763. static_cast<uint32_t>(spv::Scope::Workgroup))
  5764. : 0;
  5765. // Get <result-id> for memory scope
  5766. const spv::Scope memScope =
  5767. (isDevice || isAllBarrier) ? spv::Scope::Device : spv::Scope::Workgroup;
  5768. const uint32_t memScopeId =
  5769. theBuilder.getConstantUint32(static_cast<uint32_t>(memScope));
  5770. // Get <result-id> for memory semantics
  5771. const auto memSemaMask = isAllBarrier ? allMemoryBarrierSema
  5772. : isDevice ? deviceMemoryBarrierSema
  5773. : groupMemoryBarrierSema;
  5774. const uint32_t memSema =
  5775. theBuilder.getConstantUint32(static_cast<uint32_t>(memSemaMask));
  5776. theBuilder.createBarrier(execScopeId, memScopeId, memSema);
  5777. return 0;
  5778. }
  5779. uint32_t SPIRVEmitter::processIntrinsicMul(const CallExpr *callExpr) {
  5780. const QualType returnType = callExpr->getType();
  5781. const uint32_t returnTypeId =
  5782. typeTranslator.translateType(callExpr->getType());
  5783. // Get the function parameters. Expect 2 parameters.
  5784. assert(callExpr->getNumArgs() == 2u);
  5785. const Expr *arg0 = callExpr->getArg(0);
  5786. const Expr *arg1 = callExpr->getArg(1);
  5787. const QualType arg0Type = arg0->getType();
  5788. const QualType arg1Type = arg1->getType();
  5789. // The HLSL mul() function takes 2 arguments. Each argument may be a scalar,
  5790. // vector, or matrix. The frontend ensures that the two arguments have the
  5791. // same component type. The only allowed component types are int and float.
  5792. // mul(scalar, vector)
  5793. {
  5794. uint32_t elemCount = 0;
  5795. if (TypeTranslator::isScalarType(arg0Type) &&
  5796. TypeTranslator::isVectorType(arg1Type, nullptr, &elemCount)) {
  5797. const uint32_t arg1Id = doExpr(arg1);
  5798. // We can use OpVectorTimesScalar if arguments are floats.
  5799. if (arg0Type->isFloatingType())
  5800. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  5801. returnTypeId, arg1Id, doExpr(arg0));
  5802. // Use OpIMul for integers
  5803. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId,
  5804. createVectorSplat(arg0, elemCount),
  5805. arg1Id);
  5806. }
  5807. }
  5808. // mul(vector, scalar)
  5809. {
  5810. uint32_t elemCount = 0;
  5811. if (TypeTranslator::isVectorType(arg0Type, nullptr, &elemCount) &&
  5812. TypeTranslator::isScalarType(arg1Type)) {
  5813. const uint32_t arg0Id = doExpr(arg0);
  5814. // We can use OpVectorTimesScalar if arguments are floats.
  5815. if (arg1Type->isFloatingType())
  5816. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesScalar,
  5817. returnTypeId, arg0Id, doExpr(arg1));
  5818. // Use OpIMul for integers
  5819. return theBuilder.createBinaryOp(spv::Op::OpIMul, returnTypeId, arg0Id,
  5820. createVectorSplat(arg1, elemCount));
  5821. }
  5822. }
  5823. // mul(vector, vector)
  5824. if (TypeTranslator::isVectorType(arg0Type) &&
  5825. TypeTranslator::isVectorType(arg1Type))
  5826. return processIntrinsicDot(callExpr);
  5827. // All the following cases require handling arg0 and arg1 expressions first.
  5828. const uint32_t arg0Id = doExpr(arg0);
  5829. const uint32_t arg1Id = doExpr(arg1);
  5830. // mul(scalar, scalar)
  5831. if (TypeTranslator::isScalarType(arg0Type) &&
  5832. TypeTranslator::isScalarType(arg1Type))
  5833. return theBuilder.createBinaryOp(translateOp(BO_Mul, arg0Type),
  5834. returnTypeId, arg0Id, arg1Id);
  5835. // mul(scalar, matrix)
  5836. if (TypeTranslator::isScalarType(arg0Type) &&
  5837. TypeTranslator::isMxNMatrix(arg1Type)) {
  5838. // We currently only support float matrices. So we can use
  5839. // OpMatrixTimesScalar
  5840. if (arg0Type->isFloatingType())
  5841. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  5842. returnTypeId, arg1Id, arg0Id);
  5843. }
  5844. // mul(matrix, scalar)
  5845. if (TypeTranslator::isScalarType(arg1Type) &&
  5846. TypeTranslator::isMxNMatrix(arg0Type)) {
  5847. // We currently only support float matrices. So we can use
  5848. // OpMatrixTimesScalar
  5849. if (arg1Type->isFloatingType())
  5850. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesScalar,
  5851. returnTypeId, arg0Id, arg1Id);
  5852. }
  5853. // mul(vector, matrix)
  5854. {
  5855. QualType elemType = {};
  5856. uint32_t elemCount = 0, numRows = 0;
  5857. if (TypeTranslator::isVectorType(arg0Type, &elemType, &elemCount) &&
  5858. TypeTranslator::isMxNMatrix(arg1Type, nullptr, &numRows, nullptr) &&
  5859. elemType->isFloatingType()) {
  5860. assert(elemCount == numRows);
  5861. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesVector,
  5862. returnTypeId, arg1Id, arg0Id);
  5863. }
  5864. }
  5865. // mul(matrix, vector)
  5866. {
  5867. QualType elemType = {};
  5868. uint32_t elemCount = 0, numCols = 0;
  5869. if (TypeTranslator::isMxNMatrix(arg0Type, nullptr, nullptr, &numCols) &&
  5870. TypeTranslator::isVectorType(arg1Type, &elemType, &elemCount) &&
  5871. elemType->isFloatingType()) {
  5872. assert(elemCount == numCols);
  5873. return theBuilder.createBinaryOp(spv::Op::OpVectorTimesMatrix,
  5874. returnTypeId, arg1Id, arg0Id);
  5875. }
  5876. }
  5877. // mul(matrix, matrix)
  5878. {
  5879. QualType elemType = {};
  5880. uint32_t arg0Cols = 0, arg1Rows = 0;
  5881. if (TypeTranslator::isMxNMatrix(arg0Type, &elemType, nullptr, &arg0Cols) &&
  5882. TypeTranslator::isMxNMatrix(arg1Type, nullptr, &arg1Rows, nullptr) &&
  5883. elemType->isFloatingType()) {
  5884. assert(arg0Cols == arg1Rows);
  5885. return theBuilder.createBinaryOp(spv::Op::OpMatrixTimesMatrix,
  5886. returnTypeId, arg1Id, arg0Id);
  5887. }
  5888. }
  5889. emitError("invalid argument type passed to mul intrinsic function",
  5890. callExpr->getExprLoc());
  5891. return 0;
  5892. }
  5893. uint32_t SPIRVEmitter::processIntrinsicDot(const CallExpr *callExpr) {
  5894. const QualType returnType = callExpr->getType();
  5895. const uint32_t returnTypeId =
  5896. typeTranslator.translateType(callExpr->getType());
  5897. // Get the function parameters. Expect 2 vectors as parameters.
  5898. assert(callExpr->getNumArgs() == 2u);
  5899. const Expr *arg0 = callExpr->getArg(0);
  5900. const Expr *arg1 = callExpr->getArg(1);
  5901. const uint32_t arg0Id = doExpr(arg0);
  5902. const uint32_t arg1Id = doExpr(arg1);
  5903. QualType arg0Type = arg0->getType();
  5904. QualType arg1Type = arg1->getType();
  5905. const size_t vec0Size = hlsl::GetHLSLVecSize(arg0Type);
  5906. const size_t vec1Size = hlsl::GetHLSLVecSize(arg1Type);
  5907. const QualType vec0ComponentType = hlsl::GetHLSLVecElementType(arg0Type);
  5908. const QualType vec1ComponentType = hlsl::GetHLSLVecElementType(arg1Type);
  5909. assert(returnType == vec1ComponentType);
  5910. assert(vec0ComponentType == vec1ComponentType);
  5911. assert(vec0Size == vec1Size);
  5912. assert(vec0Size >= 1 && vec0Size <= 4);
  5913. // According to HLSL reference, the dot function only works on integers
  5914. // and floats.
  5915. assert(returnType->isFloatingType() || returnType->isIntegerType());
  5916. // Special case: dot product of two vectors, each of size 1. That is
  5917. // basically the same as regular multiplication of 2 scalars.
  5918. if (vec0Size == 1) {
  5919. const spv::Op spvOp = translateOp(BO_Mul, arg0Type);
  5920. return theBuilder.createBinaryOp(spvOp, returnTypeId, arg0Id, arg1Id);
  5921. }
  5922. // If the vectors are of type Float, we can use OpDot.
  5923. if (returnType->isFloatingType()) {
  5924. return theBuilder.createBinaryOp(spv::Op::OpDot, returnTypeId, arg0Id,
  5925. arg1Id);
  5926. }
  5927. // Vector component type is Integer (signed or unsigned).
  5928. // Create all instructions necessary to perform a dot product on
  5929. // two integer vectors. SPIR-V OpDot does not support integer vectors.
  5930. // Therefore, we use other SPIR-V instructions (addition and
  5931. // multiplication).
  5932. else {
  5933. uint32_t result = 0;
  5934. llvm::SmallVector<uint32_t, 4> multIds;
  5935. const spv::Op multSpvOp = translateOp(BO_Mul, arg0Type);
  5936. const spv::Op addSpvOp = translateOp(BO_Add, arg0Type);
  5937. // Extract members from the two vectors and multiply them.
  5938. for (unsigned int i = 0; i < vec0Size; ++i) {
  5939. const uint32_t vec0member =
  5940. theBuilder.createCompositeExtract(returnTypeId, arg0Id, {i});
  5941. const uint32_t vec1member =
  5942. theBuilder.createCompositeExtract(returnTypeId, arg1Id, {i});
  5943. const uint32_t multId = theBuilder.createBinaryOp(multSpvOp, returnTypeId,
  5944. vec0member, vec1member);
  5945. multIds.push_back(multId);
  5946. }
  5947. // Add all the multiplications.
  5948. result = multIds[0];
  5949. for (unsigned int i = 1; i < vec0Size; ++i) {
  5950. const uint32_t additionId =
  5951. theBuilder.createBinaryOp(addSpvOp, returnTypeId, result, multIds[i]);
  5952. result = additionId;
  5953. }
  5954. return result;
  5955. }
  5956. }
  5957. uint32_t SPIRVEmitter::processIntrinsicRcp(const CallExpr *callExpr) {
  5958. // 'rcp' takes only 1 argument that is a scalar, vector, or matrix of type
  5959. // float or double.
  5960. assert(callExpr->getNumArgs() == 1u);
  5961. const QualType returnType = callExpr->getType();
  5962. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  5963. const Expr *arg = callExpr->getArg(0);
  5964. const uint32_t argId = doExpr(arg);
  5965. const QualType argType = arg->getType();
  5966. // For cases with matrix argument.
  5967. QualType elemType = {};
  5968. uint32_t numRows = 0, numCols = 0;
  5969. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  5970. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  5971. const auto actOnEachVec = [this, vecOne](uint32_t /*index*/,
  5972. uint32_t vecType,
  5973. uint32_t curRowId) {
  5974. return theBuilder.createBinaryOp(spv::Op::OpFDiv, vecType, vecOne,
  5975. curRowId);
  5976. };
  5977. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  5978. }
  5979. // For cases with scalar or vector arguments.
  5980. return theBuilder.createBinaryOp(spv::Op::OpFDiv, returnTypeId,
  5981. getValueOne(argType), argId);
  5982. }
  5983. uint32_t SPIRVEmitter::processIntrinsicAllOrAny(const CallExpr *callExpr,
  5984. spv::Op spvOp) {
  5985. // 'all' and 'any' take only 1 parameter.
  5986. assert(callExpr->getNumArgs() == 1u);
  5987. const QualType returnType = callExpr->getType();
  5988. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  5989. const Expr *arg = callExpr->getArg(0);
  5990. const QualType argType = arg->getType();
  5991. // Handle scalars, vectors of size 1, and 1x1 matrices as arguments.
  5992. // Optimization: can directly cast them to boolean. No need for OpAny/OpAll.
  5993. {
  5994. QualType scalarType = {};
  5995. if (TypeTranslator::isScalarType(argType, &scalarType) &&
  5996. (scalarType->isBooleanType() || scalarType->isFloatingType() ||
  5997. scalarType->isIntegerType()))
  5998. return castToBool(doExpr(arg), argType, returnType);
  5999. }
  6000. // Handle vectors larger than 1, Mx1 matrices, and 1xN matrices as arguments.
  6001. // Cast the vector to a boolean vector, then run OpAny/OpAll on it.
  6002. {
  6003. QualType elemType = {};
  6004. uint32_t size = 0;
  6005. if (TypeTranslator::isVectorType(argType, &elemType, &size)) {
  6006. const QualType castToBoolType =
  6007. astContext.getExtVectorType(returnType, size);
  6008. uint32_t castedToBoolId =
  6009. castToBool(doExpr(arg), argType, castToBoolType);
  6010. return theBuilder.createUnaryOp(spvOp, returnTypeId, castedToBoolId);
  6011. }
  6012. }
  6013. // Handle MxN matrices as arguments.
  6014. {
  6015. QualType elemType = {};
  6016. uint32_t matRowCount = 0, matColCount = 0;
  6017. if (TypeTranslator::isMxNMatrix(argType, &elemType, &matRowCount,
  6018. &matColCount)) {
  6019. if (!elemType->isFloatingType()) {
  6020. emitError("non-floating-point matrix arguments in all/any intrinsic "
  6021. "function unimplemented",
  6022. callExpr->getExprLoc());
  6023. return 0;
  6024. }
  6025. uint32_t matrixId = doExpr(arg);
  6026. const uint32_t vecType = typeTranslator.getComponentVectorType(argType);
  6027. llvm::SmallVector<uint32_t, 4> rowResults;
  6028. for (uint32_t i = 0; i < matRowCount; ++i) {
  6029. // Extract the row which is a float vector of size matColCount.
  6030. const uint32_t rowFloatVec =
  6031. theBuilder.createCompositeExtract(vecType, matrixId, {i});
  6032. // Cast the float vector to boolean vector.
  6033. const auto rowFloatQualType =
  6034. astContext.getExtVectorType(elemType, matColCount);
  6035. const auto rowBoolQualType =
  6036. astContext.getExtVectorType(returnType, matColCount);
  6037. const uint32_t rowBoolVec =
  6038. castToBool(rowFloatVec, rowFloatQualType, rowBoolQualType);
  6039. // Perform OpAny/OpAll on the boolean vector.
  6040. rowResults.push_back(
  6041. theBuilder.createUnaryOp(spvOp, returnTypeId, rowBoolVec));
  6042. }
  6043. // Create a new vector that is the concatenation of results of all rows.
  6044. uint32_t boolId = theBuilder.getBoolType();
  6045. uint32_t vecOfBoolsId = theBuilder.getVecType(boolId, matRowCount);
  6046. const uint32_t rowResultsId =
  6047. theBuilder.createCompositeConstruct(vecOfBoolsId, rowResults);
  6048. // Run OpAny/OpAll on the newly-created vector.
  6049. return theBuilder.createUnaryOp(spvOp, returnTypeId, rowResultsId);
  6050. }
  6051. }
  6052. // All types should be handled already.
  6053. llvm_unreachable("Unknown argument type passed to all()/any().");
  6054. return 0;
  6055. }
  6056. uint32_t SPIRVEmitter::processIntrinsicAsType(const CallExpr *callExpr) {
  6057. // This function handles 'asint', 'asuint', 'asfloat', and 'asdouble'.
  6058. // Method 1: ret asint(arg)
  6059. // arg component type = {float, uint}
  6060. // arg template type = {scalar, vector, matrix}
  6061. // ret template type = same as arg template type.
  6062. // ret component type = int
  6063. // Method 2: ret asuint(arg)
  6064. // arg component type = {float, int}
  6065. // arg template type = {scalar, vector, matrix}
  6066. // ret template type = same as arg template type.
  6067. // ret component type = uint
  6068. // Method 3: ret asfloat(arg)
  6069. // arg component type = {float, uint, int}
  6070. // arg template type = {scalar, vector, matrix}
  6071. // ret template type = same as arg template type.
  6072. // ret component type = float
  6073. // Method 4: double asdouble(uint lowbits, uint highbits)
  6074. // Method 5: double2 asdouble(uint2 lowbits, uint2 highbits)
  6075. // Method 6:
  6076. // void asuint(
  6077. // in double value,
  6078. // out uint lowbits,
  6079. // out uint highbits
  6080. // );
  6081. const QualType returnType = callExpr->getType();
  6082. const uint32_t numArgs = callExpr->getNumArgs();
  6083. const uint32_t returnTypeId = typeTranslator.translateType(returnType);
  6084. const Expr *arg0 = callExpr->getArg(0);
  6085. const QualType argType = arg0->getType();
  6086. // Method 3 return type may be the same as arg type, so it would be a no-op.
  6087. if (returnType.getCanonicalType() == argType.getCanonicalType())
  6088. return doExpr(arg0);
  6089. // SPIR-V does not support non-floating point matrices. For the above methods
  6090. // that involve matrices, either the input or the output is a non-float
  6091. // matrix. (except for 'asfloat' taking a float matrix and returning a float
  6092. // matrix, which is a no-op and is handled by the condition above).
  6093. if (TypeTranslator::isMxNMatrix(argType)) {
  6094. emitError("non-floating-point matrix type unimplemented",
  6095. callExpr->getExprLoc());
  6096. return 0;
  6097. }
  6098. switch (numArgs) {
  6099. case 1: {
  6100. // Handling Method 1, 2, and 3.
  6101. return theBuilder.createUnaryOp(spv::Op::OpBitcast, returnTypeId,
  6102. doExpr(arg0));
  6103. }
  6104. case 2: {
  6105. const uint32_t lowbits = doExpr(arg0);
  6106. const uint32_t highbits = doExpr(callExpr->getArg(1));
  6107. const uint32_t uintType = theBuilder.getUint32Type();
  6108. const uint32_t doubleType = theBuilder.getFloat64Type();
  6109. // Handling Method 4
  6110. if (argType->isUnsignedIntegerType()) {
  6111. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  6112. const uint32_t operand = theBuilder.createCompositeConstruct(
  6113. uintVec2Type, {lowbits, highbits});
  6114. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleType, operand);
  6115. }
  6116. // Handling Method 5
  6117. else {
  6118. const uint32_t uintVec4Type = theBuilder.getVecType(uintType, 4);
  6119. const uint32_t doubleVec2Type = theBuilder.getVecType(doubleType, 2);
  6120. const uint32_t operand = theBuilder.createVectorShuffle(
  6121. uintVec4Type, lowbits, highbits, {0, 2, 1, 3});
  6122. return theBuilder.createUnaryOp(spv::Op::OpBitcast, doubleVec2Type,
  6123. operand);
  6124. }
  6125. }
  6126. case 3: {
  6127. // Handling Method 6.
  6128. const uint32_t value = doExpr(arg0);
  6129. const uint32_t lowbits = doExpr(callExpr->getArg(1));
  6130. const uint32_t highbits = doExpr(callExpr->getArg(2));
  6131. const uint32_t uintType = theBuilder.getUint32Type();
  6132. const uint32_t uintVec2Type = theBuilder.getVecType(uintType, 2);
  6133. const uint32_t vecResult =
  6134. theBuilder.createUnaryOp(spv::Op::OpBitcast, uintVec2Type, value);
  6135. theBuilder.createStore(
  6136. lowbits, theBuilder.createCompositeExtract(uintType, vecResult, {0}));
  6137. theBuilder.createStore(
  6138. highbits, theBuilder.createCompositeExtract(uintType, vecResult, {1}));
  6139. return 0;
  6140. }
  6141. default:
  6142. emitError("unrecognized signature for %0 intrinsic function",
  6143. callExpr->getExprLoc())
  6144. << callExpr->getDirectCallee()->getName();
  6145. return 0;
  6146. }
  6147. }
  6148. uint32_t SPIRVEmitter::processD3DCOLORtoUBYTE4(const CallExpr *callExpr) {
  6149. // Should take a float4 and return an int4 by doing:
  6150. // int4 result = input.zyxw * 255.001953;
  6151. // Maximum float precision makes the scaling factor 255.002.
  6152. const auto arg = callExpr->getArg(0);
  6153. const auto argId = doExpr(arg);
  6154. const auto argTypeId = typeTranslator.translateType(arg->getType());
  6155. const auto swizzle =
  6156. theBuilder.createVectorShuffle(argTypeId, argId, argId, {2, 1, 0, 3});
  6157. const auto scaled = theBuilder.createBinaryOp(
  6158. spv::Op::OpVectorTimesScalar, argTypeId, swizzle,
  6159. theBuilder.getConstantFloat32(255.002f));
  6160. return castToInt(scaled, arg->getType(), callExpr->getType(),
  6161. callExpr->getExprLoc());
  6162. }
  6163. uint32_t SPIRVEmitter::processIntrinsicIsFinite(const CallExpr *callExpr) {
  6164. // Since OpIsFinite needs the Kernel capability, translation is instead done
  6165. // using OpIsNan and OpIsInf:
  6166. // isFinite = !(isNan || isInf)
  6167. const auto arg = doExpr(callExpr->getArg(0));
  6168. const auto returnType = typeTranslator.translateType(callExpr->getType());
  6169. const auto isNan =
  6170. theBuilder.createUnaryOp(spv::Op::OpIsNan, returnType, arg);
  6171. const auto isInf =
  6172. theBuilder.createUnaryOp(spv::Op::OpIsInf, returnType, arg);
  6173. const auto isNanOrInf =
  6174. theBuilder.createBinaryOp(spv::Op::OpLogicalOr, returnType, isNan, isInf);
  6175. return theBuilder.createUnaryOp(spv::Op::OpLogicalNot, returnType,
  6176. isNanOrInf);
  6177. }
  6178. uint32_t SPIRVEmitter::processIntrinsicSinCos(const CallExpr *callExpr) {
  6179. // Since there is no sincos equivalent in SPIR-V, we need to perform Sin
  6180. // once and Cos once. We can reuse existing Sine/Cosine handling functions.
  6181. CallExpr *sincosExpr =
  6182. new (astContext) CallExpr(astContext, Stmt::StmtClass::NoStmtClass, {});
  6183. sincosExpr->setType(callExpr->getArg(0)->getType());
  6184. sincosExpr->setNumArgs(astContext, 1);
  6185. sincosExpr->setArg(0, const_cast<Expr *>(callExpr->getArg(0)));
  6186. // Perform Sin and store results in argument 1.
  6187. const uint32_t sin =
  6188. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Sin,
  6189. /*actPerRowForMatrices*/ true);
  6190. theBuilder.createStore(doExpr(callExpr->getArg(1)), sin);
  6191. // Perform Cos and store results in argument 2.
  6192. const uint32_t cos =
  6193. processIntrinsicUsingGLSLInst(sincosExpr, GLSLstd450::GLSLstd450Cos,
  6194. /*actPerRowForMatrices*/ true);
  6195. theBuilder.createStore(doExpr(callExpr->getArg(2)), cos);
  6196. return 0;
  6197. }
  6198. uint32_t SPIRVEmitter::processIntrinsicSaturate(const CallExpr *callExpr) {
  6199. const auto *arg = callExpr->getArg(0);
  6200. const auto argId = doExpr(arg);
  6201. const auto argType = arg->getType();
  6202. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  6203. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6204. if (argType->isFloatingType()) {
  6205. const uint32_t floatZero = getValueZero(argType);
  6206. const uint32_t floatOne = getValueOne(argType);
  6207. return theBuilder.createExtInst(returnType, glslInstSetId,
  6208. GLSLstd450::GLSLstd450FClamp,
  6209. {argId, floatZero, floatOne});
  6210. }
  6211. QualType elemType = {};
  6212. uint32_t vecSize = 0;
  6213. if (TypeTranslator::isVectorType(argType, &elemType, &vecSize)) {
  6214. const uint32_t vecZero = getVecValueZero(elemType, vecSize);
  6215. const uint32_t vecOne = getVecValueOne(elemType, vecSize);
  6216. return theBuilder.createExtInst(returnType, glslInstSetId,
  6217. GLSLstd450::GLSLstd450FClamp,
  6218. {argId, vecZero, vecOne});
  6219. }
  6220. uint32_t numRows = 0, numCols = 0;
  6221. if (TypeTranslator::isMxNMatrix(argType, &elemType, &numRows, &numCols)) {
  6222. const uint32_t vecZero = getVecValueZero(elemType, numCols);
  6223. const uint32_t vecOne = getVecValueOne(elemType, numCols);
  6224. const auto actOnEachVec = [this, vecZero, vecOne, glslInstSetId](
  6225. uint32_t /*index*/, uint32_t vecType,
  6226. uint32_t curRowId) {
  6227. return theBuilder.createExtInst(vecType, glslInstSetId,
  6228. GLSLstd450::GLSLstd450FClamp,
  6229. {curRowId, vecZero, vecOne});
  6230. };
  6231. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  6232. }
  6233. emitError("invalid argument type passed to saturate intrinsic function",
  6234. callExpr->getExprLoc());
  6235. return 0;
  6236. }
  6237. uint32_t SPIRVEmitter::processIntrinsicFloatSign(const CallExpr *callExpr) {
  6238. // Import the GLSL.std.450 extended instruction set.
  6239. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6240. const Expr *arg = callExpr->getArg(0);
  6241. const QualType returnType = callExpr->getType();
  6242. const QualType argType = arg->getType();
  6243. assert(isFloatOrVecMatOfFloatType(argType));
  6244. const uint32_t argTypeId = typeTranslator.translateType(argType);
  6245. const uint32_t argId = doExpr(arg);
  6246. uint32_t floatSignResultId = 0;
  6247. // For matrices, we can perform the instruction on each vector of the matrix.
  6248. if (TypeTranslator::isSpirvAcceptableMatrixType(argType)) {
  6249. const auto actOnEachVec = [this, glslInstSetId](uint32_t /*index*/,
  6250. uint32_t vecType,
  6251. uint32_t curRowId) {
  6252. return theBuilder.createExtInst(vecType, glslInstSetId,
  6253. GLSLstd450::GLSLstd450FSign, {curRowId});
  6254. };
  6255. floatSignResultId = processEachVectorInMatrix(arg, argId, actOnEachVec);
  6256. } else {
  6257. floatSignResultId = theBuilder.createExtInst(
  6258. argTypeId, glslInstSetId, GLSLstd450::GLSLstd450FSign, {argId});
  6259. }
  6260. return castToInt(floatSignResultId, arg->getType(), returnType,
  6261. arg->getExprLoc());
  6262. }
  6263. uint32_t SPIRVEmitter::processIntrinsicF16ToF32(const CallExpr *callExpr) {
  6264. // f16tof32() takes in (vector of) uint and returns (vector of) float.
  6265. // The frontend should guarantee that by inserting implicit casts.
  6266. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  6267. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  6268. const uint32_t u32TypeId = theBuilder.getUint32Type();
  6269. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  6270. const auto *arg = callExpr->getArg(0);
  6271. const uint32_t argId = doExpr(arg);
  6272. uint32_t elemCount = {};
  6273. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  6274. // The input is a vector. We need to handle each element separately.
  6275. llvm::SmallVector<uint32_t, 4> elements;
  6276. for (uint32_t i = 0; i < elemCount; ++i) {
  6277. const uint32_t srcElem =
  6278. theBuilder.createCompositeExtract(u32TypeId, argId, {i});
  6279. const uint32_t convert = theBuilder.createExtInst(
  6280. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, srcElem);
  6281. elements.push_back(
  6282. theBuilder.createCompositeExtract(f32TypeId, convert, {0}));
  6283. }
  6284. return theBuilder.createCompositeConstruct(
  6285. theBuilder.getVecType(f32TypeId, elemCount), elements);
  6286. }
  6287. const uint32_t convert = theBuilder.createExtInst(
  6288. v2f32TypeId, glsl, GLSLstd450::GLSLstd450UnpackHalf2x16, argId);
  6289. // f16tof32() converts the float16 stored in the low-half of the uint to
  6290. // a float. So just need to return the first component.
  6291. return theBuilder.createCompositeExtract(f32TypeId, convert, {0});
  6292. }
  6293. uint32_t SPIRVEmitter::processIntrinsicF32ToF16(const CallExpr *callExpr) {
  6294. // f32tof16() takes in (vector of) float and returns (vector of) uint.
  6295. // The frontend should guarantee that by inserting implicit casts.
  6296. const uint32_t glsl = theBuilder.getGLSLExtInstSet();
  6297. const uint32_t f32TypeId = theBuilder.getFloat32Type();
  6298. const uint32_t u32TypeId = theBuilder.getUint32Type();
  6299. const uint32_t v2f32TypeId = theBuilder.getVecType(f32TypeId, 2);
  6300. const uint32_t zero = theBuilder.getConstantFloat32(0);
  6301. const auto *arg = callExpr->getArg(0);
  6302. const uint32_t argId = doExpr(arg);
  6303. uint32_t elemCount = {};
  6304. if (TypeTranslator::isVectorType(arg->getType(), nullptr, &elemCount)) {
  6305. // The input is a vector. We need to handle each element separately.
  6306. llvm::SmallVector<uint32_t, 4> elements;
  6307. for (uint32_t i = 0; i < elemCount; ++i) {
  6308. const uint32_t srcElem =
  6309. theBuilder.createCompositeExtract(f32TypeId, argId, {i});
  6310. const uint32_t srcVec =
  6311. theBuilder.createCompositeConstruct(v2f32TypeId, {srcElem, zero});
  6312. elements.push_back(theBuilder.createExtInst(
  6313. u32TypeId, glsl, GLSLstd450::GLSLstd450PackHalf2x16, srcVec));
  6314. }
  6315. return theBuilder.createCompositeConstruct(
  6316. theBuilder.getVecType(u32TypeId, elemCount), elements);
  6317. }
  6318. // f16tof32() stores the float into the low-half of the uint. So we need
  6319. // to supply another zero to take the other half.
  6320. const uint32_t srcVec =
  6321. theBuilder.createCompositeConstruct(v2f32TypeId, {argId, zero});
  6322. return theBuilder.createExtInst(u32TypeId, glsl,
  6323. GLSLstd450::GLSLstd450PackHalf2x16, srcVec);
  6324. }
  6325. uint32_t SPIRVEmitter::processIntrinsicUsingSpirvInst(
  6326. const CallExpr *callExpr, spv::Op opcode, bool actPerRowForMatrices) {
  6327. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  6328. if (callExpr->getNumArgs() == 1u) {
  6329. const Expr *arg = callExpr->getArg(0);
  6330. const uint32_t argId = doExpr(arg);
  6331. // If the instruction does not operate on matrices, we can perform the
  6332. // instruction on each vector of the matrix.
  6333. if (actPerRowForMatrices &&
  6334. TypeTranslator::isSpirvAcceptableMatrixType(arg->getType())) {
  6335. const auto actOnEachVec = [this, opcode](uint32_t /*index*/,
  6336. uint32_t vecType,
  6337. uint32_t curRowId) {
  6338. return theBuilder.createUnaryOp(opcode, vecType, {curRowId});
  6339. };
  6340. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  6341. }
  6342. return theBuilder.createUnaryOp(opcode, returnType, {argId});
  6343. } else if (callExpr->getNumArgs() == 2u) {
  6344. const Expr *arg0 = callExpr->getArg(0);
  6345. const uint32_t arg0Id = doExpr(arg0);
  6346. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  6347. // If the instruction does not operate on matrices, we can perform the
  6348. // instruction on each vector of the matrix.
  6349. if (actPerRowForMatrices &&
  6350. TypeTranslator::isSpirvAcceptableMatrixType(arg0->getType())) {
  6351. const auto actOnEachVec = [this, opcode, arg1Id](uint32_t index,
  6352. uint32_t vecType,
  6353. uint32_t arg0RowId) {
  6354. const uint32_t arg1RowId =
  6355. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  6356. return theBuilder.createBinaryOp(opcode, vecType, arg0RowId, arg1RowId);
  6357. };
  6358. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  6359. }
  6360. return theBuilder.createBinaryOp(opcode, returnType, arg0Id, arg1Id);
  6361. }
  6362. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  6363. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  6364. return 0;
  6365. }
  6366. uint32_t SPIRVEmitter::processIntrinsicUsingGLSLInst(
  6367. const CallExpr *callExpr, GLSLstd450 opcode, bool actPerRowForMatrices) {
  6368. // Import the GLSL.std.450 extended instruction set.
  6369. const uint32_t glslInstSetId = theBuilder.getGLSLExtInstSet();
  6370. const uint32_t returnType = typeTranslator.translateType(callExpr->getType());
  6371. if (callExpr->getNumArgs() == 1u) {
  6372. const Expr *arg = callExpr->getArg(0);
  6373. const uint32_t argId = doExpr(arg);
  6374. // If the instruction does not operate on matrices, we can perform the
  6375. // instruction on each vector of the matrix.
  6376. if (actPerRowForMatrices &&
  6377. TypeTranslator::isSpirvAcceptableMatrixType(arg->getType())) {
  6378. const auto actOnEachVec = [this, glslInstSetId,
  6379. opcode](uint32_t /*index*/, uint32_t vecType,
  6380. uint32_t curRowId) {
  6381. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  6382. {curRowId});
  6383. };
  6384. return processEachVectorInMatrix(arg, argId, actOnEachVec);
  6385. }
  6386. return theBuilder.createExtInst(returnType, glslInstSetId, opcode, {argId});
  6387. } else if (callExpr->getNumArgs() == 2u) {
  6388. const Expr *arg0 = callExpr->getArg(0);
  6389. const uint32_t arg0Id = doExpr(arg0);
  6390. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  6391. // If the instruction does not operate on matrices, we can perform the
  6392. // instruction on each vector of the matrix.
  6393. if (actPerRowForMatrices &&
  6394. TypeTranslator::isSpirvAcceptableMatrixType(arg0->getType())) {
  6395. const auto actOnEachVec = [this, glslInstSetId, opcode,
  6396. arg1Id](uint32_t index, uint32_t vecType,
  6397. uint32_t arg0RowId) {
  6398. const uint32_t arg1RowId =
  6399. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  6400. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  6401. {arg0RowId, arg1RowId});
  6402. };
  6403. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  6404. }
  6405. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  6406. {arg0Id, arg1Id});
  6407. } else if (callExpr->getNumArgs() == 3u) {
  6408. const Expr *arg0 = callExpr->getArg(0);
  6409. const uint32_t arg0Id = doExpr(arg0);
  6410. const uint32_t arg1Id = doExpr(callExpr->getArg(1));
  6411. const uint32_t arg2Id = doExpr(callExpr->getArg(2));
  6412. // If the instruction does not operate on matrices, we can perform the
  6413. // instruction on each vector of the matrix.
  6414. if (actPerRowForMatrices &&
  6415. TypeTranslator::isSpirvAcceptableMatrixType(arg0->getType())) {
  6416. const auto actOnEachVec = [this, glslInstSetId, opcode, arg0Id, arg1Id,
  6417. arg2Id](uint32_t index, uint32_t vecType,
  6418. uint32_t arg0RowId) {
  6419. const uint32_t arg1RowId =
  6420. theBuilder.createCompositeExtract(vecType, arg1Id, {index});
  6421. const uint32_t arg2RowId =
  6422. theBuilder.createCompositeExtract(vecType, arg2Id, {index});
  6423. return theBuilder.createExtInst(vecType, glslInstSetId, opcode,
  6424. {arg0RowId, arg1RowId, arg2RowId});
  6425. };
  6426. return processEachVectorInMatrix(arg0, arg0Id, actOnEachVec);
  6427. }
  6428. return theBuilder.createExtInst(returnType, glslInstSetId, opcode,
  6429. {arg0Id, arg1Id, arg2Id});
  6430. }
  6431. emitError("unsupported %0 intrinsic function", callExpr->getExprLoc())
  6432. << cast<DeclRefExpr>(callExpr->getCallee())->getNameInfo().getAsString();
  6433. return 0;
  6434. }
  6435. uint32_t SPIRVEmitter::processIntrinsicLog10(const CallExpr *callExpr) {
  6436. // Since there is no log10 instruction in SPIR-V, we can use:
  6437. // log10(x) = log2(x) * ( 1 / log2(10) )
  6438. // 1 / log2(10) = 0.30103
  6439. const auto scale = theBuilder.getConstantFloat32(0.30103f);
  6440. const auto log2 =
  6441. processIntrinsicUsingGLSLInst(callExpr, GLSLstd450::GLSLstd450Log2, true);
  6442. const auto returnType = callExpr->getType();
  6443. const auto returnTypeId = typeTranslator.translateType(returnType);
  6444. spv::Op scaleOp = TypeTranslator::isScalarType(returnType)
  6445. ? spv::Op::OpFMul
  6446. : TypeTranslator::isVectorType(returnType)
  6447. ? spv::Op::OpVectorTimesScalar
  6448. : spv::Op::OpMatrixTimesScalar;
  6449. return theBuilder.createBinaryOp(scaleOp, returnTypeId, log2, scale);
  6450. }
  6451. uint32_t SPIRVEmitter::getValueZero(QualType type) {
  6452. {
  6453. QualType scalarType = {};
  6454. if (TypeTranslator::isScalarType(type, &scalarType)) {
  6455. if (scalarType->isSignedIntegerType()) {
  6456. return theBuilder.getConstantInt32(0);
  6457. }
  6458. if (scalarType->isUnsignedIntegerType()) {
  6459. return theBuilder.getConstantUint32(0);
  6460. }
  6461. if (scalarType->isFloatingType()) {
  6462. return theBuilder.getConstantFloat32(0.0);
  6463. }
  6464. }
  6465. }
  6466. {
  6467. QualType elemType = {};
  6468. uint32_t size = {};
  6469. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  6470. return getVecValueZero(elemType, size);
  6471. }
  6472. }
  6473. // TODO: Handle getValueZero for MxN matrices.
  6474. emitError("getting value 0 for type %0 unimplemented", {})
  6475. << type.getAsString();
  6476. return 0;
  6477. }
  6478. uint32_t SPIRVEmitter::getVecValueZero(QualType elemType, uint32_t size) {
  6479. const uint32_t elemZeroId = getValueZero(elemType);
  6480. if (size == 1)
  6481. return elemZeroId;
  6482. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemZeroId);
  6483. const uint32_t vecType =
  6484. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  6485. return theBuilder.getConstantComposite(vecType, elements);
  6486. }
  6487. uint32_t SPIRVEmitter::getValueOne(QualType type) {
  6488. {
  6489. QualType scalarType = {};
  6490. if (TypeTranslator::isScalarType(type, &scalarType)) {
  6491. // TODO: Support other types such as short, half, etc.
  6492. if (scalarType->isSignedIntegerType()) {
  6493. return theBuilder.getConstantInt32(1);
  6494. }
  6495. if (scalarType->isUnsignedIntegerType()) {
  6496. return theBuilder.getConstantUint32(1);
  6497. }
  6498. if (const auto *builtinType = scalarType->getAs<BuiltinType>()) {
  6499. // TODO: Add support for other types that are not covered yet.
  6500. switch (builtinType->getKind()) {
  6501. case BuiltinType::Double:
  6502. return theBuilder.getConstantFloat64(1.0);
  6503. case BuiltinType::Float:
  6504. return theBuilder.getConstantFloat32(1.0);
  6505. }
  6506. }
  6507. }
  6508. }
  6509. {
  6510. QualType elemType = {};
  6511. uint32_t size = {};
  6512. if (TypeTranslator::isVectorType(type, &elemType, &size)) {
  6513. return getVecValueOne(elemType, size);
  6514. }
  6515. }
  6516. emitError("getting value 1 for type %0 unimplemented", {}) << type;
  6517. return 0;
  6518. }
  6519. uint32_t SPIRVEmitter::getVecValueOne(QualType elemType, uint32_t size) {
  6520. const uint32_t elemOneId = getValueOne(elemType);
  6521. if (size == 1)
  6522. return elemOneId;
  6523. llvm::SmallVector<uint32_t, 4> elements(size_t(size), elemOneId);
  6524. const uint32_t vecType =
  6525. theBuilder.getVecType(typeTranslator.translateType(elemType), size);
  6526. return theBuilder.getConstantComposite(vecType, elements);
  6527. }
  6528. uint32_t SPIRVEmitter::getMatElemValueOne(QualType type) {
  6529. assert(hlsl::IsHLSLMatType(type));
  6530. const auto elemType = hlsl::GetHLSLMatElementType(type);
  6531. uint32_t rowCount = 0, colCount = 0;
  6532. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  6533. if (rowCount == 1 && colCount == 1)
  6534. return getValueOne(elemType);
  6535. if (colCount == 1)
  6536. return getVecValueOne(elemType, rowCount);
  6537. return getVecValueOne(elemType, colCount);
  6538. }
  6539. uint32_t SPIRVEmitter::translateAPValue(const APValue &value,
  6540. const QualType targetType) {
  6541. uint32_t result = 0;
  6542. // Provide a hint to the typeTranslator that if a literal is discovered, its
  6543. // intended usage is targetType.
  6544. TypeTranslator::LiteralTypeHint hint(typeTranslator, targetType);
  6545. if (targetType->isBooleanType()) {
  6546. result = theBuilder.getConstantBool(value.getInt().getBoolValue(),
  6547. isSpecConstantMode);
  6548. } else if (targetType->isIntegerType()) {
  6549. result = translateAPInt(value.getInt(), targetType);
  6550. } else if (targetType->isFloatingType()) {
  6551. result = translateAPFloat(value.getFloat(), targetType);
  6552. } else if (hlsl::IsHLSLVecType(targetType)) {
  6553. const uint32_t vecType = typeTranslator.translateType(targetType);
  6554. const QualType elemType = hlsl::GetHLSLVecElementType(targetType);
  6555. const auto numElements = value.getVectorLength();
  6556. // Special case for vectors of size 1. SPIR-V doesn't support this vector
  6557. // size so we need to translate it to scalar values.
  6558. if (numElements == 1) {
  6559. result = translateAPValue(value.getVectorElt(0), elemType);
  6560. } else {
  6561. llvm::SmallVector<uint32_t, 4> elements;
  6562. for (uint32_t i = 0; i < numElements; ++i) {
  6563. elements.push_back(translateAPValue(value.getVectorElt(i), elemType));
  6564. }
  6565. result = theBuilder.getConstantComposite(vecType, elements);
  6566. }
  6567. }
  6568. if (result)
  6569. return result;
  6570. emitError("APValue of type %0 unimplemented", {}) << value.getKind();
  6571. value.dump();
  6572. return 0;
  6573. }
  6574. uint32_t SPIRVEmitter::translateAPInt(const llvm::APInt &intValue,
  6575. QualType targetType) {
  6576. targetType = typeTranslator.getIntendedLiteralType(targetType);
  6577. const auto targetTypeBitWidth = astContext.getTypeSize(targetType);
  6578. const bool isSigned = targetType->isSignedIntegerType();
  6579. switch (targetTypeBitWidth) {
  6580. case 16: {
  6581. if (spirvOptions.enable16BitTypes) {
  6582. if (isSigned) {
  6583. return theBuilder.getConstantInt16(
  6584. static_cast<int16_t>(intValue.getSExtValue()));
  6585. } else {
  6586. return theBuilder.getConstantUint16(
  6587. static_cast<uint16_t>(intValue.getZExtValue()));
  6588. }
  6589. } else {
  6590. // If enable16BitTypes option is not true, treat as 32-bit integer.
  6591. if (isSigned)
  6592. return theBuilder.getConstantInt32(
  6593. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  6594. else
  6595. return theBuilder.getConstantUint32(
  6596. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  6597. }
  6598. }
  6599. case 32: {
  6600. if (isSigned) {
  6601. if (!intValue.isSignedIntN(32)) {
  6602. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  6603. "inforamtion",
  6604. {})
  6605. << std::to_string(intValue.getSExtValue());
  6606. return 0;
  6607. }
  6608. return theBuilder.getConstantInt32(
  6609. static_cast<int32_t>(intValue.getSExtValue()), isSpecConstantMode);
  6610. } else {
  6611. if (!intValue.isIntN(32)) {
  6612. emitError("evaluating integer literal %0 as a 32-bit integer loses "
  6613. "inforamtion",
  6614. {})
  6615. << std::to_string(intValue.getZExtValue());
  6616. return 0;
  6617. }
  6618. return theBuilder.getConstantUint32(
  6619. static_cast<uint32_t>(intValue.getZExtValue()), isSpecConstantMode);
  6620. }
  6621. }
  6622. case 64: {
  6623. if (isSigned)
  6624. return theBuilder.getConstantInt64(intValue.getSExtValue());
  6625. else
  6626. return theBuilder.getConstantUint64(intValue.getZExtValue());
  6627. }
  6628. }
  6629. emitError("APInt for target bitwidth %0 unimplemented", {})
  6630. << astContext.getIntWidth(targetType);
  6631. return 0;
  6632. }
  6633. bool SPIRVEmitter::isLiteralLargerThan32Bits(const Expr *expr) {
  6634. if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
  6635. const bool isSigned = expr->getType()->isSignedIntegerType();
  6636. const llvm::APInt &value = intLiteral->getValue();
  6637. return (isSigned && !value.isSignedIntN(32)) ||
  6638. (!isSigned && !value.isIntN(32));
  6639. }
  6640. if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
  6641. llvm::APFloat value = floatLiteral->getValue();
  6642. const auto &semantics = value.getSemantics();
  6643. // regular 'half' and 'float' can be represented in 32 bits.
  6644. if (&semantics == &llvm::APFloat::IEEEsingle ||
  6645. &semantics == &llvm::APFloat::IEEEhalf)
  6646. return true;
  6647. // See if 'double' value can be represented in 32 bits without losing info.
  6648. bool losesInfo = false;
  6649. const auto convertStatus =
  6650. value.convert(llvm::APFloat::IEEEsingle,
  6651. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  6652. if (convertStatus != llvm::APFloat::opOK &&
  6653. convertStatus != llvm::APFloat::opInexact)
  6654. return true;
  6655. }
  6656. return false;
  6657. }
  6658. uint32_t SPIRVEmitter::tryToEvaluateAsInt32(const llvm::APInt &intValue,
  6659. bool isSigned) {
  6660. if (isSigned && intValue.isSignedIntN(32)) {
  6661. return theBuilder.getConstantInt32(
  6662. static_cast<int32_t>(intValue.getSExtValue()));
  6663. }
  6664. if (!isSigned && intValue.isIntN(32)) {
  6665. return theBuilder.getConstantUint32(
  6666. static_cast<uint32_t>(intValue.getZExtValue()));
  6667. }
  6668. // Couldn't evaluate as a 32-bit int without losing information.
  6669. return 0;
  6670. }
  6671. uint32_t SPIRVEmitter::tryToEvaluateAsFloat32(const llvm::APFloat &floatValue) {
  6672. const auto &semantics = floatValue.getSemantics();
  6673. // If the given value is already a 32-bit float, there is no need to convert.
  6674. if (&semantics == &llvm::APFloat::IEEEsingle) {
  6675. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  6676. isSpecConstantMode);
  6677. }
  6678. // Try to see if this literal float can be represented in 32-bit.
  6679. // Since the convert function below may modify the fp value, we call it on a
  6680. // temporary copy.
  6681. llvm::APFloat eval = floatValue;
  6682. bool losesInfo = false;
  6683. const auto convertStatus =
  6684. eval.convert(llvm::APFloat::IEEEsingle,
  6685. llvm::APFloat::rmNearestTiesToEven, &losesInfo);
  6686. if (convertStatus == llvm::APFloat::opOK && !losesInfo)
  6687. return theBuilder.getConstantFloat32(eval.convertToFloat());
  6688. // Couldn't evaluate as a 32-bit float without losing information.
  6689. return 0;
  6690. }
  6691. uint32_t SPIRVEmitter::translateAPFloat(llvm::APFloat floatValue,
  6692. QualType targetType) {
  6693. using llvm::APFloat;
  6694. const auto originalValue = floatValue;
  6695. const auto valueBitwidth = APFloat::getSizeInBits(floatValue.getSemantics());
  6696. // Find out the target bitwidth.
  6697. targetType = typeTranslator.getIntendedLiteralType(targetType);
  6698. auto targetBitwidth =
  6699. APFloat::getSizeInBits(astContext.getFloatTypeSemantics(targetType));
  6700. // If 16-bit types are not enabled, treat them as 32-bit float.
  6701. if (targetBitwidth == 16 && !spirvOptions.enable16BitTypes)
  6702. targetBitwidth = 32;
  6703. if (targetBitwidth != valueBitwidth) {
  6704. bool losesInfo = false;
  6705. const llvm::fltSemantics &targetSemantics =
  6706. targetBitwidth == 16
  6707. ? APFloat::IEEEhalf
  6708. : targetBitwidth == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble;
  6709. const auto status = floatValue.convert(
  6710. targetSemantics, APFloat::roundingMode::rmTowardZero, &losesInfo);
  6711. if (status != APFloat::opStatus::opOK &&
  6712. status != APFloat::opStatus::opInexact) {
  6713. emitError(
  6714. "evaluating float literal %0 at a lower bitwidth loses information",
  6715. {})
  6716. // Converting from 16bit to 32/64-bit won't lose information.
  6717. // So only 32/64-bit values can reach here.
  6718. << std::to_string(valueBitwidth == 32
  6719. ? originalValue.convertToFloat()
  6720. : originalValue.convertToDouble());
  6721. return 0;
  6722. }
  6723. }
  6724. switch (targetBitwidth) {
  6725. case 16:
  6726. return theBuilder.getConstantFloat16(
  6727. static_cast<uint16_t>(floatValue.bitcastToAPInt().getZExtValue()));
  6728. case 32:
  6729. return theBuilder.getConstantFloat32(floatValue.convertToFloat(),
  6730. isSpecConstantMode);
  6731. case 64:
  6732. return theBuilder.getConstantFloat64(floatValue.convertToDouble());
  6733. default:
  6734. break;
  6735. }
  6736. emitError("APFloat for target bitwidth %0 unimplemented", {})
  6737. << targetBitwidth;
  6738. return 0;
  6739. }
  6740. uint32_t SPIRVEmitter::tryToEvaluateAsConst(const Expr *expr) {
  6741. Expr::EvalResult evalResult;
  6742. if (expr->EvaluateAsRValue(evalResult, astContext) &&
  6743. !evalResult.HasSideEffects) {
  6744. return translateAPValue(evalResult.Val, expr->getType());
  6745. }
  6746. return 0;
  6747. }
  6748. spv::ExecutionModel
  6749. SPIRVEmitter::getSpirvShaderStage(const hlsl::ShaderModel &model) {
  6750. // DXIL Models are:
  6751. // Profile (DXIL Model) : HLSL Shader Kind : SPIR-V Shader Stage
  6752. // vs_<version> : Vertex Shader : Vertex Shader
  6753. // hs_<version> : Hull Shader : Tassellation Control Shader
  6754. // ds_<version> : Domain Shader : Tessellation Evaluation Shader
  6755. // gs_<version> : Geometry Shader : Geometry Shader
  6756. // ps_<version> : Pixel Shader : Fragment Shader
  6757. // cs_<version> : Compute Shader : Compute Shader
  6758. switch (model.GetKind()) {
  6759. case hlsl::ShaderModel::Kind::Vertex:
  6760. return spv::ExecutionModel::Vertex;
  6761. case hlsl::ShaderModel::Kind::Hull:
  6762. return spv::ExecutionModel::TessellationControl;
  6763. case hlsl::ShaderModel::Kind::Domain:
  6764. return spv::ExecutionModel::TessellationEvaluation;
  6765. case hlsl::ShaderModel::Kind::Geometry:
  6766. return spv::ExecutionModel::Geometry;
  6767. case hlsl::ShaderModel::Kind::Pixel:
  6768. return spv::ExecutionModel::Fragment;
  6769. case hlsl::ShaderModel::Kind::Compute:
  6770. return spv::ExecutionModel::GLCompute;
  6771. default:
  6772. break;
  6773. }
  6774. llvm_unreachable("unknown shader model");
  6775. }
  6776. void SPIRVEmitter::AddRequiredCapabilitiesForShaderModel() {
  6777. if (shaderModel.IsHS() || shaderModel.IsDS()) {
  6778. theBuilder.requireCapability(spv::Capability::Tessellation);
  6779. } else if (shaderModel.IsGS()) {
  6780. theBuilder.requireCapability(spv::Capability::Geometry);
  6781. } else {
  6782. theBuilder.requireCapability(spv::Capability::Shader);
  6783. }
  6784. }
  6785. void SPIRVEmitter::AddExecutionModeForEntryPoint(uint32_t entryPointId) {
  6786. if (shaderModel.IsPS()) {
  6787. theBuilder.addExecutionMode(entryPointId,
  6788. spv::ExecutionMode::OriginUpperLeft, {});
  6789. }
  6790. }
  6791. bool SPIRVEmitter::processGeometryShaderAttributes(const FunctionDecl *decl,
  6792. uint32_t *arraySize) {
  6793. bool success = true;
  6794. assert(shaderModel.IsGS());
  6795. if (auto *vcAttr = decl->getAttr<HLSLMaxVertexCountAttr>()) {
  6796. theBuilder.addExecutionMode(entryFunctionId,
  6797. spv::ExecutionMode::OutputVertices,
  6798. {static_cast<uint32_t>(vcAttr->getCount())});
  6799. }
  6800. uint32_t invocations = 1;
  6801. if (auto *instanceAttr = decl->getAttr<HLSLInstanceAttr>()) {
  6802. invocations = static_cast<uint32_t>(instanceAttr->getCount());
  6803. }
  6804. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::Invocations,
  6805. {invocations});
  6806. // Only one primitive type is permitted for the geometry shader.
  6807. bool outPoint = false, outLine = false, outTriangle = false, inPoint = false,
  6808. inLine = false, inTriangle = false, inLineAdj = false,
  6809. inTriangleAdj = false;
  6810. for (const auto *param : decl->params()) {
  6811. // Add an execution mode based on the output stream type. Do not an
  6812. // execution mode more than once.
  6813. if (param->hasAttr<HLSLInOutAttr>()) {
  6814. const auto paramType = param->getType();
  6815. if (hlsl::IsHLSLTriangleStreamType(paramType) && !outTriangle) {
  6816. theBuilder.addExecutionMode(
  6817. entryFunctionId, spv::ExecutionMode::OutputTriangleStrip, {});
  6818. outTriangle = true;
  6819. } else if (hlsl::IsHLSLLineStreamType(paramType) && !outLine) {
  6820. theBuilder.addExecutionMode(entryFunctionId,
  6821. spv::ExecutionMode::OutputLineStrip, {});
  6822. outLine = true;
  6823. } else if (hlsl::IsHLSLPointStreamType(paramType) && !outPoint) {
  6824. theBuilder.addExecutionMode(entryFunctionId,
  6825. spv::ExecutionMode::OutputPoints, {});
  6826. outPoint = true;
  6827. }
  6828. // An output stream parameter will not have the input primitive type
  6829. // attributes, so we can continue to the next parameter.
  6830. continue;
  6831. }
  6832. // Add an execution mode based on the input primitive type. Do not add an
  6833. // execution mode more than once.
  6834. if (param->hasAttr<HLSLPointAttr>() && !inPoint) {
  6835. theBuilder.addExecutionMode(entryFunctionId,
  6836. spv::ExecutionMode::InputPoints, {});
  6837. *arraySize = 1;
  6838. inPoint = true;
  6839. } else if (param->hasAttr<HLSLLineAttr>() && !inLine) {
  6840. theBuilder.addExecutionMode(entryFunctionId,
  6841. spv::ExecutionMode::InputLines, {});
  6842. *arraySize = 2;
  6843. inLine = true;
  6844. } else if (param->hasAttr<HLSLTriangleAttr>() && !inTriangle) {
  6845. theBuilder.addExecutionMode(entryFunctionId,
  6846. spv::ExecutionMode::Triangles, {});
  6847. *arraySize = 3;
  6848. inTriangle = true;
  6849. } else if (param->hasAttr<HLSLLineAdjAttr>() && !inLineAdj) {
  6850. theBuilder.addExecutionMode(entryFunctionId,
  6851. spv::ExecutionMode::InputLinesAdjacency, {});
  6852. *arraySize = 4;
  6853. inLineAdj = true;
  6854. } else if (param->hasAttr<HLSLTriangleAdjAttr>() && !inTriangleAdj) {
  6855. theBuilder.addExecutionMode(
  6856. entryFunctionId, spv::ExecutionMode::InputTrianglesAdjacency, {});
  6857. *arraySize = 6;
  6858. inTriangleAdj = true;
  6859. }
  6860. }
  6861. if (inPoint + inLine + inLineAdj + inTriangle + inTriangleAdj > 1) {
  6862. emitError("only one input primitive type can be specified in the geometry "
  6863. "shader",
  6864. {});
  6865. success = false;
  6866. }
  6867. if (outPoint + outTriangle + outLine > 1) {
  6868. emitError("only one output primitive type can be specified in the geometry "
  6869. "shader",
  6870. {});
  6871. success = false;
  6872. }
  6873. return success;
  6874. }
  6875. void SPIRVEmitter::processComputeShaderAttributes(const FunctionDecl *decl) {
  6876. // If not explicitly specified, x, y, and z should be defaulted to 1.
  6877. uint32_t x = 1, y = 1, z = 1;
  6878. if (auto *numThreadsAttr = decl->getAttr<HLSLNumThreadsAttr>()) {
  6879. x = static_cast<uint32_t>(numThreadsAttr->getX());
  6880. y = static_cast<uint32_t>(numThreadsAttr->getY());
  6881. z = static_cast<uint32_t>(numThreadsAttr->getZ());
  6882. }
  6883. theBuilder.addExecutionMode(entryFunctionId, spv::ExecutionMode::LocalSize,
  6884. {x, y, z});
  6885. }
  6886. bool SPIRVEmitter::processTessellationShaderAttributes(
  6887. const FunctionDecl *decl, uint32_t *numOutputControlPoints) {
  6888. assert(shaderModel.IsHS() || shaderModel.IsDS());
  6889. using namespace spv;
  6890. if (auto *domain = decl->getAttr<HLSLDomainAttr>()) {
  6891. const auto domainType = domain->getDomainType().lower();
  6892. const ExecutionMode hsExecMode =
  6893. llvm::StringSwitch<ExecutionMode>(domainType)
  6894. .Case("tri", ExecutionMode::Triangles)
  6895. .Case("quad", ExecutionMode::Quads)
  6896. .Case("isoline", ExecutionMode::Isolines)
  6897. .Default(ExecutionMode::Max);
  6898. if (hsExecMode == ExecutionMode::Max) {
  6899. emitError("unknown domain type specified for entry function",
  6900. domain->getLocation());
  6901. return false;
  6902. }
  6903. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  6904. }
  6905. // Early return for domain shaders as domain shaders only takes the 'domain'
  6906. // attribute.
  6907. if (shaderModel.IsDS())
  6908. return true;
  6909. if (auto *partitioning = decl->getAttr<HLSLPartitioningAttr>()) {
  6910. const auto scheme = partitioning->getScheme().lower();
  6911. if (scheme == "pow2") {
  6912. emitError("pow2 partitioning scheme is not supported since there is no "
  6913. "equivalent in Vulkan",
  6914. partitioning->getLocation());
  6915. return false;
  6916. }
  6917. const ExecutionMode hsExecMode =
  6918. llvm::StringSwitch<ExecutionMode>(scheme)
  6919. .Case("fractional_even", ExecutionMode::SpacingFractionalEven)
  6920. .Case("fractional_odd", ExecutionMode::SpacingFractionalOdd)
  6921. .Case("integer", ExecutionMode::SpacingEqual)
  6922. .Default(ExecutionMode::Max);
  6923. if (hsExecMode == ExecutionMode::Max) {
  6924. emitError("unknown partitioning scheme in hull shader",
  6925. partitioning->getLocation());
  6926. return false;
  6927. }
  6928. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  6929. }
  6930. if (auto *outputTopology = decl->getAttr<HLSLOutputTopologyAttr>()) {
  6931. const auto topology = outputTopology->getTopology().lower();
  6932. const ExecutionMode hsExecMode =
  6933. llvm::StringSwitch<ExecutionMode>(topology)
  6934. .Case("point", ExecutionMode::PointMode)
  6935. .Case("triangle_cw", ExecutionMode::VertexOrderCw)
  6936. .Case("triangle_ccw", ExecutionMode::VertexOrderCcw)
  6937. .Default(ExecutionMode::Max);
  6938. // TODO: There is no SPIR-V equivalent for "line" topology. Is it the
  6939. // default?
  6940. if (topology != "line") {
  6941. if (hsExecMode != spv::ExecutionMode::Max) {
  6942. theBuilder.addExecutionMode(entryFunctionId, hsExecMode, {});
  6943. } else {
  6944. emitError("unknown output topology in hull shader",
  6945. outputTopology->getLocation());
  6946. return false;
  6947. }
  6948. }
  6949. }
  6950. if (auto *controlPoints = decl->getAttr<HLSLOutputControlPointsAttr>()) {
  6951. *numOutputControlPoints = controlPoints->getCount();
  6952. theBuilder.addExecutionMode(entryFunctionId,
  6953. spv::ExecutionMode::OutputVertices,
  6954. {*numOutputControlPoints});
  6955. }
  6956. return true;
  6957. }
  6958. bool SPIRVEmitter::emitEntryFunctionWrapper(const FunctionDecl *decl,
  6959. const uint32_t entryFuncId) {
  6960. // HS specific attributes
  6961. uint32_t numOutputControlPoints = 0;
  6962. uint32_t outputControlPointIdVal = 0; // SV_OutputControlPointID value
  6963. uint32_t primitiveIdVar = 0; // SV_PrimitiveID variable
  6964. uint32_t viewIdVar = 0; // SV_ViewID variable
  6965. uint32_t hullMainInputPatchParam = 0; // Temporary parameter for InputPatch<>
  6966. // The array size of per-vertex input/output variables
  6967. // Used by HS/DS/GS for the additional arrayness, zero means not an array.
  6968. uint32_t inputArraySize = 0;
  6969. uint32_t outputArraySize = 0;
  6970. // Construct the wrapper function signature.
  6971. const uint32_t voidType = theBuilder.getVoidType();
  6972. const uint32_t funcType = theBuilder.getFunctionType(voidType, {});
  6973. // The wrapper entry function surely does not have pre-assigned <result-id>
  6974. // for it like other functions that got added to the work queue following
  6975. // function calls. And the wrapper is the entry function.
  6976. entryFunctionId =
  6977. theBuilder.beginFunction(funcType, voidType, decl->getName());
  6978. // Note this should happen before using declIdMapper for other tasks.
  6979. declIdMapper.setEntryFunctionId(entryFunctionId);
  6980. // Handle attributes specific to each shader stage
  6981. if (shaderModel.IsCS()) {
  6982. processComputeShaderAttributes(decl);
  6983. } else if (shaderModel.IsHS()) {
  6984. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  6985. return false;
  6986. // The input array size for HS is specified in the InputPatch parameter.
  6987. for (const auto *param : decl->params())
  6988. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  6989. inputArraySize = hlsl::GetHLSLInputPatchCount(param->getType());
  6990. break;
  6991. }
  6992. outputArraySize = numOutputControlPoints;
  6993. } else if (shaderModel.IsDS()) {
  6994. if (!processTessellationShaderAttributes(decl, &numOutputControlPoints))
  6995. return false;
  6996. // The input array size for HS is specified in the OutputPatch parameter.
  6997. for (const auto *param : decl->params())
  6998. if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  6999. inputArraySize = hlsl::GetHLSLOutputPatchCount(param->getType());
  7000. break;
  7001. }
  7002. // The per-vertex output of DS is not an array.
  7003. } else if (shaderModel.IsGS()) {
  7004. if (!processGeometryShaderAttributes(decl, &inputArraySize))
  7005. return false;
  7006. // The per-vertex output of GS is not an array.
  7007. }
  7008. // Go through all parameters and record the declaration of SV_ClipDistance
  7009. // and SV_CullDistance. We need to do this extra step because in HLSL we
  7010. // can declare multiple SV_ClipDistance/SV_CullDistance variables of float
  7011. // or vector of float types, but we can only have one single float array
  7012. // for the ClipDistance/CullDistance builtin. So we need to group all
  7013. // SV_ClipDistance/SV_CullDistance variables into one float array, thus we
  7014. // need to calculate the total size of the array and the offset of each
  7015. // variable within that array.
  7016. for (const auto *param : decl->params()) {
  7017. if (canActAsInParmVar(param))
  7018. if (!declIdMapper.glPerVertex.recordClipCullDistanceDecl(param, true))
  7019. return false;
  7020. if (canActAsOutParmVar(param))
  7021. if (!declIdMapper.glPerVertex.recordClipCullDistanceDecl(param, false))
  7022. return false;
  7023. }
  7024. // Also consider the SV_ClipDistance/SV_CullDistance in the return type
  7025. if (!declIdMapper.glPerVertex.recordClipCullDistanceDecl(decl, false))
  7026. return false;
  7027. // Calculate the total size of the ClipDistance/CullDistance array and the
  7028. // offset of SV_ClipDistance/SV_CullDistance variables within the array.
  7029. declIdMapper.glPerVertex.calculateClipCullDistanceArraySize();
  7030. if (!shaderModel.IsCS()) {
  7031. // Generate the gl_PerVertex structs or stand-alone builtins of
  7032. // Position, ClipDistance, and CullDistance.
  7033. declIdMapper.glPerVertex.generateVars(inputArraySize, outputArraySize);
  7034. }
  7035. // Require the ClipDistance/CullDistance capability if necessary.
  7036. // It is legal to just use the ClipDistance/CullDistance builtin without
  7037. // requiring the ClipDistance/CullDistance capability, as long as we don't
  7038. // read or write the builtin variable.
  7039. // For our CodeGen, that corresponds to not seeing SV_ClipDistance or
  7040. // SV_CullDistance at all. If we see them, we will generate code to read
  7041. // them to initialize temporary variable for calling the source code entry
  7042. // function or write to them after calling the source code entry function.
  7043. declIdMapper.glPerVertex.requireCapabilityIfNecessary();
  7044. // The entry basic block.
  7045. const uint32_t entryLabel = theBuilder.createBasicBlock();
  7046. theBuilder.setInsertPoint(entryLabel);
  7047. // Initialize all global variables at the beginning of the wrapper
  7048. for (const VarDecl *varDecl : toInitGloalVars) {
  7049. const auto varInfo = declIdMapper.getDeclEvalInfo(varDecl);
  7050. if (const auto *init = varDecl->getInit()) {
  7051. storeValue(varInfo, doExpr(init), varDecl->getType());
  7052. // Update counter variable associated with global variables
  7053. tryToAssignCounterVar(varDecl, init);
  7054. } else {
  7055. const auto typeId = typeTranslator.translateType(varDecl->getType());
  7056. theBuilder.createStore(varInfo, theBuilder.getConstantNull(typeId));
  7057. }
  7058. }
  7059. // Create temporary variables for holding function call arguments
  7060. llvm::SmallVector<uint32_t, 4> params;
  7061. for (const auto *param : decl->params()) {
  7062. const auto paramType = param->getType();
  7063. const uint32_t typeId = typeTranslator.translateType(paramType);
  7064. std::string tempVarName = "param.var." + param->getNameAsString();
  7065. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  7066. params.push_back(tempVar);
  7067. // Create the stage input variable for parameter not marked as pure out and
  7068. // initialize the corresponding temporary variable
  7069. // Also do not create input variables for output stream objects of geometry
  7070. // shaders (e.g. TriangleStream) which are required to be marked as 'inout'.
  7071. if (canActAsInParmVar(param)) {
  7072. if (shaderModel.IsHS() && hlsl::IsHLSLInputPatchType(paramType)) {
  7073. // Record the temporary variable holding InputPatch. It may be used
  7074. // later in the patch constant function.
  7075. hullMainInputPatchParam = tempVar;
  7076. }
  7077. uint32_t loadedValue = 0;
  7078. if (!declIdMapper.createStageInputVar(param, &loadedValue, false))
  7079. return false;
  7080. theBuilder.createStore(tempVar, loadedValue);
  7081. // Record the temporary variable holding SV_OutputControlPointID,
  7082. // SV_PrimitiveID, and SV_ViewID. It may be used later in the patch
  7083. // constant function.
  7084. if (hasSemantic(param, hlsl::DXIL::SemanticKind::OutputControlPointID))
  7085. outputControlPointIdVal = loadedValue;
  7086. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID))
  7087. primitiveIdVar = tempVar;
  7088. else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID))
  7089. viewIdVar = tempVar;
  7090. }
  7091. }
  7092. // Call the original entry function
  7093. const uint32_t retType = typeTranslator.translateType(decl->getReturnType());
  7094. const uint32_t retVal =
  7095. theBuilder.createFunctionCall(retType, entryFuncId, params);
  7096. // Create and write stage output variables for return value. Special case for
  7097. // Hull shaders since they operate differently in 2 ways:
  7098. // 1- Their return value is in fact an array and each invocation should write
  7099. // to the proper offset in the array.
  7100. // 2- The patch constant function must be called *once* after all invocations
  7101. // of the main entry point function is done.
  7102. if (shaderModel.IsHS()) {
  7103. // Create stage output variables out of the return type.
  7104. if (!declIdMapper.createStageOutputVar(decl, numOutputControlPoints,
  7105. outputControlPointIdVal, retVal))
  7106. return false;
  7107. if (!processHSEntryPointOutputAndPCF(
  7108. decl, retType, retVal, numOutputControlPoints,
  7109. outputControlPointIdVal, primitiveIdVar, viewIdVar,
  7110. hullMainInputPatchParam))
  7111. return false;
  7112. } else {
  7113. if (!declIdMapper.createStageOutputVar(decl, retVal, /*forPCF*/ false))
  7114. return false;
  7115. }
  7116. // Create and write stage output variables for parameters marked as
  7117. // out/inout
  7118. for (uint32_t i = 0; i < decl->getNumParams(); ++i) {
  7119. const auto *param = decl->getParamDecl(i);
  7120. if (canActAsOutParmVar(param)) {
  7121. // Load the value from the parameter after function call
  7122. const uint32_t typeId = typeTranslator.translateType(param->getType());
  7123. uint32_t loadedParam = 0;
  7124. // Write back of stage output variables in GS is manually controlled by
  7125. // .Append() intrinsic method. No need to load the parameter since we
  7126. // won't need to write back here.
  7127. if (!shaderModel.IsGS())
  7128. loadedParam = theBuilder.createLoad(typeId, params[i]);
  7129. if (!declIdMapper.createStageOutputVar(param, loadedParam, false))
  7130. return false;
  7131. }
  7132. }
  7133. theBuilder.createReturn();
  7134. theBuilder.endFunction();
  7135. // For Hull shaders, there is no explicit call to the PCF in the HLSL source.
  7136. // We should invoke a translation of the PCF manually.
  7137. if (shaderModel.IsHS())
  7138. doDecl(patchConstFunc);
  7139. return true;
  7140. }
  7141. bool SPIRVEmitter::processHSEntryPointOutputAndPCF(
  7142. const FunctionDecl *hullMainFuncDecl, uint32_t retType, uint32_t retVal,
  7143. uint32_t numOutputControlPoints, uint32_t outputControlPointId,
  7144. uint32_t primitiveId, uint32_t viewId, uint32_t hullMainInputPatch) {
  7145. // This method may only be called for Hull shaders.
  7146. assert(shaderModel.IsHS());
  7147. // For Hull shaders, the real output is an array of size
  7148. // numOutputControlPoints. The results of the main should be written to the
  7149. // correct offset in the array (based on InvocationID).
  7150. if (!numOutputControlPoints) {
  7151. emitError("number of output control points cannot be zero",
  7152. hullMainFuncDecl->getLocation());
  7153. return false;
  7154. }
  7155. // TODO: We should be able to handle cases where the SV_OutputControlPointID
  7156. // is not provided.
  7157. if (!outputControlPointId) {
  7158. emitError(
  7159. "SV_OutputControlPointID semantic must be provided in hull shader",
  7160. hullMainFuncDecl->getLocation());
  7161. return false;
  7162. }
  7163. if (!patchConstFunc) {
  7164. emitError("patch constant function not defined in hull shader",
  7165. hullMainFuncDecl->getLocation());
  7166. return false;
  7167. }
  7168. uint32_t hullMainOutputPatch = 0;
  7169. // If the patch constant function (PCF) takes the result of the Hull main
  7170. // entry point, create a temporary function-scope variable and write the
  7171. // results to it, so it can be passed to the PCF.
  7172. if (patchConstFuncTakesHullOutputPatch(patchConstFunc)) {
  7173. const uint32_t hullMainRetType = theBuilder.getArrayType(
  7174. retType, theBuilder.getConstantUint32(numOutputControlPoints));
  7175. hullMainOutputPatch =
  7176. theBuilder.addFnVar(hullMainRetType, "temp.var.hullMainRetVal");
  7177. const auto tempLocation = theBuilder.createAccessChain(
  7178. theBuilder.getPointerType(retType, spv::StorageClass::Function),
  7179. hullMainOutputPatch, {outputControlPointId});
  7180. theBuilder.createStore(tempLocation, retVal);
  7181. }
  7182. // Now create a barrier before calling the Patch Constant Function (PCF).
  7183. // Flags are:
  7184. // Execution Barrier scope = Workgroup (2)
  7185. // Memory Barrier scope = Device (1)
  7186. // Memory Semantics Barrier scope = None (0)
  7187. theBuilder.createBarrier(theBuilder.getConstantUint32(2),
  7188. theBuilder.getConstantUint32(1),
  7189. theBuilder.getConstantUint32(0));
  7190. // The PCF should be called only once. Therefore, we check the invocationID,
  7191. // and we only allow ID 0 to call the PCF.
  7192. const uint32_t condition = theBuilder.createBinaryOp(
  7193. spv::Op::OpIEqual, theBuilder.getBoolType(), outputControlPointId,
  7194. theBuilder.getConstantUint32(0));
  7195. const uint32_t thenBB = theBuilder.createBasicBlock("if.true");
  7196. const uint32_t mergeBB = theBuilder.createBasicBlock("if.merge");
  7197. theBuilder.createConditionalBranch(condition, thenBB, mergeBB, mergeBB);
  7198. theBuilder.addSuccessor(thenBB);
  7199. theBuilder.addSuccessor(mergeBB);
  7200. theBuilder.setMergeTarget(mergeBB);
  7201. theBuilder.setInsertPoint(thenBB);
  7202. // Call the PCF. Since the function is not explicitly called, we must first
  7203. // register an ID for it.
  7204. const uint32_t pcfId = declIdMapper.getOrRegisterFnResultId(patchConstFunc);
  7205. const uint32_t pcfRetType =
  7206. typeTranslator.translateType(patchConstFunc->getReturnType());
  7207. std::vector<uint32_t> pcfParams;
  7208. // A lambda for creating a stage input variable and its associated temporary
  7209. // variable for function call. Also initializes the temporary variable using
  7210. // the contents loaded from the stage input variable. Returns the <result-id>
  7211. // of the temporary variable.
  7212. const auto createParmVarAndInitFromStageInputVar =
  7213. [this](const ParmVarDecl *param) {
  7214. const uint32_t typeId = typeTranslator.translateType(param->getType());
  7215. std::string tempVarName = "param.var." + param->getNameAsString();
  7216. const uint32_t tempVar = theBuilder.addFnVar(typeId, tempVarName);
  7217. uint32_t loadedValue = 0;
  7218. declIdMapper.createStageInputVar(param, &loadedValue, /*forPCF*/ true);
  7219. theBuilder.createStore(tempVar, loadedValue);
  7220. return tempVar;
  7221. };
  7222. for (const auto *param : patchConstFunc->parameters()) {
  7223. // Note: According to the HLSL reference, the PCF takes an InputPatch of
  7224. // ControlPoints as well as the PatchID (PrimitiveID). This does not
  7225. // necessarily mean that they are present. There is also no requirement
  7226. // for the order of parameters passed to PCF.
  7227. if (hlsl::IsHLSLInputPatchType(param->getType())) {
  7228. pcfParams.push_back(hullMainInputPatch);
  7229. } else if (hlsl::IsHLSLOutputPatchType(param->getType())) {
  7230. pcfParams.push_back(hullMainOutputPatch);
  7231. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::PrimitiveID)) {
  7232. if (!primitiveId) {
  7233. primitiveId = createParmVarAndInitFromStageInputVar(param);
  7234. }
  7235. pcfParams.push_back(primitiveId);
  7236. } else if (hasSemantic(param, hlsl::DXIL::SemanticKind::ViewID)) {
  7237. if (!viewId) {
  7238. viewId = createParmVarAndInitFromStageInputVar(param);
  7239. }
  7240. pcfParams.push_back(viewId);
  7241. } else {
  7242. emitError("patch constant function parameter '%0' unknown",
  7243. param->getLocation())
  7244. << param->getName();
  7245. }
  7246. }
  7247. const uint32_t pcfResultId =
  7248. theBuilder.createFunctionCall(pcfRetType, pcfId, {pcfParams});
  7249. if (!declIdMapper.createStageOutputVar(patchConstFunc, pcfResultId,
  7250. /*forPCF*/ true))
  7251. return false;
  7252. theBuilder.createBranch(mergeBB);
  7253. theBuilder.addSuccessor(mergeBB);
  7254. theBuilder.setInsertPoint(mergeBB);
  7255. return true;
  7256. }
  7257. bool SPIRVEmitter::allSwitchCasesAreIntegerLiterals(const Stmt *root) {
  7258. if (!root)
  7259. return false;
  7260. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  7261. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  7262. if (!caseStmt && !compoundStmt)
  7263. return true;
  7264. if (caseStmt) {
  7265. const Expr *caseExpr = caseStmt->getLHS();
  7266. return caseExpr && caseExpr->isEvaluatable(astContext);
  7267. }
  7268. // Recurse down if facing a compound statement.
  7269. for (auto *st : compoundStmt->body())
  7270. if (!allSwitchCasesAreIntegerLiterals(st))
  7271. return false;
  7272. return true;
  7273. }
  7274. void SPIRVEmitter::discoverAllCaseStmtInSwitchStmt(
  7275. const Stmt *root, uint32_t *defaultBB,
  7276. std::vector<std::pair<uint32_t, uint32_t>> *targets) {
  7277. if (!root)
  7278. return;
  7279. // A switch case can only appear in DefaultStmt, CaseStmt, or
  7280. // CompoundStmt. For the rest, we can just return.
  7281. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  7282. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  7283. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  7284. if (!defaultStmt && !caseStmt && !compoundStmt)
  7285. return;
  7286. // Recurse down if facing a compound statement.
  7287. if (compoundStmt) {
  7288. for (auto *st : compoundStmt->body())
  7289. discoverAllCaseStmtInSwitchStmt(st, defaultBB, targets);
  7290. return;
  7291. }
  7292. std::string caseLabel;
  7293. uint32_t caseValue = 0;
  7294. if (defaultStmt) {
  7295. // This is the default branch.
  7296. caseLabel = "switch.default";
  7297. } else if (caseStmt) {
  7298. // This is a non-default case.
  7299. // When using OpSwitch, we only allow integer literal cases. e.g:
  7300. // case <literal_integer>: {...; break;}
  7301. const Expr *caseExpr = caseStmt->getLHS();
  7302. assert(caseExpr && caseExpr->isEvaluatable(astContext));
  7303. auto bitWidth = astContext.getIntWidth(caseExpr->getType());
  7304. if (bitWidth != 32)
  7305. emitError(
  7306. "non-32bit integer case value in switch statement unimplemented",
  7307. caseExpr->getExprLoc());
  7308. Expr::EvalResult evalResult;
  7309. caseExpr->EvaluateAsRValue(evalResult, astContext);
  7310. const int64_t value = evalResult.Val.getInt().getSExtValue();
  7311. caseValue = static_cast<uint32_t>(value);
  7312. caseLabel = "switch." + std::string(value < 0 ? "n" : "") +
  7313. llvm::itostr(std::abs(value));
  7314. }
  7315. const uint32_t caseBB = theBuilder.createBasicBlock(caseLabel);
  7316. theBuilder.addSuccessor(caseBB);
  7317. stmtBasicBlock[root] = caseBB;
  7318. // Add all cases to the 'targets' vector.
  7319. if (caseStmt)
  7320. targets->emplace_back(caseValue, caseBB);
  7321. // The default label is not part of the 'targets' vector that is passed
  7322. // to the OpSwitch instruction.
  7323. // If default statement was discovered, return its label via defaultBB.
  7324. if (defaultStmt)
  7325. *defaultBB = caseBB;
  7326. // Process cases nested in other cases. It happens when we have fall through
  7327. // cases. For example:
  7328. // case 1: case 2: ...; break;
  7329. // will result in the CaseSmt for case 2 nested in the one for case 1.
  7330. discoverAllCaseStmtInSwitchStmt(caseStmt ? caseStmt->getSubStmt()
  7331. : defaultStmt->getSubStmt(),
  7332. defaultBB, targets);
  7333. }
  7334. void SPIRVEmitter::flattenSwitchStmtAST(const Stmt *root,
  7335. std::vector<const Stmt *> *flatSwitch) {
  7336. const auto *caseStmt = dyn_cast<CaseStmt>(root);
  7337. const auto *compoundStmt = dyn_cast<CompoundStmt>(root);
  7338. const auto *defaultStmt = dyn_cast<DefaultStmt>(root);
  7339. if (!compoundStmt) {
  7340. flatSwitch->push_back(root);
  7341. }
  7342. if (compoundStmt) {
  7343. for (const auto *st : compoundStmt->body())
  7344. flattenSwitchStmtAST(st, flatSwitch);
  7345. } else if (caseStmt) {
  7346. flattenSwitchStmtAST(caseStmt->getSubStmt(), flatSwitch);
  7347. } else if (defaultStmt) {
  7348. flattenSwitchStmtAST(defaultStmt->getSubStmt(), flatSwitch);
  7349. }
  7350. }
  7351. void SPIRVEmitter::processCaseStmtOrDefaultStmt(const Stmt *stmt) {
  7352. auto *caseStmt = dyn_cast<CaseStmt>(stmt);
  7353. auto *defaultStmt = dyn_cast<DefaultStmt>(stmt);
  7354. assert(caseStmt || defaultStmt);
  7355. uint32_t caseBB = stmtBasicBlock[stmt];
  7356. if (!theBuilder.isCurrentBasicBlockTerminated()) {
  7357. // We are about to handle the case passed in as parameter. If the current
  7358. // basic block is not terminated, it means the previous case is a fall
  7359. // through case. We need to link it to the case to be processed.
  7360. theBuilder.createBranch(caseBB);
  7361. theBuilder.addSuccessor(caseBB);
  7362. }
  7363. theBuilder.setInsertPoint(caseBB);
  7364. doStmt(caseStmt ? caseStmt->getSubStmt() : defaultStmt->getSubStmt());
  7365. }
  7366. void SPIRVEmitter::processSwitchStmtUsingSpirvOpSwitch(
  7367. const SwitchStmt *switchStmt) {
  7368. // First handle the condition variable DeclStmt if one exists.
  7369. // For example: handle 'int a = b' in the following:
  7370. // switch (int a = b) {...}
  7371. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  7372. doDeclStmt(condVarDeclStmt);
  7373. const uint32_t selector = doExpr(switchStmt->getCond());
  7374. // We need a merge block regardless of the number of switch cases.
  7375. // Since OpSwitch always requires a default label, if the switch statement
  7376. // does not have a default branch, we use the merge block as the default
  7377. // target.
  7378. const uint32_t mergeBB = theBuilder.createBasicBlock("switch.merge");
  7379. theBuilder.setMergeTarget(mergeBB);
  7380. breakStack.push(mergeBB);
  7381. uint32_t defaultBB = mergeBB;
  7382. // (literal, labelId) pairs to pass to the OpSwitch instruction.
  7383. std::vector<std::pair<uint32_t, uint32_t>> targets;
  7384. discoverAllCaseStmtInSwitchStmt(switchStmt->getBody(), &defaultBB, &targets);
  7385. // Create the OpSelectionMerge and OpSwitch.
  7386. theBuilder.createSwitch(mergeBB, selector, defaultBB, targets);
  7387. // Handle the switch body.
  7388. doStmt(switchStmt->getBody());
  7389. if (!theBuilder.isCurrentBasicBlockTerminated())
  7390. theBuilder.createBranch(mergeBB);
  7391. theBuilder.setInsertPoint(mergeBB);
  7392. breakStack.pop();
  7393. }
  7394. void SPIRVEmitter::processSwitchStmtUsingIfStmts(const SwitchStmt *switchStmt) {
  7395. std::vector<const Stmt *> flatSwitch;
  7396. flattenSwitchStmtAST(switchStmt->getBody(), &flatSwitch);
  7397. // First handle the condition variable DeclStmt if one exists.
  7398. // For example: handle 'int a = b' in the following:
  7399. // switch (int a = b) {...}
  7400. if (const auto *condVarDeclStmt = switchStmt->getConditionVariableDeclStmt())
  7401. doDeclStmt(condVarDeclStmt);
  7402. // Figure out the indexes of CaseStmts (and DefaultStmt if it exists) in
  7403. // the flattened switch AST.
  7404. // For instance, for the following flat vector:
  7405. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  7406. // |Case1|Stmt1|Case2|Stmt2|Break|Case3|Case4|Stmt4|Break|Default|Stmt5|
  7407. // +-----+-----+-----+-----+-----+-----+-----+-----+-----+-------+-----+
  7408. // The indexes are: {0, 2, 5, 6, 9}
  7409. std::vector<uint32_t> caseStmtLocs;
  7410. for (uint32_t i = 0; i < flatSwitch.size(); ++i)
  7411. if (isa<CaseStmt>(flatSwitch[i]) || isa<DefaultStmt>(flatSwitch[i]))
  7412. caseStmtLocs.push_back(i);
  7413. IfStmt *prevIfStmt = nullptr;
  7414. IfStmt *rootIfStmt = nullptr;
  7415. CompoundStmt *defaultBody = nullptr;
  7416. // For each case, start at its index in the vector, and go forward
  7417. // accumulating statements until BreakStmt or end of vector is reached.
  7418. for (auto curCaseIndex : caseStmtLocs) {
  7419. const Stmt *curCase = flatSwitch[curCaseIndex];
  7420. // CompoundStmt to hold all statements for this case.
  7421. CompoundStmt *cs = new (astContext) CompoundStmt(Stmt::EmptyShell());
  7422. // Accumulate all non-case/default/break statements as the body for the
  7423. // current case.
  7424. std::vector<Stmt *> statements;
  7425. for (int i = curCaseIndex + 1;
  7426. i < flatSwitch.size() && !isa<BreakStmt>(flatSwitch[i]); ++i) {
  7427. if (!isa<CaseStmt>(flatSwitch[i]) && !isa<DefaultStmt>(flatSwitch[i]))
  7428. statements.push_back(const_cast<Stmt *>(flatSwitch[i]));
  7429. }
  7430. if (!statements.empty())
  7431. cs->setStmts(astContext, statements.data(), statements.size());
  7432. // For non-default cases, generate the IfStmt that compares the switch
  7433. // value to the case value.
  7434. if (auto *caseStmt = dyn_cast<CaseStmt>(curCase)) {
  7435. IfStmt *curIf = new (astContext) IfStmt(Stmt::EmptyShell());
  7436. BinaryOperator *bo = new (astContext) BinaryOperator(Stmt::EmptyShell());
  7437. bo->setLHS(const_cast<Expr *>(switchStmt->getCond()));
  7438. bo->setRHS(const_cast<Expr *>(caseStmt->getLHS()));
  7439. bo->setOpcode(BO_EQ);
  7440. bo->setType(astContext.getLogicalOperationType());
  7441. curIf->setCond(bo);
  7442. curIf->setThen(cs);
  7443. // No conditional variable associated with this faux if statement.
  7444. curIf->setConditionVariable(astContext, nullptr);
  7445. // Each If statement is the "else" of the previous if statement.
  7446. if (prevIfStmt)
  7447. prevIfStmt->setElse(curIf);
  7448. else
  7449. rootIfStmt = curIf;
  7450. prevIfStmt = curIf;
  7451. } else {
  7452. // Record the DefaultStmt body as it will be used as the body of the
  7453. // "else" block in the if-elseif-...-else pattern.
  7454. defaultBody = cs;
  7455. }
  7456. }
  7457. // If a default case exists, it is the "else" of the last if statement.
  7458. if (prevIfStmt)
  7459. prevIfStmt->setElse(defaultBody);
  7460. // Since all else-if and else statements are the child nodes of the first
  7461. // IfStmt, we only need to call doStmt for the first IfStmt.
  7462. if (rootIfStmt)
  7463. doStmt(rootIfStmt);
  7464. // If there are no CaseStmt and there is only 1 DefaultStmt, there will be
  7465. // no if statements. The switch in that case only executes the body of the
  7466. // default case.
  7467. else if (defaultBody)
  7468. doStmt(defaultBody);
  7469. }
  7470. uint32_t SPIRVEmitter::extractVecFromVec4(uint32_t fromId,
  7471. uint32_t targetVecSize,
  7472. uint32_t targetElemTypeId) {
  7473. assert(targetVecSize > 0 && targetVecSize < 5);
  7474. const uint32_t retType =
  7475. targetVecSize == 1
  7476. ? targetElemTypeId
  7477. : theBuilder.getVecType(targetElemTypeId, targetVecSize);
  7478. switch (targetVecSize) {
  7479. case 1:
  7480. return theBuilder.createCompositeExtract(retType, fromId, {0});
  7481. break;
  7482. case 2:
  7483. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1});
  7484. break;
  7485. case 3:
  7486. return theBuilder.createVectorShuffle(retType, fromId, fromId, {0, 1, 2});
  7487. break;
  7488. case 4:
  7489. return fromId;
  7490. default:
  7491. llvm_unreachable("vector element count must be 1, 2, 3, or 4");
  7492. }
  7493. }
  7494. } // end namespace spirv
  7495. } // end namespace clang