GlslangToSpv.cpp 436 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081
  1. //
  2. // Copyright (C) 2014-2016 LunarG, Inc.
  3. // Copyright (C) 2015-2020 Google, Inc.
  4. // Copyright (C) 2017 ARM Limited.
  5. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
  6. //
  7. // All rights reserved.
  8. //
  9. // Redistribution and use in source and binary forms, with or without
  10. // modification, are permitted provided that the following conditions
  11. // are met:
  12. //
  13. // Redistributions of source code must retain the above copyright
  14. // notice, this list of conditions and the following disclaimer.
  15. //
  16. // Redistributions in binary form must reproduce the above
  17. // copyright notice, this list of conditions and the following
  18. // disclaimer in the documentation and/or other materials provided
  19. // with the distribution.
  20. //
  21. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  22. // contributors may be used to endorse or promote products derived
  23. // from this software without specific prior written permission.
  24. //
  25. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  28. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  29. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  30. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  31. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  32. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  33. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  34. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  35. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  36. // POSSIBILITY OF SUCH DAMAGE.
  37. //
  38. // Visit the nodes in the glslang intermediate tree representation to
  39. // translate them to SPIR-V.
  40. //
  41. #include "spirv.hpp"
  42. #include "GlslangToSpv.h"
  43. #include "SpvBuilder.h"
  44. namespace spv {
  45. #include "GLSL.std.450.h"
  46. #include "GLSL.ext.KHR.h"
  47. #include "GLSL.ext.EXT.h"
  48. #include "GLSL.ext.AMD.h"
  49. #include "GLSL.ext.NV.h"
  50. #include "GLSL.ext.ARM.h"
  51. #include "NonSemanticDebugPrintf.h"
  52. }
  53. // Glslang includes
  54. #include "../glslang/MachineIndependent/localintermediate.h"
  55. #include "../glslang/MachineIndependent/SymbolTable.h"
  56. #include "../glslang/Include/Common.h"
  57. // Build-time generated includes
  58. #include "glslang/build_info.h"
  59. #include <fstream>
  60. #include <iomanip>
  61. #include <list>
  62. #include <map>
  63. #include <stack>
  64. #include <string>
  65. #include <vector>
  66. namespace {
  67. namespace {
  68. class SpecConstantOpModeGuard {
  69. public:
  70. SpecConstantOpModeGuard(spv::Builder* builder)
  71. : builder_(builder) {
  72. previous_flag_ = builder->isInSpecConstCodeGenMode();
  73. }
  74. ~SpecConstantOpModeGuard() {
  75. previous_flag_ ? builder_->setToSpecConstCodeGenMode()
  76. : builder_->setToNormalCodeGenMode();
  77. }
  78. void turnOnSpecConstantOpMode() {
  79. builder_->setToSpecConstCodeGenMode();
  80. }
  81. private:
  82. spv::Builder* builder_;
  83. bool previous_flag_;
  84. };
  85. struct OpDecorations {
  86. public:
  87. OpDecorations(spv::Decoration precision, spv::Decoration noContraction, spv::Decoration nonUniform) :
  88. precision(precision)
  89. ,
  90. noContraction(noContraction),
  91. nonUniform(nonUniform)
  92. { }
  93. spv::Decoration precision;
  94. void addNoContraction(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, noContraction); }
  95. void addNonUniform(spv::Builder& builder, spv::Id t) { builder.addDecoration(t, nonUniform); }
  96. protected:
  97. spv::Decoration noContraction;
  98. spv::Decoration nonUniform;
  99. };
  100. } // namespace
  101. //
  102. // The main holder of information for translating glslang to SPIR-V.
  103. //
  104. // Derives from the AST walking base class.
  105. //
  106. class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
  107. public:
  108. TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
  109. glslang::SpvOptions& options);
  110. virtual ~TGlslangToSpvTraverser() { }
  111. bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
  112. bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
  113. void visitConstantUnion(glslang::TIntermConstantUnion*);
  114. bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
  115. bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
  116. void visitSymbol(glslang::TIntermSymbol* symbol);
  117. bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
  118. bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
  119. bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
  120. void finishSpv();
  121. void dumpSpv(std::vector<unsigned int>& out);
  122. protected:
  123. TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
  124. TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
  125. spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
  126. spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
  127. spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
  128. spv::Decoration TranslateNonUniformDecoration(const spv::Builder::AccessChain::CoherentFlags& coherentFlags);
  129. spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
  130. spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
  131. spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
  132. spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
  133. spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
  134. spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
  135. spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
  136. spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
  137. spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
  138. spv::StorageClass TranslateStorageClass(const glslang::TType&);
  139. void TranslateLiterals(const glslang::TVector<const glslang::TIntermConstantUnion*>&, std::vector<unsigned>&) const;
  140. void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
  141. spv::Id createSpvVariable(const glslang::TIntermSymbol*, spv::Id forcedType);
  142. spv::Id getSampledType(const glslang::TSampler&);
  143. spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
  144. spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
  145. void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
  146. spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
  147. spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
  148. bool lastBufferBlockMember, bool forwardReferenceOnly = false);
  149. bool filterMember(const glslang::TType& member);
  150. spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
  151. glslang::TLayoutPacking, const glslang::TQualifier&);
  152. void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
  153. const glslang::TQualifier&, spv::Id, const std::vector<spv::Id>& spvMembers);
  154. spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim, bool allowZero = false);
  155. spv::Id accessChainLoad(const glslang::TType& type);
  156. void accessChainStore(const glslang::TType& type, spv::Id rvalue);
  157. void multiTypeStore(const glslang::TType&, spv::Id rValue);
  158. spv::Id convertLoadedBoolInUniformToUint(const glslang::TType& type, spv::Id nominalTypeId, spv::Id loadedId);
  159. glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
  160. int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
  161. int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
  162. void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
  163. int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
  164. void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
  165. bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
  166. bool writableParam(glslang::TStorageQualifier) const;
  167. bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
  168. void makeFunctions(const glslang::TIntermSequence&);
  169. void makeGlobalInitializers(const glslang::TIntermSequence&);
  170. void collectRayTracingLinkerObjects();
  171. void visitFunctions(const glslang::TIntermSequence&);
  172. void handleFunctionEntry(const glslang::TIntermAggregate* node);
  173. void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
  174. spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
  175. void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
  176. spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
  177. spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
  178. spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
  179. glslang::TBasicType typeProxy, bool reduceComparison = true);
  180. spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
  181. spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
  182. glslang::TBasicType typeProxy,
  183. const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
  184. spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
  185. glslang::TBasicType typeProxy);
  186. spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
  187. glslang::TBasicType typeProxy);
  188. spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize, spv::Id destType);
  189. spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
  190. spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
  191. std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
  192. const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags);
  193. spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
  194. glslang::TBasicType typeProxy);
  195. spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
  196. spv::Id typeId, std::vector<spv::Id>& operands);
  197. spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands,
  198. glslang::TBasicType typeProxy);
  199. spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId,
  200. std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
  201. spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
  202. spv::Id getSymbolId(const glslang::TIntermSymbol* node);
  203. void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
  204. spv::Id createSpvConstant(const glslang::TIntermTyped&);
  205. spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&,
  206. int& nextConst, bool specConstant);
  207. bool isTrivialLeaf(const glslang::TIntermTyped* node);
  208. bool isTrivial(const glslang::TIntermTyped* node);
  209. spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
  210. spv::Id getExtBuiltins(const char* name);
  211. std::pair<spv::Id, spv::Id> getForcedType(glslang::TBuiltInVariable builtIn, const glslang::TType&);
  212. spv::Id translateForcedType(spv::Id object);
  213. spv::Id createCompositeConstruct(spv::Id typeId, std::vector<spv::Id> constituents);
  214. glslang::SpvOptions& options;
  215. spv::Function* shaderEntry;
  216. spv::Function* currentFunction;
  217. spv::Instruction* entryPoint;
  218. int sequenceDepth;
  219. spv::SpvBuildLogger* logger;
  220. // There is a 1:1 mapping between a spv builder and a module; this is thread safe
  221. spv::Builder builder;
  222. bool inEntryPoint;
  223. bool entryPointTerminated;
  224. bool linkageOnly; // true when visiting the set of objects in the AST present only for
  225. // establishing interface, whether or not they were statically used
  226. std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
  227. const glslang::TIntermediate* glslangIntermediate;
  228. bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
  229. spv::Id stdBuiltins;
  230. spv::Id nonSemanticDebugPrintf;
  231. std::unordered_map<std::string, spv::Id> extBuiltinMap;
  232. std::unordered_map<long long, spv::Id> symbolValues;
  233. std::unordered_map<uint32_t, spv::Id> builtInVariableIds;
  234. std::unordered_set<long long> rValueParameters; // set of formal function parameters passed as rValues,
  235. // rather than a pointer
  236. std::unordered_map<std::string, spv::Function*> functionMap;
  237. std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
  238. // for mapping glslang block indices to spv indices (e.g., due to hidden members):
  239. std::unordered_map<long long, std::vector<int>> memberRemapper;
  240. // for mapping glslang symbol struct to symbol Id
  241. std::unordered_map<const glslang::TTypeList*, long long> glslangTypeToIdMap;
  242. std::stack<bool> breakForLoop; // false means break for switch
  243. std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
  244. // Map pointee types for EbtReference to their forward pointers
  245. std::map<const glslang::TType *, spv::Id> forwardPointers;
  246. // Type forcing, for when SPIR-V wants a different type than the AST,
  247. // requiring local translation to and from SPIR-V type on every access.
  248. // Maps <builtin-variable-id -> AST-required-type-id>
  249. std::unordered_map<spv::Id, spv::Id> forceType;
  250. // Used by Task shader while generating opearnds for OpEmitMeshTasksEXT
  251. spv::Id taskPayloadID;
  252. // Used later for generating OpTraceKHR/OpExecuteCallableKHR/OpHitObjectRecordHit*/OpHitObjectGetShaderBindingTableData
  253. std::unordered_map<unsigned int, glslang::TIntermSymbol *> locationToSymbol[4];
  254. };
  255. //
  256. // Helper functions for translating glslang representations to SPIR-V enumerants.
  257. //
  258. // Translate glslang profile to SPIR-V source language.
  259. spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
  260. {
  261. switch (source) {
  262. case glslang::EShSourceGlsl:
  263. switch (profile) {
  264. case ENoProfile:
  265. case ECoreProfile:
  266. case ECompatibilityProfile:
  267. return spv::SourceLanguageGLSL;
  268. case EEsProfile:
  269. return spv::SourceLanguageESSL;
  270. default:
  271. return spv::SourceLanguageUnknown;
  272. }
  273. case glslang::EShSourceHlsl:
  274. return spv::SourceLanguageHLSL;
  275. default:
  276. return spv::SourceLanguageUnknown;
  277. }
  278. }
  279. // Translate glslang language (stage) to SPIR-V execution model.
  280. spv::ExecutionModel TranslateExecutionModel(EShLanguage stage, bool isMeshShaderEXT = false)
  281. {
  282. switch (stage) {
  283. case EShLangVertex: return spv::ExecutionModelVertex;
  284. case EShLangFragment: return spv::ExecutionModelFragment;
  285. case EShLangCompute: return spv::ExecutionModelGLCompute;
  286. case EShLangTessControl: return spv::ExecutionModelTessellationControl;
  287. case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
  288. case EShLangGeometry: return spv::ExecutionModelGeometry;
  289. case EShLangRayGen: return spv::ExecutionModelRayGenerationKHR;
  290. case EShLangIntersect: return spv::ExecutionModelIntersectionKHR;
  291. case EShLangAnyHit: return spv::ExecutionModelAnyHitKHR;
  292. case EShLangClosestHit: return spv::ExecutionModelClosestHitKHR;
  293. case EShLangMiss: return spv::ExecutionModelMissKHR;
  294. case EShLangCallable: return spv::ExecutionModelCallableKHR;
  295. case EShLangTask: return (isMeshShaderEXT)? spv::ExecutionModelTaskEXT : spv::ExecutionModelTaskNV;
  296. case EShLangMesh: return (isMeshShaderEXT)? spv::ExecutionModelMeshEXT: spv::ExecutionModelMeshNV;
  297. default:
  298. assert(0);
  299. return spv::ExecutionModelFragment;
  300. }
  301. }
  302. // Translate glslang sampler type to SPIR-V dimensionality.
  303. spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
  304. {
  305. switch (sampler.dim) {
  306. case glslang::Esd1D: return spv::Dim1D;
  307. case glslang::Esd2D: return spv::Dim2D;
  308. case glslang::Esd3D: return spv::Dim3D;
  309. case glslang::EsdCube: return spv::DimCube;
  310. case glslang::EsdRect: return spv::DimRect;
  311. case glslang::EsdBuffer: return spv::DimBuffer;
  312. case glslang::EsdSubpass: return spv::DimSubpassData;
  313. case glslang::EsdAttachmentEXT: return spv::DimTileImageDataEXT;
  314. default:
  315. assert(0);
  316. return spv::Dim2D;
  317. }
  318. }
  319. // Translate glslang precision to SPIR-V precision decorations.
  320. spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
  321. {
  322. switch (glslangPrecision) {
  323. case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
  324. case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
  325. default:
  326. return spv::NoPrecision;
  327. }
  328. }
  329. // Translate glslang type to SPIR-V precision decorations.
  330. spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
  331. {
  332. return TranslatePrecisionDecoration(type.getQualifier().precision);
  333. }
  334. // Translate glslang type to SPIR-V block decorations.
  335. spv::Decoration TranslateBlockDecoration(const glslang::TStorageQualifier storage, bool useStorageBuffer)
  336. {
  337. switch (storage) {
  338. case glslang::EvqUniform: return spv::DecorationBlock;
  339. case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
  340. case glslang::EvqVaryingIn: return spv::DecorationBlock;
  341. case glslang::EvqVaryingOut: return spv::DecorationBlock;
  342. case glslang::EvqShared: return spv::DecorationBlock;
  343. case glslang::EvqPayload: return spv::DecorationBlock;
  344. case glslang::EvqPayloadIn: return spv::DecorationBlock;
  345. case glslang::EvqHitAttr: return spv::DecorationBlock;
  346. case glslang::EvqCallableData: return spv::DecorationBlock;
  347. case glslang::EvqCallableDataIn: return spv::DecorationBlock;
  348. case glslang::EvqHitObjectAttrNV: return spv::DecorationBlock;
  349. default:
  350. assert(0);
  351. break;
  352. }
  353. return spv::DecorationMax;
  354. }
  355. // Translate glslang type to SPIR-V memory decorations.
  356. void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory,
  357. bool useVulkanMemoryModel)
  358. {
  359. if (!useVulkanMemoryModel) {
  360. if (qualifier.isCoherent())
  361. memory.push_back(spv::DecorationCoherent);
  362. if (qualifier.isVolatile()) {
  363. memory.push_back(spv::DecorationVolatile);
  364. memory.push_back(spv::DecorationCoherent);
  365. }
  366. }
  367. if (qualifier.isRestrict())
  368. memory.push_back(spv::DecorationRestrict);
  369. if (qualifier.isReadOnly())
  370. memory.push_back(spv::DecorationNonWritable);
  371. if (qualifier.isWriteOnly())
  372. memory.push_back(spv::DecorationNonReadable);
  373. }
  374. // Translate glslang type to SPIR-V layout decorations.
  375. spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
  376. {
  377. if (type.isMatrix()) {
  378. switch (matrixLayout) {
  379. case glslang::ElmRowMajor:
  380. return spv::DecorationRowMajor;
  381. case glslang::ElmColumnMajor:
  382. return spv::DecorationColMajor;
  383. default:
  384. // opaque layouts don't need a majorness
  385. return spv::DecorationMax;
  386. }
  387. } else {
  388. switch (type.getBasicType()) {
  389. default:
  390. return spv::DecorationMax;
  391. break;
  392. case glslang::EbtBlock:
  393. switch (type.getQualifier().storage) {
  394. case glslang::EvqShared:
  395. case glslang::EvqUniform:
  396. case glslang::EvqBuffer:
  397. switch (type.getQualifier().layoutPacking) {
  398. case glslang::ElpShared: return spv::DecorationGLSLShared;
  399. case glslang::ElpPacked: return spv::DecorationGLSLPacked;
  400. default:
  401. return spv::DecorationMax;
  402. }
  403. case glslang::EvqVaryingIn:
  404. case glslang::EvqVaryingOut:
  405. if (type.getQualifier().isTaskMemory()) {
  406. switch (type.getQualifier().layoutPacking) {
  407. case glslang::ElpShared: return spv::DecorationGLSLShared;
  408. case glslang::ElpPacked: return spv::DecorationGLSLPacked;
  409. default: break;
  410. }
  411. } else {
  412. assert(type.getQualifier().layoutPacking == glslang::ElpNone);
  413. }
  414. return spv::DecorationMax;
  415. case glslang::EvqPayload:
  416. case glslang::EvqPayloadIn:
  417. case glslang::EvqHitAttr:
  418. case glslang::EvqCallableData:
  419. case glslang::EvqCallableDataIn:
  420. case glslang::EvqHitObjectAttrNV:
  421. return spv::DecorationMax;
  422. default:
  423. assert(0);
  424. return spv::DecorationMax;
  425. }
  426. }
  427. }
  428. }
  429. // Translate glslang type to SPIR-V interpolation decorations.
  430. // Returns spv::DecorationMax when no decoration
  431. // should be applied.
  432. spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
  433. {
  434. if (qualifier.smooth)
  435. // Smooth decoration doesn't exist in SPIR-V 1.0
  436. return spv::DecorationMax;
  437. else if (qualifier.isNonPerspective())
  438. return spv::DecorationNoPerspective;
  439. else if (qualifier.flat)
  440. return spv::DecorationFlat;
  441. else if (qualifier.isExplicitInterpolation()) {
  442. builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  443. return spv::DecorationExplicitInterpAMD;
  444. }
  445. else
  446. return spv::DecorationMax;
  447. }
  448. // Translate glslang type to SPIR-V auxiliary storage decorations.
  449. // Returns spv::DecorationMax when no decoration
  450. // should be applied.
  451. spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
  452. {
  453. if (qualifier.centroid)
  454. return spv::DecorationCentroid;
  455. else if (qualifier.patch)
  456. return spv::DecorationPatch;
  457. else if (qualifier.sample) {
  458. builder.addCapability(spv::CapabilitySampleRateShading);
  459. return spv::DecorationSample;
  460. }
  461. return spv::DecorationMax;
  462. }
  463. // If glslang type is invariant, return SPIR-V invariant decoration.
  464. spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
  465. {
  466. if (qualifier.invariant)
  467. return spv::DecorationInvariant;
  468. else
  469. return spv::DecorationMax;
  470. }
  471. // If glslang type is noContraction, return SPIR-V NoContraction decoration.
  472. spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
  473. {
  474. if (qualifier.isNoContraction())
  475. return spv::DecorationNoContraction;
  476. else
  477. return spv::DecorationMax;
  478. }
  479. // If glslang type is nonUniform, return SPIR-V NonUniform decoration.
  480. spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
  481. {
  482. if (qualifier.isNonUniform()) {
  483. builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
  484. builder.addCapability(spv::CapabilityShaderNonUniformEXT);
  485. return spv::DecorationNonUniformEXT;
  486. } else
  487. return spv::DecorationMax;
  488. }
  489. // If lvalue flags contains nonUniform, return SPIR-V NonUniform decoration.
  490. spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(
  491. const spv::Builder::AccessChain::CoherentFlags& coherentFlags)
  492. {
  493. if (coherentFlags.isNonUniform()) {
  494. builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
  495. builder.addCapability(spv::CapabilityShaderNonUniformEXT);
  496. return spv::DecorationNonUniformEXT;
  497. } else
  498. return spv::DecorationMax;
  499. }
  500. spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(
  501. const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
  502. {
  503. spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
  504. if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage)
  505. return mask;
  506. if (coherentFlags.isVolatile() || coherentFlags.anyCoherent()) {
  507. mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
  508. spv::MemoryAccessMakePointerVisibleKHRMask;
  509. }
  510. if (coherentFlags.nonprivate) {
  511. mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
  512. }
  513. if (coherentFlags.volatil) {
  514. mask = mask | spv::MemoryAccessVolatileMask;
  515. }
  516. if (mask != spv::MemoryAccessMaskNone) {
  517. builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
  518. }
  519. return mask;
  520. }
  521. spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(
  522. const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
  523. {
  524. spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
  525. if (!glslangIntermediate->usingVulkanMemoryModel())
  526. return mask;
  527. if (coherentFlags.volatil ||
  528. coherentFlags.anyCoherent()) {
  529. mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
  530. spv::ImageOperandsMakeTexelVisibleKHRMask;
  531. }
  532. if (coherentFlags.nonprivate) {
  533. mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
  534. }
  535. if (coherentFlags.volatil) {
  536. mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
  537. }
  538. if (mask != spv::ImageOperandsMaskNone) {
  539. builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
  540. }
  541. return mask;
  542. }
  543. spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
  544. {
  545. spv::Builder::AccessChain::CoherentFlags flags = {};
  546. flags.coherent = type.getQualifier().coherent;
  547. flags.devicecoherent = type.getQualifier().devicecoherent;
  548. flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
  549. // shared variables are implicitly workgroupcoherent in GLSL.
  550. flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
  551. type.getQualifier().storage == glslang::EvqShared;
  552. flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
  553. flags.shadercallcoherent = type.getQualifier().shadercallcoherent;
  554. flags.volatil = type.getQualifier().volatil;
  555. // *coherent variables are implicitly nonprivate in GLSL
  556. flags.nonprivate = type.getQualifier().nonprivate ||
  557. flags.anyCoherent() ||
  558. flags.volatil;
  559. flags.isImage = type.getBasicType() == glslang::EbtSampler;
  560. flags.nonUniform = type.getQualifier().nonUniform;
  561. return flags;
  562. }
  563. spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(
  564. const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
  565. {
  566. spv::Scope scope = spv::ScopeMax;
  567. if (coherentFlags.volatil || coherentFlags.coherent) {
  568. // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
  569. scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
  570. } else if (coherentFlags.devicecoherent) {
  571. scope = spv::ScopeDevice;
  572. } else if (coherentFlags.queuefamilycoherent) {
  573. scope = spv::ScopeQueueFamilyKHR;
  574. } else if (coherentFlags.workgroupcoherent) {
  575. scope = spv::ScopeWorkgroup;
  576. } else if (coherentFlags.subgroupcoherent) {
  577. scope = spv::ScopeSubgroup;
  578. } else if (coherentFlags.shadercallcoherent) {
  579. scope = spv::ScopeShaderCallKHR;
  580. }
  581. if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
  582. builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
  583. }
  584. return scope;
  585. }
  586. // Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
  587. // associated capabilities when required. For some built-in variables, a capability
  588. // is generated only when using the variable in an executable instruction, but not when
  589. // just declaring a struct member variable with it. This is true for PointSize,
  590. // ClipDistance, and CullDistance.
  591. spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn,
  592. bool memberDeclaration)
  593. {
  594. switch (builtIn) {
  595. case glslang::EbvPointSize:
  596. // Defer adding the capability until the built-in is actually used.
  597. if (! memberDeclaration) {
  598. switch (glslangIntermediate->getStage()) {
  599. case EShLangGeometry:
  600. builder.addCapability(spv::CapabilityGeometryPointSize);
  601. break;
  602. case EShLangTessControl:
  603. case EShLangTessEvaluation:
  604. builder.addCapability(spv::CapabilityTessellationPointSize);
  605. break;
  606. default:
  607. break;
  608. }
  609. }
  610. return spv::BuiltInPointSize;
  611. case glslang::EbvPosition: return spv::BuiltInPosition;
  612. case glslang::EbvVertexId: return spv::BuiltInVertexId;
  613. case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
  614. case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
  615. case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
  616. case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
  617. case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
  618. case glslang::EbvFace: return spv::BuiltInFrontFacing;
  619. case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
  620. case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
  621. case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
  622. case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
  623. case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
  624. case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
  625. case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
  626. // These *Distance capabilities logically belong here, but if the member is declared and
  627. // then never used, consumers of SPIR-V prefer the capability not be declared.
  628. // They are now generated when used, rather than here when declared.
  629. // Potentially, the specification should be more clear what the minimum
  630. // use needed is to trigger the capability.
  631. //
  632. case glslang::EbvClipDistance:
  633. if (!memberDeclaration)
  634. builder.addCapability(spv::CapabilityClipDistance);
  635. return spv::BuiltInClipDistance;
  636. case glslang::EbvCullDistance:
  637. if (!memberDeclaration)
  638. builder.addCapability(spv::CapabilityCullDistance);
  639. return spv::BuiltInCullDistance;
  640. case glslang::EbvViewportIndex:
  641. if (glslangIntermediate->getStage() == EShLangGeometry ||
  642. glslangIntermediate->getStage() == EShLangFragment) {
  643. builder.addCapability(spv::CapabilityMultiViewport);
  644. }
  645. if (glslangIntermediate->getStage() == EShLangVertex ||
  646. glslangIntermediate->getStage() == EShLangTessControl ||
  647. glslangIntermediate->getStage() == EShLangTessEvaluation) {
  648. if (builder.getSpvVersion() < spv::Spv_1_5) {
  649. builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
  650. builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
  651. }
  652. else
  653. builder.addCapability(spv::CapabilityShaderViewportIndex);
  654. }
  655. return spv::BuiltInViewportIndex;
  656. case glslang::EbvSampleId:
  657. builder.addCapability(spv::CapabilitySampleRateShading);
  658. return spv::BuiltInSampleId;
  659. case glslang::EbvSamplePosition:
  660. builder.addCapability(spv::CapabilitySampleRateShading);
  661. return spv::BuiltInSamplePosition;
  662. case glslang::EbvSampleMask:
  663. return spv::BuiltInSampleMask;
  664. case glslang::EbvLayer:
  665. if (glslangIntermediate->getStage() == EShLangMesh) {
  666. return spv::BuiltInLayer;
  667. }
  668. if (glslangIntermediate->getStage() == EShLangGeometry ||
  669. glslangIntermediate->getStage() == EShLangFragment) {
  670. builder.addCapability(spv::CapabilityGeometry);
  671. }
  672. if (glslangIntermediate->getStage() == EShLangVertex ||
  673. glslangIntermediate->getStage() == EShLangTessControl ||
  674. glslangIntermediate->getStage() == EShLangTessEvaluation) {
  675. if (builder.getSpvVersion() < spv::Spv_1_5) {
  676. builder.addIncorporatedExtension(spv::E_SPV_EXT_shader_viewport_index_layer, spv::Spv_1_5);
  677. builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
  678. } else
  679. builder.addCapability(spv::CapabilityShaderLayer);
  680. }
  681. return spv::BuiltInLayer;
  682. case glslang::EbvBaseVertex:
  683. builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
  684. builder.addCapability(spv::CapabilityDrawParameters);
  685. return spv::BuiltInBaseVertex;
  686. case glslang::EbvBaseInstance:
  687. builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
  688. builder.addCapability(spv::CapabilityDrawParameters);
  689. return spv::BuiltInBaseInstance;
  690. case glslang::EbvDrawId:
  691. builder.addIncorporatedExtension(spv::E_SPV_KHR_shader_draw_parameters, spv::Spv_1_3);
  692. builder.addCapability(spv::CapabilityDrawParameters);
  693. return spv::BuiltInDrawIndex;
  694. case glslang::EbvPrimitiveId:
  695. if (glslangIntermediate->getStage() == EShLangFragment)
  696. builder.addCapability(spv::CapabilityGeometry);
  697. return spv::BuiltInPrimitiveId;
  698. case glslang::EbvFragStencilRef:
  699. builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
  700. builder.addCapability(spv::CapabilityStencilExportEXT);
  701. return spv::BuiltInFragStencilRefEXT;
  702. case glslang::EbvShadingRateKHR:
  703. builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
  704. builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
  705. return spv::BuiltInShadingRateKHR;
  706. case glslang::EbvPrimitiveShadingRateKHR:
  707. builder.addExtension(spv::E_SPV_KHR_fragment_shading_rate);
  708. builder.addCapability(spv::CapabilityFragmentShadingRateKHR);
  709. return spv::BuiltInPrimitiveShadingRateKHR;
  710. case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
  711. case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
  712. case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
  713. case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
  714. case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
  715. case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
  716. case glslang::EbvSubGroupSize:
  717. builder.addExtension(spv::E_SPV_KHR_shader_ballot);
  718. builder.addCapability(spv::CapabilitySubgroupBallotKHR);
  719. return spv::BuiltInSubgroupSize;
  720. case glslang::EbvSubGroupInvocation:
  721. builder.addExtension(spv::E_SPV_KHR_shader_ballot);
  722. builder.addCapability(spv::CapabilitySubgroupBallotKHR);
  723. return spv::BuiltInSubgroupLocalInvocationId;
  724. case glslang::EbvSubGroupEqMask:
  725. builder.addExtension(spv::E_SPV_KHR_shader_ballot);
  726. builder.addCapability(spv::CapabilitySubgroupBallotKHR);
  727. return spv::BuiltInSubgroupEqMask;
  728. case glslang::EbvSubGroupGeMask:
  729. builder.addExtension(spv::E_SPV_KHR_shader_ballot);
  730. builder.addCapability(spv::CapabilitySubgroupBallotKHR);
  731. return spv::BuiltInSubgroupGeMask;
  732. case glslang::EbvSubGroupGtMask:
  733. builder.addExtension(spv::E_SPV_KHR_shader_ballot);
  734. builder.addCapability(spv::CapabilitySubgroupBallotKHR);
  735. return spv::BuiltInSubgroupGtMask;
  736. case glslang::EbvSubGroupLeMask:
  737. builder.addExtension(spv::E_SPV_KHR_shader_ballot);
  738. builder.addCapability(spv::CapabilitySubgroupBallotKHR);
  739. return spv::BuiltInSubgroupLeMask;
  740. case glslang::EbvSubGroupLtMask:
  741. builder.addExtension(spv::E_SPV_KHR_shader_ballot);
  742. builder.addCapability(spv::CapabilitySubgroupBallotKHR);
  743. return spv::BuiltInSubgroupLtMask;
  744. case glslang::EbvNumSubgroups:
  745. builder.addCapability(spv::CapabilityGroupNonUniform);
  746. return spv::BuiltInNumSubgroups;
  747. case glslang::EbvSubgroupID:
  748. builder.addCapability(spv::CapabilityGroupNonUniform);
  749. return spv::BuiltInSubgroupId;
  750. case glslang::EbvSubgroupSize2:
  751. builder.addCapability(spv::CapabilityGroupNonUniform);
  752. return spv::BuiltInSubgroupSize;
  753. case glslang::EbvSubgroupInvocation2:
  754. builder.addCapability(spv::CapabilityGroupNonUniform);
  755. return spv::BuiltInSubgroupLocalInvocationId;
  756. case glslang::EbvSubgroupEqMask2:
  757. builder.addCapability(spv::CapabilityGroupNonUniform);
  758. builder.addCapability(spv::CapabilityGroupNonUniformBallot);
  759. return spv::BuiltInSubgroupEqMask;
  760. case glslang::EbvSubgroupGeMask2:
  761. builder.addCapability(spv::CapabilityGroupNonUniform);
  762. builder.addCapability(spv::CapabilityGroupNonUniformBallot);
  763. return spv::BuiltInSubgroupGeMask;
  764. case glslang::EbvSubgroupGtMask2:
  765. builder.addCapability(spv::CapabilityGroupNonUniform);
  766. builder.addCapability(spv::CapabilityGroupNonUniformBallot);
  767. return spv::BuiltInSubgroupGtMask;
  768. case glslang::EbvSubgroupLeMask2:
  769. builder.addCapability(spv::CapabilityGroupNonUniform);
  770. builder.addCapability(spv::CapabilityGroupNonUniformBallot);
  771. return spv::BuiltInSubgroupLeMask;
  772. case glslang::EbvSubgroupLtMask2:
  773. builder.addCapability(spv::CapabilityGroupNonUniform);
  774. builder.addCapability(spv::CapabilityGroupNonUniformBallot);
  775. return spv::BuiltInSubgroupLtMask;
  776. case glslang::EbvBaryCoordNoPersp:
  777. builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  778. return spv::BuiltInBaryCoordNoPerspAMD;
  779. case glslang::EbvBaryCoordNoPerspCentroid:
  780. builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  781. return spv::BuiltInBaryCoordNoPerspCentroidAMD;
  782. case glslang::EbvBaryCoordNoPerspSample:
  783. builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  784. return spv::BuiltInBaryCoordNoPerspSampleAMD;
  785. case glslang::EbvBaryCoordSmooth:
  786. builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  787. return spv::BuiltInBaryCoordSmoothAMD;
  788. case glslang::EbvBaryCoordSmoothCentroid:
  789. builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  790. return spv::BuiltInBaryCoordSmoothCentroidAMD;
  791. case glslang::EbvBaryCoordSmoothSample:
  792. builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  793. return spv::BuiltInBaryCoordSmoothSampleAMD;
  794. case glslang::EbvBaryCoordPullModel:
  795. builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  796. return spv::BuiltInBaryCoordPullModelAMD;
  797. case glslang::EbvDeviceIndex:
  798. builder.addIncorporatedExtension(spv::E_SPV_KHR_device_group, spv::Spv_1_3);
  799. builder.addCapability(spv::CapabilityDeviceGroup);
  800. return spv::BuiltInDeviceIndex;
  801. case glslang::EbvViewIndex:
  802. builder.addIncorporatedExtension(spv::E_SPV_KHR_multiview, spv::Spv_1_3);
  803. builder.addCapability(spv::CapabilityMultiView);
  804. return spv::BuiltInViewIndex;
  805. case glslang::EbvFragSizeEXT:
  806. builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
  807. builder.addCapability(spv::CapabilityFragmentDensityEXT);
  808. return spv::BuiltInFragSizeEXT;
  809. case glslang::EbvFragInvocationCountEXT:
  810. builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
  811. builder.addCapability(spv::CapabilityFragmentDensityEXT);
  812. return spv::BuiltInFragInvocationCountEXT;
  813. case glslang::EbvViewportMaskNV:
  814. if (!memberDeclaration) {
  815. builder.addExtension(spv::E_SPV_NV_viewport_array2);
  816. builder.addCapability(spv::CapabilityShaderViewportMaskNV);
  817. }
  818. return spv::BuiltInViewportMaskNV;
  819. case glslang::EbvSecondaryPositionNV:
  820. if (!memberDeclaration) {
  821. builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
  822. builder.addCapability(spv::CapabilityShaderStereoViewNV);
  823. }
  824. return spv::BuiltInSecondaryPositionNV;
  825. case glslang::EbvSecondaryViewportMaskNV:
  826. if (!memberDeclaration) {
  827. builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
  828. builder.addCapability(spv::CapabilityShaderStereoViewNV);
  829. }
  830. return spv::BuiltInSecondaryViewportMaskNV;
  831. case glslang::EbvPositionPerViewNV:
  832. if (!memberDeclaration) {
  833. builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
  834. builder.addCapability(spv::CapabilityPerViewAttributesNV);
  835. }
  836. return spv::BuiltInPositionPerViewNV;
  837. case glslang::EbvViewportMaskPerViewNV:
  838. if (!memberDeclaration) {
  839. builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
  840. builder.addCapability(spv::CapabilityPerViewAttributesNV);
  841. }
  842. return spv::BuiltInViewportMaskPerViewNV;
  843. case glslang::EbvFragFullyCoveredNV:
  844. builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
  845. builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
  846. return spv::BuiltInFullyCoveredEXT;
  847. case glslang::EbvFragmentSizeNV:
  848. builder.addExtension(spv::E_SPV_NV_shading_rate);
  849. builder.addCapability(spv::CapabilityShadingRateNV);
  850. return spv::BuiltInFragmentSizeNV;
  851. case glslang::EbvInvocationsPerPixelNV:
  852. builder.addExtension(spv::E_SPV_NV_shading_rate);
  853. builder.addCapability(spv::CapabilityShadingRateNV);
  854. return spv::BuiltInInvocationsPerPixelNV;
  855. // ray tracing
  856. case glslang::EbvLaunchId:
  857. return spv::BuiltInLaunchIdKHR;
  858. case glslang::EbvLaunchSize:
  859. return spv::BuiltInLaunchSizeKHR;
  860. case glslang::EbvWorldRayOrigin:
  861. return spv::BuiltInWorldRayOriginKHR;
  862. case glslang::EbvWorldRayDirection:
  863. return spv::BuiltInWorldRayDirectionKHR;
  864. case glslang::EbvObjectRayOrigin:
  865. return spv::BuiltInObjectRayOriginKHR;
  866. case glslang::EbvObjectRayDirection:
  867. return spv::BuiltInObjectRayDirectionKHR;
  868. case glslang::EbvRayTmin:
  869. return spv::BuiltInRayTminKHR;
  870. case glslang::EbvRayTmax:
  871. return spv::BuiltInRayTmaxKHR;
  872. case glslang::EbvCullMask:
  873. return spv::BuiltInCullMaskKHR;
  874. case glslang::EbvPositionFetch:
  875. return spv::BuiltInHitTriangleVertexPositionsKHR;
  876. case glslang::EbvInstanceCustomIndex:
  877. return spv::BuiltInInstanceCustomIndexKHR;
  878. case glslang::EbvHitT:
  879. {
  880. // this is a GLSL alias of RayTmax
  881. // in SPV_NV_ray_tracing it has a dedicated builtin
  882. // but in SPV_KHR_ray_tracing it gets mapped to RayTmax
  883. auto& extensions = glslangIntermediate->getRequestedExtensions();
  884. if (extensions.find("GL_NV_ray_tracing") != extensions.end()) {
  885. return spv::BuiltInHitTNV;
  886. } else {
  887. return spv::BuiltInRayTmaxKHR;
  888. }
  889. }
  890. case glslang::EbvHitKind:
  891. return spv::BuiltInHitKindKHR;
  892. case glslang::EbvObjectToWorld:
  893. case glslang::EbvObjectToWorld3x4:
  894. return spv::BuiltInObjectToWorldKHR;
  895. case glslang::EbvWorldToObject:
  896. case glslang::EbvWorldToObject3x4:
  897. return spv::BuiltInWorldToObjectKHR;
  898. case glslang::EbvIncomingRayFlags:
  899. return spv::BuiltInIncomingRayFlagsKHR;
  900. case glslang::EbvGeometryIndex:
  901. return spv::BuiltInRayGeometryIndexKHR;
  902. case glslang::EbvCurrentRayTimeNV:
  903. builder.addExtension(spv::E_SPV_NV_ray_tracing_motion_blur);
  904. builder.addCapability(spv::CapabilityRayTracingMotionBlurNV);
  905. return spv::BuiltInCurrentRayTimeNV;
  906. // barycentrics
  907. case glslang::EbvBaryCoordNV:
  908. builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
  909. builder.addCapability(spv::CapabilityFragmentBarycentricNV);
  910. return spv::BuiltInBaryCoordNV;
  911. case glslang::EbvBaryCoordNoPerspNV:
  912. builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
  913. builder.addCapability(spv::CapabilityFragmentBarycentricNV);
  914. return spv::BuiltInBaryCoordNoPerspNV;
  915. case glslang::EbvBaryCoordEXT:
  916. builder.addExtension(spv::E_SPV_KHR_fragment_shader_barycentric);
  917. builder.addCapability(spv::CapabilityFragmentBarycentricKHR);
  918. return spv::BuiltInBaryCoordKHR;
  919. case glslang::EbvBaryCoordNoPerspEXT:
  920. builder.addExtension(spv::E_SPV_KHR_fragment_shader_barycentric);
  921. builder.addCapability(spv::CapabilityFragmentBarycentricKHR);
  922. return spv::BuiltInBaryCoordNoPerspKHR;
  923. // mesh shaders
  924. case glslang::EbvTaskCountNV:
  925. return spv::BuiltInTaskCountNV;
  926. case glslang::EbvPrimitiveCountNV:
  927. return spv::BuiltInPrimitiveCountNV;
  928. case glslang::EbvPrimitiveIndicesNV:
  929. return spv::BuiltInPrimitiveIndicesNV;
  930. case glslang::EbvClipDistancePerViewNV:
  931. return spv::BuiltInClipDistancePerViewNV;
  932. case glslang::EbvCullDistancePerViewNV:
  933. return spv::BuiltInCullDistancePerViewNV;
  934. case glslang::EbvLayerPerViewNV:
  935. return spv::BuiltInLayerPerViewNV;
  936. case glslang::EbvMeshViewCountNV:
  937. return spv::BuiltInMeshViewCountNV;
  938. case glslang::EbvMeshViewIndicesNV:
  939. return spv::BuiltInMeshViewIndicesNV;
  940. // SPV_EXT_mesh_shader
  941. case glslang::EbvPrimitivePointIndicesEXT:
  942. return spv::BuiltInPrimitivePointIndicesEXT;
  943. case glslang::EbvPrimitiveLineIndicesEXT:
  944. return spv::BuiltInPrimitiveLineIndicesEXT;
  945. case glslang::EbvPrimitiveTriangleIndicesEXT:
  946. return spv::BuiltInPrimitiveTriangleIndicesEXT;
  947. case glslang::EbvCullPrimitiveEXT:
  948. return spv::BuiltInCullPrimitiveEXT;
  949. // sm builtins
  950. case glslang::EbvWarpsPerSM:
  951. builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
  952. builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
  953. return spv::BuiltInWarpsPerSMNV;
  954. case glslang::EbvSMCount:
  955. builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
  956. builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
  957. return spv::BuiltInSMCountNV;
  958. case glslang::EbvWarpID:
  959. builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
  960. builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
  961. return spv::BuiltInWarpIDNV;
  962. case glslang::EbvSMID:
  963. builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
  964. builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
  965. return spv::BuiltInSMIDNV;
  966. // ARM builtins
  967. case glslang::EbvCoreCountARM:
  968. builder.addExtension(spv::E_SPV_ARM_core_builtins);
  969. builder.addCapability(spv::CapabilityCoreBuiltinsARM);
  970. return spv::BuiltInCoreCountARM;
  971. case glslang::EbvCoreIDARM:
  972. builder.addExtension(spv::E_SPV_ARM_core_builtins);
  973. builder.addCapability(spv::CapabilityCoreBuiltinsARM);
  974. return spv::BuiltInCoreIDARM;
  975. case glslang::EbvCoreMaxIDARM:
  976. builder.addExtension(spv::E_SPV_ARM_core_builtins);
  977. builder.addCapability(spv::CapabilityCoreBuiltinsARM);
  978. return spv::BuiltInCoreMaxIDARM;
  979. case glslang::EbvWarpIDARM:
  980. builder.addExtension(spv::E_SPV_ARM_core_builtins);
  981. builder.addCapability(spv::CapabilityCoreBuiltinsARM);
  982. return spv::BuiltInWarpIDARM;
  983. case glslang::EbvWarpMaxIDARM:
  984. builder.addExtension(spv::E_SPV_ARM_core_builtins);
  985. builder.addCapability(spv::CapabilityCoreBuiltinsARM);
  986. return spv::BuiltInWarpMaxIDARM;
  987. default:
  988. return spv::BuiltInMax;
  989. }
  990. }
  991. // Translate glslang image layout format to SPIR-V image format.
  992. spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
  993. {
  994. assert(type.getBasicType() == glslang::EbtSampler);
  995. // Check for capabilities
  996. switch (type.getQualifier().getFormat()) {
  997. case glslang::ElfRg32f:
  998. case glslang::ElfRg16f:
  999. case glslang::ElfR11fG11fB10f:
  1000. case glslang::ElfR16f:
  1001. case glslang::ElfRgba16:
  1002. case glslang::ElfRgb10A2:
  1003. case glslang::ElfRg16:
  1004. case glslang::ElfRg8:
  1005. case glslang::ElfR16:
  1006. case glslang::ElfR8:
  1007. case glslang::ElfRgba16Snorm:
  1008. case glslang::ElfRg16Snorm:
  1009. case glslang::ElfRg8Snorm:
  1010. case glslang::ElfR16Snorm:
  1011. case glslang::ElfR8Snorm:
  1012. case glslang::ElfRg32i:
  1013. case glslang::ElfRg16i:
  1014. case glslang::ElfRg8i:
  1015. case glslang::ElfR16i:
  1016. case glslang::ElfR8i:
  1017. case glslang::ElfRgb10a2ui:
  1018. case glslang::ElfRg32ui:
  1019. case glslang::ElfRg16ui:
  1020. case glslang::ElfRg8ui:
  1021. case glslang::ElfR16ui:
  1022. case glslang::ElfR8ui:
  1023. builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
  1024. break;
  1025. case glslang::ElfR64ui:
  1026. case glslang::ElfR64i:
  1027. builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
  1028. builder.addCapability(spv::CapabilityInt64ImageEXT);
  1029. default:
  1030. break;
  1031. }
  1032. // do the translation
  1033. switch (type.getQualifier().getFormat()) {
  1034. case glslang::ElfNone: return spv::ImageFormatUnknown;
  1035. case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
  1036. case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
  1037. case glslang::ElfR32f: return spv::ImageFormatR32f;
  1038. case glslang::ElfRgba8: return spv::ImageFormatRgba8;
  1039. case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
  1040. case glslang::ElfRg32f: return spv::ImageFormatRg32f;
  1041. case glslang::ElfRg16f: return spv::ImageFormatRg16f;
  1042. case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
  1043. case glslang::ElfR16f: return spv::ImageFormatR16f;
  1044. case glslang::ElfRgba16: return spv::ImageFormatRgba16;
  1045. case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
  1046. case glslang::ElfRg16: return spv::ImageFormatRg16;
  1047. case glslang::ElfRg8: return spv::ImageFormatRg8;
  1048. case glslang::ElfR16: return spv::ImageFormatR16;
  1049. case glslang::ElfR8: return spv::ImageFormatR8;
  1050. case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
  1051. case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
  1052. case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
  1053. case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
  1054. case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
  1055. case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
  1056. case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
  1057. case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
  1058. case glslang::ElfR32i: return spv::ImageFormatR32i;
  1059. case glslang::ElfRg32i: return spv::ImageFormatRg32i;
  1060. case glslang::ElfRg16i: return spv::ImageFormatRg16i;
  1061. case glslang::ElfRg8i: return spv::ImageFormatRg8i;
  1062. case glslang::ElfR16i: return spv::ImageFormatR16i;
  1063. case glslang::ElfR8i: return spv::ImageFormatR8i;
  1064. case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
  1065. case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
  1066. case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
  1067. case glslang::ElfR32ui: return spv::ImageFormatR32ui;
  1068. case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
  1069. case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
  1070. case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
  1071. case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
  1072. case glslang::ElfR16ui: return spv::ImageFormatR16ui;
  1073. case glslang::ElfR8ui: return spv::ImageFormatR8ui;
  1074. case glslang::ElfR64ui: return spv::ImageFormatR64ui;
  1075. case glslang::ElfR64i: return spv::ImageFormatR64i;
  1076. default: return spv::ImageFormatMax;
  1077. }
  1078. }
  1079. spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(
  1080. const glslang::TIntermSelection& selectionNode) const
  1081. {
  1082. if (selectionNode.getFlatten())
  1083. return spv::SelectionControlFlattenMask;
  1084. if (selectionNode.getDontFlatten())
  1085. return spv::SelectionControlDontFlattenMask;
  1086. return spv::SelectionControlMaskNone;
  1087. }
  1088. spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode)
  1089. const
  1090. {
  1091. if (switchNode.getFlatten())
  1092. return spv::SelectionControlFlattenMask;
  1093. if (switchNode.getDontFlatten())
  1094. return spv::SelectionControlDontFlattenMask;
  1095. return spv::SelectionControlMaskNone;
  1096. }
  1097. // return a non-0 dependency if the dependency argument must be set
  1098. spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
  1099. std::vector<unsigned int>& operands) const
  1100. {
  1101. spv::LoopControlMask control = spv::LoopControlMaskNone;
  1102. if (loopNode.getDontUnroll())
  1103. control = control | spv::LoopControlDontUnrollMask;
  1104. if (loopNode.getUnroll())
  1105. control = control | spv::LoopControlUnrollMask;
  1106. if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
  1107. control = control | spv::LoopControlDependencyInfiniteMask;
  1108. else if (loopNode.getLoopDependency() > 0) {
  1109. control = control | spv::LoopControlDependencyLengthMask;
  1110. operands.push_back((unsigned int)loopNode.getLoopDependency());
  1111. }
  1112. if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
  1113. if (loopNode.getMinIterations() > 0) {
  1114. control = control | spv::LoopControlMinIterationsMask;
  1115. operands.push_back(loopNode.getMinIterations());
  1116. }
  1117. if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
  1118. control = control | spv::LoopControlMaxIterationsMask;
  1119. operands.push_back(loopNode.getMaxIterations());
  1120. }
  1121. if (loopNode.getIterationMultiple() > 1) {
  1122. control = control | spv::LoopControlIterationMultipleMask;
  1123. operands.push_back(loopNode.getIterationMultiple());
  1124. }
  1125. if (loopNode.getPeelCount() > 0) {
  1126. control = control | spv::LoopControlPeelCountMask;
  1127. operands.push_back(loopNode.getPeelCount());
  1128. }
  1129. if (loopNode.getPartialCount() > 0) {
  1130. control = control | spv::LoopControlPartialCountMask;
  1131. operands.push_back(loopNode.getPartialCount());
  1132. }
  1133. }
  1134. return control;
  1135. }
  1136. // Translate glslang type to SPIR-V storage class.
  1137. spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
  1138. {
  1139. if (type.getBasicType() == glslang::EbtRayQuery || type.getBasicType() == glslang::EbtHitObjectNV)
  1140. return spv::StorageClassPrivate;
  1141. if (type.getQualifier().isSpirvByReference()) {
  1142. if (type.getQualifier().isParamInput() || type.getQualifier().isParamOutput())
  1143. return spv::StorageClassFunction;
  1144. }
  1145. if (type.getQualifier().isPipeInput())
  1146. return spv::StorageClassInput;
  1147. if (type.getQualifier().isPipeOutput())
  1148. return spv::StorageClassOutput;
  1149. if (type.getQualifier().storage == glslang::EvqTileImageEXT || type.isAttachmentEXT()) {
  1150. builder.addExtension(spv::E_SPV_EXT_shader_tile_image);
  1151. builder.addCapability(spv::CapabilityTileImageColorReadAccessEXT);
  1152. return spv::StorageClassTileImageEXT;
  1153. }
  1154. if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
  1155. type.getQualifier().storage == glslang::EvqUniform) {
  1156. if (type.isAtomic())
  1157. return spv::StorageClassAtomicCounter;
  1158. if (type.containsOpaque() && !glslangIntermediate->getBindlessMode())
  1159. return spv::StorageClassUniformConstant;
  1160. }
  1161. if (type.getQualifier().isUniformOrBuffer() &&
  1162. type.getQualifier().isShaderRecord()) {
  1163. return spv::StorageClassShaderRecordBufferKHR;
  1164. }
  1165. if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
  1166. builder.addIncorporatedExtension(spv::E_SPV_KHR_storage_buffer_storage_class, spv::Spv_1_3);
  1167. return spv::StorageClassStorageBuffer;
  1168. }
  1169. if (type.getQualifier().isUniformOrBuffer()) {
  1170. if (type.getQualifier().isPushConstant())
  1171. return spv::StorageClassPushConstant;
  1172. if (type.getBasicType() == glslang::EbtBlock)
  1173. return spv::StorageClassUniform;
  1174. return spv::StorageClassUniformConstant;
  1175. }
  1176. if (type.getQualifier().storage == glslang::EvqShared && type.getBasicType() == glslang::EbtBlock) {
  1177. builder.addExtension(spv::E_SPV_KHR_workgroup_memory_explicit_layout);
  1178. builder.addCapability(spv::CapabilityWorkgroupMemoryExplicitLayoutKHR);
  1179. return spv::StorageClassWorkgroup;
  1180. }
  1181. switch (type.getQualifier().storage) {
  1182. case glslang::EvqGlobal: return spv::StorageClassPrivate;
  1183. case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
  1184. case glslang::EvqTemporary: return spv::StorageClassFunction;
  1185. case glslang::EvqShared: return spv::StorageClassWorkgroup;
  1186. case glslang::EvqPayload: return spv::StorageClassRayPayloadKHR;
  1187. case glslang::EvqPayloadIn: return spv::StorageClassIncomingRayPayloadKHR;
  1188. case glslang::EvqHitAttr: return spv::StorageClassHitAttributeKHR;
  1189. case glslang::EvqCallableData: return spv::StorageClassCallableDataKHR;
  1190. case glslang::EvqCallableDataIn: return spv::StorageClassIncomingCallableDataKHR;
  1191. case glslang::EvqtaskPayloadSharedEXT : return spv::StorageClassTaskPayloadWorkgroupEXT;
  1192. case glslang::EvqHitObjectAttrNV: return spv::StorageClassHitObjectAttributeNV;
  1193. case glslang::EvqSpirvStorageClass: return static_cast<spv::StorageClass>(type.getQualifier().spirvStorageClass);
  1194. default:
  1195. assert(0);
  1196. break;
  1197. }
  1198. return spv::StorageClassFunction;
  1199. }
  1200. // Translate glslang constants to SPIR-V literals
  1201. void TGlslangToSpvTraverser::TranslateLiterals(const glslang::TVector<const glslang::TIntermConstantUnion*>& constants,
  1202. std::vector<unsigned>& literals) const
  1203. {
  1204. for (auto constant : constants) {
  1205. if (constant->getBasicType() == glslang::EbtFloat) {
  1206. float floatValue = static_cast<float>(constant->getConstArray()[0].getDConst());
  1207. unsigned literal;
  1208. static_assert(sizeof(literal) == sizeof(floatValue), "sizeof(unsigned) != sizeof(float)");
  1209. memcpy(&literal, &floatValue, sizeof(literal));
  1210. literals.push_back(literal);
  1211. } else if (constant->getBasicType() == glslang::EbtInt) {
  1212. unsigned literal = constant->getConstArray()[0].getIConst();
  1213. literals.push_back(literal);
  1214. } else if (constant->getBasicType() == glslang::EbtUint) {
  1215. unsigned literal = constant->getConstArray()[0].getUConst();
  1216. literals.push_back(literal);
  1217. } else if (constant->getBasicType() == glslang::EbtBool) {
  1218. unsigned literal = constant->getConstArray()[0].getBConst();
  1219. literals.push_back(literal);
  1220. } else if (constant->getBasicType() == glslang::EbtString) {
  1221. auto str = constant->getConstArray()[0].getSConst()->c_str();
  1222. unsigned literal = 0;
  1223. char* literalPtr = reinterpret_cast<char*>(&literal);
  1224. unsigned charCount = 0;
  1225. char ch = 0;
  1226. do {
  1227. ch = *(str++);
  1228. *(literalPtr++) = ch;
  1229. ++charCount;
  1230. if (charCount == 4) {
  1231. literals.push_back(literal);
  1232. literalPtr = reinterpret_cast<char*>(&literal);
  1233. charCount = 0;
  1234. }
  1235. } while (ch != 0);
  1236. // Partial literal is padded with 0
  1237. if (charCount > 0) {
  1238. for (; charCount < 4; ++charCount)
  1239. *(literalPtr++) = 0;
  1240. literals.push_back(literal);
  1241. }
  1242. } else
  1243. assert(0); // Unexpected type
  1244. }
  1245. }
  1246. // Add capabilities pertaining to how an array is indexed.
  1247. void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
  1248. const glslang::TType& indexType)
  1249. {
  1250. if (indexType.getQualifier().isNonUniform()) {
  1251. // deal with an asserted non-uniform index
  1252. // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
  1253. if (baseType.getBasicType() == glslang::EbtSampler) {
  1254. if (baseType.getQualifier().hasAttachment())
  1255. builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
  1256. else if (baseType.isImage() && baseType.getSampler().isBuffer())
  1257. builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
  1258. else if (baseType.isTexture() && baseType.getSampler().isBuffer())
  1259. builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
  1260. else if (baseType.isImage())
  1261. builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
  1262. else if (baseType.isTexture())
  1263. builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
  1264. } else if (baseType.getBasicType() == glslang::EbtBlock) {
  1265. if (baseType.getQualifier().storage == glslang::EvqBuffer)
  1266. builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
  1267. else if (baseType.getQualifier().storage == glslang::EvqUniform)
  1268. builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
  1269. }
  1270. } else {
  1271. // assume a dynamically uniform index
  1272. if (baseType.getBasicType() == glslang::EbtSampler) {
  1273. if (baseType.getQualifier().hasAttachment()) {
  1274. builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
  1275. builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
  1276. } else if (baseType.isImage() && baseType.getSampler().isBuffer()) {
  1277. builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
  1278. builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
  1279. } else if (baseType.isTexture() && baseType.getSampler().isBuffer()) {
  1280. builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
  1281. builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
  1282. }
  1283. }
  1284. }
  1285. }
  1286. // Return whether or not the given type is something that should be tied to a
  1287. // descriptor set.
  1288. bool IsDescriptorResource(const glslang::TType& type)
  1289. {
  1290. // uniform and buffer blocks are included, unless it is a push_constant
  1291. if (type.getBasicType() == glslang::EbtBlock)
  1292. return type.getQualifier().isUniformOrBuffer() &&
  1293. ! type.getQualifier().isShaderRecord() &&
  1294. ! type.getQualifier().isPushConstant();
  1295. // non block...
  1296. // basically samplerXXX/subpass/sampler/texture are all included
  1297. // if they are the global-scope-class, not the function parameter
  1298. // (or local, if they ever exist) class.
  1299. if (type.getBasicType() == glslang::EbtSampler ||
  1300. type.getBasicType() == glslang::EbtAccStruct)
  1301. return type.getQualifier().isUniformOrBuffer();
  1302. // None of the above.
  1303. return false;
  1304. }
  1305. void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
  1306. {
  1307. if (child.layoutMatrix == glslang::ElmNone)
  1308. child.layoutMatrix = parent.layoutMatrix;
  1309. if (parent.invariant)
  1310. child.invariant = true;
  1311. if (parent.flat)
  1312. child.flat = true;
  1313. if (parent.centroid)
  1314. child.centroid = true;
  1315. if (parent.nopersp)
  1316. child.nopersp = true;
  1317. if (parent.explicitInterp)
  1318. child.explicitInterp = true;
  1319. if (parent.perPrimitiveNV)
  1320. child.perPrimitiveNV = true;
  1321. if (parent.perViewNV)
  1322. child.perViewNV = true;
  1323. if (parent.perTaskNV)
  1324. child.perTaskNV = true;
  1325. if (parent.storage == glslang::EvqtaskPayloadSharedEXT)
  1326. child.storage = glslang::EvqtaskPayloadSharedEXT;
  1327. if (parent.patch)
  1328. child.patch = true;
  1329. if (parent.sample)
  1330. child.sample = true;
  1331. if (parent.coherent)
  1332. child.coherent = true;
  1333. if (parent.devicecoherent)
  1334. child.devicecoherent = true;
  1335. if (parent.queuefamilycoherent)
  1336. child.queuefamilycoherent = true;
  1337. if (parent.workgroupcoherent)
  1338. child.workgroupcoherent = true;
  1339. if (parent.subgroupcoherent)
  1340. child.subgroupcoherent = true;
  1341. if (parent.shadercallcoherent)
  1342. child.shadercallcoherent = true;
  1343. if (parent.nonprivate)
  1344. child.nonprivate = true;
  1345. if (parent.volatil)
  1346. child.volatil = true;
  1347. if (parent.restrict)
  1348. child.restrict = true;
  1349. if (parent.readonly)
  1350. child.readonly = true;
  1351. if (parent.writeonly)
  1352. child.writeonly = true;
  1353. if (parent.nonUniform)
  1354. child.nonUniform = true;
  1355. }
  1356. bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
  1357. {
  1358. // This should list qualifiers that simultaneous satisfy:
  1359. // - struct members might inherit from a struct declaration
  1360. // (note that non-block structs don't explicitly inherit,
  1361. // only implicitly, meaning no decoration involved)
  1362. // - affect decorations on the struct members
  1363. // (note smooth does not, and expecting something like volatile
  1364. // to effect the whole object)
  1365. // - are not part of the offset/st430/etc or row/column-major layout
  1366. return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
  1367. }
  1368. //
  1369. // Implement the TGlslangToSpvTraverser class.
  1370. //
  1371. TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion,
  1372. const glslang::TIntermediate* glslangIntermediate,
  1373. spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options) :
  1374. TIntermTraverser(true, false, true),
  1375. options(options),
  1376. shaderEntry(nullptr), currentFunction(nullptr),
  1377. sequenceDepth(0), logger(buildLogger),
  1378. builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
  1379. inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
  1380. glslangIntermediate(glslangIntermediate),
  1381. nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp()),
  1382. nonSemanticDebugPrintf(0),
  1383. taskPayloadID(0)
  1384. {
  1385. bool isMeshShaderExt = (glslangIntermediate->getRequestedExtensions().find(glslang::E_GL_EXT_mesh_shader) !=
  1386. glslangIntermediate->getRequestedExtensions().end());
  1387. spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage(), isMeshShaderExt);
  1388. builder.clearAccessChain();
  1389. builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
  1390. glslangIntermediate->getVersion());
  1391. if (options.emitNonSemanticShaderDebugSource)
  1392. this->options.emitNonSemanticShaderDebugInfo = true;
  1393. if (options.emitNonSemanticShaderDebugInfo)
  1394. this->options.generateDebugInfo = true;
  1395. if (this->options.generateDebugInfo) {
  1396. builder.setEmitOpLines();
  1397. builder.setSourceFile(glslangIntermediate->getSourceFile());
  1398. // Set the source shader's text. If for SPV version 1.0, include
  1399. // a preamble in comments stating the OpModuleProcessed instructions.
  1400. // Otherwise, emit those as actual instructions.
  1401. std::string text;
  1402. const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
  1403. for (int p = 0; p < (int)processes.size(); ++p) {
  1404. if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
  1405. text.append("// OpModuleProcessed ");
  1406. text.append(processes[p]);
  1407. text.append("\n");
  1408. } else
  1409. builder.addModuleProcessed(processes[p]);
  1410. }
  1411. if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
  1412. text.append("#line 1\n");
  1413. text.append(glslangIntermediate->getSourceText());
  1414. builder.setSourceText(text);
  1415. // Pass name and text for all included files
  1416. const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
  1417. for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
  1418. builder.addInclude(iItr->first, iItr->second);
  1419. }
  1420. builder.setEmitNonSemanticShaderDebugInfo(this->options.emitNonSemanticShaderDebugInfo);
  1421. builder.setEmitNonSemanticShaderDebugSource(this->options.emitNonSemanticShaderDebugSource);
  1422. stdBuiltins = builder.import("GLSL.std.450");
  1423. spv::AddressingModel addressingModel = spv::AddressingModelLogical;
  1424. spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
  1425. if (glslangIntermediate->usingPhysicalStorageBuffer()) {
  1426. addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
  1427. builder.addIncorporatedExtension(spv::E_SPV_KHR_physical_storage_buffer, spv::Spv_1_5);
  1428. builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
  1429. }
  1430. if (glslangIntermediate->usingVulkanMemoryModel()) {
  1431. memoryModel = spv::MemoryModelVulkanKHR;
  1432. builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
  1433. builder.addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
  1434. }
  1435. builder.setMemoryModel(addressingModel, memoryModel);
  1436. if (glslangIntermediate->usingVariablePointers()) {
  1437. builder.addCapability(spv::CapabilityVariablePointers);
  1438. }
  1439. shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
  1440. entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
  1441. // Add the source extensions
  1442. const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
  1443. for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
  1444. builder.addSourceExtension(it->c_str());
  1445. // Add the top-level modes for this shader.
  1446. if (glslangIntermediate->getXfbMode()) {
  1447. builder.addCapability(spv::CapabilityTransformFeedback);
  1448. builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
  1449. }
  1450. if (glslangIntermediate->getLayoutPrimitiveCulling()) {
  1451. builder.addCapability(spv::CapabilityRayTraversalPrimitiveCullingKHR);
  1452. }
  1453. if (glslangIntermediate->getSubgroupUniformControlFlow()) {
  1454. builder.addExtension(spv::E_SPV_KHR_subgroup_uniform_control_flow);
  1455. builder.addExecutionMode(shaderEntry, spv::ExecutionModeSubgroupUniformControlFlowKHR);
  1456. }
  1457. unsigned int mode;
  1458. switch (glslangIntermediate->getStage()) {
  1459. case EShLangVertex:
  1460. builder.addCapability(spv::CapabilityShader);
  1461. break;
  1462. case EShLangFragment:
  1463. builder.addCapability(spv::CapabilityShader);
  1464. if (glslangIntermediate->getPixelCenterInteger())
  1465. builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
  1466. if (glslangIntermediate->getOriginUpperLeft())
  1467. builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
  1468. else
  1469. builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
  1470. if (glslangIntermediate->getEarlyFragmentTests())
  1471. builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
  1472. if (glslangIntermediate->getEarlyAndLateFragmentTestsAMD())
  1473. {
  1474. builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyAndLateFragmentTestsAMD);
  1475. builder.addExtension(spv::E_SPV_AMD_shader_early_and_late_fragment_tests);
  1476. }
  1477. if (glslangIntermediate->getPostDepthCoverage()) {
  1478. builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
  1479. builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
  1480. builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
  1481. }
  1482. if (glslangIntermediate->getNonCoherentColorAttachmentReadEXT()) {
  1483. builder.addCapability(spv::CapabilityTileImageColorReadAccessEXT);
  1484. builder.addExecutionMode(shaderEntry, spv::ExecutionModeNonCoherentColorAttachmentReadEXT);
  1485. builder.addExtension(spv::E_SPV_EXT_shader_tile_image);
  1486. }
  1487. if (glslangIntermediate->getNonCoherentDepthAttachmentReadEXT()) {
  1488. builder.addCapability(spv::CapabilityTileImageDepthReadAccessEXT);
  1489. builder.addExecutionMode(shaderEntry, spv::ExecutionModeNonCoherentDepthAttachmentReadEXT);
  1490. builder.addExtension(spv::E_SPV_EXT_shader_tile_image);
  1491. }
  1492. if (glslangIntermediate->getNonCoherentStencilAttachmentReadEXT()) {
  1493. builder.addCapability(spv::CapabilityTileImageStencilReadAccessEXT);
  1494. builder.addExecutionMode(shaderEntry, spv::ExecutionModeNonCoherentStencilAttachmentReadEXT);
  1495. builder.addExtension(spv::E_SPV_EXT_shader_tile_image);
  1496. }
  1497. if (glslangIntermediate->isDepthReplacing())
  1498. builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
  1499. if (glslangIntermediate->isStencilReplacing())
  1500. builder.addExecutionMode(shaderEntry, spv::ExecutionModeStencilRefReplacingEXT);
  1501. switch(glslangIntermediate->getDepth()) {
  1502. case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
  1503. case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
  1504. case glslang::EldUnchanged: mode = spv::ExecutionModeDepthUnchanged; break;
  1505. default: mode = spv::ExecutionModeMax; break;
  1506. }
  1507. if (mode != spv::ExecutionModeMax)
  1508. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1509. switch (glslangIntermediate->getStencil()) {
  1510. case glslang::ElsRefUnchangedFrontAMD: mode = spv::ExecutionModeStencilRefUnchangedFrontAMD; break;
  1511. case glslang::ElsRefGreaterFrontAMD: mode = spv::ExecutionModeStencilRefGreaterFrontAMD; break;
  1512. case glslang::ElsRefLessFrontAMD: mode = spv::ExecutionModeStencilRefLessFrontAMD; break;
  1513. case glslang::ElsRefUnchangedBackAMD: mode = spv::ExecutionModeStencilRefUnchangedBackAMD; break;
  1514. case glslang::ElsRefGreaterBackAMD: mode = spv::ExecutionModeStencilRefGreaterBackAMD; break;
  1515. case glslang::ElsRefLessBackAMD: mode = spv::ExecutionModeStencilRefLessBackAMD; break;
  1516. default: mode = spv::ExecutionModeMax; break;
  1517. }
  1518. if (mode != spv::ExecutionModeMax)
  1519. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1520. switch (glslangIntermediate->getInterlockOrdering()) {
  1521. case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT;
  1522. break;
  1523. case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT;
  1524. break;
  1525. case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT;
  1526. break;
  1527. case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT;
  1528. break;
  1529. case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT;
  1530. break;
  1531. case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT;
  1532. break;
  1533. default: mode = spv::ExecutionModeMax;
  1534. break;
  1535. }
  1536. if (mode != spv::ExecutionModeMax) {
  1537. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1538. if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
  1539. mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
  1540. builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
  1541. } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
  1542. mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
  1543. builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
  1544. } else {
  1545. builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
  1546. }
  1547. builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
  1548. }
  1549. break;
  1550. case EShLangCompute:
  1551. builder.addCapability(spv::CapabilityShader);
  1552. if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_6) {
  1553. std::vector<spv::Id> dimConstId;
  1554. for (int dim = 0; dim < 3; ++dim) {
  1555. bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
  1556. dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
  1557. if (specConst) {
  1558. builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
  1559. glslangIntermediate->getLocalSizeSpecId(dim));
  1560. }
  1561. }
  1562. builder.addExecutionModeId(shaderEntry, spv::ExecutionModeLocalSizeId, dimConstId);
  1563. } else {
  1564. builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
  1565. glslangIntermediate->getLocalSize(1),
  1566. glslangIntermediate->getLocalSize(2));
  1567. }
  1568. if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
  1569. builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
  1570. builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
  1571. builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
  1572. } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
  1573. builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
  1574. builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
  1575. builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
  1576. }
  1577. break;
  1578. case EShLangTessEvaluation:
  1579. case EShLangTessControl:
  1580. builder.addCapability(spv::CapabilityTessellation);
  1581. glslang::TLayoutGeometry primitive;
  1582. if (glslangIntermediate->getStage() == EShLangTessControl) {
  1583. builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
  1584. glslangIntermediate->getVertices());
  1585. primitive = glslangIntermediate->getOutputPrimitive();
  1586. } else {
  1587. primitive = glslangIntermediate->getInputPrimitive();
  1588. }
  1589. switch (primitive) {
  1590. case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
  1591. case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
  1592. case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
  1593. default: mode = spv::ExecutionModeMax; break;
  1594. }
  1595. if (mode != spv::ExecutionModeMax)
  1596. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1597. switch (glslangIntermediate->getVertexSpacing()) {
  1598. case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
  1599. case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
  1600. case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
  1601. default: mode = spv::ExecutionModeMax; break;
  1602. }
  1603. if (mode != spv::ExecutionModeMax)
  1604. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1605. switch (glslangIntermediate->getVertexOrder()) {
  1606. case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
  1607. case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
  1608. default: mode = spv::ExecutionModeMax; break;
  1609. }
  1610. if (mode != spv::ExecutionModeMax)
  1611. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1612. if (glslangIntermediate->getPointMode())
  1613. builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
  1614. break;
  1615. case EShLangGeometry:
  1616. builder.addCapability(spv::CapabilityGeometry);
  1617. switch (glslangIntermediate->getInputPrimitive()) {
  1618. case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
  1619. case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
  1620. case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
  1621. case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
  1622. case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
  1623. default: mode = spv::ExecutionModeMax; break;
  1624. }
  1625. if (mode != spv::ExecutionModeMax)
  1626. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1627. builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
  1628. switch (glslangIntermediate->getOutputPrimitive()) {
  1629. case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
  1630. case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
  1631. case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
  1632. default: mode = spv::ExecutionModeMax; break;
  1633. }
  1634. if (mode != spv::ExecutionModeMax)
  1635. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1636. builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
  1637. break;
  1638. case EShLangRayGen:
  1639. case EShLangIntersect:
  1640. case EShLangAnyHit:
  1641. case EShLangClosestHit:
  1642. case EShLangMiss:
  1643. case EShLangCallable:
  1644. {
  1645. auto& extensions = glslangIntermediate->getRequestedExtensions();
  1646. if (extensions.find("GL_NV_ray_tracing") == extensions.end()) {
  1647. builder.addCapability(spv::CapabilityRayTracingKHR);
  1648. builder.addExtension("SPV_KHR_ray_tracing");
  1649. }
  1650. else {
  1651. builder.addCapability(spv::CapabilityRayTracingNV);
  1652. builder.addExtension("SPV_NV_ray_tracing");
  1653. }
  1654. if (glslangIntermediate->getStage() != EShLangRayGen && glslangIntermediate->getStage() != EShLangCallable) {
  1655. if (extensions.find("GL_EXT_ray_cull_mask") != extensions.end()) {
  1656. builder.addCapability(spv::CapabilityRayCullMaskKHR);
  1657. builder.addExtension("SPV_KHR_ray_cull_mask");
  1658. }
  1659. if (extensions.find("GL_EXT_ray_tracing_position_fetch") != extensions.end()) {
  1660. builder.addCapability(spv::CapabilityRayTracingPositionFetchKHR);
  1661. builder.addExtension("SPV_KHR_ray_tracing_position_fetch");
  1662. }
  1663. }
  1664. break;
  1665. }
  1666. case EShLangTask:
  1667. case EShLangMesh:
  1668. if(isMeshShaderExt) {
  1669. builder.addCapability(spv::CapabilityMeshShadingEXT);
  1670. builder.addExtension(spv::E_SPV_EXT_mesh_shader);
  1671. } else {
  1672. builder.addCapability(spv::CapabilityMeshShadingNV);
  1673. builder.addExtension(spv::E_SPV_NV_mesh_shader);
  1674. }
  1675. if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_6) {
  1676. std::vector<spv::Id> dimConstId;
  1677. for (int dim = 0; dim < 3; ++dim) {
  1678. bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
  1679. dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
  1680. if (specConst) {
  1681. builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
  1682. glslangIntermediate->getLocalSizeSpecId(dim));
  1683. }
  1684. }
  1685. builder.addExecutionModeId(shaderEntry, spv::ExecutionModeLocalSizeId, dimConstId);
  1686. } else {
  1687. builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
  1688. glslangIntermediate->getLocalSize(1),
  1689. glslangIntermediate->getLocalSize(2));
  1690. }
  1691. if (glslangIntermediate->getStage() == EShLangMesh) {
  1692. builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices,
  1693. glslangIntermediate->getVertices());
  1694. builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV,
  1695. glslangIntermediate->getPrimitives());
  1696. switch (glslangIntermediate->getOutputPrimitive()) {
  1697. case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
  1698. case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
  1699. case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
  1700. default: mode = spv::ExecutionModeMax; break;
  1701. }
  1702. if (mode != spv::ExecutionModeMax)
  1703. builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
  1704. }
  1705. break;
  1706. default:
  1707. break;
  1708. }
  1709. //
  1710. // Add SPIR-V requirements (GL_EXT_spirv_intrinsics)
  1711. //
  1712. if (glslangIntermediate->hasSpirvRequirement()) {
  1713. const glslang::TSpirvRequirement& spirvRequirement = glslangIntermediate->getSpirvRequirement();
  1714. // Add SPIR-V extension requirement
  1715. for (auto& extension : spirvRequirement.extensions)
  1716. builder.addExtension(extension.c_str());
  1717. // Add SPIR-V capability requirement
  1718. for (auto capability : spirvRequirement.capabilities)
  1719. builder.addCapability(static_cast<spv::Capability>(capability));
  1720. }
  1721. //
  1722. // Add SPIR-V execution mode qualifiers (GL_EXT_spirv_intrinsics)
  1723. //
  1724. if (glslangIntermediate->hasSpirvExecutionMode()) {
  1725. const glslang::TSpirvExecutionMode spirvExecutionMode = glslangIntermediate->getSpirvExecutionMode();
  1726. // Add spirv_execution_mode
  1727. for (auto& mode : spirvExecutionMode.modes) {
  1728. if (!mode.second.empty()) {
  1729. std::vector<unsigned> literals;
  1730. TranslateLiterals(mode.second, literals);
  1731. builder.addExecutionMode(shaderEntry, static_cast<spv::ExecutionMode>(mode.first), literals);
  1732. } else
  1733. builder.addExecutionMode(shaderEntry, static_cast<spv::ExecutionMode>(mode.first));
  1734. }
  1735. // Add spirv_execution_mode_id
  1736. for (auto& modeId : spirvExecutionMode.modeIds) {
  1737. std::vector<spv::Id> operandIds;
  1738. assert(!modeId.second.empty());
  1739. for (auto extraOperand : modeId.second) {
  1740. if (extraOperand->getType().getQualifier().isSpecConstant())
  1741. operandIds.push_back(getSymbolId(extraOperand->getAsSymbolNode()));
  1742. else
  1743. operandIds.push_back(createSpvConstant(*extraOperand));
  1744. }
  1745. builder.addExecutionModeId(shaderEntry, static_cast<spv::ExecutionMode>(modeId.first), operandIds);
  1746. }
  1747. }
  1748. }
  1749. // Finish creating SPV, after the traversal is complete.
  1750. void TGlslangToSpvTraverser::finishSpv()
  1751. {
  1752. // Finish the entry point function
  1753. if (! entryPointTerminated) {
  1754. builder.setBuildPoint(shaderEntry->getLastBlock());
  1755. builder.leaveFunction();
  1756. }
  1757. // finish off the entry-point SPV instruction by adding the Input/Output <id>
  1758. for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
  1759. entryPoint->addIdOperand(*it);
  1760. // Add capabilities, extensions, remove unneeded decorations, etc.,
  1761. // based on the resulting SPIR-V.
  1762. // Note: WebGPU code generation must have the opportunity to aggressively
  1763. // prune unreachable merge blocks and continue targets.
  1764. builder.postProcess();
  1765. }
  1766. // Write the SPV into 'out'.
  1767. void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
  1768. {
  1769. builder.dump(out);
  1770. }
  1771. //
  1772. // Implement the traversal functions.
  1773. //
  1774. // Return true from interior nodes to have the external traversal
  1775. // continue on to children. Return false if children were
  1776. // already processed.
  1777. //
  1778. //
  1779. // Symbols can turn into
  1780. // - uniform/input reads
  1781. // - output writes
  1782. // - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
  1783. // - something simple that degenerates into the last bullet
  1784. //
  1785. void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
  1786. {
  1787. // We update the line information even though no code might be generated here
  1788. // This is helpful to yield correct lines for control flow instructions
  1789. builder.setLine(symbol->getLoc().line, symbol->getLoc().getFilename());
  1790. SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
  1791. if (symbol->getType().isStruct())
  1792. glslangTypeToIdMap[symbol->getType().getStruct()] = symbol->getId();
  1793. if (symbol->getType().getQualifier().isSpecConstant())
  1794. spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
  1795. #ifdef ENABLE_HLSL
  1796. // Skip symbol handling if it is string-typed
  1797. if (symbol->getBasicType() == glslang::EbtString)
  1798. return;
  1799. #endif
  1800. // getSymbolId() will set up all the IO decorations on the first call.
  1801. // Formal function parameters were mapped during makeFunctions().
  1802. spv::Id id = getSymbolId(symbol);
  1803. if (symbol->getType().getQualifier().isTaskPayload())
  1804. taskPayloadID = id; // cache the taskPayloadID to be used it as operand for OpEmitMeshTasksEXT
  1805. if (builder.isPointer(id)) {
  1806. if (!symbol->getType().getQualifier().isParamInput() &&
  1807. !symbol->getType().getQualifier().isParamOutput()) {
  1808. // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
  1809. // Consider adding to the OpEntryPoint interface list.
  1810. // Only looking at structures if they have at least one member.
  1811. if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
  1812. spv::StorageClass sc = builder.getStorageClass(id);
  1813. // Before SPIR-V 1.4, we only want to include Input and Output.
  1814. // Starting with SPIR-V 1.4, we want all globals.
  1815. if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && builder.isGlobalStorage(id)) ||
  1816. (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
  1817. iOSet.insert(id);
  1818. }
  1819. }
  1820. }
  1821. // If the SPIR-V type is required to be different than the AST type
  1822. // (for ex SubgroupMasks or 3x4 ObjectToWorld/WorldToObject matrices),
  1823. // translate now from the SPIR-V type to the AST type, for the consuming
  1824. // operation.
  1825. // Note this turns it from an l-value to an r-value.
  1826. // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
  1827. if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
  1828. id = translateForcedType(id);
  1829. }
  1830. // Only process non-linkage-only nodes for generating actual static uses
  1831. if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
  1832. // Prepare to generate code for the access
  1833. // L-value chains will be computed left to right. We're on the symbol now,
  1834. // which is the left-most part of the access chain, so now is "clear" time,
  1835. // followed by setting the base.
  1836. builder.clearAccessChain();
  1837. // For now, we consider all user variables as being in memory, so they are pointers,
  1838. // except for
  1839. // A) R-Value arguments to a function, which are an intermediate object.
  1840. // See comments in handleUserFunctionCall().
  1841. // B) Specialization constants (normal constants don't even come in as a variable),
  1842. // These are also pure R-values.
  1843. // C) R-Values from type translation, see above call to translateForcedType()
  1844. glslang::TQualifier qualifier = symbol->getQualifier();
  1845. if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
  1846. !builder.isPointerType(builder.getTypeId(id)))
  1847. builder.setAccessChainRValue(id);
  1848. else
  1849. builder.setAccessChainLValue(id);
  1850. }
  1851. #ifdef ENABLE_HLSL
  1852. // Process linkage-only nodes for any special additional interface work.
  1853. if (linkageOnly) {
  1854. if (glslangIntermediate->getHlslFunctionality1()) {
  1855. // Map implicit counter buffers to their originating buffers, which should have been
  1856. // seen by now, given earlier pruning of unused counters, and preservation of order
  1857. // of declaration.
  1858. if (symbol->getType().getQualifier().isUniformOrBuffer()) {
  1859. if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
  1860. // Save possible originating buffers for counter buffers, keyed by
  1861. // making the potential counter-buffer name.
  1862. std::string keyName = symbol->getName().c_str();
  1863. keyName = glslangIntermediate->addCounterBufferName(keyName);
  1864. counterOriginator[keyName] = symbol;
  1865. } else {
  1866. // Handle a counter buffer, by finding the saved originating buffer.
  1867. std::string keyName = symbol->getName().c_str();
  1868. auto it = counterOriginator.find(keyName);
  1869. if (it != counterOriginator.end()) {
  1870. id = getSymbolId(it->second);
  1871. if (id != spv::NoResult) {
  1872. spv::Id counterId = getSymbolId(symbol);
  1873. if (counterId != spv::NoResult) {
  1874. builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
  1875. builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
  1876. }
  1877. }
  1878. }
  1879. }
  1880. }
  1881. }
  1882. }
  1883. #endif
  1884. }
  1885. bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
  1886. {
  1887. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  1888. if (node->getLeft()->getAsSymbolNode() != nullptr && node->getLeft()->getType().isStruct()) {
  1889. glslangTypeToIdMap[node->getLeft()->getType().getStruct()] = node->getLeft()->getAsSymbolNode()->getId();
  1890. }
  1891. if (node->getRight()->getAsSymbolNode() != nullptr && node->getRight()->getType().isStruct()) {
  1892. glslangTypeToIdMap[node->getRight()->getType().getStruct()] = node->getRight()->getAsSymbolNode()->getId();
  1893. }
  1894. SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
  1895. if (node->getType().getQualifier().isSpecConstant())
  1896. spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
  1897. // First, handle special cases
  1898. switch (node->getOp()) {
  1899. case glslang::EOpAssign:
  1900. case glslang::EOpAddAssign:
  1901. case glslang::EOpSubAssign:
  1902. case glslang::EOpMulAssign:
  1903. case glslang::EOpVectorTimesMatrixAssign:
  1904. case glslang::EOpVectorTimesScalarAssign:
  1905. case glslang::EOpMatrixTimesScalarAssign:
  1906. case glslang::EOpMatrixTimesMatrixAssign:
  1907. case glslang::EOpDivAssign:
  1908. case glslang::EOpModAssign:
  1909. case glslang::EOpAndAssign:
  1910. case glslang::EOpInclusiveOrAssign:
  1911. case glslang::EOpExclusiveOrAssign:
  1912. case glslang::EOpLeftShiftAssign:
  1913. case glslang::EOpRightShiftAssign:
  1914. // A bin-op assign "a += b" means the same thing as "a = a + b"
  1915. // where a is evaluated before b. For a simple assignment, GLSL
  1916. // says to evaluate the left before the right. So, always, left
  1917. // node then right node.
  1918. {
  1919. // get the left l-value, save it away
  1920. builder.clearAccessChain();
  1921. node->getLeft()->traverse(this);
  1922. spv::Builder::AccessChain lValue = builder.getAccessChain();
  1923. // evaluate the right
  1924. builder.clearAccessChain();
  1925. node->getRight()->traverse(this);
  1926. spv::Id rValue = accessChainLoad(node->getRight()->getType());
  1927. // reset line number for assignment
  1928. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  1929. if (node->getOp() != glslang::EOpAssign) {
  1930. // the left is also an r-value
  1931. builder.setAccessChain(lValue);
  1932. spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
  1933. // do the operation
  1934. spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
  1935. coherentFlags |= TranslateCoherent(node->getRight()->getType());
  1936. OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
  1937. TranslateNoContractionDecoration(node->getType().getQualifier()),
  1938. TranslateNonUniformDecoration(coherentFlags) };
  1939. rValue = createBinaryOperation(node->getOp(), decorations,
  1940. convertGlslangToSpvType(node->getType()), leftRValue, rValue,
  1941. node->getType().getBasicType());
  1942. // these all need their counterparts in createBinaryOperation()
  1943. assert(rValue != spv::NoResult);
  1944. }
  1945. // store the result
  1946. builder.setAccessChain(lValue);
  1947. multiTypeStore(node->getLeft()->getType(), rValue);
  1948. // assignments are expressions having an rValue after they are evaluated...
  1949. builder.clearAccessChain();
  1950. builder.setAccessChainRValue(rValue);
  1951. }
  1952. return false;
  1953. case glslang::EOpIndexDirect:
  1954. case glslang::EOpIndexDirectStruct:
  1955. {
  1956. // Structure, array, matrix, or vector indirection with statically known index.
  1957. // Get the left part of the access chain.
  1958. node->getLeft()->traverse(this);
  1959. // Add the next element in the chain
  1960. const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
  1961. if (! node->getLeft()->getType().isArray() &&
  1962. node->getLeft()->getType().isVector() &&
  1963. node->getOp() == glslang::EOpIndexDirect) {
  1964. // Swizzle is uniform so propagate uniform into access chain
  1965. spv::Builder::AccessChain::CoherentFlags coherentFlags = TranslateCoherent(node->getLeft()->getType());
  1966. coherentFlags.nonUniform = 0;
  1967. // This is essentially a hard-coded vector swizzle of size 1,
  1968. // so short circuit the access-chain stuff with a swizzle.
  1969. std::vector<unsigned> swizzle;
  1970. swizzle.push_back(glslangIndex);
  1971. int dummySize;
  1972. builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
  1973. coherentFlags,
  1974. glslangIntermediate->getBaseAlignmentScalar(
  1975. node->getLeft()->getType(), dummySize));
  1976. } else {
  1977. // Load through a block reference is performed with a dot operator that
  1978. // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
  1979. // do a load and reset the access chain.
  1980. if (node->getLeft()->isReference() &&
  1981. !node->getLeft()->getType().isArray() &&
  1982. node->getOp() == glslang::EOpIndexDirectStruct)
  1983. {
  1984. spv::Id left = accessChainLoad(node->getLeft()->getType());
  1985. builder.clearAccessChain();
  1986. builder.setAccessChainLValue(left);
  1987. }
  1988. int spvIndex = glslangIndex;
  1989. if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
  1990. node->getOp() == glslang::EOpIndexDirectStruct)
  1991. {
  1992. // This may be, e.g., an anonymous block-member selection, which generally need
  1993. // index remapping due to hidden members in anonymous blocks.
  1994. long long glslangId = glslangTypeToIdMap[node->getLeft()->getType().getStruct()];
  1995. if (memberRemapper.find(glslangId) != memberRemapper.end()) {
  1996. std::vector<int>& remapper = memberRemapper[glslangId];
  1997. assert(remapper.size() > 0);
  1998. spvIndex = remapper[glslangIndex];
  1999. }
  2000. }
  2001. // Struct reference propagates uniform lvalue
  2002. spv::Builder::AccessChain::CoherentFlags coherentFlags =
  2003. TranslateCoherent(node->getLeft()->getType());
  2004. coherentFlags.nonUniform = 0;
  2005. // normal case for indexing array or structure or block
  2006. builder.accessChainPush(builder.makeIntConstant(spvIndex),
  2007. coherentFlags,
  2008. node->getLeft()->getType().getBufferReferenceAlignment());
  2009. // Add capabilities here for accessing PointSize and clip/cull distance.
  2010. // We have deferred generation of associated capabilities until now.
  2011. if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
  2012. declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
  2013. }
  2014. }
  2015. return false;
  2016. case glslang::EOpIndexIndirect:
  2017. {
  2018. // Array, matrix, or vector indirection with variable index.
  2019. // Will use native SPIR-V access-chain for and array indirection;
  2020. // matrices are arrays of vectors, so will also work for a matrix.
  2021. // Will use the access chain's 'component' for variable index into a vector.
  2022. // This adapter is building access chains left to right.
  2023. // Set up the access chain to the left.
  2024. node->getLeft()->traverse(this);
  2025. // save it so that computing the right side doesn't trash it
  2026. spv::Builder::AccessChain partial = builder.getAccessChain();
  2027. // compute the next index in the chain
  2028. builder.clearAccessChain();
  2029. node->getRight()->traverse(this);
  2030. spv::Id index = accessChainLoad(node->getRight()->getType());
  2031. addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
  2032. // restore the saved access chain
  2033. builder.setAccessChain(partial);
  2034. // Only if index is nonUniform should we propagate nonUniform into access chain
  2035. spv::Builder::AccessChain::CoherentFlags index_flags = TranslateCoherent(node->getRight()->getType());
  2036. spv::Builder::AccessChain::CoherentFlags coherent_flags = TranslateCoherent(node->getLeft()->getType());
  2037. coherent_flags.nonUniform = index_flags.nonUniform;
  2038. if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
  2039. int dummySize;
  2040. builder.accessChainPushComponent(
  2041. index, convertGlslangToSpvType(node->getLeft()->getType()), coherent_flags,
  2042. glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
  2043. dummySize));
  2044. } else
  2045. builder.accessChainPush(index, coherent_flags,
  2046. node->getLeft()->getType().getBufferReferenceAlignment());
  2047. }
  2048. return false;
  2049. case glslang::EOpVectorSwizzle:
  2050. {
  2051. node->getLeft()->traverse(this);
  2052. std::vector<unsigned> swizzle;
  2053. convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
  2054. int dummySize;
  2055. builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
  2056. TranslateCoherent(node->getLeft()->getType()),
  2057. glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(),
  2058. dummySize));
  2059. }
  2060. return false;
  2061. case glslang::EOpMatrixSwizzle:
  2062. logger->missingFunctionality("matrix swizzle");
  2063. return true;
  2064. case glslang::EOpLogicalOr:
  2065. case glslang::EOpLogicalAnd:
  2066. {
  2067. // These may require short circuiting, but can sometimes be done as straight
  2068. // binary operations. The right operand must be short circuited if it has
  2069. // side effects, and should probably be if it is complex.
  2070. if (isTrivial(node->getRight()->getAsTyped()))
  2071. break; // handle below as a normal binary operation
  2072. // otherwise, we need to do dynamic short circuiting on the right operand
  2073. spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(),
  2074. *node->getRight()->getAsTyped());
  2075. builder.clearAccessChain();
  2076. builder.setAccessChainRValue(result);
  2077. }
  2078. return false;
  2079. default:
  2080. break;
  2081. }
  2082. // Assume generic binary op...
  2083. // get right operand
  2084. builder.clearAccessChain();
  2085. node->getLeft()->traverse(this);
  2086. spv::Id left = accessChainLoad(node->getLeft()->getType());
  2087. // get left operand
  2088. builder.clearAccessChain();
  2089. node->getRight()->traverse(this);
  2090. spv::Id right = accessChainLoad(node->getRight()->getType());
  2091. // get result
  2092. OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
  2093. TranslateNoContractionDecoration(node->getType().getQualifier()),
  2094. TranslateNonUniformDecoration(node->getType().getQualifier()) };
  2095. spv::Id result = createBinaryOperation(node->getOp(), decorations,
  2096. convertGlslangToSpvType(node->getType()), left, right,
  2097. node->getLeft()->getType().getBasicType());
  2098. builder.clearAccessChain();
  2099. if (! result) {
  2100. logger->missingFunctionality("unknown glslang binary operation");
  2101. return true; // pick up a child as the place-holder result
  2102. } else {
  2103. builder.setAccessChainRValue(result);
  2104. return false;
  2105. }
  2106. }
  2107. spv::Id TGlslangToSpvTraverser::convertLoadedBoolInUniformToUint(const glslang::TType& type,
  2108. spv::Id nominalTypeId,
  2109. spv::Id loadedId)
  2110. {
  2111. if (builder.isScalarType(nominalTypeId)) {
  2112. // Conversion for bool
  2113. spv::Id boolType = builder.makeBoolType();
  2114. if (nominalTypeId != boolType)
  2115. return builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
  2116. } else if (builder.isVectorType(nominalTypeId)) {
  2117. // Conversion for bvec
  2118. int vecSize = builder.getNumTypeComponents(nominalTypeId);
  2119. spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
  2120. if (nominalTypeId != bvecType)
  2121. loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId,
  2122. makeSmearedConstant(builder.makeUintConstant(0), vecSize));
  2123. } else if (builder.isArrayType(nominalTypeId)) {
  2124. // Conversion for bool array
  2125. spv::Id boolArrayTypeId = convertGlslangToSpvType(type);
  2126. if (nominalTypeId != boolArrayTypeId)
  2127. {
  2128. // Use OpCopyLogical from SPIR-V 1.4 if available.
  2129. if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4)
  2130. return builder.createUnaryOp(spv::OpCopyLogical, boolArrayTypeId, loadedId);
  2131. glslang::TType glslangElementType(type, 0);
  2132. spv::Id elementNominalTypeId = builder.getContainedTypeId(nominalTypeId);
  2133. std::vector<spv::Id> constituents;
  2134. for (int index = 0; index < type.getOuterArraySize(); ++index) {
  2135. // get the element
  2136. spv::Id elementValue = builder.createCompositeExtract(loadedId, elementNominalTypeId, index);
  2137. // recursively convert it
  2138. spv::Id elementConvertedValue = convertLoadedBoolInUniformToUint(glslangElementType, elementNominalTypeId, elementValue);
  2139. constituents.push_back(elementConvertedValue);
  2140. }
  2141. return builder.createCompositeConstruct(boolArrayTypeId, constituents);
  2142. }
  2143. }
  2144. return loadedId;
  2145. }
  2146. // Figure out what, if any, type changes are needed when accessing a specific built-in.
  2147. // Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
  2148. // Also see comment for 'forceType', regarding tracking SPIR-V-required types.
  2149. std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(glslang::TBuiltInVariable glslangBuiltIn,
  2150. const glslang::TType& glslangType)
  2151. {
  2152. switch(glslangBuiltIn)
  2153. {
  2154. case glslang::EbvSubGroupEqMask:
  2155. case glslang::EbvSubGroupGeMask:
  2156. case glslang::EbvSubGroupGtMask:
  2157. case glslang::EbvSubGroupLeMask:
  2158. case glslang::EbvSubGroupLtMask: {
  2159. // these require changing a 64-bit scaler -> a vector of 32-bit components
  2160. if (glslangType.isVector())
  2161. break;
  2162. spv::Id ivec4_type = builder.makeVectorType(builder.makeUintType(32), 4);
  2163. spv::Id uint64_type = builder.makeUintType(64);
  2164. std::pair<spv::Id, spv::Id> ret(ivec4_type, uint64_type);
  2165. return ret;
  2166. }
  2167. // There are no SPIR-V builtins defined for these and map onto original non-transposed
  2168. // builtins. During visitBinary we insert a transpose
  2169. case glslang::EbvWorldToObject3x4:
  2170. case glslang::EbvObjectToWorld3x4: {
  2171. spv::Id mat43 = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
  2172. spv::Id mat34 = builder.makeMatrixType(builder.makeFloatType(32), 3, 4);
  2173. std::pair<spv::Id, spv::Id> ret(mat43, mat34);
  2174. return ret;
  2175. }
  2176. default:
  2177. break;
  2178. }
  2179. std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
  2180. return ret;
  2181. }
  2182. // For an object previously identified (see getForcedType() and forceType)
  2183. // as needing type translations, do the translation needed for a load, turning
  2184. // an L-value into in R-value.
  2185. spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
  2186. {
  2187. const auto forceIt = forceType.find(object);
  2188. if (forceIt == forceType.end())
  2189. return object;
  2190. spv::Id desiredTypeId = forceIt->second;
  2191. spv::Id objectTypeId = builder.getTypeId(object);
  2192. assert(builder.isPointerType(objectTypeId));
  2193. objectTypeId = builder.getContainedTypeId(objectTypeId);
  2194. if (builder.isVectorType(objectTypeId) &&
  2195. builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
  2196. if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
  2197. // handle 32-bit v.xy* -> 64-bit
  2198. builder.clearAccessChain();
  2199. builder.setAccessChainLValue(object);
  2200. object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
  2201. std::vector<spv::Id> components;
  2202. components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
  2203. components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
  2204. spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
  2205. return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
  2206. builder.createCompositeConstruct(vecType, components));
  2207. } else {
  2208. logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
  2209. }
  2210. } else if (builder.isMatrixType(objectTypeId)) {
  2211. // There are no SPIR-V builtins defined for 3x4 variants of ObjectToWorld/WorldToObject
  2212. // and we insert a transpose after loading the original non-transposed builtins
  2213. builder.clearAccessChain();
  2214. builder.setAccessChainLValue(object);
  2215. object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, spv::DecorationMax, objectTypeId);
  2216. return builder.createUnaryOp(spv::OpTranspose, desiredTypeId, object);
  2217. } else {
  2218. logger->missingFunctionality("forcing non 32-bit vector type");
  2219. }
  2220. return object;
  2221. }
  2222. bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
  2223. {
  2224. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  2225. SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
  2226. if (node->getType().getQualifier().isSpecConstant())
  2227. spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
  2228. spv::Id result = spv::NoResult;
  2229. // try texturing first
  2230. result = createImageTextureFunctionCall(node);
  2231. if (result != spv::NoResult) {
  2232. builder.clearAccessChain();
  2233. builder.setAccessChainRValue(result);
  2234. return false; // done with this node
  2235. }
  2236. // Non-texturing.
  2237. if (node->getOp() == glslang::EOpArrayLength) {
  2238. // Quite special; won't want to evaluate the operand.
  2239. // Currently, the front-end does not allow .length() on an array until it is sized,
  2240. // except for the last block membeor of an SSBO.
  2241. // TODO: If this changes, link-time sized arrays might show up here, and need their
  2242. // size extracted.
  2243. // Normal .length() would have been constant folded by the front-end.
  2244. // So, this has to be block.lastMember.length().
  2245. // SPV wants "block" and member number as the operands, go get them.
  2246. spv::Id length;
  2247. if (node->getOperand()->getType().isCoopMat()) {
  2248. spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
  2249. assert(builder.isCooperativeMatrixType(typeId));
  2250. if (node->getOperand()->getType().isCoopMatKHR()) {
  2251. length = builder.createCooperativeMatrixLengthKHR(typeId);
  2252. } else {
  2253. spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
  2254. length = builder.createCooperativeMatrixLengthNV(typeId);
  2255. }
  2256. } else {
  2257. glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
  2258. block->traverse(this);
  2259. unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()
  2260. ->getConstArray()[0].getUConst();
  2261. length = builder.createArrayLength(builder.accessChainGetLValue(), member);
  2262. }
  2263. // GLSL semantics say the result of .length() is an int, while SPIR-V says
  2264. // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
  2265. // AST expectation of a signed result.
  2266. if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
  2267. if (builder.isInSpecConstCodeGenMode()) {
  2268. length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
  2269. } else {
  2270. length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
  2271. }
  2272. }
  2273. builder.clearAccessChain();
  2274. builder.setAccessChainRValue(length);
  2275. return false;
  2276. }
  2277. // Force variable declaration - Debug Mode Only
  2278. if (node->getOp() == glslang::EOpDeclare) {
  2279. builder.clearAccessChain();
  2280. node->getOperand()->traverse(this);
  2281. builder.clearAccessChain();
  2282. return false;
  2283. }
  2284. // Start by evaluating the operand
  2285. // Does it need a swizzle inversion? If so, evaluation is inverted;
  2286. // operate first on the swizzle base, then apply the swizzle.
  2287. spv::Id invertedType = spv::NoType;
  2288. auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
  2289. invertedType : convertGlslangToSpvType(node->getType()); };
  2290. if (node->getOp() == glslang::EOpInterpolateAtCentroid)
  2291. invertedType = getInvertedSwizzleType(*node->getOperand());
  2292. builder.clearAccessChain();
  2293. TIntermNode *operandNode;
  2294. if (invertedType != spv::NoType)
  2295. operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
  2296. else
  2297. operandNode = node->getOperand();
  2298. operandNode->traverse(this);
  2299. spv::Id operand = spv::NoResult;
  2300. spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
  2301. const auto hitObjectOpsWithLvalue = [](glslang::TOperator op) {
  2302. switch(op) {
  2303. case glslang::EOpReorderThreadNV:
  2304. case glslang::EOpHitObjectGetCurrentTimeNV:
  2305. case glslang::EOpHitObjectGetHitKindNV:
  2306. case glslang::EOpHitObjectGetPrimitiveIndexNV:
  2307. case glslang::EOpHitObjectGetGeometryIndexNV:
  2308. case glslang::EOpHitObjectGetInstanceIdNV:
  2309. case glslang::EOpHitObjectGetInstanceCustomIndexNV:
  2310. case glslang::EOpHitObjectGetObjectRayDirectionNV:
  2311. case glslang::EOpHitObjectGetObjectRayOriginNV:
  2312. case glslang::EOpHitObjectGetWorldRayDirectionNV:
  2313. case glslang::EOpHitObjectGetWorldRayOriginNV:
  2314. case glslang::EOpHitObjectGetWorldToObjectNV:
  2315. case glslang::EOpHitObjectGetObjectToWorldNV:
  2316. case glslang::EOpHitObjectGetRayTMaxNV:
  2317. case glslang::EOpHitObjectGetRayTMinNV:
  2318. case glslang::EOpHitObjectIsEmptyNV:
  2319. case glslang::EOpHitObjectIsHitNV:
  2320. case glslang::EOpHitObjectIsMissNV:
  2321. case glslang::EOpHitObjectRecordEmptyNV:
  2322. case glslang::EOpHitObjectGetShaderBindingTableRecordIndexNV:
  2323. case glslang::EOpHitObjectGetShaderRecordBufferHandleNV:
  2324. return true;
  2325. default:
  2326. return false;
  2327. }
  2328. };
  2329. if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
  2330. node->getOp() == glslang::EOpAtomicCounterDecrement ||
  2331. node->getOp() == glslang::EOpAtomicCounter ||
  2332. (node->getOp() == glslang::EOpInterpolateAtCentroid &&
  2333. glslangIntermediate->getSource() != glslang::EShSourceHlsl) ||
  2334. node->getOp() == glslang::EOpRayQueryProceed ||
  2335. node->getOp() == glslang::EOpRayQueryGetRayTMin ||
  2336. node->getOp() == glslang::EOpRayQueryGetRayFlags ||
  2337. node->getOp() == glslang::EOpRayQueryGetWorldRayOrigin ||
  2338. node->getOp() == glslang::EOpRayQueryGetWorldRayDirection ||
  2339. node->getOp() == glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque ||
  2340. node->getOp() == glslang::EOpRayQueryTerminate ||
  2341. node->getOp() == glslang::EOpRayQueryConfirmIntersection ||
  2342. (node->getOp() == glslang::EOpSpirvInst && operandNode->getAsTyped()->getQualifier().isSpirvByReference()) ||
  2343. hitObjectOpsWithLvalue(node->getOp())) {
  2344. operand = builder.accessChainGetLValue(); // Special case l-value operands
  2345. lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
  2346. lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
  2347. } else if (operandNode->getAsTyped()->getQualifier().isSpirvLiteral()) {
  2348. // Will be translated to a literal value, make a placeholder here
  2349. operand = spv::NoResult;
  2350. } else {
  2351. operand = accessChainLoad(node->getOperand()->getType());
  2352. }
  2353. OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
  2354. TranslateNoContractionDecoration(node->getType().getQualifier()),
  2355. TranslateNonUniformDecoration(node->getType().getQualifier()) };
  2356. // it could be a conversion
  2357. if (! result)
  2358. result = createConversion(node->getOp(), decorations, resultType(), operand,
  2359. node->getOperand()->getBasicType());
  2360. // if not, then possibly an operation
  2361. if (! result)
  2362. result = createUnaryOperation(node->getOp(), decorations, resultType(), operand,
  2363. node->getOperand()->getBasicType(), lvalueCoherentFlags);
  2364. // it could be attached to a SPIR-V intruction
  2365. if (!result) {
  2366. if (node->getOp() == glslang::EOpSpirvInst) {
  2367. const auto& spirvInst = node->getSpirvInstruction();
  2368. if (spirvInst.set == "") {
  2369. spv::IdImmediate idImmOp = {true, operand};
  2370. if (operandNode->getAsTyped()->getQualifier().isSpirvLiteral()) {
  2371. // Translate the constant to a literal value
  2372. std::vector<unsigned> literals;
  2373. glslang::TVector<const glslang::TIntermConstantUnion*> constants;
  2374. constants.push_back(operandNode->getAsConstantUnion());
  2375. TranslateLiterals(constants, literals);
  2376. idImmOp = {false, literals[0]};
  2377. }
  2378. if (node->getBasicType() == glslang::EbtVoid)
  2379. builder.createNoResultOp(static_cast<spv::Op>(spirvInst.id), {idImmOp});
  2380. else
  2381. result = builder.createOp(static_cast<spv::Op>(spirvInst.id), resultType(), {idImmOp});
  2382. } else {
  2383. result = builder.createBuiltinCall(
  2384. resultType(), spirvInst.set == "GLSL.std.450" ? stdBuiltins : getExtBuiltins(spirvInst.set.c_str()),
  2385. spirvInst.id, {operand});
  2386. }
  2387. if (node->getBasicType() == glslang::EbtVoid)
  2388. return false; // done with this node
  2389. }
  2390. }
  2391. if (result) {
  2392. if (invertedType) {
  2393. result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
  2394. decorations.addNonUniform(builder, result);
  2395. }
  2396. builder.clearAccessChain();
  2397. builder.setAccessChainRValue(result);
  2398. return false; // done with this node
  2399. }
  2400. // it must be a special case, check...
  2401. switch (node->getOp()) {
  2402. case glslang::EOpPostIncrement:
  2403. case glslang::EOpPostDecrement:
  2404. case glslang::EOpPreIncrement:
  2405. case glslang::EOpPreDecrement:
  2406. {
  2407. // we need the integer value "1" or the floating point "1.0" to add/subtract
  2408. spv::Id one = 0;
  2409. if (node->getBasicType() == glslang::EbtFloat)
  2410. one = builder.makeFloatConstant(1.0F);
  2411. else if (node->getBasicType() == glslang::EbtDouble)
  2412. one = builder.makeDoubleConstant(1.0);
  2413. else if (node->getBasicType() == glslang::EbtFloat16)
  2414. one = builder.makeFloat16Constant(1.0F);
  2415. else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
  2416. one = builder.makeInt8Constant(1);
  2417. else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
  2418. one = builder.makeInt16Constant(1);
  2419. else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
  2420. one = builder.makeInt64Constant(1);
  2421. else
  2422. one = builder.makeIntConstant(1);
  2423. glslang::TOperator op;
  2424. if (node->getOp() == glslang::EOpPreIncrement ||
  2425. node->getOp() == glslang::EOpPostIncrement)
  2426. op = glslang::EOpAdd;
  2427. else
  2428. op = glslang::EOpSub;
  2429. spv::Id result = createBinaryOperation(op, decorations,
  2430. convertGlslangToSpvType(node->getType()), operand, one,
  2431. node->getType().getBasicType());
  2432. assert(result != spv::NoResult);
  2433. // The result of operation is always stored, but conditionally the
  2434. // consumed result. The consumed result is always an r-value.
  2435. builder.accessChainStore(result,
  2436. TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags));
  2437. builder.clearAccessChain();
  2438. if (node->getOp() == glslang::EOpPreIncrement ||
  2439. node->getOp() == glslang::EOpPreDecrement)
  2440. builder.setAccessChainRValue(result);
  2441. else
  2442. builder.setAccessChainRValue(operand);
  2443. }
  2444. return false;
  2445. case glslang::EOpEmitStreamVertex:
  2446. builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
  2447. return false;
  2448. case glslang::EOpEndStreamPrimitive:
  2449. builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
  2450. return false;
  2451. case glslang::EOpRayQueryTerminate:
  2452. builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operand);
  2453. return false;
  2454. case glslang::EOpRayQueryConfirmIntersection:
  2455. builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operand);
  2456. return false;
  2457. case glslang::EOpReorderThreadNV:
  2458. builder.createNoResultOp(spv::OpReorderThreadWithHitObjectNV, operand);
  2459. return false;
  2460. case glslang::EOpHitObjectRecordEmptyNV:
  2461. builder.createNoResultOp(spv::OpHitObjectRecordEmptyNV, operand);
  2462. return false;
  2463. default:
  2464. logger->missingFunctionality("unknown glslang unary");
  2465. return true; // pick up operand as placeholder result
  2466. }
  2467. }
  2468. // Construct a composite object, recursively copying members if their types don't match
  2469. spv::Id TGlslangToSpvTraverser::createCompositeConstruct(spv::Id resultTypeId, std::vector<spv::Id> constituents)
  2470. {
  2471. for (int c = 0; c < (int)constituents.size(); ++c) {
  2472. spv::Id& constituent = constituents[c];
  2473. spv::Id lType = builder.getContainedTypeId(resultTypeId, c);
  2474. spv::Id rType = builder.getTypeId(constituent);
  2475. if (lType != rType) {
  2476. if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
  2477. constituent = builder.createUnaryOp(spv::OpCopyLogical, lType, constituent);
  2478. } else if (builder.isStructType(rType)) {
  2479. std::vector<spv::Id> rTypeConstituents;
  2480. int numrTypeConstituents = builder.getNumTypeConstituents(rType);
  2481. for (int i = 0; i < numrTypeConstituents; ++i) {
  2482. rTypeConstituents.push_back(builder.createCompositeExtract(constituent,
  2483. builder.getContainedTypeId(rType, i), i));
  2484. }
  2485. constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
  2486. } else {
  2487. assert(builder.isArrayType(rType));
  2488. std::vector<spv::Id> rTypeConstituents;
  2489. int numrTypeConstituents = builder.getNumTypeConstituents(rType);
  2490. spv::Id elementRType = builder.getContainedTypeId(rType);
  2491. for (int i = 0; i < numrTypeConstituents; ++i) {
  2492. rTypeConstituents.push_back(builder.createCompositeExtract(constituent, elementRType, i));
  2493. }
  2494. constituents[c] = createCompositeConstruct(lType, rTypeConstituents);
  2495. }
  2496. }
  2497. }
  2498. return builder.createCompositeConstruct(resultTypeId, constituents);
  2499. }
  2500. bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
  2501. {
  2502. SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
  2503. if (node->getType().getQualifier().isSpecConstant())
  2504. spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
  2505. spv::Id result = spv::NoResult;
  2506. spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
  2507. std::vector<spv::Builder::AccessChain> complexLvalues; // for holding swizzling l-values too complex for
  2508. // SPIR-V, for an out parameter
  2509. std::vector<spv::Id> temporaryLvalues; // temporaries to pass, as proxies for complexLValues
  2510. auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ?
  2511. invertedType :
  2512. convertGlslangToSpvType(node->getType()); };
  2513. // try texturing
  2514. result = createImageTextureFunctionCall(node);
  2515. if (result != spv::NoResult) {
  2516. builder.clearAccessChain();
  2517. builder.setAccessChainRValue(result);
  2518. return false;
  2519. } else if (node->getOp() == glslang::EOpImageStore ||
  2520. node->getOp() == glslang::EOpImageStoreLod ||
  2521. node->getOp() == glslang::EOpImageAtomicStore) {
  2522. // "imageStore" is a special case, which has no result
  2523. return false;
  2524. }
  2525. glslang::TOperator binOp = glslang::EOpNull;
  2526. bool reduceComparison = true;
  2527. bool isMatrix = false;
  2528. bool noReturnValue = false;
  2529. bool atomic = false;
  2530. spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
  2531. assert(node->getOp());
  2532. spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
  2533. switch (node->getOp()) {
  2534. case glslang::EOpScope:
  2535. case glslang::EOpSequence:
  2536. {
  2537. if (visit == glslang::EvPreVisit) {
  2538. ++sequenceDepth;
  2539. if (sequenceDepth == 1) {
  2540. // If this is the parent node of all the functions, we want to see them
  2541. // early, so all call points have actual SPIR-V functions to reference.
  2542. // In all cases, still let the traverser visit the children for us.
  2543. makeFunctions(node->getAsAggregate()->getSequence());
  2544. // Also, we want all globals initializers to go into the beginning of the entry point, before
  2545. // anything else gets there, so visit out of order, doing them all now.
  2546. makeGlobalInitializers(node->getAsAggregate()->getSequence());
  2547. //Pre process linker objects for ray tracing stages
  2548. if (glslangIntermediate->isRayTracingStage())
  2549. collectRayTracingLinkerObjects();
  2550. // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
  2551. // so do them manually.
  2552. visitFunctions(node->getAsAggregate()->getSequence());
  2553. return false;
  2554. } else {
  2555. if (node->getOp() == glslang::EOpScope)
  2556. builder.enterScope(0);
  2557. }
  2558. } else {
  2559. if (sequenceDepth > 1 && node->getOp() == glslang::EOpScope)
  2560. builder.leaveScope();
  2561. --sequenceDepth;
  2562. }
  2563. return true;
  2564. }
  2565. case glslang::EOpLinkerObjects:
  2566. {
  2567. if (visit == glslang::EvPreVisit)
  2568. linkageOnly = true;
  2569. else
  2570. linkageOnly = false;
  2571. return true;
  2572. }
  2573. case glslang::EOpComma:
  2574. {
  2575. // processing from left to right naturally leaves the right-most
  2576. // lying around in the access chain
  2577. glslang::TIntermSequence& glslangOperands = node->getSequence();
  2578. for (int i = 0; i < (int)glslangOperands.size(); ++i)
  2579. glslangOperands[i]->traverse(this);
  2580. return false;
  2581. }
  2582. case glslang::EOpFunction:
  2583. if (visit == glslang::EvPreVisit) {
  2584. if (isShaderEntryPoint(node)) {
  2585. inEntryPoint = true;
  2586. builder.setBuildPoint(shaderEntry->getLastBlock());
  2587. builder.enterFunction(shaderEntry);
  2588. currentFunction = shaderEntry;
  2589. } else {
  2590. handleFunctionEntry(node);
  2591. }
  2592. if (options.generateDebugInfo) {
  2593. const auto& loc = node->getLoc();
  2594. const char* sourceFileName = loc.getFilename();
  2595. spv::Id sourceFileId = sourceFileName ? builder.getStringId(sourceFileName) : builder.getSourceFile();
  2596. currentFunction->setDebugLineInfo(sourceFileId, loc.line, loc.column);
  2597. }
  2598. } else {
  2599. if (inEntryPoint)
  2600. entryPointTerminated = true;
  2601. builder.leaveFunction();
  2602. inEntryPoint = false;
  2603. }
  2604. return true;
  2605. case glslang::EOpParameters:
  2606. // Parameters will have been consumed by EOpFunction processing, but not
  2607. // the body, so we still visited the function node's children, making this
  2608. // child redundant.
  2609. return false;
  2610. case glslang::EOpFunctionCall:
  2611. {
  2612. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  2613. if (node->isUserDefined())
  2614. result = handleUserFunctionCall(node);
  2615. if (result) {
  2616. builder.clearAccessChain();
  2617. builder.setAccessChainRValue(result);
  2618. } else
  2619. logger->missingFunctionality("missing user function; linker needs to catch that");
  2620. return false;
  2621. }
  2622. case glslang::EOpConstructMat2x2:
  2623. case glslang::EOpConstructMat2x3:
  2624. case glslang::EOpConstructMat2x4:
  2625. case glslang::EOpConstructMat3x2:
  2626. case glslang::EOpConstructMat3x3:
  2627. case glslang::EOpConstructMat3x4:
  2628. case glslang::EOpConstructMat4x2:
  2629. case glslang::EOpConstructMat4x3:
  2630. case glslang::EOpConstructMat4x4:
  2631. case glslang::EOpConstructDMat2x2:
  2632. case glslang::EOpConstructDMat2x3:
  2633. case glslang::EOpConstructDMat2x4:
  2634. case glslang::EOpConstructDMat3x2:
  2635. case glslang::EOpConstructDMat3x3:
  2636. case glslang::EOpConstructDMat3x4:
  2637. case glslang::EOpConstructDMat4x2:
  2638. case glslang::EOpConstructDMat4x3:
  2639. case glslang::EOpConstructDMat4x4:
  2640. case glslang::EOpConstructIMat2x2:
  2641. case glslang::EOpConstructIMat2x3:
  2642. case glslang::EOpConstructIMat2x4:
  2643. case glslang::EOpConstructIMat3x2:
  2644. case glslang::EOpConstructIMat3x3:
  2645. case glslang::EOpConstructIMat3x4:
  2646. case glslang::EOpConstructIMat4x2:
  2647. case glslang::EOpConstructIMat4x3:
  2648. case glslang::EOpConstructIMat4x4:
  2649. case glslang::EOpConstructUMat2x2:
  2650. case glslang::EOpConstructUMat2x3:
  2651. case glslang::EOpConstructUMat2x4:
  2652. case glslang::EOpConstructUMat3x2:
  2653. case glslang::EOpConstructUMat3x3:
  2654. case glslang::EOpConstructUMat3x4:
  2655. case glslang::EOpConstructUMat4x2:
  2656. case glslang::EOpConstructUMat4x3:
  2657. case glslang::EOpConstructUMat4x4:
  2658. case glslang::EOpConstructBMat2x2:
  2659. case glslang::EOpConstructBMat2x3:
  2660. case glslang::EOpConstructBMat2x4:
  2661. case glslang::EOpConstructBMat3x2:
  2662. case glslang::EOpConstructBMat3x3:
  2663. case glslang::EOpConstructBMat3x4:
  2664. case glslang::EOpConstructBMat4x2:
  2665. case glslang::EOpConstructBMat4x3:
  2666. case glslang::EOpConstructBMat4x4:
  2667. case glslang::EOpConstructF16Mat2x2:
  2668. case glslang::EOpConstructF16Mat2x3:
  2669. case glslang::EOpConstructF16Mat2x4:
  2670. case glslang::EOpConstructF16Mat3x2:
  2671. case glslang::EOpConstructF16Mat3x3:
  2672. case glslang::EOpConstructF16Mat3x4:
  2673. case glslang::EOpConstructF16Mat4x2:
  2674. case glslang::EOpConstructF16Mat4x3:
  2675. case glslang::EOpConstructF16Mat4x4:
  2676. isMatrix = true;
  2677. // fall through
  2678. case glslang::EOpConstructFloat:
  2679. case glslang::EOpConstructVec2:
  2680. case glslang::EOpConstructVec3:
  2681. case glslang::EOpConstructVec4:
  2682. case glslang::EOpConstructDouble:
  2683. case glslang::EOpConstructDVec2:
  2684. case glslang::EOpConstructDVec3:
  2685. case glslang::EOpConstructDVec4:
  2686. case glslang::EOpConstructFloat16:
  2687. case glslang::EOpConstructF16Vec2:
  2688. case glslang::EOpConstructF16Vec3:
  2689. case glslang::EOpConstructF16Vec4:
  2690. case glslang::EOpConstructBool:
  2691. case glslang::EOpConstructBVec2:
  2692. case glslang::EOpConstructBVec3:
  2693. case glslang::EOpConstructBVec4:
  2694. case glslang::EOpConstructInt8:
  2695. case glslang::EOpConstructI8Vec2:
  2696. case glslang::EOpConstructI8Vec3:
  2697. case glslang::EOpConstructI8Vec4:
  2698. case glslang::EOpConstructUint8:
  2699. case glslang::EOpConstructU8Vec2:
  2700. case glslang::EOpConstructU8Vec3:
  2701. case glslang::EOpConstructU8Vec4:
  2702. case glslang::EOpConstructInt16:
  2703. case glslang::EOpConstructI16Vec2:
  2704. case glslang::EOpConstructI16Vec3:
  2705. case glslang::EOpConstructI16Vec4:
  2706. case glslang::EOpConstructUint16:
  2707. case glslang::EOpConstructU16Vec2:
  2708. case glslang::EOpConstructU16Vec3:
  2709. case glslang::EOpConstructU16Vec4:
  2710. case glslang::EOpConstructInt:
  2711. case glslang::EOpConstructIVec2:
  2712. case glslang::EOpConstructIVec3:
  2713. case glslang::EOpConstructIVec4:
  2714. case glslang::EOpConstructUint:
  2715. case glslang::EOpConstructUVec2:
  2716. case glslang::EOpConstructUVec3:
  2717. case glslang::EOpConstructUVec4:
  2718. case glslang::EOpConstructInt64:
  2719. case glslang::EOpConstructI64Vec2:
  2720. case glslang::EOpConstructI64Vec3:
  2721. case glslang::EOpConstructI64Vec4:
  2722. case glslang::EOpConstructUint64:
  2723. case glslang::EOpConstructU64Vec2:
  2724. case glslang::EOpConstructU64Vec3:
  2725. case glslang::EOpConstructU64Vec4:
  2726. case glslang::EOpConstructStruct:
  2727. case glslang::EOpConstructTextureSampler:
  2728. case glslang::EOpConstructReference:
  2729. case glslang::EOpConstructCooperativeMatrixNV:
  2730. case glslang::EOpConstructCooperativeMatrixKHR:
  2731. {
  2732. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  2733. std::vector<spv::Id> arguments;
  2734. translateArguments(*node, arguments, lvalueCoherentFlags);
  2735. spv::Id constructed;
  2736. if (node->getOp() == glslang::EOpConstructTextureSampler) {
  2737. const glslang::TType& texType = node->getSequence()[0]->getAsTyped()->getType();
  2738. if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_6 &&
  2739. texType.getSampler().isBuffer()) {
  2740. // SamplerBuffer is not supported in spirv1.6 so
  2741. // `samplerBuffer(textureBuffer, sampler)` is a no-op
  2742. // and textureBuffer is the result going forward
  2743. constructed = arguments[0];
  2744. } else
  2745. constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
  2746. } else if (node->getOp() == glslang::EOpConstructStruct ||
  2747. node->getOp() == glslang::EOpConstructCooperativeMatrixNV ||
  2748. node->getOp() == glslang::EOpConstructCooperativeMatrixKHR ||
  2749. node->getType().isArray()) {
  2750. std::vector<spv::Id> constituents;
  2751. for (int c = 0; c < (int)arguments.size(); ++c)
  2752. constituents.push_back(arguments[c]);
  2753. constructed = createCompositeConstruct(resultType(), constituents);
  2754. } else if (isMatrix)
  2755. constructed = builder.createMatrixConstructor(precision, arguments, resultType());
  2756. else
  2757. constructed = builder.createConstructor(precision, arguments, resultType());
  2758. if (node->getType().getQualifier().isNonUniform()) {
  2759. builder.addDecoration(constructed, spv::DecorationNonUniformEXT);
  2760. }
  2761. builder.clearAccessChain();
  2762. builder.setAccessChainRValue(constructed);
  2763. return false;
  2764. }
  2765. // These six are component-wise compares with component-wise results.
  2766. // Forward on to createBinaryOperation(), requesting a vector result.
  2767. case glslang::EOpLessThan:
  2768. case glslang::EOpGreaterThan:
  2769. case glslang::EOpLessThanEqual:
  2770. case glslang::EOpGreaterThanEqual:
  2771. case glslang::EOpVectorEqual:
  2772. case glslang::EOpVectorNotEqual:
  2773. {
  2774. // Map the operation to a binary
  2775. binOp = node->getOp();
  2776. reduceComparison = false;
  2777. switch (node->getOp()) {
  2778. case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
  2779. case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
  2780. default: binOp = node->getOp(); break;
  2781. }
  2782. break;
  2783. }
  2784. case glslang::EOpMul:
  2785. // component-wise matrix multiply
  2786. binOp = glslang::EOpMul;
  2787. break;
  2788. case glslang::EOpOuterProduct:
  2789. // two vectors multiplied to make a matrix
  2790. binOp = glslang::EOpOuterProduct;
  2791. break;
  2792. case glslang::EOpDot:
  2793. {
  2794. // for scalar dot product, use multiply
  2795. glslang::TIntermSequence& glslangOperands = node->getSequence();
  2796. if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
  2797. binOp = glslang::EOpMul;
  2798. break;
  2799. }
  2800. case glslang::EOpMod:
  2801. // when an aggregate, this is the floating-point mod built-in function,
  2802. // which can be emitted by the one in createBinaryOperation()
  2803. binOp = glslang::EOpMod;
  2804. break;
  2805. case glslang::EOpEmitVertex:
  2806. case glslang::EOpEndPrimitive:
  2807. case glslang::EOpBarrier:
  2808. case glslang::EOpMemoryBarrier:
  2809. case glslang::EOpMemoryBarrierAtomicCounter:
  2810. case glslang::EOpMemoryBarrierBuffer:
  2811. case glslang::EOpMemoryBarrierImage:
  2812. case glslang::EOpMemoryBarrierShared:
  2813. case glslang::EOpGroupMemoryBarrier:
  2814. case glslang::EOpDeviceMemoryBarrier:
  2815. case glslang::EOpAllMemoryBarrierWithGroupSync:
  2816. case glslang::EOpDeviceMemoryBarrierWithGroupSync:
  2817. case glslang::EOpWorkgroupMemoryBarrier:
  2818. case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
  2819. case glslang::EOpSubgroupBarrier:
  2820. case glslang::EOpSubgroupMemoryBarrier:
  2821. case glslang::EOpSubgroupMemoryBarrierBuffer:
  2822. case glslang::EOpSubgroupMemoryBarrierImage:
  2823. case glslang::EOpSubgroupMemoryBarrierShared:
  2824. noReturnValue = true;
  2825. // These all have 0 operands and will naturally finish up in the code below for 0 operands
  2826. break;
  2827. case glslang::EOpAtomicAdd:
  2828. case glslang::EOpAtomicSubtract:
  2829. case glslang::EOpAtomicMin:
  2830. case glslang::EOpAtomicMax:
  2831. case glslang::EOpAtomicAnd:
  2832. case glslang::EOpAtomicOr:
  2833. case glslang::EOpAtomicXor:
  2834. case glslang::EOpAtomicExchange:
  2835. case glslang::EOpAtomicCompSwap:
  2836. atomic = true;
  2837. break;
  2838. case glslang::EOpAtomicStore:
  2839. noReturnValue = true;
  2840. // fallthrough
  2841. case glslang::EOpAtomicLoad:
  2842. atomic = true;
  2843. break;
  2844. case glslang::EOpAtomicCounterAdd:
  2845. case glslang::EOpAtomicCounterSubtract:
  2846. case glslang::EOpAtomicCounterMin:
  2847. case glslang::EOpAtomicCounterMax:
  2848. case glslang::EOpAtomicCounterAnd:
  2849. case glslang::EOpAtomicCounterOr:
  2850. case glslang::EOpAtomicCounterXor:
  2851. case glslang::EOpAtomicCounterExchange:
  2852. case glslang::EOpAtomicCounterCompSwap:
  2853. builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
  2854. builder.addCapability(spv::CapabilityAtomicStorageOps);
  2855. atomic = true;
  2856. break;
  2857. case glslang::EOpAbsDifference:
  2858. case glslang::EOpAddSaturate:
  2859. case glslang::EOpSubSaturate:
  2860. case glslang::EOpAverage:
  2861. case glslang::EOpAverageRounded:
  2862. case glslang::EOpMul32x16:
  2863. builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
  2864. builder.addExtension("SPV_INTEL_shader_integer_functions2");
  2865. binOp = node->getOp();
  2866. break;
  2867. case glslang::EOpIgnoreIntersectionNV:
  2868. case glslang::EOpTerminateRayNV:
  2869. case glslang::EOpTraceNV:
  2870. case glslang::EOpTraceRayMotionNV:
  2871. case glslang::EOpTraceKHR:
  2872. case glslang::EOpExecuteCallableNV:
  2873. case glslang::EOpExecuteCallableKHR:
  2874. case glslang::EOpWritePackedPrimitiveIndices4x8NV:
  2875. case glslang::EOpEmitMeshTasksEXT:
  2876. case glslang::EOpSetMeshOutputsEXT:
  2877. noReturnValue = true;
  2878. break;
  2879. case glslang::EOpRayQueryInitialize:
  2880. case glslang::EOpRayQueryTerminate:
  2881. case glslang::EOpRayQueryGenerateIntersection:
  2882. case glslang::EOpRayQueryConfirmIntersection:
  2883. builder.addExtension("SPV_KHR_ray_query");
  2884. builder.addCapability(spv::CapabilityRayQueryKHR);
  2885. noReturnValue = true;
  2886. break;
  2887. case glslang::EOpRayQueryProceed:
  2888. case glslang::EOpRayQueryGetIntersectionType:
  2889. case glslang::EOpRayQueryGetRayTMin:
  2890. case glslang::EOpRayQueryGetRayFlags:
  2891. case glslang::EOpRayQueryGetIntersectionT:
  2892. case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
  2893. case glslang::EOpRayQueryGetIntersectionInstanceId:
  2894. case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
  2895. case glslang::EOpRayQueryGetIntersectionGeometryIndex:
  2896. case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
  2897. case glslang::EOpRayQueryGetIntersectionBarycentrics:
  2898. case glslang::EOpRayQueryGetIntersectionFrontFace:
  2899. case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
  2900. case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
  2901. case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
  2902. case glslang::EOpRayQueryGetWorldRayDirection:
  2903. case glslang::EOpRayQueryGetWorldRayOrigin:
  2904. case glslang::EOpRayQueryGetIntersectionObjectToWorld:
  2905. case glslang::EOpRayQueryGetIntersectionWorldToObject:
  2906. builder.addExtension("SPV_KHR_ray_query");
  2907. builder.addCapability(spv::CapabilityRayQueryKHR);
  2908. break;
  2909. case glslang::EOpCooperativeMatrixLoad:
  2910. case glslang::EOpCooperativeMatrixStore:
  2911. case glslang::EOpCooperativeMatrixLoadNV:
  2912. case glslang::EOpCooperativeMatrixStoreNV:
  2913. noReturnValue = true;
  2914. break;
  2915. case glslang::EOpBeginInvocationInterlock:
  2916. case glslang::EOpEndInvocationInterlock:
  2917. builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
  2918. noReturnValue = true;
  2919. break;
  2920. case glslang::EOpHitObjectTraceRayNV:
  2921. case glslang::EOpHitObjectTraceRayMotionNV:
  2922. case glslang::EOpHitObjectGetAttributesNV:
  2923. case glslang::EOpHitObjectExecuteShaderNV:
  2924. case glslang::EOpHitObjectRecordEmptyNV:
  2925. case glslang::EOpHitObjectRecordMissNV:
  2926. case glslang::EOpHitObjectRecordMissMotionNV:
  2927. case glslang::EOpHitObjectRecordHitNV:
  2928. case glslang::EOpHitObjectRecordHitMotionNV:
  2929. case glslang::EOpHitObjectRecordHitWithIndexNV:
  2930. case glslang::EOpHitObjectRecordHitWithIndexMotionNV:
  2931. case glslang::EOpReorderThreadNV:
  2932. noReturnValue = true;
  2933. //Fallthrough
  2934. case glslang::EOpHitObjectIsEmptyNV:
  2935. case glslang::EOpHitObjectIsMissNV:
  2936. case glslang::EOpHitObjectIsHitNV:
  2937. case glslang::EOpHitObjectGetRayTMinNV:
  2938. case glslang::EOpHitObjectGetRayTMaxNV:
  2939. case glslang::EOpHitObjectGetObjectRayOriginNV:
  2940. case glslang::EOpHitObjectGetObjectRayDirectionNV:
  2941. case glslang::EOpHitObjectGetWorldRayOriginNV:
  2942. case glslang::EOpHitObjectGetWorldRayDirectionNV:
  2943. case glslang::EOpHitObjectGetObjectToWorldNV:
  2944. case glslang::EOpHitObjectGetWorldToObjectNV:
  2945. case glslang::EOpHitObjectGetInstanceCustomIndexNV:
  2946. case glslang::EOpHitObjectGetInstanceIdNV:
  2947. case glslang::EOpHitObjectGetGeometryIndexNV:
  2948. case glslang::EOpHitObjectGetPrimitiveIndexNV:
  2949. case glslang::EOpHitObjectGetHitKindNV:
  2950. case glslang::EOpHitObjectGetCurrentTimeNV:
  2951. case glslang::EOpHitObjectGetShaderBindingTableRecordIndexNV:
  2952. case glslang::EOpHitObjectGetShaderRecordBufferHandleNV:
  2953. builder.addExtension(spv::E_SPV_NV_shader_invocation_reorder);
  2954. builder.addCapability(spv::CapabilityShaderInvocationReorderNV);
  2955. break;
  2956. case glslang::EOpRayQueryGetIntersectionTriangleVertexPositionsEXT:
  2957. builder.addExtension(spv::E_SPV_KHR_ray_tracing_position_fetch);
  2958. builder.addCapability(spv::CapabilityRayQueryPositionFetchKHR);
  2959. noReturnValue = true;
  2960. break;
  2961. case glslang::EOpDebugPrintf:
  2962. noReturnValue = true;
  2963. break;
  2964. default:
  2965. break;
  2966. }
  2967. //
  2968. // See if it maps to a regular operation.
  2969. //
  2970. if (binOp != glslang::EOpNull) {
  2971. glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
  2972. glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
  2973. assert(left && right);
  2974. builder.clearAccessChain();
  2975. left->traverse(this);
  2976. spv::Id leftId = accessChainLoad(left->getType());
  2977. builder.clearAccessChain();
  2978. right->traverse(this);
  2979. spv::Id rightId = accessChainLoad(right->getType());
  2980. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  2981. OpDecorations decorations = { precision,
  2982. TranslateNoContractionDecoration(node->getType().getQualifier()),
  2983. TranslateNonUniformDecoration(node->getType().getQualifier()) };
  2984. result = createBinaryOperation(binOp, decorations,
  2985. resultType(), leftId, rightId,
  2986. left->getType().getBasicType(), reduceComparison);
  2987. // code above should only make binOp that exists in createBinaryOperation
  2988. assert(result != spv::NoResult);
  2989. builder.clearAccessChain();
  2990. builder.setAccessChainRValue(result);
  2991. return false;
  2992. }
  2993. //
  2994. // Create the list of operands.
  2995. //
  2996. glslang::TIntermSequence& glslangOperands = node->getSequence();
  2997. std::vector<spv::Id> operands;
  2998. std::vector<spv::IdImmediate> memoryAccessOperands;
  2999. for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
  3000. // special case l-value operands; there are just a few
  3001. bool lvalue = false;
  3002. switch (node->getOp()) {
  3003. case glslang::EOpModf:
  3004. if (arg == 1)
  3005. lvalue = true;
  3006. break;
  3007. case glslang::EOpHitObjectRecordHitNV:
  3008. case glslang::EOpHitObjectRecordHitMotionNV:
  3009. case glslang::EOpHitObjectRecordHitWithIndexNV:
  3010. case glslang::EOpHitObjectRecordHitWithIndexMotionNV:
  3011. case glslang::EOpHitObjectTraceRayNV:
  3012. case glslang::EOpHitObjectTraceRayMotionNV:
  3013. case glslang::EOpHitObjectExecuteShaderNV:
  3014. case glslang::EOpHitObjectRecordMissNV:
  3015. case glslang::EOpHitObjectRecordMissMotionNV:
  3016. case glslang::EOpHitObjectGetAttributesNV:
  3017. if (arg == 0)
  3018. lvalue = true;
  3019. break;
  3020. case glslang::EOpRayQueryInitialize:
  3021. case glslang::EOpRayQueryTerminate:
  3022. case glslang::EOpRayQueryConfirmIntersection:
  3023. case glslang::EOpRayQueryProceed:
  3024. case glslang::EOpRayQueryGenerateIntersection:
  3025. case glslang::EOpRayQueryGetIntersectionType:
  3026. case glslang::EOpRayQueryGetIntersectionT:
  3027. case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
  3028. case glslang::EOpRayQueryGetIntersectionInstanceId:
  3029. case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
  3030. case glslang::EOpRayQueryGetIntersectionGeometryIndex:
  3031. case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
  3032. case glslang::EOpRayQueryGetIntersectionBarycentrics:
  3033. case glslang::EOpRayQueryGetIntersectionFrontFace:
  3034. case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
  3035. case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
  3036. case glslang::EOpRayQueryGetIntersectionObjectToWorld:
  3037. case glslang::EOpRayQueryGetIntersectionWorldToObject:
  3038. if (arg == 0)
  3039. lvalue = true;
  3040. break;
  3041. case glslang::EOpAtomicAdd:
  3042. case glslang::EOpAtomicSubtract:
  3043. case glslang::EOpAtomicMin:
  3044. case glslang::EOpAtomicMax:
  3045. case glslang::EOpAtomicAnd:
  3046. case glslang::EOpAtomicOr:
  3047. case glslang::EOpAtomicXor:
  3048. case glslang::EOpAtomicExchange:
  3049. case glslang::EOpAtomicCompSwap:
  3050. if (arg == 0)
  3051. lvalue = true;
  3052. break;
  3053. case glslang::EOpFrexp:
  3054. if (arg == 1)
  3055. lvalue = true;
  3056. break;
  3057. case glslang::EOpInterpolateAtSample:
  3058. case glslang::EOpInterpolateAtOffset:
  3059. case glslang::EOpInterpolateAtVertex:
  3060. if (arg == 0) {
  3061. // If GLSL, use the address of the interpolant argument.
  3062. // If HLSL, use an internal version of OpInterolates that takes
  3063. // the rvalue of the interpolant. A fixup pass in spirv-opt
  3064. // legalization will remove the OpLoad and convert to an lvalue.
  3065. // Had to do this because legalization will only propagate a
  3066. // builtin into an rvalue.
  3067. lvalue = glslangIntermediate->getSource() != glslang::EShSourceHlsl;
  3068. // Does it need a swizzle inversion? If so, evaluation is inverted;
  3069. // operate first on the swizzle base, then apply the swizzle.
  3070. // That is, we transform
  3071. //
  3072. // interpolate(v.zy) -> interpolate(v).zy
  3073. //
  3074. if (glslangOperands[0]->getAsOperator() &&
  3075. glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
  3076. invertedType = convertGlslangToSpvType(
  3077. glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
  3078. }
  3079. break;
  3080. case glslang::EOpAtomicLoad:
  3081. case glslang::EOpAtomicStore:
  3082. case glslang::EOpAtomicCounterAdd:
  3083. case glslang::EOpAtomicCounterSubtract:
  3084. case glslang::EOpAtomicCounterMin:
  3085. case glslang::EOpAtomicCounterMax:
  3086. case glslang::EOpAtomicCounterAnd:
  3087. case glslang::EOpAtomicCounterOr:
  3088. case glslang::EOpAtomicCounterXor:
  3089. case glslang::EOpAtomicCounterExchange:
  3090. case glslang::EOpAtomicCounterCompSwap:
  3091. if (arg == 0)
  3092. lvalue = true;
  3093. break;
  3094. case glslang::EOpAddCarry:
  3095. case glslang::EOpSubBorrow:
  3096. if (arg == 2)
  3097. lvalue = true;
  3098. break;
  3099. case glslang::EOpUMulExtended:
  3100. case glslang::EOpIMulExtended:
  3101. if (arg >= 2)
  3102. lvalue = true;
  3103. break;
  3104. case glslang::EOpCooperativeMatrixLoad:
  3105. case glslang::EOpCooperativeMatrixLoadNV:
  3106. if (arg == 0 || arg == 1)
  3107. lvalue = true;
  3108. break;
  3109. case glslang::EOpCooperativeMatrixStore:
  3110. case glslang::EOpCooperativeMatrixStoreNV:
  3111. if (arg == 1)
  3112. lvalue = true;
  3113. break;
  3114. case glslang::EOpSpirvInst:
  3115. if (glslangOperands[arg]->getAsTyped()->getQualifier().isSpirvByReference())
  3116. lvalue = true;
  3117. break;
  3118. case glslang::EOpReorderThreadNV:
  3119. //Three variants of reorderThreadNV, two of them use hitObjectNV
  3120. if (arg == 0 && glslangOperands.size() != 2)
  3121. lvalue = true;
  3122. break;
  3123. case glslang::EOpRayQueryGetIntersectionTriangleVertexPositionsEXT:
  3124. if (arg == 0 || arg == 2)
  3125. lvalue = true;
  3126. break;
  3127. default:
  3128. break;
  3129. }
  3130. builder.clearAccessChain();
  3131. if (invertedType != spv::NoType && arg == 0)
  3132. glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
  3133. else
  3134. glslangOperands[arg]->traverse(this);
  3135. if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
  3136. node->getOp() == glslang::EOpCooperativeMatrixStore ||
  3137. node->getOp() == glslang::EOpCooperativeMatrixLoadNV ||
  3138. node->getOp() == glslang::EOpCooperativeMatrixStoreNV) {
  3139. if (arg == 1) {
  3140. // fold "element" parameter into the access chain
  3141. spv::Builder::AccessChain save = builder.getAccessChain();
  3142. builder.clearAccessChain();
  3143. glslangOperands[2]->traverse(this);
  3144. spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
  3145. builder.setAccessChain(save);
  3146. // Point to the first element of the array.
  3147. builder.accessChainPush(elementId,
  3148. TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
  3149. glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
  3150. spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
  3151. unsigned int alignment = builder.getAccessChain().alignment;
  3152. int memoryAccess = TranslateMemoryAccess(coherentFlags);
  3153. if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
  3154. node->getOp() == glslang::EOpCooperativeMatrixLoadNV)
  3155. memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
  3156. if (node->getOp() == glslang::EOpCooperativeMatrixStore ||
  3157. node->getOp() == glslang::EOpCooperativeMatrixStoreNV)
  3158. memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
  3159. if (builder.getStorageClass(builder.getAccessChain().base) ==
  3160. spv::StorageClassPhysicalStorageBufferEXT) {
  3161. memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
  3162. }
  3163. memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
  3164. if (memoryAccess & spv::MemoryAccessAlignedMask) {
  3165. memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
  3166. }
  3167. if (memoryAccess &
  3168. (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
  3169. memoryAccessOperands.push_back(spv::IdImmediate(true,
  3170. builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
  3171. }
  3172. } else if (arg == 2) {
  3173. continue;
  3174. }
  3175. }
  3176. // for l-values, pass the address, for r-values, pass the value
  3177. if (lvalue) {
  3178. if (invertedType == spv::NoType && !builder.isSpvLvalue()) {
  3179. // SPIR-V cannot represent an l-value containing a swizzle that doesn't
  3180. // reduce to a simple access chain. So, we need a temporary vector to
  3181. // receive the result, and must later swizzle that into the original
  3182. // l-value.
  3183. complexLvalues.push_back(builder.getAccessChain());
  3184. temporaryLvalues.push_back(builder.createVariable(
  3185. spv::NoPrecision, spv::StorageClassFunction,
  3186. builder.accessChainGetInferredType(), "swizzleTemp"));
  3187. operands.push_back(temporaryLvalues.back());
  3188. } else {
  3189. operands.push_back(builder.accessChainGetLValue());
  3190. }
  3191. lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
  3192. lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
  3193. } else {
  3194. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  3195. glslang::TOperator glslangOp = node->getOp();
  3196. if (arg == 1 &&
  3197. (glslangOp == glslang::EOpRayQueryGetIntersectionType ||
  3198. glslangOp == glslang::EOpRayQueryGetIntersectionT ||
  3199. glslangOp == glslang::EOpRayQueryGetIntersectionInstanceCustomIndex ||
  3200. glslangOp == glslang::EOpRayQueryGetIntersectionInstanceId ||
  3201. glslangOp == glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset ||
  3202. glslangOp == glslang::EOpRayQueryGetIntersectionGeometryIndex ||
  3203. glslangOp == glslang::EOpRayQueryGetIntersectionPrimitiveIndex ||
  3204. glslangOp == glslang::EOpRayQueryGetIntersectionBarycentrics ||
  3205. glslangOp == glslang::EOpRayQueryGetIntersectionFrontFace ||
  3206. glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayDirection ||
  3207. glslangOp == glslang::EOpRayQueryGetIntersectionObjectRayOrigin ||
  3208. glslangOp == glslang::EOpRayQueryGetIntersectionObjectToWorld ||
  3209. glslangOp == glslang::EOpRayQueryGetIntersectionWorldToObject ||
  3210. glslangOp == glslang::EOpRayQueryGetIntersectionTriangleVertexPositionsEXT
  3211. )) {
  3212. bool cond = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getBConst();
  3213. operands.push_back(builder.makeIntConstant(cond ? 1 : 0));
  3214. } else if ((arg == 10 && glslangOp == glslang::EOpTraceKHR) ||
  3215. (arg == 11 && glslangOp == glslang::EOpTraceRayMotionNV) ||
  3216. (arg == 1 && glslangOp == glslang::EOpExecuteCallableKHR) ||
  3217. (arg == 1 && glslangOp == glslang::EOpHitObjectExecuteShaderNV) ||
  3218. (arg == 11 && glslangOp == glslang::EOpHitObjectTraceRayNV) ||
  3219. (arg == 12 && glslangOp == glslang::EOpHitObjectTraceRayMotionNV)) {
  3220. const int set = glslangOp == glslang::EOpExecuteCallableKHR ? 1 : 0;
  3221. const int location = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getUConst();
  3222. auto itNode = locationToSymbol[set].find(location);
  3223. visitSymbol(itNode->second);
  3224. spv::Id symId = getSymbolId(itNode->second);
  3225. operands.push_back(symId);
  3226. } else if ((arg == 12 && glslangOp == glslang::EOpHitObjectRecordHitNV) ||
  3227. (arg == 13 && glslangOp == glslang::EOpHitObjectRecordHitMotionNV) ||
  3228. (arg == 11 && glslangOp == glslang::EOpHitObjectRecordHitWithIndexNV) ||
  3229. (arg == 12 && glslangOp == glslang::EOpHitObjectRecordHitWithIndexMotionNV) ||
  3230. (arg == 1 && glslangOp == glslang::EOpHitObjectGetAttributesNV)) {
  3231. const int location = glslangOperands[arg]->getAsConstantUnion()->getConstArray()[0].getUConst();
  3232. const int set = 2;
  3233. auto itNode = locationToSymbol[set].find(location);
  3234. visitSymbol(itNode->second);
  3235. spv::Id symId = getSymbolId(itNode->second);
  3236. operands.push_back(symId);
  3237. } else if (glslangOperands[arg]->getAsTyped()->getQualifier().isSpirvLiteral()) {
  3238. // Will be translated to a literal value, make a placeholder here
  3239. operands.push_back(spv::NoResult);
  3240. } else {
  3241. operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
  3242. }
  3243. }
  3244. }
  3245. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  3246. if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
  3247. node->getOp() == glslang::EOpCooperativeMatrixLoadNV) {
  3248. std::vector<spv::IdImmediate> idImmOps;
  3249. idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
  3250. if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
  3251. idImmOps.push_back(spv::IdImmediate(true, operands[3])); // matrixLayout
  3252. idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
  3253. } else {
  3254. idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
  3255. idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
  3256. }
  3257. idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
  3258. // get the pointee type
  3259. spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
  3260. assert(builder.isCooperativeMatrixType(typeId));
  3261. // do the op
  3262. spv::Id result = node->getOp() == glslang::EOpCooperativeMatrixLoad
  3263. ? builder.createOp(spv::OpCooperativeMatrixLoadKHR, typeId, idImmOps)
  3264. : builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
  3265. // store the result to the pointer (out param 'm')
  3266. builder.createStore(result, operands[0]);
  3267. result = 0;
  3268. } else if (node->getOp() == glslang::EOpCooperativeMatrixStore ||
  3269. node->getOp() == glslang::EOpCooperativeMatrixStoreNV) {
  3270. std::vector<spv::IdImmediate> idImmOps;
  3271. idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
  3272. idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
  3273. if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
  3274. idImmOps.push_back(spv::IdImmediate(true, operands[3])); // matrixLayout
  3275. idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
  3276. } else {
  3277. idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
  3278. idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
  3279. }
  3280. idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
  3281. if (node->getOp() == glslang::EOpCooperativeMatrixStore)
  3282. builder.createNoResultOp(spv::OpCooperativeMatrixStoreKHR, idImmOps);
  3283. else
  3284. builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
  3285. result = 0;
  3286. } else if (node->getOp() == glslang::EOpRayQueryGetIntersectionTriangleVertexPositionsEXT) {
  3287. std::vector<spv::IdImmediate> idImmOps;
  3288. idImmOps.push_back(spv::IdImmediate(true, operands[0])); // q
  3289. idImmOps.push_back(spv::IdImmediate(true, operands[1])); // committed
  3290. spv::Id typeId = builder.makeArrayType(builder.makeVectorType(builder.makeFloatType(32), 3),
  3291. builder.makeUintConstant(3), 0);
  3292. // do the op
  3293. spv::Id result = builder.createOp(spv::OpRayQueryGetIntersectionTriangleVertexPositionsKHR, typeId, idImmOps);
  3294. // store the result to the pointer (out param 'm')
  3295. builder.createStore(result, operands[2]);
  3296. result = 0;
  3297. } else if (node->getOp() == glslang::EOpCooperativeMatrixMulAdd) {
  3298. uint32_t matrixOperands = 0;
  3299. // If the optional operand is present, initialize matrixOperands to that value.
  3300. if (glslangOperands.size() == 4 && glslangOperands[3]->getAsConstantUnion()) {
  3301. matrixOperands = glslangOperands[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
  3302. }
  3303. // Determine Cooperative Matrix Operands bits from the signedness of the types.
  3304. if (isTypeSignedInt(glslangOperands[0]->getAsTyped()->getBasicType()))
  3305. matrixOperands |= spv::CooperativeMatrixOperandsMatrixASignedComponentsMask;
  3306. if (isTypeSignedInt(glslangOperands[1]->getAsTyped()->getBasicType()))
  3307. matrixOperands |= spv::CooperativeMatrixOperandsMatrixBSignedComponentsMask;
  3308. if (isTypeSignedInt(glslangOperands[2]->getAsTyped()->getBasicType()))
  3309. matrixOperands |= spv::CooperativeMatrixOperandsMatrixCSignedComponentsMask;
  3310. if (isTypeSignedInt(node->getBasicType()))
  3311. matrixOperands |= spv::CooperativeMatrixOperandsMatrixResultSignedComponentsMask;
  3312. std::vector<spv::IdImmediate> idImmOps;
  3313. idImmOps.push_back(spv::IdImmediate(true, operands[0]));
  3314. idImmOps.push_back(spv::IdImmediate(true, operands[1]));
  3315. idImmOps.push_back(spv::IdImmediate(true, operands[2]));
  3316. if (matrixOperands != 0)
  3317. idImmOps.push_back(spv::IdImmediate(false, matrixOperands));
  3318. result = builder.createOp(spv::OpCooperativeMatrixMulAddKHR, resultType(), idImmOps);
  3319. } else if (atomic) {
  3320. // Handle all atomics
  3321. glslang::TBasicType typeProxy = (node->getOp() == glslang::EOpAtomicStore)
  3322. ? node->getSequence()[0]->getAsTyped()->getBasicType() : node->getBasicType();
  3323. result = createAtomicOperation(node->getOp(), precision, resultType(), operands, typeProxy,
  3324. lvalueCoherentFlags);
  3325. } else if (node->getOp() == glslang::EOpSpirvInst) {
  3326. const auto& spirvInst = node->getSpirvInstruction();
  3327. if (spirvInst.set == "") {
  3328. std::vector<spv::IdImmediate> idImmOps;
  3329. for (unsigned int i = 0; i < glslangOperands.size(); ++i) {
  3330. if (glslangOperands[i]->getAsTyped()->getQualifier().isSpirvLiteral()) {
  3331. // Translate the constant to a literal value
  3332. std::vector<unsigned> literals;
  3333. glslang::TVector<const glslang::TIntermConstantUnion*> constants;
  3334. constants.push_back(glslangOperands[i]->getAsConstantUnion());
  3335. TranslateLiterals(constants, literals);
  3336. idImmOps.push_back({false, literals[0]});
  3337. } else
  3338. idImmOps.push_back({true, operands[i]});
  3339. }
  3340. if (node->getBasicType() == glslang::EbtVoid)
  3341. builder.createNoResultOp(static_cast<spv::Op>(spirvInst.id), idImmOps);
  3342. else
  3343. result = builder.createOp(static_cast<spv::Op>(spirvInst.id), resultType(), idImmOps);
  3344. } else {
  3345. result = builder.createBuiltinCall(
  3346. resultType(), spirvInst.set == "GLSL.std.450" ? stdBuiltins : getExtBuiltins(spirvInst.set.c_str()),
  3347. spirvInst.id, operands);
  3348. }
  3349. noReturnValue = node->getBasicType() == glslang::EbtVoid;
  3350. } else if (node->getOp() == glslang::EOpDebugPrintf) {
  3351. if (!nonSemanticDebugPrintf) {
  3352. nonSemanticDebugPrintf = builder.import("NonSemantic.DebugPrintf");
  3353. }
  3354. result = builder.createBuiltinCall(builder.makeVoidType(), nonSemanticDebugPrintf, spv::NonSemanticDebugPrintfDebugPrintf, operands);
  3355. builder.addExtension(spv::E_SPV_KHR_non_semantic_info);
  3356. } else {
  3357. // Pass through to generic operations.
  3358. switch (glslangOperands.size()) {
  3359. case 0:
  3360. result = createNoArgOperation(node->getOp(), precision, resultType());
  3361. break;
  3362. case 1:
  3363. {
  3364. OpDecorations decorations = { precision,
  3365. TranslateNoContractionDecoration(node->getType().getQualifier()),
  3366. TranslateNonUniformDecoration(node->getType().getQualifier()) };
  3367. result = createUnaryOperation(
  3368. node->getOp(), decorations,
  3369. resultType(), operands.front(),
  3370. glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
  3371. }
  3372. break;
  3373. default:
  3374. result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
  3375. break;
  3376. }
  3377. if (invertedType != spv::NoResult)
  3378. result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
  3379. for (unsigned int i = 0; i < temporaryLvalues.size(); ++i) {
  3380. builder.setAccessChain(complexLvalues[i]);
  3381. builder.accessChainStore(builder.createLoad(temporaryLvalues[i], spv::NoPrecision),
  3382. TranslateNonUniformDecoration(complexLvalues[i].coherentFlags));
  3383. }
  3384. }
  3385. if (noReturnValue)
  3386. return false;
  3387. if (! result) {
  3388. logger->missingFunctionality("unknown glslang aggregate");
  3389. return true; // pick up a child as a placeholder operand
  3390. } else {
  3391. builder.clearAccessChain();
  3392. builder.setAccessChainRValue(result);
  3393. return false;
  3394. }
  3395. }
  3396. // This path handles both if-then-else and ?:
  3397. // The if-then-else has a node type of void, while
  3398. // ?: has either a void or a non-void node type
  3399. //
  3400. // Leaving the result, when not void:
  3401. // GLSL only has r-values as the result of a :?, but
  3402. // if we have an l-value, that can be more efficient if it will
  3403. // become the base of a complex r-value expression, because the
  3404. // next layer copies r-values into memory to use the access-chain mechanism
  3405. bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
  3406. {
  3407. // see if OpSelect can handle it
  3408. const auto isOpSelectable = [&]() {
  3409. if (node->getBasicType() == glslang::EbtVoid)
  3410. return false;
  3411. // OpSelect can do all other types starting with SPV 1.4
  3412. if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
  3413. // pre-1.4, only scalars and vectors can be handled
  3414. if ((!node->getType().isScalar() && !node->getType().isVector()))
  3415. return false;
  3416. }
  3417. return true;
  3418. };
  3419. // See if it simple and safe, or required, to execute both sides.
  3420. // Crucially, side effects must be either semantically required or avoided,
  3421. // and there are performance trade-offs.
  3422. // Return true if required or a good idea (and safe) to execute both sides,
  3423. // false otherwise.
  3424. const auto bothSidesPolicy = [&]() -> bool {
  3425. // do we have both sides?
  3426. if (node->getTrueBlock() == nullptr ||
  3427. node->getFalseBlock() == nullptr)
  3428. return false;
  3429. // required? (unless we write additional code to look for side effects
  3430. // and make performance trade-offs if none are present)
  3431. if (!node->getShortCircuit())
  3432. return true;
  3433. // if not required to execute both, decide based on performance/practicality...
  3434. if (!isOpSelectable())
  3435. return false;
  3436. assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
  3437. node->getType() == node->getFalseBlock()->getAsTyped()->getType());
  3438. // return true if a single operand to ? : is okay for OpSelect
  3439. const auto operandOkay = [](glslang::TIntermTyped* node) {
  3440. return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
  3441. };
  3442. return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
  3443. operandOkay(node->getFalseBlock()->getAsTyped());
  3444. };
  3445. spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
  3446. // emit the condition before doing anything with selection
  3447. node->getCondition()->traverse(this);
  3448. spv::Id condition = accessChainLoad(node->getCondition()->getType());
  3449. // Find a way of executing both sides and selecting the right result.
  3450. const auto executeBothSides = [&]() -> void {
  3451. // execute both sides
  3452. spv::Id resultType = convertGlslangToSpvType(node->getType());
  3453. node->getTrueBlock()->traverse(this);
  3454. spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
  3455. node->getFalseBlock()->traverse(this);
  3456. spv::Id falseValue = accessChainLoad(node->getFalseBlock()->getAsTyped()->getType());
  3457. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  3458. // done if void
  3459. if (node->getBasicType() == glslang::EbtVoid)
  3460. return;
  3461. // emit code to select between trueValue and falseValue
  3462. // see if OpSelect can handle the result type, and that the SPIR-V types
  3463. // of the inputs match the result type.
  3464. if (isOpSelectable()) {
  3465. // Emit OpSelect for this selection.
  3466. // smear condition to vector, if necessary (AST is always scalar)
  3467. // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
  3468. if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
  3469. condition = builder.smearScalar(spv::NoPrecision, condition,
  3470. builder.makeVectorType(builder.makeBoolType(),
  3471. builder.getNumComponents(trueValue)));
  3472. }
  3473. // If the types do not match, it is because of mismatched decorations on aggregates.
  3474. // Since isOpSelectable only lets us get here for SPIR-V >= 1.4, we can use OpCopyObject
  3475. // to get matching types.
  3476. if (builder.getTypeId(trueValue) != resultType) {
  3477. trueValue = builder.createUnaryOp(spv::OpCopyLogical, resultType, trueValue);
  3478. }
  3479. if (builder.getTypeId(falseValue) != resultType) {
  3480. falseValue = builder.createUnaryOp(spv::OpCopyLogical, resultType, falseValue);
  3481. }
  3482. // OpSelect
  3483. result = builder.createTriOp(spv::OpSelect, resultType, condition, trueValue, falseValue);
  3484. builder.clearAccessChain();
  3485. builder.setAccessChainRValue(result);
  3486. } else {
  3487. // We need control flow to select the result.
  3488. // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
  3489. result = builder.createVariable(TranslatePrecisionDecoration(node->getType()),
  3490. spv::StorageClassFunction, resultType);
  3491. // Selection control:
  3492. const spv::SelectionControlMask control = TranslateSelectionControl(*node);
  3493. // make an "if" based on the value created by the condition
  3494. spv::Builder::If ifBuilder(condition, control, builder);
  3495. // emit the "then" statement
  3496. builder.clearAccessChain();
  3497. builder.setAccessChainLValue(result);
  3498. multiTypeStore(node->getType(), trueValue);
  3499. ifBuilder.makeBeginElse();
  3500. // emit the "else" statement
  3501. builder.clearAccessChain();
  3502. builder.setAccessChainLValue(result);
  3503. multiTypeStore(node->getType(), falseValue);
  3504. // finish off the control flow
  3505. ifBuilder.makeEndIf();
  3506. builder.clearAccessChain();
  3507. builder.setAccessChainLValue(result);
  3508. }
  3509. };
  3510. // Execute the one side needed, as per the condition
  3511. const auto executeOneSide = [&]() {
  3512. // Always emit control flow.
  3513. if (node->getBasicType() != glslang::EbtVoid) {
  3514. result = builder.createVariable(TranslatePrecisionDecoration(node->getType()), spv::StorageClassFunction,
  3515. convertGlslangToSpvType(node->getType()));
  3516. }
  3517. // Selection control:
  3518. const spv::SelectionControlMask control = TranslateSelectionControl(*node);
  3519. // make an "if" based on the value created by the condition
  3520. spv::Builder::If ifBuilder(condition, control, builder);
  3521. // emit the "then" statement
  3522. if (node->getTrueBlock() != nullptr) {
  3523. node->getTrueBlock()->traverse(this);
  3524. if (result != spv::NoResult) {
  3525. spv::Id load = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
  3526. builder.clearAccessChain();
  3527. builder.setAccessChainLValue(result);
  3528. multiTypeStore(node->getType(), load);
  3529. }
  3530. }
  3531. if (node->getFalseBlock() != nullptr) {
  3532. ifBuilder.makeBeginElse();
  3533. // emit the "else" statement
  3534. node->getFalseBlock()->traverse(this);
  3535. if (result != spv::NoResult) {
  3536. spv::Id load = accessChainLoad(node->getFalseBlock()->getAsTyped()->getType());
  3537. builder.clearAccessChain();
  3538. builder.setAccessChainLValue(result);
  3539. multiTypeStore(node->getType(), load);
  3540. }
  3541. }
  3542. // finish off the control flow
  3543. ifBuilder.makeEndIf();
  3544. if (result != spv::NoResult) {
  3545. builder.clearAccessChain();
  3546. builder.setAccessChainLValue(result);
  3547. }
  3548. };
  3549. // Try for OpSelect (or a requirement to execute both sides)
  3550. if (bothSidesPolicy()) {
  3551. SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
  3552. if (node->getType().getQualifier().isSpecConstant())
  3553. spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
  3554. executeBothSides();
  3555. } else
  3556. executeOneSide();
  3557. return false;
  3558. }
  3559. bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
  3560. {
  3561. // emit and get the condition before doing anything with switch
  3562. node->getCondition()->traverse(this);
  3563. spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
  3564. // Selection control:
  3565. const spv::SelectionControlMask control = TranslateSwitchControl(*node);
  3566. // browse the children to sort out code segments
  3567. int defaultSegment = -1;
  3568. std::vector<TIntermNode*> codeSegments;
  3569. glslang::TIntermSequence& sequence = node->getBody()->getSequence();
  3570. std::vector<int> caseValues;
  3571. std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
  3572. for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
  3573. TIntermNode* child = *c;
  3574. if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
  3575. defaultSegment = (int)codeSegments.size();
  3576. else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
  3577. valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
  3578. caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()
  3579. ->getConstArray()[0].getIConst());
  3580. } else
  3581. codeSegments.push_back(child);
  3582. }
  3583. // handle the case where the last code segment is missing, due to no code
  3584. // statements between the last case and the end of the switch statement
  3585. if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
  3586. (int)codeSegments.size() == defaultSegment)
  3587. codeSegments.push_back(nullptr);
  3588. // make the switch statement
  3589. std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
  3590. builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment,
  3591. segmentBlocks);
  3592. // emit all the code in the segments
  3593. breakForLoop.push(false);
  3594. for (unsigned int s = 0; s < codeSegments.size(); ++s) {
  3595. builder.nextSwitchSegment(segmentBlocks, s);
  3596. if (codeSegments[s])
  3597. codeSegments[s]->traverse(this);
  3598. else
  3599. builder.addSwitchBreak();
  3600. }
  3601. breakForLoop.pop();
  3602. builder.endSwitch(segmentBlocks);
  3603. return false;
  3604. }
  3605. void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
  3606. {
  3607. if (node->getQualifier().isSpirvLiteral())
  3608. return; // Translated to a literal value, skip further processing
  3609. int nextConst = 0;
  3610. spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
  3611. builder.clearAccessChain();
  3612. builder.setAccessChainRValue(constant);
  3613. }
  3614. bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
  3615. {
  3616. auto blocks = builder.makeNewLoop();
  3617. builder.createBranch(&blocks.head);
  3618. // Loop control:
  3619. std::vector<unsigned int> operands;
  3620. const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
  3621. // Spec requires back edges to target header blocks, and every header block
  3622. // must dominate its merge block. Make a header block first to ensure these
  3623. // conditions are met. By definition, it will contain OpLoopMerge, followed
  3624. // by a block-ending branch. But we don't want to put any other body/test
  3625. // instructions in it, since the body/test may have arbitrary instructions,
  3626. // including merges of its own.
  3627. builder.setBuildPoint(&blocks.head);
  3628. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  3629. builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
  3630. if (node->testFirst() && node->getTest()) {
  3631. spv::Block& test = builder.makeNewBlock();
  3632. builder.createBranch(&test);
  3633. builder.setBuildPoint(&test);
  3634. node->getTest()->traverse(this);
  3635. spv::Id condition = accessChainLoad(node->getTest()->getType());
  3636. builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
  3637. builder.setBuildPoint(&blocks.body);
  3638. breakForLoop.push(true);
  3639. if (node->getBody())
  3640. node->getBody()->traverse(this);
  3641. builder.createBranch(&blocks.continue_target);
  3642. breakForLoop.pop();
  3643. builder.setBuildPoint(&blocks.continue_target);
  3644. if (node->getTerminal())
  3645. node->getTerminal()->traverse(this);
  3646. builder.createBranch(&blocks.head);
  3647. } else {
  3648. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  3649. builder.createBranch(&blocks.body);
  3650. breakForLoop.push(true);
  3651. builder.setBuildPoint(&blocks.body);
  3652. if (node->getBody())
  3653. node->getBody()->traverse(this);
  3654. builder.createBranch(&blocks.continue_target);
  3655. breakForLoop.pop();
  3656. builder.setBuildPoint(&blocks.continue_target);
  3657. if (node->getTerminal())
  3658. node->getTerminal()->traverse(this);
  3659. if (node->getTest()) {
  3660. node->getTest()->traverse(this);
  3661. spv::Id condition =
  3662. accessChainLoad(node->getTest()->getType());
  3663. builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
  3664. } else {
  3665. // TODO: unless there was a break/return/discard instruction
  3666. // somewhere in the body, this is an infinite loop, so we should
  3667. // issue a warning.
  3668. builder.createBranch(&blocks.head);
  3669. }
  3670. }
  3671. builder.setBuildPoint(&blocks.merge);
  3672. builder.closeLoop();
  3673. return false;
  3674. }
  3675. bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
  3676. {
  3677. if (node->getExpression())
  3678. node->getExpression()->traverse(this);
  3679. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  3680. switch (node->getFlowOp()) {
  3681. case glslang::EOpKill:
  3682. if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_6) {
  3683. if (glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
  3684. builder.addCapability(spv::CapabilityDemoteToHelperInvocation);
  3685. builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
  3686. } else {
  3687. builder.makeStatementTerminator(spv::OpTerminateInvocation, "post-terminate-invocation");
  3688. }
  3689. } else {
  3690. builder.makeStatementTerminator(spv::OpKill, "post-discard");
  3691. }
  3692. break;
  3693. case glslang::EOpTerminateInvocation:
  3694. builder.addExtension(spv::E_SPV_KHR_terminate_invocation);
  3695. builder.makeStatementTerminator(spv::OpTerminateInvocation, "post-terminate-invocation");
  3696. break;
  3697. case glslang::EOpBreak:
  3698. if (breakForLoop.top())
  3699. builder.createLoopExit();
  3700. else
  3701. builder.addSwitchBreak();
  3702. break;
  3703. case glslang::EOpContinue:
  3704. builder.createLoopContinue();
  3705. break;
  3706. case glslang::EOpReturn:
  3707. if (node->getExpression() != nullptr) {
  3708. const glslang::TType& glslangReturnType = node->getExpression()->getType();
  3709. spv::Id returnId = accessChainLoad(glslangReturnType);
  3710. if (builder.getTypeId(returnId) != currentFunction->getReturnType() ||
  3711. TranslatePrecisionDecoration(glslangReturnType) != currentFunction->getReturnPrecision()) {
  3712. builder.clearAccessChain();
  3713. spv::Id copyId = builder.createVariable(currentFunction->getReturnPrecision(),
  3714. spv::StorageClassFunction, currentFunction->getReturnType());
  3715. builder.setAccessChainLValue(copyId);
  3716. multiTypeStore(glslangReturnType, returnId);
  3717. returnId = builder.createLoad(copyId, currentFunction->getReturnPrecision());
  3718. }
  3719. builder.makeReturn(false, returnId);
  3720. } else
  3721. builder.makeReturn(false);
  3722. builder.clearAccessChain();
  3723. break;
  3724. case glslang::EOpDemote:
  3725. builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
  3726. builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
  3727. builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
  3728. break;
  3729. case glslang::EOpTerminateRayKHR:
  3730. builder.makeStatementTerminator(spv::OpTerminateRayKHR, "post-terminateRayKHR");
  3731. break;
  3732. case glslang::EOpIgnoreIntersectionKHR:
  3733. builder.makeStatementTerminator(spv::OpIgnoreIntersectionKHR, "post-ignoreIntersectionKHR");
  3734. break;
  3735. default:
  3736. assert(0);
  3737. break;
  3738. }
  3739. return false;
  3740. }
  3741. spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
  3742. {
  3743. // First, steer off constants, which are not SPIR-V variables, but
  3744. // can still have a mapping to a SPIR-V Id.
  3745. // This includes specialization constants.
  3746. if (node->getQualifier().isConstant()) {
  3747. spv::Id result = createSpvConstant(*node);
  3748. if (result != spv::NoResult)
  3749. return result;
  3750. }
  3751. // Now, handle actual variables
  3752. spv::StorageClass storageClass = TranslateStorageClass(node->getType());
  3753. spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
  3754. : forcedType;
  3755. const bool contains16BitType = node->getType().contains16BitFloat() ||
  3756. node->getType().contains16BitInt();
  3757. if (contains16BitType) {
  3758. switch (storageClass) {
  3759. case spv::StorageClassInput:
  3760. case spv::StorageClassOutput:
  3761. builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
  3762. builder.addCapability(spv::CapabilityStorageInputOutput16);
  3763. break;
  3764. case spv::StorageClassUniform:
  3765. builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
  3766. if (node->getType().getQualifier().storage == glslang::EvqBuffer)
  3767. builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
  3768. else
  3769. builder.addCapability(spv::CapabilityStorageUniform16);
  3770. break;
  3771. case spv::StorageClassPushConstant:
  3772. builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
  3773. builder.addCapability(spv::CapabilityStoragePushConstant16);
  3774. break;
  3775. case spv::StorageClassStorageBuffer:
  3776. case spv::StorageClassPhysicalStorageBufferEXT:
  3777. builder.addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
  3778. builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
  3779. break;
  3780. default:
  3781. if (storageClass == spv::StorageClassWorkgroup &&
  3782. node->getType().getBasicType() == glslang::EbtBlock) {
  3783. builder.addCapability(spv::CapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR);
  3784. break;
  3785. }
  3786. if (node->getType().contains16BitFloat())
  3787. builder.addCapability(spv::CapabilityFloat16);
  3788. if (node->getType().contains16BitInt())
  3789. builder.addCapability(spv::CapabilityInt16);
  3790. break;
  3791. }
  3792. }
  3793. if (node->getType().contains8BitInt()) {
  3794. if (storageClass == spv::StorageClassPushConstant) {
  3795. builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
  3796. builder.addCapability(spv::CapabilityStoragePushConstant8);
  3797. } else if (storageClass == spv::StorageClassUniform) {
  3798. builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
  3799. builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
  3800. } else if (storageClass == spv::StorageClassStorageBuffer) {
  3801. builder.addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
  3802. builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
  3803. } else if (storageClass == spv::StorageClassWorkgroup &&
  3804. node->getType().getBasicType() == glslang::EbtBlock) {
  3805. builder.addCapability(spv::CapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR);
  3806. } else {
  3807. builder.addCapability(spv::CapabilityInt8);
  3808. }
  3809. }
  3810. const char* name = node->getName().c_str();
  3811. if (glslang::IsAnonymous(name))
  3812. name = "";
  3813. spv::Id initializer = spv::NoResult;
  3814. if (node->getType().getQualifier().storage == glslang::EvqUniform && !node->getConstArray().empty()) {
  3815. int nextConst = 0;
  3816. initializer = createSpvConstantFromConstUnionArray(node->getType(),
  3817. node->getConstArray(),
  3818. nextConst,
  3819. false /* specConst */);
  3820. } else if (node->getType().getQualifier().isNullInit()) {
  3821. initializer = builder.makeNullConstant(spvType);
  3822. }
  3823. return builder.createVariable(spv::NoPrecision, storageClass, spvType, name, initializer, false);
  3824. }
  3825. // Return type Id of the sampled type.
  3826. spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
  3827. {
  3828. switch (sampler.type) {
  3829. case glslang::EbtInt: return builder.makeIntType(32);
  3830. case glslang::EbtUint: return builder.makeUintType(32);
  3831. case glslang::EbtFloat: return builder.makeFloatType(32);
  3832. case glslang::EbtFloat16:
  3833. builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
  3834. builder.addCapability(spv::CapabilityFloat16ImageAMD);
  3835. return builder.makeFloatType(16);
  3836. case glslang::EbtInt64:
  3837. builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
  3838. builder.addCapability(spv::CapabilityInt64ImageEXT);
  3839. return builder.makeIntType(64);
  3840. case glslang::EbtUint64:
  3841. builder.addExtension(spv::E_SPV_EXT_shader_image_int64);
  3842. builder.addCapability(spv::CapabilityInt64ImageEXT);
  3843. return builder.makeUintType(64);
  3844. default:
  3845. assert(0);
  3846. return builder.makeFloatType(32);
  3847. }
  3848. }
  3849. // If node is a swizzle operation, return the type that should be used if
  3850. // the swizzle base is first consumed by another operation, before the swizzle
  3851. // is applied.
  3852. spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
  3853. {
  3854. if (node.getAsOperator() &&
  3855. node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
  3856. return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
  3857. else
  3858. return spv::NoType;
  3859. }
  3860. // When inverting a swizzle with a parent op, this function
  3861. // will apply the swizzle operation to a completed parent operation.
  3862. spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node,
  3863. spv::Id parentResult)
  3864. {
  3865. std::vector<unsigned> swizzle;
  3866. convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
  3867. return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
  3868. }
  3869. // Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
  3870. void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
  3871. {
  3872. const glslang::TIntermSequence& swizzleSequence = node.getSequence();
  3873. for (int i = 0; i < (int)swizzleSequence.size(); ++i)
  3874. swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
  3875. }
  3876. // Convert from a glslang type to an SPV type, by calling into a
  3877. // recursive version of this function. This establishes the inherited
  3878. // layout state rooted from the top-level type.
  3879. spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
  3880. {
  3881. return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
  3882. }
  3883. // Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
  3884. // explicitLayout can be kept the same throughout the hierarchical recursive walk.
  3885. // Mutually recursive with convertGlslangStructToSpvType().
  3886. spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
  3887. glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
  3888. bool lastBufferBlockMember, bool forwardReferenceOnly)
  3889. {
  3890. spv::Id spvType = spv::NoResult;
  3891. switch (type.getBasicType()) {
  3892. case glslang::EbtVoid:
  3893. spvType = builder.makeVoidType();
  3894. assert (! type.isArray());
  3895. break;
  3896. case glslang::EbtBool:
  3897. // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
  3898. // a 32-bit int where non-0 means true.
  3899. if (explicitLayout != glslang::ElpNone)
  3900. spvType = builder.makeUintType(32);
  3901. else
  3902. spvType = builder.makeBoolType(false);
  3903. break;
  3904. case glslang::EbtInt:
  3905. spvType = builder.makeIntType(32);
  3906. break;
  3907. case glslang::EbtUint:
  3908. spvType = builder.makeUintType(32);
  3909. break;
  3910. case glslang::EbtFloat:
  3911. spvType = builder.makeFloatType(32);
  3912. break;
  3913. case glslang::EbtDouble:
  3914. spvType = builder.makeFloatType(64);
  3915. break;
  3916. case glslang::EbtFloat16:
  3917. spvType = builder.makeFloatType(16);
  3918. break;
  3919. case glslang::EbtInt8:
  3920. spvType = builder.makeIntType(8);
  3921. break;
  3922. case glslang::EbtUint8:
  3923. spvType = builder.makeUintType(8);
  3924. break;
  3925. case glslang::EbtInt16:
  3926. spvType = builder.makeIntType(16);
  3927. break;
  3928. case glslang::EbtUint16:
  3929. spvType = builder.makeUintType(16);
  3930. break;
  3931. case glslang::EbtInt64:
  3932. spvType = builder.makeIntType(64);
  3933. break;
  3934. case glslang::EbtUint64:
  3935. spvType = builder.makeUintType(64);
  3936. break;
  3937. case glslang::EbtAtomicUint:
  3938. builder.addCapability(spv::CapabilityAtomicStorage);
  3939. spvType = builder.makeUintType(32);
  3940. break;
  3941. case glslang::EbtAccStruct:
  3942. switch (glslangIntermediate->getStage()) {
  3943. case EShLangRayGen:
  3944. case EShLangIntersect:
  3945. case EShLangAnyHit:
  3946. case EShLangClosestHit:
  3947. case EShLangMiss:
  3948. case EShLangCallable:
  3949. // these all should have the RayTracingNV/KHR capability already
  3950. break;
  3951. default:
  3952. {
  3953. auto& extensions = glslangIntermediate->getRequestedExtensions();
  3954. if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
  3955. builder.addExtension(spv::E_SPV_KHR_ray_query);
  3956. builder.addCapability(spv::CapabilityRayQueryKHR);
  3957. }
  3958. }
  3959. break;
  3960. }
  3961. spvType = builder.makeAccelerationStructureType();
  3962. break;
  3963. case glslang::EbtRayQuery:
  3964. {
  3965. auto& extensions = glslangIntermediate->getRequestedExtensions();
  3966. if (extensions.find("GL_EXT_ray_query") != extensions.end()) {
  3967. builder.addExtension(spv::E_SPV_KHR_ray_query);
  3968. builder.addCapability(spv::CapabilityRayQueryKHR);
  3969. }
  3970. spvType = builder.makeRayQueryType();
  3971. }
  3972. break;
  3973. case glslang::EbtReference:
  3974. {
  3975. // Make the forward pointer, then recurse to convert the structure type, then
  3976. // patch up the forward pointer with a real pointer type.
  3977. if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
  3978. spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
  3979. forwardPointers[type.getReferentType()] = forwardId;
  3980. }
  3981. spvType = forwardPointers[type.getReferentType()];
  3982. if (!forwardReferenceOnly) {
  3983. spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
  3984. builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
  3985. forwardPointers[type.getReferentType()],
  3986. referentType);
  3987. }
  3988. }
  3989. break;
  3990. case glslang::EbtSampler:
  3991. {
  3992. const glslang::TSampler& sampler = type.getSampler();
  3993. if (sampler.isPureSampler()) {
  3994. spvType = builder.makeSamplerType();
  3995. } else {
  3996. // an image is present, make its type
  3997. spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler),
  3998. sampler.isShadow(), sampler.isArrayed(), sampler.isMultiSample(),
  3999. sampler.isImageClass() ? 2 : 1, TranslateImageFormat(type));
  4000. if (sampler.isCombined() &&
  4001. (!sampler.isBuffer() || glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_6)) {
  4002. // Already has both image and sampler, make the combined type. Only combine sampler to
  4003. // buffer if before SPIR-V 1.6.
  4004. spvType = builder.makeSampledImageType(spvType);
  4005. }
  4006. }
  4007. }
  4008. break;
  4009. case glslang::EbtStruct:
  4010. case glslang::EbtBlock:
  4011. {
  4012. // If we've seen this struct type, return it
  4013. const glslang::TTypeList* glslangMembers = type.getStruct();
  4014. // Try to share structs for different layouts, but not yet for other
  4015. // kinds of qualification (primarily not yet including interpolant qualification).
  4016. if (! HasNonLayoutQualifiers(type, qualifier))
  4017. spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
  4018. if (spvType != spv::NoResult)
  4019. break;
  4020. // else, we haven't seen it...
  4021. if (type.getBasicType() == glslang::EbtBlock)
  4022. memberRemapper[glslangTypeToIdMap[glslangMembers]].resize(glslangMembers->size());
  4023. spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
  4024. }
  4025. break;
  4026. case glslang::EbtString:
  4027. // no type used for OpString
  4028. return 0;
  4029. case glslang::EbtHitObjectNV: {
  4030. builder.addExtension(spv::E_SPV_NV_shader_invocation_reorder);
  4031. builder.addCapability(spv::CapabilityShaderInvocationReorderNV);
  4032. spvType = builder.makeHitObjectNVType();
  4033. }
  4034. break;
  4035. case glslang::EbtSpirvType: {
  4036. // GL_EXT_spirv_intrinsics
  4037. const auto& spirvType = type.getSpirvType();
  4038. const auto& spirvInst = spirvType.spirvInst;
  4039. std::vector<spv::IdImmediate> operands;
  4040. for (const auto& typeParam : spirvType.typeParams) {
  4041. if (typeParam.constant != nullptr) {
  4042. // Constant expression
  4043. if (typeParam.constant->isLiteral()) {
  4044. if (typeParam.constant->getBasicType() == glslang::EbtFloat) {
  4045. float floatValue = static_cast<float>(typeParam.constant->getConstArray()[0].getDConst());
  4046. unsigned literal;
  4047. static_assert(sizeof(literal) == sizeof(floatValue), "sizeof(unsigned) != sizeof(float)");
  4048. memcpy(&literal, &floatValue, sizeof(literal));
  4049. operands.push_back({false, literal});
  4050. } else if (typeParam.constant->getBasicType() == glslang::EbtInt) {
  4051. unsigned literal = typeParam.constant->getConstArray()[0].getIConst();
  4052. operands.push_back({false, literal});
  4053. } else if (typeParam.constant->getBasicType() == glslang::EbtUint) {
  4054. unsigned literal = typeParam.constant->getConstArray()[0].getUConst();
  4055. operands.push_back({false, literal});
  4056. } else if (typeParam.constant->getBasicType() == glslang::EbtBool) {
  4057. unsigned literal = typeParam.constant->getConstArray()[0].getBConst();
  4058. operands.push_back({false, literal});
  4059. } else if (typeParam.constant->getBasicType() == glslang::EbtString) {
  4060. auto str = typeParam.constant->getConstArray()[0].getSConst()->c_str();
  4061. unsigned literal = 0;
  4062. char* literalPtr = reinterpret_cast<char*>(&literal);
  4063. unsigned charCount = 0;
  4064. char ch = 0;
  4065. do {
  4066. ch = *(str++);
  4067. *(literalPtr++) = ch;
  4068. ++charCount;
  4069. if (charCount == 4) {
  4070. operands.push_back({false, literal});
  4071. literalPtr = reinterpret_cast<char*>(&literal);
  4072. charCount = 0;
  4073. }
  4074. } while (ch != 0);
  4075. // Partial literal is padded with 0
  4076. if (charCount > 0) {
  4077. for (; charCount < 4; ++charCount)
  4078. *(literalPtr++) = 0;
  4079. operands.push_back({false, literal});
  4080. }
  4081. } else
  4082. assert(0); // Unexpected type
  4083. } else
  4084. operands.push_back({true, createSpvConstant(*typeParam.constant)});
  4085. } else {
  4086. // Type specifier
  4087. assert(typeParam.type != nullptr);
  4088. operands.push_back({true, convertGlslangToSpvType(*typeParam.type)});
  4089. }
  4090. }
  4091. assert(spirvInst.set == ""); // Currently, couldn't be extended instructions.
  4092. spvType = builder.makeGenericType(static_cast<spv::Op>(spirvInst.id), operands);
  4093. break;
  4094. }
  4095. default:
  4096. assert(0);
  4097. break;
  4098. }
  4099. if (type.isMatrix())
  4100. spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
  4101. else {
  4102. // If this variable has a vector element count greater than 1, create a SPIR-V vector
  4103. if (type.getVectorSize() > 1)
  4104. spvType = builder.makeVectorType(spvType, type.getVectorSize());
  4105. }
  4106. if (type.isCoopMatNV()) {
  4107. builder.addCapability(spv::CapabilityCooperativeMatrixNV);
  4108. builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
  4109. if (type.getBasicType() == glslang::EbtFloat16)
  4110. builder.addCapability(spv::CapabilityFloat16);
  4111. if (type.getBasicType() == glslang::EbtUint8 ||
  4112. type.getBasicType() == glslang::EbtInt8) {
  4113. builder.addCapability(spv::CapabilityInt8);
  4114. }
  4115. spv::Id scope = makeArraySizeId(*type.getTypeParameters()->arraySizes, 1);
  4116. spv::Id rows = makeArraySizeId(*type.getTypeParameters()->arraySizes, 2);
  4117. spv::Id cols = makeArraySizeId(*type.getTypeParameters()->arraySizes, 3);
  4118. spvType = builder.makeCooperativeMatrixTypeNV(spvType, scope, rows, cols);
  4119. }
  4120. if (type.isCoopMatKHR()) {
  4121. builder.addCapability(spv::CapabilityCooperativeMatrixKHR);
  4122. builder.addExtension(spv::E_SPV_KHR_cooperative_matrix);
  4123. if (type.getBasicType() == glslang::EbtFloat16)
  4124. builder.addCapability(spv::CapabilityFloat16);
  4125. if (type.getBasicType() == glslang::EbtUint8 || type.getBasicType() == glslang::EbtInt8) {
  4126. builder.addCapability(spv::CapabilityInt8);
  4127. }
  4128. spv::Id scope = makeArraySizeId(*type.getTypeParameters()->arraySizes, 0);
  4129. spv::Id rows = makeArraySizeId(*type.getTypeParameters()->arraySizes, 1);
  4130. spv::Id cols = makeArraySizeId(*type.getTypeParameters()->arraySizes, 2);
  4131. spv::Id use = builder.makeUintConstant(type.getCoopMatKHRuse());
  4132. spvType = builder.makeCooperativeMatrixTypeKHR(spvType, scope, rows, cols, use);
  4133. }
  4134. if (type.isArray()) {
  4135. int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
  4136. // Do all but the outer dimension
  4137. if (type.getArraySizes()->getNumDims() > 1) {
  4138. // We need to decorate array strides for types needing explicit layout, except blocks.
  4139. if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
  4140. // Use a dummy glslang type for querying internal strides of
  4141. // arrays of arrays, but using just a one-dimensional array.
  4142. glslang::TType simpleArrayType(type, 0); // deference type of the array
  4143. while (simpleArrayType.getArraySizes()->getNumDims() > 1)
  4144. simpleArrayType.getArraySizes()->dereference();
  4145. // Will compute the higher-order strides here, rather than making a whole
  4146. // pile of types and doing repetitive recursion on their contents.
  4147. stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
  4148. }
  4149. // make the arrays
  4150. for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
  4151. spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
  4152. if (stride > 0)
  4153. builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
  4154. stride *= type.getArraySizes()->getDimSize(dim);
  4155. }
  4156. } else {
  4157. // single-dimensional array, and don't yet have stride
  4158. // We need to decorate array strides for types needing explicit layout, except blocks.
  4159. if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
  4160. stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
  4161. }
  4162. // Do the outer dimension, which might not be known for a runtime-sized array.
  4163. // (Unsized arrays that survive through linking will be runtime-sized arrays)
  4164. if (type.isSizedArray())
  4165. spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
  4166. else {
  4167. if (!lastBufferBlockMember) {
  4168. builder.addIncorporatedExtension("SPV_EXT_descriptor_indexing", spv::Spv_1_5);
  4169. builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
  4170. }
  4171. spvType = builder.makeRuntimeArray(spvType);
  4172. }
  4173. if (stride > 0)
  4174. builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
  4175. }
  4176. return spvType;
  4177. }
  4178. // TODO: this functionality should exist at a higher level, in creating the AST
  4179. //
  4180. // Identify interface members that don't have their required extension turned on.
  4181. //
  4182. bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
  4183. {
  4184. auto& extensions = glslangIntermediate->getRequestedExtensions();
  4185. if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
  4186. extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
  4187. return true;
  4188. if (member.getFieldName() == "gl_SecondaryPositionNV" &&
  4189. extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
  4190. return true;
  4191. if (glslangIntermediate->getStage() == EShLangMesh) {
  4192. if (member.getFieldName() == "gl_PrimitiveShadingRateEXT" &&
  4193. extensions.find("GL_EXT_fragment_shading_rate") == extensions.end())
  4194. return true;
  4195. }
  4196. if (glslangIntermediate->getStage() != EShLangMesh) {
  4197. if (member.getFieldName() == "gl_ViewportMask" &&
  4198. extensions.find("GL_NV_viewport_array2") == extensions.end())
  4199. return true;
  4200. if (member.getFieldName() == "gl_PositionPerViewNV" &&
  4201. extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
  4202. return true;
  4203. if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
  4204. extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
  4205. return true;
  4206. }
  4207. return false;
  4208. };
  4209. // Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
  4210. // explicitLayout can be kept the same throughout the hierarchical recursive walk.
  4211. // Mutually recursive with convertGlslangToSpvType().
  4212. spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
  4213. const glslang::TTypeList* glslangMembers,
  4214. glslang::TLayoutPacking explicitLayout,
  4215. const glslang::TQualifier& qualifier)
  4216. {
  4217. // Create a vector of struct types for SPIR-V to consume
  4218. std::vector<spv::Id> spvMembers;
  4219. int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0,
  4220. // except sometimes for blocks
  4221. std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
  4222. for (int i = 0; i < (int)glslangMembers->size(); i++) {
  4223. auto& glslangMember = (*glslangMembers)[i];
  4224. if (glslangMember.type->hiddenMember()) {
  4225. ++memberDelta;
  4226. if (type.getBasicType() == glslang::EbtBlock)
  4227. memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
  4228. } else {
  4229. if (type.getBasicType() == glslang::EbtBlock) {
  4230. if (filterMember(*glslangMember.type)) {
  4231. memberDelta++;
  4232. memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = -1;
  4233. continue;
  4234. }
  4235. memberRemapper[glslangTypeToIdMap[glslangMembers]][i] = i - memberDelta;
  4236. }
  4237. // modify just this child's view of the qualifier
  4238. glslang::TQualifier memberQualifier = glslangMember.type->getQualifier();
  4239. InheritQualifiers(memberQualifier, qualifier);
  4240. // manually inherit location
  4241. if (! memberQualifier.hasLocation() && qualifier.hasLocation())
  4242. memberQualifier.layoutLocation = qualifier.layoutLocation;
  4243. // recurse
  4244. bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
  4245. i == (int)glslangMembers->size() - 1;
  4246. // Make forward pointers for any pointer members.
  4247. if (glslangMember.type->isReference() &&
  4248. forwardPointers.find(glslangMember.type->getReferentType()) == forwardPointers.end()) {
  4249. deferredForwardPointers.push_back(std::make_pair(glslangMember.type, memberQualifier));
  4250. }
  4251. // Create the member type.
  4252. auto const spvMember = convertGlslangToSpvType(*glslangMember.type, explicitLayout, memberQualifier, lastBufferBlockMember,
  4253. glslangMember.type->isReference());
  4254. spvMembers.push_back(spvMember);
  4255. // Update the builder with the type's location so that we can create debug types for the structure members.
  4256. // There doesn't exist a "clean" entry point for this information to be passed along to the builder so, for now,
  4257. // it is stored in the builder and consumed during the construction of composite debug types.
  4258. // TODO: This probably warrants further investigation. This approach was decided to be the least ugly of the
  4259. // quick and dirty approaches that were tried.
  4260. // Advantages of this approach:
  4261. // + Relatively clean. No direct calls into debug type system.
  4262. // + Handles nested recursive structures.
  4263. // Disadvantages of this approach:
  4264. // + Not as clean as desired. Traverser queries/sets persistent state. This is fragile.
  4265. // + Table lookup during creation of composite debug types. This really shouldn't be necessary.
  4266. if(options.emitNonSemanticShaderDebugInfo) {
  4267. builder.debugTypeLocs[spvMember].name = glslangMember.type->getFieldName().c_str();
  4268. builder.debugTypeLocs[spvMember].line = glslangMember.loc.line;
  4269. builder.debugTypeLocs[spvMember].column = glslangMember.loc.column;
  4270. }
  4271. }
  4272. }
  4273. // Make the SPIR-V type
  4274. spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str(), false);
  4275. if (! HasNonLayoutQualifiers(type, qualifier))
  4276. structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
  4277. // Decorate it
  4278. decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType, spvMembers);
  4279. for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
  4280. auto it = deferredForwardPointers[i];
  4281. convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
  4282. }
  4283. return spvType;
  4284. }
  4285. void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
  4286. const glslang::TTypeList* glslangMembers,
  4287. glslang::TLayoutPacking explicitLayout,
  4288. const glslang::TQualifier& qualifier,
  4289. spv::Id spvType,
  4290. const std::vector<spv::Id>& spvMembers)
  4291. {
  4292. // Name and decorate the non-hidden members
  4293. int offset = -1;
  4294. bool memberLocationInvalid = type.isArrayOfArrays() ||
  4295. (type.isArray() && (type.getQualifier().isArrayedIo(glslangIntermediate->getStage()) == false));
  4296. for (int i = 0; i < (int)glslangMembers->size(); i++) {
  4297. glslang::TType& glslangMember = *(*glslangMembers)[i].type;
  4298. int member = i;
  4299. if (type.getBasicType() == glslang::EbtBlock) {
  4300. member = memberRemapper[glslangTypeToIdMap[glslangMembers]][i];
  4301. if (filterMember(glslangMember))
  4302. continue;
  4303. }
  4304. // modify just this child's view of the qualifier
  4305. glslang::TQualifier memberQualifier = glslangMember.getQualifier();
  4306. InheritQualifiers(memberQualifier, qualifier);
  4307. // using -1 above to indicate a hidden member
  4308. if (member < 0)
  4309. continue;
  4310. builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
  4311. builder.addMemberDecoration(spvType, member,
  4312. TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
  4313. builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
  4314. // Add interpolation and auxiliary storage decorations only to
  4315. // top-level members of Input and Output storage classes
  4316. if (type.getQualifier().storage == glslang::EvqVaryingIn ||
  4317. type.getQualifier().storage == glslang::EvqVaryingOut) {
  4318. if (type.getBasicType() == glslang::EbtBlock ||
  4319. glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
  4320. builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
  4321. builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
  4322. addMeshNVDecoration(spvType, member, memberQualifier);
  4323. }
  4324. }
  4325. builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
  4326. if (type.getBasicType() == glslang::EbtBlock &&
  4327. qualifier.storage == glslang::EvqBuffer) {
  4328. // Add memory decorations only to top-level members of shader storage block
  4329. std::vector<spv::Decoration> memory;
  4330. TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
  4331. for (unsigned int i = 0; i < memory.size(); ++i)
  4332. builder.addMemberDecoration(spvType, member, memory[i]);
  4333. }
  4334. // Location assignment was already completed correctly by the front end,
  4335. // just track whether a member needs to be decorated.
  4336. // Ignore member locations if the container is an array, as that's
  4337. // ill-specified and decisions have been made to not allow this.
  4338. if (!memberLocationInvalid && memberQualifier.hasLocation())
  4339. builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
  4340. // component, XFB, others
  4341. if (glslangMember.getQualifier().hasComponent())
  4342. builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
  4343. glslangMember.getQualifier().layoutComponent);
  4344. if (glslangMember.getQualifier().hasXfbOffset())
  4345. builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
  4346. glslangMember.getQualifier().layoutXfbOffset);
  4347. else if (explicitLayout != glslang::ElpNone) {
  4348. // figure out what to do with offset, which is accumulating
  4349. int nextOffset;
  4350. updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
  4351. if (offset >= 0)
  4352. builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
  4353. offset = nextOffset;
  4354. }
  4355. if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
  4356. builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
  4357. getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
  4358. // built-in variable decorations
  4359. spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
  4360. if (builtIn != spv::BuiltInMax)
  4361. builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
  4362. // nonuniform
  4363. builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
  4364. if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
  4365. builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
  4366. builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
  4367. memberQualifier.semanticName);
  4368. }
  4369. if (builtIn == spv::BuiltInLayer) {
  4370. // SPV_NV_viewport_array2 extension
  4371. if (glslangMember.getQualifier().layoutViewportRelative){
  4372. builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
  4373. builder.addCapability(spv::CapabilityShaderViewportMaskNV);
  4374. builder.addExtension(spv::E_SPV_NV_viewport_array2);
  4375. }
  4376. if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
  4377. builder.addMemberDecoration(spvType, member,
  4378. (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
  4379. glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
  4380. builder.addCapability(spv::CapabilityShaderStereoViewNV);
  4381. builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
  4382. }
  4383. }
  4384. if (glslangMember.getQualifier().layoutPassthrough) {
  4385. builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
  4386. builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
  4387. builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
  4388. }
  4389. //
  4390. // Add SPIR-V decorations for members (GL_EXT_spirv_intrinsics)
  4391. //
  4392. if (glslangMember.getQualifier().hasSprivDecorate()) {
  4393. const glslang::TSpirvDecorate& spirvDecorate = glslangMember.getQualifier().getSpirvDecorate();
  4394. // Add spirv_decorate
  4395. for (auto& decorate : spirvDecorate.decorates) {
  4396. if (!decorate.second.empty()) {
  4397. std::vector<unsigned> literals;
  4398. TranslateLiterals(decorate.second, literals);
  4399. builder.addMemberDecoration(spvType, member, static_cast<spv::Decoration>(decorate.first), literals);
  4400. }
  4401. else
  4402. builder.addMemberDecoration(spvType, member, static_cast<spv::Decoration>(decorate.first));
  4403. }
  4404. // spirv_decorate_id not applied to members
  4405. assert(spirvDecorate.decorateIds.empty());
  4406. // Add spirv_decorate_string
  4407. for (auto& decorateString : spirvDecorate.decorateStrings) {
  4408. std::vector<const char*> strings;
  4409. assert(!decorateString.second.empty());
  4410. for (auto extraOperand : decorateString.second) {
  4411. const char* string = extraOperand->getConstArray()[0].getSConst()->c_str();
  4412. strings.push_back(string);
  4413. }
  4414. builder.addDecoration(spvType, static_cast<spv::Decoration>(decorateString.first), strings);
  4415. }
  4416. }
  4417. }
  4418. // Decorate the structure
  4419. builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
  4420. const auto basicType = type.getBasicType();
  4421. const auto typeStorageQualifier = type.getQualifier().storage;
  4422. if (basicType == glslang::EbtBlock) {
  4423. builder.addDecoration(spvType, TranslateBlockDecoration(typeStorageQualifier, glslangIntermediate->usingStorageBuffer()));
  4424. } else if (basicType == glslang::EbtStruct && glslangIntermediate->getSpv().vulkan > 0) {
  4425. const auto hasRuntimeArray = !spvMembers.empty() && builder.getOpCode(spvMembers.back()) == spv::OpTypeRuntimeArray;
  4426. if (hasRuntimeArray) {
  4427. builder.addDecoration(spvType, TranslateBlockDecoration(typeStorageQualifier, glslangIntermediate->usingStorageBuffer()));
  4428. }
  4429. }
  4430. if (qualifier.hasHitObjectShaderRecordNV())
  4431. builder.addDecoration(spvType, spv::DecorationHitObjectShaderRecordBufferNV);
  4432. }
  4433. // Turn the expression forming the array size into an id.
  4434. // This is not quite trivial, because of specialization constants.
  4435. // Sometimes, a raw constant is turned into an Id, and sometimes
  4436. // a specialization constant expression is.
  4437. spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim, bool allowZero)
  4438. {
  4439. // First, see if this is sized with a node, meaning a specialization constant:
  4440. glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
  4441. if (specNode != nullptr) {
  4442. builder.clearAccessChain();
  4443. SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
  4444. spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
  4445. specNode->traverse(this);
  4446. return accessChainLoad(specNode->getAsTyped()->getType());
  4447. }
  4448. // Otherwise, need a compile-time (front end) size, get it:
  4449. int size = arraySizes.getDimSize(dim);
  4450. if (!allowZero)
  4451. assert(size > 0);
  4452. return builder.makeUintConstant(size);
  4453. }
  4454. // Wrap the builder's accessChainLoad to:
  4455. // - localize handling of RelaxedPrecision
  4456. // - use the SPIR-V inferred type instead of another conversion of the glslang type
  4457. // (avoids unnecessary work and possible type punning for structures)
  4458. // - do conversion of concrete to abstract type
  4459. spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
  4460. {
  4461. spv::Id nominalTypeId = builder.accessChainGetInferredType();
  4462. spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
  4463. coherentFlags |= TranslateCoherent(type);
  4464. spv::MemoryAccessMask accessMask = spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask);
  4465. // If the value being loaded is HelperInvocation, SPIR-V 1.6 is being generated (so that
  4466. // SPV_EXT_demote_to_helper_invocation is in core) and the memory model is in use, add
  4467. // the Volatile MemoryAccess semantic.
  4468. if (type.getQualifier().builtIn == glslang::EbvHelperInvocation &&
  4469. glslangIntermediate->usingVulkanMemoryModel() &&
  4470. glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_6) {
  4471. accessMask = spv::MemoryAccessMask(accessMask | spv::MemoryAccessVolatileMask);
  4472. }
  4473. unsigned int alignment = builder.getAccessChain().alignment;
  4474. alignment |= type.getBufferReferenceAlignment();
  4475. spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
  4476. TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
  4477. TranslateNonUniformDecoration(type.getQualifier()),
  4478. nominalTypeId,
  4479. accessMask,
  4480. TranslateMemoryScope(coherentFlags),
  4481. alignment);
  4482. // Need to convert to abstract types when necessary
  4483. if (type.getBasicType() == glslang::EbtBool) {
  4484. loadedId = convertLoadedBoolInUniformToUint(type, nominalTypeId, loadedId);
  4485. }
  4486. return loadedId;
  4487. }
  4488. // Wrap the builder's accessChainStore to:
  4489. // - do conversion of concrete to abstract type
  4490. //
  4491. // Implicitly uses the existing builder.accessChain as the storage target.
  4492. void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
  4493. {
  4494. // Need to convert to abstract types when necessary
  4495. if (type.getBasicType() == glslang::EbtBool) {
  4496. spv::Id nominalTypeId = builder.accessChainGetInferredType();
  4497. if (builder.isScalarType(nominalTypeId)) {
  4498. // Conversion for bool
  4499. spv::Id boolType = builder.makeBoolType();
  4500. if (nominalTypeId != boolType) {
  4501. // keep these outside arguments, for determinant order-of-evaluation
  4502. spv::Id one = builder.makeUintConstant(1);
  4503. spv::Id zero = builder.makeUintConstant(0);
  4504. rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
  4505. } else if (builder.getTypeId(rvalue) != boolType)
  4506. rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
  4507. } else if (builder.isVectorType(nominalTypeId)) {
  4508. // Conversion for bvec
  4509. int vecSize = builder.getNumTypeComponents(nominalTypeId);
  4510. spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
  4511. if (nominalTypeId != bvecType) {
  4512. // keep these outside arguments, for determinant order-of-evaluation
  4513. spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
  4514. spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
  4515. rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
  4516. } else if (builder.getTypeId(rvalue) != bvecType)
  4517. rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
  4518. makeSmearedConstant(builder.makeUintConstant(0), vecSize));
  4519. }
  4520. }
  4521. spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
  4522. coherentFlags |= TranslateCoherent(type);
  4523. unsigned int alignment = builder.getAccessChain().alignment;
  4524. alignment |= type.getBufferReferenceAlignment();
  4525. builder.accessChainStore(rvalue, TranslateNonUniformDecoration(builder.getAccessChain().coherentFlags),
  4526. spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) &
  4527. ~spv::MemoryAccessMakePointerVisibleKHRMask),
  4528. TranslateMemoryScope(coherentFlags), alignment);
  4529. }
  4530. // For storing when types match at the glslang level, but not might match at the
  4531. // SPIR-V level.
  4532. //
  4533. // This especially happens when a single glslang type expands to multiple
  4534. // SPIR-V types, like a struct that is used in a member-undecorated way as well
  4535. // as in a member-decorated way.
  4536. //
  4537. // NOTE: This function can handle any store request; if it's not special it
  4538. // simplifies to a simple OpStore.
  4539. //
  4540. // Implicitly uses the existing builder.accessChain as the storage target.
  4541. void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
  4542. {
  4543. // we only do the complex path here if it's an aggregate
  4544. if (! type.isStruct() && ! type.isArray()) {
  4545. accessChainStore(type, rValue);
  4546. return;
  4547. }
  4548. // and, it has to be a case of type aliasing
  4549. spv::Id rType = builder.getTypeId(rValue);
  4550. spv::Id lValue = builder.accessChainGetLValue();
  4551. spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
  4552. if (lType == rType) {
  4553. accessChainStore(type, rValue);
  4554. return;
  4555. }
  4556. // Recursively (as needed) copy an aggregate type to a different aggregate type,
  4557. // where the two types were the same type in GLSL. This requires member
  4558. // by member copy, recursively.
  4559. // SPIR-V 1.4 added an instruction to do help do this.
  4560. if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
  4561. // However, bool in uniform space is changed to int, so
  4562. // OpCopyLogical does not work for that.
  4563. // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
  4564. bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
  4565. bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
  4566. if (lBool == rBool) {
  4567. spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
  4568. accessChainStore(type, logicalCopy);
  4569. return;
  4570. }
  4571. }
  4572. // If an array, copy element by element.
  4573. if (type.isArray()) {
  4574. glslang::TType glslangElementType(type, 0);
  4575. spv::Id elementRType = builder.getContainedTypeId(rType);
  4576. for (int index = 0; index < type.getOuterArraySize(); ++index) {
  4577. // get the source member
  4578. spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
  4579. // set up the target storage
  4580. builder.clearAccessChain();
  4581. builder.setAccessChainLValue(lValue);
  4582. builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type),
  4583. type.getBufferReferenceAlignment());
  4584. // store the member
  4585. multiTypeStore(glslangElementType, elementRValue);
  4586. }
  4587. } else {
  4588. assert(type.isStruct());
  4589. // loop over structure members
  4590. const glslang::TTypeList& members = *type.getStruct();
  4591. for (int m = 0; m < (int)members.size(); ++m) {
  4592. const glslang::TType& glslangMemberType = *members[m].type;
  4593. // get the source member
  4594. spv::Id memberRType = builder.getContainedTypeId(rType, m);
  4595. spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
  4596. // set up the target storage
  4597. builder.clearAccessChain();
  4598. builder.setAccessChainLValue(lValue);
  4599. builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type),
  4600. type.getBufferReferenceAlignment());
  4601. // store the member
  4602. multiTypeStore(glslangMemberType, memberRValue);
  4603. }
  4604. }
  4605. }
  4606. // Decide whether or not this type should be
  4607. // decorated with offsets and strides, and if so
  4608. // whether std140 or std430 rules should be applied.
  4609. glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
  4610. {
  4611. // has to be a block
  4612. if (type.getBasicType() != glslang::EbtBlock)
  4613. return glslang::ElpNone;
  4614. // has to be a uniform or buffer block or task in/out blocks
  4615. if (type.getQualifier().storage != glslang::EvqUniform &&
  4616. type.getQualifier().storage != glslang::EvqBuffer &&
  4617. type.getQualifier().storage != glslang::EvqShared &&
  4618. !type.getQualifier().isTaskMemory())
  4619. return glslang::ElpNone;
  4620. // return the layout to use
  4621. switch (type.getQualifier().layoutPacking) {
  4622. case glslang::ElpStd140:
  4623. case glslang::ElpStd430:
  4624. case glslang::ElpScalar:
  4625. return type.getQualifier().layoutPacking;
  4626. default:
  4627. return glslang::ElpNone;
  4628. }
  4629. }
  4630. // Given an array type, returns the integer stride required for that array
  4631. int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout,
  4632. glslang::TLayoutMatrix matrixLayout)
  4633. {
  4634. int size;
  4635. int stride;
  4636. glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout,
  4637. matrixLayout == glslang::ElmRowMajor);
  4638. return stride;
  4639. }
  4640. // Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
  4641. // when used as a member of an interface block
  4642. int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout,
  4643. glslang::TLayoutMatrix matrixLayout)
  4644. {
  4645. glslang::TType elementType;
  4646. elementType.shallowCopy(matrixType);
  4647. elementType.clearArraySizes();
  4648. int size;
  4649. int stride;
  4650. glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout,
  4651. matrixLayout == glslang::ElmRowMajor);
  4652. return stride;
  4653. }
  4654. // Given a member type of a struct, realign the current offset for it, and compute
  4655. // the next (not yet aligned) offset for the next member, which will get aligned
  4656. // on the next call.
  4657. // 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
  4658. // the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
  4659. // -1 means a non-forced member offset (no decoration needed).
  4660. void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType,
  4661. int& currentOffset, int& nextOffset, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
  4662. {
  4663. // this will get a positive value when deemed necessary
  4664. nextOffset = -1;
  4665. // override anything in currentOffset with user-set offset
  4666. if (memberType.getQualifier().hasOffset())
  4667. currentOffset = memberType.getQualifier().layoutOffset;
  4668. // It could be that current linker usage in glslang updated all the layoutOffset,
  4669. // in which case the following code does not matter. But, that's not quite right
  4670. // once cross-compilation unit GLSL validation is done, as the original user
  4671. // settings are needed in layoutOffset, and then the following will come into play.
  4672. if (explicitLayout == glslang::ElpNone) {
  4673. if (! memberType.getQualifier().hasOffset())
  4674. currentOffset = -1;
  4675. return;
  4676. }
  4677. // Getting this far means we need explicit offsets
  4678. if (currentOffset < 0)
  4679. currentOffset = 0;
  4680. // Now, currentOffset is valid (either 0, or from a previous nextOffset),
  4681. // but possibly not yet correctly aligned.
  4682. int memberSize;
  4683. int dummyStride;
  4684. int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout,
  4685. matrixLayout == glslang::ElmRowMajor);
  4686. // Adjust alignment for HLSL rules
  4687. // TODO: make this consistent in early phases of code:
  4688. // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
  4689. // Until reflection is brought in sync with these adjustments, don't apply to $Global,
  4690. // which is the most likely to rely on reflection, and least likely to rely implicit layouts
  4691. if (glslangIntermediate->usingHlslOffsets() &&
  4692. ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
  4693. int dummySize;
  4694. int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
  4695. if (componentAlignment <= 4)
  4696. memberAlignment = componentAlignment;
  4697. }
  4698. // Bump up to member alignment
  4699. glslang::RoundToPow2(currentOffset, memberAlignment);
  4700. // Bump up to vec4 if there is a bad straddle
  4701. if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize,
  4702. currentOffset))
  4703. glslang::RoundToPow2(currentOffset, 16);
  4704. nextOffset = currentOffset + memberSize;
  4705. }
  4706. void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
  4707. {
  4708. const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
  4709. switch (glslangBuiltIn)
  4710. {
  4711. case glslang::EbvPointSize:
  4712. case glslang::EbvClipDistance:
  4713. case glslang::EbvCullDistance:
  4714. case glslang::EbvViewportMaskNV:
  4715. case glslang::EbvSecondaryPositionNV:
  4716. case glslang::EbvSecondaryViewportMaskNV:
  4717. case glslang::EbvPositionPerViewNV:
  4718. case glslang::EbvViewportMaskPerViewNV:
  4719. case glslang::EbvTaskCountNV:
  4720. case glslang::EbvPrimitiveCountNV:
  4721. case glslang::EbvPrimitiveIndicesNV:
  4722. case glslang::EbvClipDistancePerViewNV:
  4723. case glslang::EbvCullDistancePerViewNV:
  4724. case glslang::EbvLayerPerViewNV:
  4725. case glslang::EbvMeshViewCountNV:
  4726. case glslang::EbvMeshViewIndicesNV:
  4727. // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
  4728. // Alternately, we could just call this for any glslang built-in, since the
  4729. // capability already guards against duplicates.
  4730. TranslateBuiltInDecoration(glslangBuiltIn, false);
  4731. break;
  4732. default:
  4733. // Capabilities were already generated when the struct was declared.
  4734. break;
  4735. }
  4736. }
  4737. bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
  4738. {
  4739. return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
  4740. }
  4741. // Does parameter need a place to keep writes, separate from the original?
  4742. // Assumes called after originalParam(), which filters out block/buffer/opaque-based
  4743. // qualifiers such that we should have only in/out/inout/constreadonly here.
  4744. bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
  4745. {
  4746. assert(qualifier == glslang::EvqIn ||
  4747. qualifier == glslang::EvqOut ||
  4748. qualifier == glslang::EvqInOut ||
  4749. qualifier == glslang::EvqUniform ||
  4750. qualifier == glslang::EvqConstReadOnly);
  4751. return qualifier != glslang::EvqConstReadOnly &&
  4752. qualifier != glslang::EvqUniform;
  4753. }
  4754. // Is parameter pass-by-original?
  4755. bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
  4756. bool implicitThisParam)
  4757. {
  4758. if (implicitThisParam) // implicit this
  4759. return true;
  4760. if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
  4761. return paramType.getBasicType() == glslang::EbtBlock;
  4762. return (paramType.containsOpaque() && !glslangIntermediate->getBindlessMode()) || // sampler, etc.
  4763. paramType.getQualifier().isSpirvByReference() || // spirv_by_reference
  4764. (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
  4765. }
  4766. // Make all the functions, skeletally, without actually visiting their bodies.
  4767. void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
  4768. {
  4769. const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type,
  4770. bool useVulkanMemoryModel) {
  4771. spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
  4772. if (paramPrecision != spv::NoPrecision)
  4773. decorations.push_back(paramPrecision);
  4774. TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
  4775. if (type.isReference()) {
  4776. // Original and non-writable params pass the pointer directly and
  4777. // use restrict/aliased, others are stored to a pointer in Function
  4778. // memory and use RestrictPointer/AliasedPointer.
  4779. if (originalParam(type.getQualifier().storage, type, false) ||
  4780. !writableParam(type.getQualifier().storage)) {
  4781. decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrict :
  4782. spv::DecorationAliased);
  4783. } else {
  4784. decorations.push_back(type.getQualifier().isRestrict() ? spv::DecorationRestrictPointerEXT :
  4785. spv::DecorationAliasedPointerEXT);
  4786. }
  4787. }
  4788. };
  4789. for (int f = 0; f < (int)glslFunctions.size(); ++f) {
  4790. glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
  4791. if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
  4792. continue;
  4793. // We're on a user function. Set up the basic interface for the function now,
  4794. // so that it's available to call. Translating the body will happen later.
  4795. //
  4796. // Typically (except for a "const in" parameter), an address will be passed to the
  4797. // function. What it is an address of varies:
  4798. //
  4799. // - "in" parameters not marked as "const" can be written to without modifying the calling
  4800. // argument so that write needs to be to a copy, hence the address of a copy works.
  4801. //
  4802. // - "const in" parameters can just be the r-value, as no writes need occur.
  4803. //
  4804. // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
  4805. // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
  4806. std::vector<spv::Id> paramTypes;
  4807. std::vector<char const*> paramNames;
  4808. std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
  4809. glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
  4810. #ifdef ENABLE_HLSL
  4811. bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
  4812. glslangIntermediate->implicitThisName;
  4813. #else
  4814. bool implicitThis = false;
  4815. #endif
  4816. paramDecorations.resize(parameters.size());
  4817. for (int p = 0; p < (int)parameters.size(); ++p) {
  4818. const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
  4819. spv::Id typeId = convertGlslangToSpvType(paramType);
  4820. if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
  4821. typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
  4822. else if (writableParam(paramType.getQualifier().storage))
  4823. typeId = builder.makePointer(spv::StorageClassFunction, typeId);
  4824. else
  4825. rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
  4826. getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
  4827. paramTypes.push_back(typeId);
  4828. }
  4829. for (auto const parameter:parameters) {
  4830. paramNames.push_back(parameter->getAsSymbolNode()->getName().c_str());
  4831. }
  4832. spv::Block* functionBlock;
  4833. spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
  4834. convertGlslangToSpvType(glslFunction->getType()),
  4835. glslFunction->getName().c_str(), paramTypes, paramNames,
  4836. paramDecorations, &functionBlock);
  4837. if (implicitThis)
  4838. function->setImplicitThis();
  4839. // Track function to emit/call later
  4840. functionMap[glslFunction->getName().c_str()] = function;
  4841. // Set the parameter id's
  4842. for (int p = 0; p < (int)parameters.size(); ++p) {
  4843. symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
  4844. // give a name too
  4845. builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
  4846. const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
  4847. if (paramType.contains8BitInt())
  4848. builder.addCapability(spv::CapabilityInt8);
  4849. if (paramType.contains16BitInt())
  4850. builder.addCapability(spv::CapabilityInt16);
  4851. if (paramType.contains16BitFloat())
  4852. builder.addCapability(spv::CapabilityFloat16);
  4853. }
  4854. }
  4855. }
  4856. // Process all the initializers, while skipping the functions and link objects
  4857. void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
  4858. {
  4859. builder.setBuildPoint(shaderEntry->getLastBlock());
  4860. for (int i = 0; i < (int)initializers.size(); ++i) {
  4861. glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
  4862. if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() !=
  4863. glslang::EOpLinkerObjects) {
  4864. // We're on a top-level node that's not a function. Treat as an initializer, whose
  4865. // code goes into the beginning of the entry point.
  4866. initializer->traverse(this);
  4867. }
  4868. }
  4869. }
  4870. // Walk over all linker objects to create a map for payload and callable data linker objects
  4871. // and their location to be used during codegen for OpTraceKHR and OpExecuteCallableKHR
  4872. // This is done here since it is possible that these linker objects are not be referenced in the AST
  4873. void TGlslangToSpvTraverser::collectRayTracingLinkerObjects()
  4874. {
  4875. glslang::TIntermAggregate* linkerObjects = glslangIntermediate->findLinkerObjects();
  4876. for (auto& objSeq : linkerObjects->getSequence()) {
  4877. auto objNode = objSeq->getAsSymbolNode();
  4878. if (objNode != nullptr) {
  4879. if (objNode->getQualifier().hasLocation()) {
  4880. unsigned int location = objNode->getQualifier().layoutLocation;
  4881. auto st = objNode->getQualifier().storage;
  4882. int set;
  4883. switch (st)
  4884. {
  4885. case glslang::EvqPayload:
  4886. case glslang::EvqPayloadIn:
  4887. set = 0;
  4888. break;
  4889. case glslang::EvqCallableData:
  4890. case glslang::EvqCallableDataIn:
  4891. set = 1;
  4892. break;
  4893. case glslang::EvqHitObjectAttrNV:
  4894. set = 2;
  4895. break;
  4896. default:
  4897. set = -1;
  4898. }
  4899. if (set != -1)
  4900. locationToSymbol[set].insert(std::make_pair(location, objNode));
  4901. }
  4902. }
  4903. }
  4904. }
  4905. // Process all the functions, while skipping initializers.
  4906. void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
  4907. {
  4908. for (int f = 0; f < (int)glslFunctions.size(); ++f) {
  4909. glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
  4910. if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
  4911. node->traverse(this);
  4912. }
  4913. }
  4914. void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
  4915. {
  4916. // SPIR-V functions should already be in the functionMap from the prepass
  4917. // that called makeFunctions().
  4918. currentFunction = functionMap[node->getName().c_str()];
  4919. spv::Block* functionBlock = currentFunction->getEntryBlock();
  4920. builder.setBuildPoint(functionBlock);
  4921. builder.enterFunction(currentFunction);
  4922. }
  4923. void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments,
  4924. spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
  4925. {
  4926. const glslang::TIntermSequence& glslangArguments = node.getSequence();
  4927. glslang::TSampler sampler = {};
  4928. bool cubeCompare = false;
  4929. bool f16ShadowCompare = false;
  4930. if (node.isTexture() || node.isImage()) {
  4931. sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
  4932. cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
  4933. f16ShadowCompare = sampler.shadow &&
  4934. glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
  4935. }
  4936. for (int i = 0; i < (int)glslangArguments.size(); ++i) {
  4937. builder.clearAccessChain();
  4938. glslangArguments[i]->traverse(this);
  4939. // Special case l-value operands
  4940. bool lvalue = false;
  4941. switch (node.getOp()) {
  4942. case glslang::EOpImageAtomicAdd:
  4943. case glslang::EOpImageAtomicMin:
  4944. case glslang::EOpImageAtomicMax:
  4945. case glslang::EOpImageAtomicAnd:
  4946. case glslang::EOpImageAtomicOr:
  4947. case glslang::EOpImageAtomicXor:
  4948. case glslang::EOpImageAtomicExchange:
  4949. case glslang::EOpImageAtomicCompSwap:
  4950. case glslang::EOpImageAtomicLoad:
  4951. case glslang::EOpImageAtomicStore:
  4952. if (i == 0)
  4953. lvalue = true;
  4954. break;
  4955. case glslang::EOpSparseImageLoad:
  4956. if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
  4957. lvalue = true;
  4958. break;
  4959. case glslang::EOpSparseTexture:
  4960. if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
  4961. lvalue = true;
  4962. break;
  4963. case glslang::EOpSparseTextureClamp:
  4964. if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
  4965. lvalue = true;
  4966. break;
  4967. case glslang::EOpSparseTextureLod:
  4968. case glslang::EOpSparseTextureOffset:
  4969. if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
  4970. lvalue = true;
  4971. break;
  4972. case glslang::EOpSparseTextureFetch:
  4973. if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
  4974. lvalue = true;
  4975. break;
  4976. case glslang::EOpSparseTextureFetchOffset:
  4977. if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
  4978. lvalue = true;
  4979. break;
  4980. case glslang::EOpSparseTextureLodOffset:
  4981. case glslang::EOpSparseTextureGrad:
  4982. case glslang::EOpSparseTextureOffsetClamp:
  4983. if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
  4984. lvalue = true;
  4985. break;
  4986. case glslang::EOpSparseTextureGradOffset:
  4987. case glslang::EOpSparseTextureGradClamp:
  4988. if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
  4989. lvalue = true;
  4990. break;
  4991. case glslang::EOpSparseTextureGradOffsetClamp:
  4992. if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
  4993. lvalue = true;
  4994. break;
  4995. case glslang::EOpSparseTextureGather:
  4996. if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
  4997. lvalue = true;
  4998. break;
  4999. case glslang::EOpSparseTextureGatherOffset:
  5000. case glslang::EOpSparseTextureGatherOffsets:
  5001. if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
  5002. lvalue = true;
  5003. break;
  5004. case glslang::EOpSparseTextureGatherLod:
  5005. if (i == 3)
  5006. lvalue = true;
  5007. break;
  5008. case glslang::EOpSparseTextureGatherLodOffset:
  5009. case glslang::EOpSparseTextureGatherLodOffsets:
  5010. if (i == 4)
  5011. lvalue = true;
  5012. break;
  5013. case glslang::EOpSparseImageLoadLod:
  5014. if (i == 3)
  5015. lvalue = true;
  5016. break;
  5017. case glslang::EOpImageSampleFootprintNV:
  5018. if (i == 4)
  5019. lvalue = true;
  5020. break;
  5021. case glslang::EOpImageSampleFootprintClampNV:
  5022. case glslang::EOpImageSampleFootprintLodNV:
  5023. if (i == 5)
  5024. lvalue = true;
  5025. break;
  5026. case glslang::EOpImageSampleFootprintGradNV:
  5027. if (i == 6)
  5028. lvalue = true;
  5029. break;
  5030. case glslang::EOpImageSampleFootprintGradClampNV:
  5031. if (i == 7)
  5032. lvalue = true;
  5033. break;
  5034. case glslang::EOpRayQueryGetIntersectionTriangleVertexPositionsEXT:
  5035. if (i == 2)
  5036. lvalue = true;
  5037. break;
  5038. default:
  5039. break;
  5040. }
  5041. if (lvalue) {
  5042. spv::Id lvalue_id = builder.accessChainGetLValue();
  5043. arguments.push_back(lvalue_id);
  5044. lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
  5045. builder.addDecoration(lvalue_id, TranslateNonUniformDecoration(lvalueCoherentFlags));
  5046. lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
  5047. } else
  5048. arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
  5049. }
  5050. }
  5051. void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
  5052. {
  5053. builder.clearAccessChain();
  5054. node.getOperand()->traverse(this);
  5055. arguments.push_back(accessChainLoad(node.getOperand()->getType()));
  5056. }
  5057. spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
  5058. {
  5059. if (! node->isImage() && ! node->isTexture())
  5060. return spv::NoResult;
  5061. builder.setLine(node->getLoc().line, node->getLoc().getFilename());
  5062. // Process a GLSL texturing op (will be SPV image)
  5063. const glslang::TType &imageType = node->getAsAggregate()
  5064. ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
  5065. : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
  5066. const glslang::TSampler sampler = imageType.getSampler();
  5067. bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
  5068. ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
  5069. : false;
  5070. const auto signExtensionMask = [&]() {
  5071. if (builder.getSpvVersion() >= spv::Spv_1_4) {
  5072. if (sampler.type == glslang::EbtUint)
  5073. return spv::ImageOperandsZeroExtendMask;
  5074. else if (sampler.type == glslang::EbtInt)
  5075. return spv::ImageOperandsSignExtendMask;
  5076. }
  5077. return spv::ImageOperandsMaskNone;
  5078. };
  5079. spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
  5080. std::vector<spv::Id> arguments;
  5081. if (node->getAsAggregate())
  5082. translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
  5083. else
  5084. translateArguments(*node->getAsUnaryNode(), arguments);
  5085. spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
  5086. spv::Builder::TextureParameters params = { };
  5087. params.sampler = arguments[0];
  5088. glslang::TCrackedTextureOp cracked;
  5089. node->crackTexture(sampler, cracked);
  5090. const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
  5091. if (builder.isSampledImage(params.sampler) &&
  5092. ((cracked.query && node->getOp() != glslang::EOpTextureQueryLod) || cracked.fragMask || cracked.fetch)) {
  5093. params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
  5094. if (imageType.getQualifier().isNonUniform()) {
  5095. builder.addDecoration(params.sampler, spv::DecorationNonUniformEXT);
  5096. }
  5097. }
  5098. // Check for queries
  5099. if (cracked.query) {
  5100. switch (node->getOp()) {
  5101. case glslang::EOpImageQuerySize:
  5102. case glslang::EOpTextureQuerySize:
  5103. if (arguments.size() > 1) {
  5104. params.lod = arguments[1];
  5105. return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
  5106. } else
  5107. return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
  5108. case glslang::EOpImageQuerySamples:
  5109. case glslang::EOpTextureQuerySamples:
  5110. return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
  5111. case glslang::EOpTextureQueryLod:
  5112. params.coords = arguments[1];
  5113. return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
  5114. case glslang::EOpTextureQueryLevels:
  5115. return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
  5116. case glslang::EOpSparseTexelsResident:
  5117. return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
  5118. default:
  5119. assert(0);
  5120. break;
  5121. }
  5122. }
  5123. int components = node->getType().getVectorSize();
  5124. if (node->getOp() == glslang::EOpImageLoad ||
  5125. node->getOp() == glslang::EOpImageLoadLod ||
  5126. node->getOp() == glslang::EOpTextureFetch ||
  5127. node->getOp() == glslang::EOpTextureFetchOffset) {
  5128. // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
  5129. // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
  5130. // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
  5131. // here around e.g. which ones return scalars or other types.
  5132. components = 4;
  5133. }
  5134. glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
  5135. auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
  5136. // Check for image functions other than queries
  5137. if (node->isImage()) {
  5138. std::vector<spv::IdImmediate> operands;
  5139. auto opIt = arguments.begin();
  5140. spv::IdImmediate image = { true, *(opIt++) };
  5141. operands.push_back(image);
  5142. // Handle subpass operations
  5143. // TODO: GLSL should change to have the "MS" only on the type rather than the
  5144. // built-in function.
  5145. if (cracked.subpass) {
  5146. // add on the (0,0) coordinate
  5147. spv::Id zero = builder.makeIntConstant(0);
  5148. std::vector<spv::Id> comps;
  5149. comps.push_back(zero);
  5150. comps.push_back(zero);
  5151. spv::IdImmediate coord = { true,
  5152. builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
  5153. operands.push_back(coord);
  5154. spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
  5155. imageOperands.word = imageOperands.word | signExtensionMask();
  5156. if (sampler.isMultiSample()) {
  5157. imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
  5158. }
  5159. if (imageOperands.word != spv::ImageOperandsMaskNone) {
  5160. operands.push_back(imageOperands);
  5161. if (sampler.isMultiSample()) {
  5162. spv::IdImmediate imageOperand = { true, *(opIt++) };
  5163. operands.push_back(imageOperand);
  5164. }
  5165. }
  5166. spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
  5167. builder.setPrecision(result, precision);
  5168. return result;
  5169. }
  5170. if (cracked.attachmentEXT) {
  5171. if (opIt != arguments.end()) {
  5172. spv::IdImmediate sample = { true, *opIt };
  5173. operands.push_back(sample);
  5174. }
  5175. spv::Id result = builder.createOp(spv::OpColorAttachmentReadEXT, resultType(), operands);
  5176. builder.addExtension(spv::E_SPV_EXT_shader_tile_image);
  5177. builder.setPrecision(result, precision);
  5178. return result;
  5179. }
  5180. spv::IdImmediate coord = { true, *(opIt++) };
  5181. operands.push_back(coord);
  5182. if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
  5183. spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
  5184. if (sampler.isMultiSample()) {
  5185. mask = mask | spv::ImageOperandsSampleMask;
  5186. }
  5187. if (cracked.lod) {
  5188. builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
  5189. builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
  5190. mask = mask | spv::ImageOperandsLodMask;
  5191. }
  5192. mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
  5193. mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
  5194. mask = mask | signExtensionMask();
  5195. if (mask != spv::ImageOperandsMaskNone) {
  5196. spv::IdImmediate imageOperands = { false, (unsigned int)mask };
  5197. operands.push_back(imageOperands);
  5198. }
  5199. if (mask & spv::ImageOperandsSampleMask) {
  5200. spv::IdImmediate imageOperand = { true, *opIt++ };
  5201. operands.push_back(imageOperand);
  5202. }
  5203. if (mask & spv::ImageOperandsLodMask) {
  5204. spv::IdImmediate imageOperand = { true, *opIt++ };
  5205. operands.push_back(imageOperand);
  5206. }
  5207. if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
  5208. spv::IdImmediate imageOperand = { true,
  5209. builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
  5210. operands.push_back(imageOperand);
  5211. }
  5212. if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
  5213. builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
  5214. std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
  5215. builder.setPrecision(result[0], precision);
  5216. // If needed, add a conversion constructor to the proper size.
  5217. if (components != node->getType().getVectorSize())
  5218. result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
  5219. return result[0];
  5220. } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
  5221. // Push the texel value before the operands
  5222. if (sampler.isMultiSample() || cracked.lod) {
  5223. spv::IdImmediate texel = { true, *(opIt + 1) };
  5224. operands.push_back(texel);
  5225. } else {
  5226. spv::IdImmediate texel = { true, *opIt };
  5227. operands.push_back(texel);
  5228. }
  5229. spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
  5230. if (sampler.isMultiSample()) {
  5231. mask = mask | spv::ImageOperandsSampleMask;
  5232. }
  5233. if (cracked.lod) {
  5234. builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
  5235. builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
  5236. mask = mask | spv::ImageOperandsLodMask;
  5237. }
  5238. mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
  5239. mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
  5240. mask = mask | signExtensionMask();
  5241. if (mask != spv::ImageOperandsMaskNone) {
  5242. spv::IdImmediate imageOperands = { false, (unsigned int)mask };
  5243. operands.push_back(imageOperands);
  5244. }
  5245. if (mask & spv::ImageOperandsSampleMask) {
  5246. spv::IdImmediate imageOperand = { true, *opIt++ };
  5247. operands.push_back(imageOperand);
  5248. }
  5249. if (mask & spv::ImageOperandsLodMask) {
  5250. spv::IdImmediate imageOperand = { true, *opIt++ };
  5251. operands.push_back(imageOperand);
  5252. }
  5253. if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
  5254. spv::IdImmediate imageOperand = { true,
  5255. builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
  5256. operands.push_back(imageOperand);
  5257. }
  5258. builder.createNoResultOp(spv::OpImageWrite, operands);
  5259. if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
  5260. builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
  5261. return spv::NoResult;
  5262. } else if (node->getOp() == glslang::EOpSparseImageLoad ||
  5263. node->getOp() == glslang::EOpSparseImageLoadLod) {
  5264. builder.addCapability(spv::CapabilitySparseResidency);
  5265. if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
  5266. builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
  5267. spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
  5268. if (sampler.isMultiSample()) {
  5269. mask = mask | spv::ImageOperandsSampleMask;
  5270. }
  5271. if (cracked.lod) {
  5272. builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
  5273. builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
  5274. mask = mask | spv::ImageOperandsLodMask;
  5275. }
  5276. mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
  5277. mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
  5278. mask = mask | signExtensionMask();
  5279. if (mask != spv::ImageOperandsMaskNone) {
  5280. spv::IdImmediate imageOperands = { false, (unsigned int)mask };
  5281. operands.push_back(imageOperands);
  5282. }
  5283. if (mask & spv::ImageOperandsSampleMask) {
  5284. spv::IdImmediate imageOperand = { true, *opIt++ };
  5285. operands.push_back(imageOperand);
  5286. }
  5287. if (mask & spv::ImageOperandsLodMask) {
  5288. spv::IdImmediate imageOperand = { true, *opIt++ };
  5289. operands.push_back(imageOperand);
  5290. }
  5291. if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
  5292. spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(
  5293. TranslateCoherent(imageType))) };
  5294. operands.push_back(imageOperand);
  5295. }
  5296. // Create the return type that was a special structure
  5297. spv::Id texelOut = *opIt;
  5298. spv::Id typeId0 = resultType();
  5299. spv::Id typeId1 = builder.getDerefTypeId(texelOut);
  5300. spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
  5301. spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
  5302. // Decode the return type
  5303. builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
  5304. return builder.createCompositeExtract(resultId, typeId0, 0);
  5305. } else {
  5306. // Process image atomic operations
  5307. // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
  5308. // as the first source operand, is required by SPIR-V atomic operations.
  5309. // For non-MS, the sample value should be 0
  5310. spv::IdImmediate sample = { true, sampler.isMultiSample() ? *(opIt++) : builder.makeUintConstant(0) };
  5311. operands.push_back(sample);
  5312. spv::Id resultTypeId;
  5313. glslang::TBasicType typeProxy = node->getBasicType();
  5314. // imageAtomicStore has a void return type so base the pointer type on
  5315. // the type of the value operand.
  5316. if (node->getOp() == glslang::EOpImageAtomicStore) {
  5317. resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(*opIt));
  5318. typeProxy = node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler().type;
  5319. } else {
  5320. resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
  5321. }
  5322. spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
  5323. if (imageType.getQualifier().nonUniform) {
  5324. builder.addDecoration(pointer, spv::DecorationNonUniformEXT);
  5325. }
  5326. std::vector<spv::Id> operands;
  5327. operands.push_back(pointer);
  5328. for (; opIt != arguments.end(); ++opIt)
  5329. operands.push_back(*opIt);
  5330. return createAtomicOperation(node->getOp(), precision, resultType(), operands, typeProxy,
  5331. lvalueCoherentFlags);
  5332. }
  5333. }
  5334. // Check for fragment mask functions other than queries
  5335. if (cracked.fragMask) {
  5336. assert(sampler.ms);
  5337. auto opIt = arguments.begin();
  5338. std::vector<spv::Id> operands;
  5339. operands.push_back(params.sampler);
  5340. ++opIt;
  5341. if (sampler.isSubpass()) {
  5342. // add on the (0,0) coordinate
  5343. spv::Id zero = builder.makeIntConstant(0);
  5344. std::vector<spv::Id> comps;
  5345. comps.push_back(zero);
  5346. comps.push_back(zero);
  5347. operands.push_back(builder.makeCompositeConstant(
  5348. builder.makeVectorType(builder.makeIntType(32), 2), comps));
  5349. }
  5350. for (; opIt != arguments.end(); ++opIt)
  5351. operands.push_back(*opIt);
  5352. spv::Op fragMaskOp = spv::OpNop;
  5353. if (node->getOp() == glslang::EOpFragmentMaskFetch)
  5354. fragMaskOp = spv::OpFragmentMaskFetchAMD;
  5355. else if (node->getOp() == glslang::EOpFragmentFetch)
  5356. fragMaskOp = spv::OpFragmentFetchAMD;
  5357. builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
  5358. builder.addCapability(spv::CapabilityFragmentMaskAMD);
  5359. return builder.createOp(fragMaskOp, resultType(), operands);
  5360. }
  5361. // Check for texture functions other than queries
  5362. bool sparse = node->isSparseTexture();
  5363. bool imageFootprint = node->isImageFootprint();
  5364. bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.isArrayed() && sampler.isShadow();
  5365. // check for bias argument
  5366. bool bias = false;
  5367. if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
  5368. int nonBiasArgCount = 2;
  5369. if (cracked.gather)
  5370. ++nonBiasArgCount; // comp argument should be present when bias argument is present
  5371. if (f16ShadowCompare)
  5372. ++nonBiasArgCount;
  5373. if (cracked.offset)
  5374. ++nonBiasArgCount;
  5375. else if (cracked.offsets)
  5376. ++nonBiasArgCount;
  5377. if (cracked.grad)
  5378. nonBiasArgCount += 2;
  5379. if (cracked.lodClamp)
  5380. ++nonBiasArgCount;
  5381. if (sparse)
  5382. ++nonBiasArgCount;
  5383. if (imageFootprint)
  5384. //Following three extra arguments
  5385. // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
  5386. nonBiasArgCount += 3;
  5387. if ((int)arguments.size() > nonBiasArgCount)
  5388. bias = true;
  5389. }
  5390. if (cracked.gather) {
  5391. const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
  5392. if (bias || cracked.lod ||
  5393. sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
  5394. builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
  5395. builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
  5396. }
  5397. }
  5398. // set the rest of the arguments
  5399. params.coords = arguments[1];
  5400. int extraArgs = 0;
  5401. bool noImplicitLod = false;
  5402. // sort out where Dref is coming from
  5403. if (cubeCompare || f16ShadowCompare) {
  5404. params.Dref = arguments[2];
  5405. ++extraArgs;
  5406. } else if (sampler.shadow && cracked.gather) {
  5407. params.Dref = arguments[2];
  5408. ++extraArgs;
  5409. } else if (sampler.shadow) {
  5410. std::vector<spv::Id> indexes;
  5411. int dRefComp;
  5412. if (cracked.proj)
  5413. dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
  5414. else
  5415. dRefComp = builder.getNumComponents(params.coords) - 1;
  5416. indexes.push_back(dRefComp);
  5417. params.Dref = builder.createCompositeExtract(params.coords,
  5418. builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
  5419. }
  5420. // lod
  5421. if (cracked.lod) {
  5422. params.lod = arguments[2 + extraArgs];
  5423. ++extraArgs;
  5424. } else if (glslangIntermediate->getStage() != EShLangFragment &&
  5425. !(glslangIntermediate->getStage() == EShLangCompute &&
  5426. glslangIntermediate->hasLayoutDerivativeModeNone())) {
  5427. // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
  5428. noImplicitLod = true;
  5429. }
  5430. // multisample
  5431. if (sampler.isMultiSample()) {
  5432. params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
  5433. ++extraArgs;
  5434. }
  5435. // gradient
  5436. if (cracked.grad) {
  5437. params.gradX = arguments[2 + extraArgs];
  5438. params.gradY = arguments[3 + extraArgs];
  5439. extraArgs += 2;
  5440. }
  5441. // offset and offsets
  5442. if (cracked.offset) {
  5443. params.offset = arguments[2 + extraArgs];
  5444. ++extraArgs;
  5445. } else if (cracked.offsets) {
  5446. params.offsets = arguments[2 + extraArgs];
  5447. ++extraArgs;
  5448. }
  5449. // lod clamp
  5450. if (cracked.lodClamp) {
  5451. params.lodClamp = arguments[2 + extraArgs];
  5452. ++extraArgs;
  5453. }
  5454. // sparse
  5455. if (sparse) {
  5456. params.texelOut = arguments[2 + extraArgs];
  5457. ++extraArgs;
  5458. }
  5459. // gather component
  5460. if (cracked.gather && ! sampler.shadow) {
  5461. // default component is 0, if missing, otherwise an argument
  5462. if (2 + extraArgs < (int)arguments.size()) {
  5463. params.component = arguments[2 + extraArgs];
  5464. ++extraArgs;
  5465. } else
  5466. params.component = builder.makeIntConstant(0);
  5467. }
  5468. spv::Id resultStruct = spv::NoResult;
  5469. if (imageFootprint) {
  5470. //Following three extra arguments
  5471. // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
  5472. params.granularity = arguments[2 + extraArgs];
  5473. params.coarse = arguments[3 + extraArgs];
  5474. resultStruct = arguments[4 + extraArgs];
  5475. extraArgs += 3;
  5476. }
  5477. // bias
  5478. if (bias) {
  5479. params.bias = arguments[2 + extraArgs];
  5480. ++extraArgs;
  5481. }
  5482. if (imageFootprint) {
  5483. builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
  5484. builder.addCapability(spv::CapabilityImageFootprintNV);
  5485. //resultStructType(OpenGL type) contains 5 elements:
  5486. //struct gl_TextureFootprint2DNV {
  5487. // uvec2 anchor;
  5488. // uvec2 offset;
  5489. // uvec2 mask;
  5490. // uint lod;
  5491. // uint granularity;
  5492. //};
  5493. //or
  5494. //struct gl_TextureFootprint3DNV {
  5495. // uvec3 anchor;
  5496. // uvec3 offset;
  5497. // uvec2 mask;
  5498. // uint lod;
  5499. // uint granularity;
  5500. //};
  5501. spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
  5502. assert(builder.isStructType(resultStructType));
  5503. //resType (SPIR-V type) contains 6 elements:
  5504. //Member 0 must be a Boolean type scalar(LOD),
  5505. //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
  5506. //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
  5507. //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
  5508. //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
  5509. //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
  5510. std::vector<spv::Id> members;
  5511. members.push_back(resultType());
  5512. for (int i = 0; i < 5; i++) {
  5513. members.push_back(builder.getContainedTypeId(resultStructType, i));
  5514. }
  5515. spv::Id resType = builder.makeStructType(members, "ResType");
  5516. //call ImageFootprintNV
  5517. spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
  5518. cracked.gather, noImplicitLod, params, signExtensionMask());
  5519. //copy resType (SPIR-V type) to resultStructType(OpenGL type)
  5520. for (int i = 0; i < 5; i++) {
  5521. builder.clearAccessChain();
  5522. builder.setAccessChainLValue(resultStruct);
  5523. //Accessing to a struct we created, no coherent flag is set
  5524. spv::Builder::AccessChain::CoherentFlags flags;
  5525. flags.clear();
  5526. builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
  5527. builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1),
  5528. i+1), TranslateNonUniformDecoration(imageType.getQualifier()));
  5529. }
  5530. return builder.createCompositeExtract(res, resultType(), 0);
  5531. }
  5532. // projective component (might not to move)
  5533. // GLSL: "The texture coordinates consumed from P, not including the last component of P,
  5534. // are divided by the last component of P."
  5535. // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
  5536. // unused components will appear after all used components."
  5537. if (cracked.proj) {
  5538. int projSourceComp = builder.getNumComponents(params.coords) - 1;
  5539. int projTargetComp;
  5540. switch (sampler.dim) {
  5541. case glslang::Esd1D: projTargetComp = 1; break;
  5542. case glslang::Esd2D: projTargetComp = 2; break;
  5543. case glslang::EsdRect: projTargetComp = 2; break;
  5544. default: projTargetComp = projSourceComp; break;
  5545. }
  5546. // copy the projective coordinate if we have to
  5547. if (projTargetComp != projSourceComp) {
  5548. spv::Id projComp = builder.createCompositeExtract(params.coords,
  5549. builder.getScalarTypeId(builder.getTypeId(params.coords)), projSourceComp);
  5550. params.coords = builder.createCompositeInsert(projComp, params.coords,
  5551. builder.getTypeId(params.coords), projTargetComp);
  5552. }
  5553. }
  5554. // nonprivate
  5555. if (imageType.getQualifier().nonprivate) {
  5556. params.nonprivate = true;
  5557. }
  5558. // volatile
  5559. if (imageType.getQualifier().volatil) {
  5560. params.volatil = true;
  5561. }
  5562. std::vector<spv::Id> result( 1,
  5563. builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
  5564. noImplicitLod, params, signExtensionMask())
  5565. );
  5566. if (components != node->getType().getVectorSize())
  5567. result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
  5568. return result[0];
  5569. }
  5570. spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
  5571. {
  5572. // Grab the function's pointer from the previously created function
  5573. spv::Function* function = functionMap[node->getName().c_str()];
  5574. if (! function)
  5575. return 0;
  5576. const glslang::TIntermSequence& glslangArgs = node->getSequence();
  5577. const glslang::TQualifierList& qualifiers = node->getQualifierList();
  5578. // See comments in makeFunctions() for details about the semantics for parameter passing.
  5579. //
  5580. // These imply we need a four step process:
  5581. // 1. Evaluate the arguments
  5582. // 2. Allocate and make copies of in, out, and inout arguments
  5583. // 3. Make the call
  5584. // 4. Copy back the results
  5585. // 1. Evaluate the arguments and their types
  5586. std::vector<spv::Builder::AccessChain> lValues;
  5587. std::vector<spv::Id> rValues;
  5588. std::vector<const glslang::TType*> argTypes;
  5589. for (int a = 0; a < (int)glslangArgs.size(); ++a) {
  5590. argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
  5591. // build l-value
  5592. builder.clearAccessChain();
  5593. glslangArgs[a]->traverse(this);
  5594. // keep outputs and pass-by-originals as l-values, evaluate others as r-values
  5595. if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
  5596. writableParam(qualifiers[a])) {
  5597. // save l-value
  5598. lValues.push_back(builder.getAccessChain());
  5599. } else {
  5600. // process r-value
  5601. rValues.push_back(accessChainLoad(*argTypes.back()));
  5602. }
  5603. }
  5604. // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
  5605. // copy the original into that space.
  5606. //
  5607. // Also, build up the list of actual arguments to pass in for the call
  5608. int lValueCount = 0;
  5609. int rValueCount = 0;
  5610. std::vector<spv::Id> spvArgs;
  5611. for (int a = 0; a < (int)glslangArgs.size(); ++a) {
  5612. spv::Id arg;
  5613. if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
  5614. builder.setAccessChain(lValues[lValueCount]);
  5615. arg = builder.accessChainGetLValue();
  5616. ++lValueCount;
  5617. } else if (writableParam(qualifiers[a])) {
  5618. // need space to hold the copy
  5619. arg = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction,
  5620. builder.getContainedTypeId(function->getParamType(a)), "param");
  5621. if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
  5622. // need to copy the input into output space
  5623. builder.setAccessChain(lValues[lValueCount]);
  5624. spv::Id copy = accessChainLoad(*argTypes[a]);
  5625. builder.clearAccessChain();
  5626. builder.setAccessChainLValue(arg);
  5627. multiTypeStore(*argTypes[a], copy);
  5628. }
  5629. ++lValueCount;
  5630. } else {
  5631. // process r-value, which involves a copy for a type mismatch
  5632. if (function->getParamType(a) != builder.getTypeId(rValues[rValueCount]) ||
  5633. TranslatePrecisionDecoration(*argTypes[a]) != function->getParamPrecision(a))
  5634. {
  5635. spv::Id argCopy = builder.createVariable(function->getParamPrecision(a), spv::StorageClassFunction, function->getParamType(a), "arg");
  5636. builder.clearAccessChain();
  5637. builder.setAccessChainLValue(argCopy);
  5638. multiTypeStore(*argTypes[a], rValues[rValueCount]);
  5639. arg = builder.createLoad(argCopy, function->getParamPrecision(a));
  5640. } else
  5641. arg = rValues[rValueCount];
  5642. ++rValueCount;
  5643. }
  5644. spvArgs.push_back(arg);
  5645. }
  5646. // 3. Make the call.
  5647. spv::Id result = builder.createFunctionCall(function, spvArgs);
  5648. builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
  5649. builder.addDecoration(result, TranslateNonUniformDecoration(node->getType().getQualifier()));
  5650. // 4. Copy back out an "out" arguments.
  5651. lValueCount = 0;
  5652. for (int a = 0; a < (int)glslangArgs.size(); ++a) {
  5653. if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
  5654. ++lValueCount;
  5655. else if (writableParam(qualifiers[a])) {
  5656. if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
  5657. spv::Id copy = builder.createLoad(spvArgs[a], spv::NoPrecision);
  5658. builder.addDecoration(copy, TranslateNonUniformDecoration(argTypes[a]->getQualifier()));
  5659. builder.setAccessChain(lValues[lValueCount]);
  5660. multiTypeStore(*argTypes[a], copy);
  5661. }
  5662. ++lValueCount;
  5663. }
  5664. }
  5665. return result;
  5666. }
  5667. // Translate AST operation to SPV operation, already having SPV-based operands/types.
  5668. spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
  5669. spv::Id typeId, spv::Id left, spv::Id right,
  5670. glslang::TBasicType typeProxy, bool reduceComparison)
  5671. {
  5672. bool isUnsigned = isTypeUnsignedInt(typeProxy);
  5673. bool isFloat = isTypeFloat(typeProxy);
  5674. bool isBool = typeProxy == glslang::EbtBool;
  5675. spv::Op binOp = spv::OpNop;
  5676. bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
  5677. bool comparison = false;
  5678. switch (op) {
  5679. case glslang::EOpAdd:
  5680. case glslang::EOpAddAssign:
  5681. if (isFloat)
  5682. binOp = spv::OpFAdd;
  5683. else
  5684. binOp = spv::OpIAdd;
  5685. break;
  5686. case glslang::EOpSub:
  5687. case glslang::EOpSubAssign:
  5688. if (isFloat)
  5689. binOp = spv::OpFSub;
  5690. else
  5691. binOp = spv::OpISub;
  5692. break;
  5693. case glslang::EOpMul:
  5694. case glslang::EOpMulAssign:
  5695. if (isFloat)
  5696. binOp = spv::OpFMul;
  5697. else
  5698. binOp = spv::OpIMul;
  5699. break;
  5700. case glslang::EOpVectorTimesScalar:
  5701. case glslang::EOpVectorTimesScalarAssign:
  5702. if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
  5703. if (builder.isVector(right))
  5704. std::swap(left, right);
  5705. assert(builder.isScalar(right));
  5706. needMatchingVectors = false;
  5707. binOp = spv::OpVectorTimesScalar;
  5708. } else if (isFloat)
  5709. binOp = spv::OpFMul;
  5710. else
  5711. binOp = spv::OpIMul;
  5712. break;
  5713. case glslang::EOpVectorTimesMatrix:
  5714. case glslang::EOpVectorTimesMatrixAssign:
  5715. binOp = spv::OpVectorTimesMatrix;
  5716. break;
  5717. case glslang::EOpMatrixTimesVector:
  5718. binOp = spv::OpMatrixTimesVector;
  5719. break;
  5720. case glslang::EOpMatrixTimesScalar:
  5721. case glslang::EOpMatrixTimesScalarAssign:
  5722. binOp = spv::OpMatrixTimesScalar;
  5723. break;
  5724. case glslang::EOpMatrixTimesMatrix:
  5725. case glslang::EOpMatrixTimesMatrixAssign:
  5726. binOp = spv::OpMatrixTimesMatrix;
  5727. break;
  5728. case glslang::EOpOuterProduct:
  5729. binOp = spv::OpOuterProduct;
  5730. needMatchingVectors = false;
  5731. break;
  5732. case glslang::EOpDiv:
  5733. case glslang::EOpDivAssign:
  5734. if (isFloat)
  5735. binOp = spv::OpFDiv;
  5736. else if (isUnsigned)
  5737. binOp = spv::OpUDiv;
  5738. else
  5739. binOp = spv::OpSDiv;
  5740. break;
  5741. case glslang::EOpMod:
  5742. case glslang::EOpModAssign:
  5743. if (isFloat)
  5744. binOp = spv::OpFMod;
  5745. else if (isUnsigned)
  5746. binOp = spv::OpUMod;
  5747. else
  5748. binOp = spv::OpSMod;
  5749. break;
  5750. case glslang::EOpRightShift:
  5751. case glslang::EOpRightShiftAssign:
  5752. if (isUnsigned)
  5753. binOp = spv::OpShiftRightLogical;
  5754. else
  5755. binOp = spv::OpShiftRightArithmetic;
  5756. break;
  5757. case glslang::EOpLeftShift:
  5758. case glslang::EOpLeftShiftAssign:
  5759. binOp = spv::OpShiftLeftLogical;
  5760. break;
  5761. case glslang::EOpAnd:
  5762. case glslang::EOpAndAssign:
  5763. binOp = spv::OpBitwiseAnd;
  5764. break;
  5765. case glslang::EOpLogicalAnd:
  5766. needMatchingVectors = false;
  5767. binOp = spv::OpLogicalAnd;
  5768. break;
  5769. case glslang::EOpInclusiveOr:
  5770. case glslang::EOpInclusiveOrAssign:
  5771. binOp = spv::OpBitwiseOr;
  5772. break;
  5773. case glslang::EOpLogicalOr:
  5774. needMatchingVectors = false;
  5775. binOp = spv::OpLogicalOr;
  5776. break;
  5777. case glslang::EOpExclusiveOr:
  5778. case glslang::EOpExclusiveOrAssign:
  5779. binOp = spv::OpBitwiseXor;
  5780. break;
  5781. case glslang::EOpLogicalXor:
  5782. needMatchingVectors = false;
  5783. binOp = spv::OpLogicalNotEqual;
  5784. break;
  5785. case glslang::EOpAbsDifference:
  5786. binOp = isUnsigned ? spv::OpAbsUSubINTEL : spv::OpAbsISubINTEL;
  5787. break;
  5788. case glslang::EOpAddSaturate:
  5789. binOp = isUnsigned ? spv::OpUAddSatINTEL : spv::OpIAddSatINTEL;
  5790. break;
  5791. case glslang::EOpSubSaturate:
  5792. binOp = isUnsigned ? spv::OpUSubSatINTEL : spv::OpISubSatINTEL;
  5793. break;
  5794. case glslang::EOpAverage:
  5795. binOp = isUnsigned ? spv::OpUAverageINTEL : spv::OpIAverageINTEL;
  5796. break;
  5797. case glslang::EOpAverageRounded:
  5798. binOp = isUnsigned ? spv::OpUAverageRoundedINTEL : spv::OpIAverageRoundedINTEL;
  5799. break;
  5800. case glslang::EOpMul32x16:
  5801. binOp = isUnsigned ? spv::OpUMul32x16INTEL : spv::OpIMul32x16INTEL;
  5802. break;
  5803. case glslang::EOpLessThan:
  5804. case glslang::EOpGreaterThan:
  5805. case glslang::EOpLessThanEqual:
  5806. case glslang::EOpGreaterThanEqual:
  5807. case glslang::EOpEqual:
  5808. case glslang::EOpNotEqual:
  5809. case glslang::EOpVectorEqual:
  5810. case glslang::EOpVectorNotEqual:
  5811. comparison = true;
  5812. break;
  5813. default:
  5814. break;
  5815. }
  5816. // handle mapped binary operations (should be non-comparison)
  5817. if (binOp != spv::OpNop) {
  5818. assert(comparison == false);
  5819. if (builder.isMatrix(left) || builder.isMatrix(right) ||
  5820. builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
  5821. return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
  5822. // No matrix involved; make both operands be the same number of components, if needed
  5823. if (needMatchingVectors)
  5824. builder.promoteScalar(decorations.precision, left, right);
  5825. spv::Id result = builder.createBinOp(binOp, typeId, left, right);
  5826. decorations.addNoContraction(builder, result);
  5827. decorations.addNonUniform(builder, result);
  5828. return builder.setPrecision(result, decorations.precision);
  5829. }
  5830. if (! comparison)
  5831. return 0;
  5832. // Handle comparison instructions
  5833. if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
  5834. && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
  5835. spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
  5836. decorations.addNonUniform(builder, result);
  5837. return result;
  5838. }
  5839. switch (op) {
  5840. case glslang::EOpLessThan:
  5841. if (isFloat)
  5842. binOp = spv::OpFOrdLessThan;
  5843. else if (isUnsigned)
  5844. binOp = spv::OpULessThan;
  5845. else
  5846. binOp = spv::OpSLessThan;
  5847. break;
  5848. case glslang::EOpGreaterThan:
  5849. if (isFloat)
  5850. binOp = spv::OpFOrdGreaterThan;
  5851. else if (isUnsigned)
  5852. binOp = spv::OpUGreaterThan;
  5853. else
  5854. binOp = spv::OpSGreaterThan;
  5855. break;
  5856. case glslang::EOpLessThanEqual:
  5857. if (isFloat)
  5858. binOp = spv::OpFOrdLessThanEqual;
  5859. else if (isUnsigned)
  5860. binOp = spv::OpULessThanEqual;
  5861. else
  5862. binOp = spv::OpSLessThanEqual;
  5863. break;
  5864. case glslang::EOpGreaterThanEqual:
  5865. if (isFloat)
  5866. binOp = spv::OpFOrdGreaterThanEqual;
  5867. else if (isUnsigned)
  5868. binOp = spv::OpUGreaterThanEqual;
  5869. else
  5870. binOp = spv::OpSGreaterThanEqual;
  5871. break;
  5872. case glslang::EOpEqual:
  5873. case glslang::EOpVectorEqual:
  5874. if (isFloat)
  5875. binOp = spv::OpFOrdEqual;
  5876. else if (isBool)
  5877. binOp = spv::OpLogicalEqual;
  5878. else
  5879. binOp = spv::OpIEqual;
  5880. break;
  5881. case glslang::EOpNotEqual:
  5882. case glslang::EOpVectorNotEqual:
  5883. if (isFloat)
  5884. binOp = spv::OpFUnordNotEqual;
  5885. else if (isBool)
  5886. binOp = spv::OpLogicalNotEqual;
  5887. else
  5888. binOp = spv::OpINotEqual;
  5889. break;
  5890. default:
  5891. break;
  5892. }
  5893. if (binOp != spv::OpNop) {
  5894. spv::Id result = builder.createBinOp(binOp, typeId, left, right);
  5895. decorations.addNoContraction(builder, result);
  5896. decorations.addNonUniform(builder, result);
  5897. return builder.setPrecision(result, decorations.precision);
  5898. }
  5899. return 0;
  5900. }
  5901. //
  5902. // Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
  5903. // These can be any of:
  5904. //
  5905. // matrix * scalar
  5906. // scalar * matrix
  5907. // matrix * matrix linear algebraic
  5908. // matrix * vector
  5909. // vector * matrix
  5910. // matrix * matrix componentwise
  5911. // matrix op matrix op in {+, -, /}
  5912. // matrix op scalar op in {+, -, /}
  5913. // scalar op matrix op in {+, -, /}
  5914. //
  5915. spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
  5916. spv::Id left, spv::Id right)
  5917. {
  5918. bool firstClass = true;
  5919. // First, handle first-class matrix operations (* and matrix/scalar)
  5920. switch (op) {
  5921. case spv::OpFDiv:
  5922. if (builder.isMatrix(left) && builder.isScalar(right)) {
  5923. // turn matrix / scalar into a multiply...
  5924. spv::Id resultType = builder.getTypeId(right);
  5925. right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
  5926. op = spv::OpMatrixTimesScalar;
  5927. } else
  5928. firstClass = false;
  5929. break;
  5930. case spv::OpMatrixTimesScalar:
  5931. if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
  5932. std::swap(left, right);
  5933. assert(builder.isScalar(right));
  5934. break;
  5935. case spv::OpVectorTimesMatrix:
  5936. assert(builder.isVector(left));
  5937. assert(builder.isMatrix(right));
  5938. break;
  5939. case spv::OpMatrixTimesVector:
  5940. assert(builder.isMatrix(left));
  5941. assert(builder.isVector(right));
  5942. break;
  5943. case spv::OpMatrixTimesMatrix:
  5944. assert(builder.isMatrix(left));
  5945. assert(builder.isMatrix(right));
  5946. break;
  5947. default:
  5948. firstClass = false;
  5949. break;
  5950. }
  5951. if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
  5952. firstClass = true;
  5953. if (firstClass) {
  5954. spv::Id result = builder.createBinOp(op, typeId, left, right);
  5955. decorations.addNoContraction(builder, result);
  5956. decorations.addNonUniform(builder, result);
  5957. return builder.setPrecision(result, decorations.precision);
  5958. }
  5959. // Handle component-wise +, -, *, %, and / for all combinations of type.
  5960. // The result type of all of them is the same type as the (a) matrix operand.
  5961. // The algorithm is to:
  5962. // - break the matrix(es) into vectors
  5963. // - smear any scalar to a vector
  5964. // - do vector operations
  5965. // - make a matrix out the vector results
  5966. switch (op) {
  5967. case spv::OpFAdd:
  5968. case spv::OpFSub:
  5969. case spv::OpFDiv:
  5970. case spv::OpFMod:
  5971. case spv::OpFMul:
  5972. {
  5973. // one time set up...
  5974. bool leftMat = builder.isMatrix(left);
  5975. bool rightMat = builder.isMatrix(right);
  5976. unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
  5977. int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
  5978. spv::Id scalarType = builder.getScalarTypeId(typeId);
  5979. spv::Id vecType = builder.makeVectorType(scalarType, numRows);
  5980. std::vector<spv::Id> results;
  5981. spv::Id smearVec = spv::NoResult;
  5982. if (builder.isScalar(left))
  5983. smearVec = builder.smearScalar(decorations.precision, left, vecType);
  5984. else if (builder.isScalar(right))
  5985. smearVec = builder.smearScalar(decorations.precision, right, vecType);
  5986. // do each vector op
  5987. for (unsigned int c = 0; c < numCols; ++c) {
  5988. std::vector<unsigned int> indexes;
  5989. indexes.push_back(c);
  5990. spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
  5991. spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
  5992. spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
  5993. decorations.addNoContraction(builder, result);
  5994. decorations.addNonUniform(builder, result);
  5995. results.push_back(builder.setPrecision(result, decorations.precision));
  5996. }
  5997. // put the pieces together
  5998. spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
  5999. decorations.addNonUniform(builder, result);
  6000. return result;
  6001. }
  6002. default:
  6003. assert(0);
  6004. return spv::NoResult;
  6005. }
  6006. }
  6007. spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
  6008. spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
  6009. {
  6010. spv::Op unaryOp = spv::OpNop;
  6011. int extBuiltins = -1;
  6012. int libCall = -1;
  6013. bool isUnsigned = isTypeUnsignedInt(typeProxy);
  6014. bool isFloat = isTypeFloat(typeProxy);
  6015. switch (op) {
  6016. case glslang::EOpNegative:
  6017. if (isFloat) {
  6018. unaryOp = spv::OpFNegate;
  6019. if (builder.isMatrixType(typeId))
  6020. return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
  6021. } else
  6022. unaryOp = spv::OpSNegate;
  6023. break;
  6024. case glslang::EOpLogicalNot:
  6025. case glslang::EOpVectorLogicalNot:
  6026. unaryOp = spv::OpLogicalNot;
  6027. break;
  6028. case glslang::EOpBitwiseNot:
  6029. unaryOp = spv::OpNot;
  6030. break;
  6031. case glslang::EOpDeterminant:
  6032. libCall = spv::GLSLstd450Determinant;
  6033. break;
  6034. case glslang::EOpMatrixInverse:
  6035. libCall = spv::GLSLstd450MatrixInverse;
  6036. break;
  6037. case glslang::EOpTranspose:
  6038. unaryOp = spv::OpTranspose;
  6039. break;
  6040. case glslang::EOpRadians:
  6041. libCall = spv::GLSLstd450Radians;
  6042. break;
  6043. case glslang::EOpDegrees:
  6044. libCall = spv::GLSLstd450Degrees;
  6045. break;
  6046. case glslang::EOpSin:
  6047. libCall = spv::GLSLstd450Sin;
  6048. break;
  6049. case glslang::EOpCos:
  6050. libCall = spv::GLSLstd450Cos;
  6051. break;
  6052. case glslang::EOpTan:
  6053. libCall = spv::GLSLstd450Tan;
  6054. break;
  6055. case glslang::EOpAcos:
  6056. libCall = spv::GLSLstd450Acos;
  6057. break;
  6058. case glslang::EOpAsin:
  6059. libCall = spv::GLSLstd450Asin;
  6060. break;
  6061. case glslang::EOpAtan:
  6062. libCall = spv::GLSLstd450Atan;
  6063. break;
  6064. case glslang::EOpAcosh:
  6065. libCall = spv::GLSLstd450Acosh;
  6066. break;
  6067. case glslang::EOpAsinh:
  6068. libCall = spv::GLSLstd450Asinh;
  6069. break;
  6070. case glslang::EOpAtanh:
  6071. libCall = spv::GLSLstd450Atanh;
  6072. break;
  6073. case glslang::EOpTanh:
  6074. libCall = spv::GLSLstd450Tanh;
  6075. break;
  6076. case glslang::EOpCosh:
  6077. libCall = spv::GLSLstd450Cosh;
  6078. break;
  6079. case glslang::EOpSinh:
  6080. libCall = spv::GLSLstd450Sinh;
  6081. break;
  6082. case glslang::EOpLength:
  6083. libCall = spv::GLSLstd450Length;
  6084. break;
  6085. case glslang::EOpNormalize:
  6086. libCall = spv::GLSLstd450Normalize;
  6087. break;
  6088. case glslang::EOpExp:
  6089. libCall = spv::GLSLstd450Exp;
  6090. break;
  6091. case glslang::EOpLog:
  6092. libCall = spv::GLSLstd450Log;
  6093. break;
  6094. case glslang::EOpExp2:
  6095. libCall = spv::GLSLstd450Exp2;
  6096. break;
  6097. case glslang::EOpLog2:
  6098. libCall = spv::GLSLstd450Log2;
  6099. break;
  6100. case glslang::EOpSqrt:
  6101. libCall = spv::GLSLstd450Sqrt;
  6102. break;
  6103. case glslang::EOpInverseSqrt:
  6104. libCall = spv::GLSLstd450InverseSqrt;
  6105. break;
  6106. case glslang::EOpFloor:
  6107. libCall = spv::GLSLstd450Floor;
  6108. break;
  6109. case glslang::EOpTrunc:
  6110. libCall = spv::GLSLstd450Trunc;
  6111. break;
  6112. case glslang::EOpRound:
  6113. libCall = spv::GLSLstd450Round;
  6114. break;
  6115. case glslang::EOpRoundEven:
  6116. libCall = spv::GLSLstd450RoundEven;
  6117. break;
  6118. case glslang::EOpCeil:
  6119. libCall = spv::GLSLstd450Ceil;
  6120. break;
  6121. case glslang::EOpFract:
  6122. libCall = spv::GLSLstd450Fract;
  6123. break;
  6124. case glslang::EOpIsNan:
  6125. unaryOp = spv::OpIsNan;
  6126. break;
  6127. case glslang::EOpIsInf:
  6128. unaryOp = spv::OpIsInf;
  6129. break;
  6130. case glslang::EOpIsFinite:
  6131. unaryOp = spv::OpIsFinite;
  6132. break;
  6133. case glslang::EOpFloatBitsToInt:
  6134. case glslang::EOpFloatBitsToUint:
  6135. case glslang::EOpIntBitsToFloat:
  6136. case glslang::EOpUintBitsToFloat:
  6137. case glslang::EOpDoubleBitsToInt64:
  6138. case glslang::EOpDoubleBitsToUint64:
  6139. case glslang::EOpInt64BitsToDouble:
  6140. case glslang::EOpUint64BitsToDouble:
  6141. case glslang::EOpFloat16BitsToInt16:
  6142. case glslang::EOpFloat16BitsToUint16:
  6143. case glslang::EOpInt16BitsToFloat16:
  6144. case glslang::EOpUint16BitsToFloat16:
  6145. unaryOp = spv::OpBitcast;
  6146. break;
  6147. case glslang::EOpPackSnorm2x16:
  6148. libCall = spv::GLSLstd450PackSnorm2x16;
  6149. break;
  6150. case glslang::EOpUnpackSnorm2x16:
  6151. libCall = spv::GLSLstd450UnpackSnorm2x16;
  6152. break;
  6153. case glslang::EOpPackUnorm2x16:
  6154. libCall = spv::GLSLstd450PackUnorm2x16;
  6155. break;
  6156. case glslang::EOpUnpackUnorm2x16:
  6157. libCall = spv::GLSLstd450UnpackUnorm2x16;
  6158. break;
  6159. case glslang::EOpPackHalf2x16:
  6160. libCall = spv::GLSLstd450PackHalf2x16;
  6161. break;
  6162. case glslang::EOpUnpackHalf2x16:
  6163. libCall = spv::GLSLstd450UnpackHalf2x16;
  6164. break;
  6165. case glslang::EOpPackSnorm4x8:
  6166. libCall = spv::GLSLstd450PackSnorm4x8;
  6167. break;
  6168. case glslang::EOpUnpackSnorm4x8:
  6169. libCall = spv::GLSLstd450UnpackSnorm4x8;
  6170. break;
  6171. case glslang::EOpPackUnorm4x8:
  6172. libCall = spv::GLSLstd450PackUnorm4x8;
  6173. break;
  6174. case glslang::EOpUnpackUnorm4x8:
  6175. libCall = spv::GLSLstd450UnpackUnorm4x8;
  6176. break;
  6177. case glslang::EOpPackDouble2x32:
  6178. libCall = spv::GLSLstd450PackDouble2x32;
  6179. break;
  6180. case glslang::EOpUnpackDouble2x32:
  6181. libCall = spv::GLSLstd450UnpackDouble2x32;
  6182. break;
  6183. case glslang::EOpPackInt2x32:
  6184. case glslang::EOpUnpackInt2x32:
  6185. case glslang::EOpPackUint2x32:
  6186. case glslang::EOpUnpackUint2x32:
  6187. case glslang::EOpPack16:
  6188. case glslang::EOpPack32:
  6189. case glslang::EOpPack64:
  6190. case glslang::EOpUnpack32:
  6191. case glslang::EOpUnpack16:
  6192. case glslang::EOpUnpack8:
  6193. case glslang::EOpPackInt2x16:
  6194. case glslang::EOpUnpackInt2x16:
  6195. case glslang::EOpPackUint2x16:
  6196. case glslang::EOpUnpackUint2x16:
  6197. case glslang::EOpPackInt4x16:
  6198. case glslang::EOpUnpackInt4x16:
  6199. case glslang::EOpPackUint4x16:
  6200. case glslang::EOpUnpackUint4x16:
  6201. case glslang::EOpPackFloat2x16:
  6202. case glslang::EOpUnpackFloat2x16:
  6203. unaryOp = spv::OpBitcast;
  6204. break;
  6205. case glslang::EOpDPdx:
  6206. unaryOp = spv::OpDPdx;
  6207. break;
  6208. case glslang::EOpDPdy:
  6209. unaryOp = spv::OpDPdy;
  6210. break;
  6211. case glslang::EOpFwidth:
  6212. unaryOp = spv::OpFwidth;
  6213. break;
  6214. case glslang::EOpAny:
  6215. unaryOp = spv::OpAny;
  6216. break;
  6217. case glslang::EOpAll:
  6218. unaryOp = spv::OpAll;
  6219. break;
  6220. case glslang::EOpAbs:
  6221. if (isFloat)
  6222. libCall = spv::GLSLstd450FAbs;
  6223. else
  6224. libCall = spv::GLSLstd450SAbs;
  6225. break;
  6226. case glslang::EOpSign:
  6227. if (isFloat)
  6228. libCall = spv::GLSLstd450FSign;
  6229. else
  6230. libCall = spv::GLSLstd450SSign;
  6231. break;
  6232. case glslang::EOpDPdxFine:
  6233. unaryOp = spv::OpDPdxFine;
  6234. break;
  6235. case glslang::EOpDPdyFine:
  6236. unaryOp = spv::OpDPdyFine;
  6237. break;
  6238. case glslang::EOpFwidthFine:
  6239. unaryOp = spv::OpFwidthFine;
  6240. break;
  6241. case glslang::EOpDPdxCoarse:
  6242. unaryOp = spv::OpDPdxCoarse;
  6243. break;
  6244. case glslang::EOpDPdyCoarse:
  6245. unaryOp = spv::OpDPdyCoarse;
  6246. break;
  6247. case glslang::EOpFwidthCoarse:
  6248. unaryOp = spv::OpFwidthCoarse;
  6249. break;
  6250. case glslang::EOpRayQueryProceed:
  6251. unaryOp = spv::OpRayQueryProceedKHR;
  6252. break;
  6253. case glslang::EOpRayQueryGetRayTMin:
  6254. unaryOp = spv::OpRayQueryGetRayTMinKHR;
  6255. break;
  6256. case glslang::EOpRayQueryGetRayFlags:
  6257. unaryOp = spv::OpRayQueryGetRayFlagsKHR;
  6258. break;
  6259. case glslang::EOpRayQueryGetWorldRayOrigin:
  6260. unaryOp = spv::OpRayQueryGetWorldRayOriginKHR;
  6261. break;
  6262. case glslang::EOpRayQueryGetWorldRayDirection:
  6263. unaryOp = spv::OpRayQueryGetWorldRayDirectionKHR;
  6264. break;
  6265. case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
  6266. unaryOp = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
  6267. break;
  6268. case glslang::EOpInterpolateAtCentroid:
  6269. if (typeProxy == glslang::EbtFloat16)
  6270. builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
  6271. libCall = spv::GLSLstd450InterpolateAtCentroid;
  6272. break;
  6273. case glslang::EOpAtomicCounterIncrement:
  6274. case glslang::EOpAtomicCounterDecrement:
  6275. case glslang::EOpAtomicCounter:
  6276. {
  6277. // Handle all of the atomics in one place, in createAtomicOperation()
  6278. std::vector<spv::Id> operands;
  6279. operands.push_back(operand);
  6280. return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
  6281. }
  6282. case glslang::EOpBitFieldReverse:
  6283. unaryOp = spv::OpBitReverse;
  6284. break;
  6285. case glslang::EOpBitCount:
  6286. unaryOp = spv::OpBitCount;
  6287. break;
  6288. case glslang::EOpFindLSB:
  6289. libCall = spv::GLSLstd450FindILsb;
  6290. break;
  6291. case glslang::EOpFindMSB:
  6292. if (isUnsigned)
  6293. libCall = spv::GLSLstd450FindUMsb;
  6294. else
  6295. libCall = spv::GLSLstd450FindSMsb;
  6296. break;
  6297. case glslang::EOpCountLeadingZeros:
  6298. builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
  6299. builder.addExtension("SPV_INTEL_shader_integer_functions2");
  6300. unaryOp = spv::OpUCountLeadingZerosINTEL;
  6301. break;
  6302. case glslang::EOpCountTrailingZeros:
  6303. builder.addCapability(spv::CapabilityIntegerFunctions2INTEL);
  6304. builder.addExtension("SPV_INTEL_shader_integer_functions2");
  6305. unaryOp = spv::OpUCountTrailingZerosINTEL;
  6306. break;
  6307. case glslang::EOpBallot:
  6308. case glslang::EOpReadFirstInvocation:
  6309. case glslang::EOpAnyInvocation:
  6310. case glslang::EOpAllInvocations:
  6311. case glslang::EOpAllInvocationsEqual:
  6312. case glslang::EOpMinInvocations:
  6313. case glslang::EOpMaxInvocations:
  6314. case glslang::EOpAddInvocations:
  6315. case glslang::EOpMinInvocationsNonUniform:
  6316. case glslang::EOpMaxInvocationsNonUniform:
  6317. case glslang::EOpAddInvocationsNonUniform:
  6318. case glslang::EOpMinInvocationsInclusiveScan:
  6319. case glslang::EOpMaxInvocationsInclusiveScan:
  6320. case glslang::EOpAddInvocationsInclusiveScan:
  6321. case glslang::EOpMinInvocationsInclusiveScanNonUniform:
  6322. case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
  6323. case glslang::EOpAddInvocationsInclusiveScanNonUniform:
  6324. case glslang::EOpMinInvocationsExclusiveScan:
  6325. case glslang::EOpMaxInvocationsExclusiveScan:
  6326. case glslang::EOpAddInvocationsExclusiveScan:
  6327. case glslang::EOpMinInvocationsExclusiveScanNonUniform:
  6328. case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
  6329. case glslang::EOpAddInvocationsExclusiveScanNonUniform:
  6330. {
  6331. std::vector<spv::Id> operands;
  6332. operands.push_back(operand);
  6333. return createInvocationsOperation(op, typeId, operands, typeProxy);
  6334. }
  6335. case glslang::EOpSubgroupAll:
  6336. case glslang::EOpSubgroupAny:
  6337. case glslang::EOpSubgroupAllEqual:
  6338. case glslang::EOpSubgroupBroadcastFirst:
  6339. case glslang::EOpSubgroupBallot:
  6340. case glslang::EOpSubgroupInverseBallot:
  6341. case glslang::EOpSubgroupBallotBitCount:
  6342. case glslang::EOpSubgroupBallotInclusiveBitCount:
  6343. case glslang::EOpSubgroupBallotExclusiveBitCount:
  6344. case glslang::EOpSubgroupBallotFindLSB:
  6345. case glslang::EOpSubgroupBallotFindMSB:
  6346. case glslang::EOpSubgroupAdd:
  6347. case glslang::EOpSubgroupMul:
  6348. case glslang::EOpSubgroupMin:
  6349. case glslang::EOpSubgroupMax:
  6350. case glslang::EOpSubgroupAnd:
  6351. case glslang::EOpSubgroupOr:
  6352. case glslang::EOpSubgroupXor:
  6353. case glslang::EOpSubgroupInclusiveAdd:
  6354. case glslang::EOpSubgroupInclusiveMul:
  6355. case glslang::EOpSubgroupInclusiveMin:
  6356. case glslang::EOpSubgroupInclusiveMax:
  6357. case glslang::EOpSubgroupInclusiveAnd:
  6358. case glslang::EOpSubgroupInclusiveOr:
  6359. case glslang::EOpSubgroupInclusiveXor:
  6360. case glslang::EOpSubgroupExclusiveAdd:
  6361. case glslang::EOpSubgroupExclusiveMul:
  6362. case glslang::EOpSubgroupExclusiveMin:
  6363. case glslang::EOpSubgroupExclusiveMax:
  6364. case glslang::EOpSubgroupExclusiveAnd:
  6365. case glslang::EOpSubgroupExclusiveOr:
  6366. case glslang::EOpSubgroupExclusiveXor:
  6367. case glslang::EOpSubgroupQuadSwapHorizontal:
  6368. case glslang::EOpSubgroupQuadSwapVertical:
  6369. case glslang::EOpSubgroupQuadSwapDiagonal: {
  6370. std::vector<spv::Id> operands;
  6371. operands.push_back(operand);
  6372. return createSubgroupOperation(op, typeId, operands, typeProxy);
  6373. }
  6374. case glslang::EOpMbcnt:
  6375. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
  6376. libCall = spv::MbcntAMD;
  6377. break;
  6378. case glslang::EOpCubeFaceIndex:
  6379. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
  6380. libCall = spv::CubeFaceIndexAMD;
  6381. break;
  6382. case glslang::EOpCubeFaceCoord:
  6383. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
  6384. libCall = spv::CubeFaceCoordAMD;
  6385. break;
  6386. case glslang::EOpSubgroupPartition:
  6387. unaryOp = spv::OpGroupNonUniformPartitionNV;
  6388. break;
  6389. case glslang::EOpConstructReference:
  6390. unaryOp = spv::OpBitcast;
  6391. break;
  6392. case glslang::EOpConvUint64ToAccStruct:
  6393. case glslang::EOpConvUvec2ToAccStruct:
  6394. unaryOp = spv::OpConvertUToAccelerationStructureKHR;
  6395. break;
  6396. case glslang::EOpHitObjectIsEmptyNV:
  6397. unaryOp = spv::OpHitObjectIsEmptyNV;
  6398. break;
  6399. case glslang::EOpHitObjectIsMissNV:
  6400. unaryOp = spv::OpHitObjectIsMissNV;
  6401. break;
  6402. case glslang::EOpHitObjectIsHitNV:
  6403. unaryOp = spv::OpHitObjectIsHitNV;
  6404. break;
  6405. case glslang::EOpHitObjectGetObjectRayOriginNV:
  6406. unaryOp = spv::OpHitObjectGetObjectRayOriginNV;
  6407. break;
  6408. case glslang::EOpHitObjectGetObjectRayDirectionNV:
  6409. unaryOp = spv::OpHitObjectGetObjectRayDirectionNV;
  6410. break;
  6411. case glslang::EOpHitObjectGetWorldRayOriginNV:
  6412. unaryOp = spv::OpHitObjectGetWorldRayOriginNV;
  6413. break;
  6414. case glslang::EOpHitObjectGetWorldRayDirectionNV:
  6415. unaryOp = spv::OpHitObjectGetWorldRayDirectionNV;
  6416. break;
  6417. case glslang::EOpHitObjectGetObjectToWorldNV:
  6418. unaryOp = spv::OpHitObjectGetObjectToWorldNV;
  6419. break;
  6420. case glslang::EOpHitObjectGetWorldToObjectNV:
  6421. unaryOp = spv::OpHitObjectGetWorldToObjectNV;
  6422. break;
  6423. case glslang::EOpHitObjectGetRayTMinNV:
  6424. unaryOp = spv::OpHitObjectGetRayTMinNV;
  6425. break;
  6426. case glslang::EOpHitObjectGetRayTMaxNV:
  6427. unaryOp = spv::OpHitObjectGetRayTMaxNV;
  6428. break;
  6429. case glslang::EOpHitObjectGetPrimitiveIndexNV:
  6430. unaryOp = spv::OpHitObjectGetPrimitiveIndexNV;
  6431. break;
  6432. case glslang::EOpHitObjectGetInstanceIdNV:
  6433. unaryOp = spv::OpHitObjectGetInstanceIdNV;
  6434. break;
  6435. case glslang::EOpHitObjectGetInstanceCustomIndexNV:
  6436. unaryOp = spv::OpHitObjectGetInstanceCustomIndexNV;
  6437. break;
  6438. case glslang::EOpHitObjectGetGeometryIndexNV:
  6439. unaryOp = spv::OpHitObjectGetGeometryIndexNV;
  6440. break;
  6441. case glslang::EOpHitObjectGetHitKindNV:
  6442. unaryOp = spv::OpHitObjectGetHitKindNV;
  6443. break;
  6444. case glslang::EOpHitObjectGetCurrentTimeNV:
  6445. unaryOp = spv::OpHitObjectGetCurrentTimeNV;
  6446. break;
  6447. case glslang::EOpHitObjectGetShaderBindingTableRecordIndexNV:
  6448. unaryOp = spv::OpHitObjectGetShaderBindingTableRecordIndexNV;
  6449. break;
  6450. case glslang::EOpHitObjectGetShaderRecordBufferHandleNV:
  6451. unaryOp = spv::OpHitObjectGetShaderRecordBufferHandleNV;
  6452. break;
  6453. case glslang::EOpCopyObject:
  6454. unaryOp = spv::OpCopyObject;
  6455. break;
  6456. case glslang::EOpDepthAttachmentReadEXT:
  6457. builder.addExtension(spv::E_SPV_EXT_shader_tile_image);
  6458. builder.addCapability(spv::CapabilityTileImageDepthReadAccessEXT);
  6459. unaryOp = spv::OpDepthAttachmentReadEXT;
  6460. decorations.precision = spv::NoPrecision;
  6461. break;
  6462. case glslang::EOpStencilAttachmentReadEXT:
  6463. builder.addExtension(spv::E_SPV_EXT_shader_tile_image);
  6464. builder.addCapability(spv::CapabilityTileImageStencilReadAccessEXT);
  6465. unaryOp = spv::OpStencilAttachmentReadEXT;
  6466. decorations.precision = spv::DecorationRelaxedPrecision;
  6467. break;
  6468. default:
  6469. return 0;
  6470. }
  6471. spv::Id id;
  6472. if (libCall >= 0) {
  6473. std::vector<spv::Id> args;
  6474. args.push_back(operand);
  6475. id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
  6476. } else {
  6477. id = builder.createUnaryOp(unaryOp, typeId, operand);
  6478. }
  6479. decorations.addNoContraction(builder, id);
  6480. decorations.addNonUniform(builder, id);
  6481. return builder.setPrecision(id, decorations.precision);
  6482. }
  6483. // Create a unary operation on a matrix
  6484. spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
  6485. spv::Id operand, glslang::TBasicType /* typeProxy */)
  6486. {
  6487. // Handle unary operations vector by vector.
  6488. // The result type is the same type as the original type.
  6489. // The algorithm is to:
  6490. // - break the matrix into vectors
  6491. // - apply the operation to each vector
  6492. // - make a matrix out the vector results
  6493. // get the types sorted out
  6494. int numCols = builder.getNumColumns(operand);
  6495. int numRows = builder.getNumRows(operand);
  6496. spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
  6497. spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
  6498. std::vector<spv::Id> results;
  6499. // do each vector op
  6500. for (int c = 0; c < numCols; ++c) {
  6501. std::vector<unsigned int> indexes;
  6502. indexes.push_back(c);
  6503. spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
  6504. spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
  6505. decorations.addNoContraction(builder, destVec);
  6506. decorations.addNonUniform(builder, destVec);
  6507. results.push_back(builder.setPrecision(destVec, decorations.precision));
  6508. }
  6509. // put the pieces together
  6510. spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
  6511. decorations.addNonUniform(builder, result);
  6512. return result;
  6513. }
  6514. // For converting integers where both the bitwidth and the signedness could
  6515. // change, but only do the width change here. The caller is still responsible
  6516. // for the signedness conversion.
  6517. // destType is the final type that will be converted to, but this function
  6518. // may only be doing part of that conversion.
  6519. spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize, spv::Id destType)
  6520. {
  6521. // Get the result type width, based on the type to convert to.
  6522. int width = 32;
  6523. switch(op) {
  6524. case glslang::EOpConvInt16ToUint8:
  6525. case glslang::EOpConvIntToUint8:
  6526. case glslang::EOpConvInt64ToUint8:
  6527. case glslang::EOpConvUint16ToInt8:
  6528. case glslang::EOpConvUintToInt8:
  6529. case glslang::EOpConvUint64ToInt8:
  6530. width = 8;
  6531. break;
  6532. case glslang::EOpConvInt8ToUint16:
  6533. case glslang::EOpConvIntToUint16:
  6534. case glslang::EOpConvInt64ToUint16:
  6535. case glslang::EOpConvUint8ToInt16:
  6536. case glslang::EOpConvUintToInt16:
  6537. case glslang::EOpConvUint64ToInt16:
  6538. width = 16;
  6539. break;
  6540. case glslang::EOpConvInt8ToUint:
  6541. case glslang::EOpConvInt16ToUint:
  6542. case glslang::EOpConvInt64ToUint:
  6543. case glslang::EOpConvUint8ToInt:
  6544. case glslang::EOpConvUint16ToInt:
  6545. case glslang::EOpConvUint64ToInt:
  6546. width = 32;
  6547. break;
  6548. case glslang::EOpConvInt8ToUint64:
  6549. case glslang::EOpConvInt16ToUint64:
  6550. case glslang::EOpConvIntToUint64:
  6551. case glslang::EOpConvUint8ToInt64:
  6552. case glslang::EOpConvUint16ToInt64:
  6553. case glslang::EOpConvUintToInt64:
  6554. width = 64;
  6555. break;
  6556. default:
  6557. assert(false && "Default missing");
  6558. break;
  6559. }
  6560. // Get the conversion operation and result type,
  6561. // based on the target width, but the source type.
  6562. spv::Id type = spv::NoType;
  6563. spv::Op convOp = spv::OpNop;
  6564. switch(op) {
  6565. case glslang::EOpConvInt8ToUint16:
  6566. case glslang::EOpConvInt8ToUint:
  6567. case glslang::EOpConvInt8ToUint64:
  6568. case glslang::EOpConvInt16ToUint8:
  6569. case glslang::EOpConvInt16ToUint:
  6570. case glslang::EOpConvInt16ToUint64:
  6571. case glslang::EOpConvIntToUint8:
  6572. case glslang::EOpConvIntToUint16:
  6573. case glslang::EOpConvIntToUint64:
  6574. case glslang::EOpConvInt64ToUint8:
  6575. case glslang::EOpConvInt64ToUint16:
  6576. case glslang::EOpConvInt64ToUint:
  6577. convOp = spv::OpSConvert;
  6578. type = builder.makeIntType(width);
  6579. break;
  6580. default:
  6581. convOp = spv::OpUConvert;
  6582. type = builder.makeUintType(width);
  6583. break;
  6584. }
  6585. if (vectorSize > 0)
  6586. type = builder.makeVectorType(type, vectorSize);
  6587. else if (builder.getOpCode(destType) == spv::OpTypeCooperativeMatrixKHR ||
  6588. builder.getOpCode(destType) == spv::OpTypeCooperativeMatrixNV) {
  6589. type = builder.makeCooperativeMatrixTypeWithSameShape(type, destType);
  6590. }
  6591. return builder.createUnaryOp(convOp, type, operand);
  6592. }
  6593. spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
  6594. spv::Id operand, glslang::TBasicType typeProxy)
  6595. {
  6596. spv::Op convOp = spv::OpNop;
  6597. spv::Id zero = 0;
  6598. spv::Id one = 0;
  6599. int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
  6600. switch (op) {
  6601. case glslang::EOpConvIntToBool:
  6602. case glslang::EOpConvUintToBool:
  6603. zero = builder.makeUintConstant(0);
  6604. zero = makeSmearedConstant(zero, vectorSize);
  6605. return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
  6606. case glslang::EOpConvFloatToBool:
  6607. zero = builder.makeFloatConstant(0.0F);
  6608. zero = makeSmearedConstant(zero, vectorSize);
  6609. return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
  6610. case glslang::EOpConvBoolToFloat:
  6611. convOp = spv::OpSelect;
  6612. zero = builder.makeFloatConstant(0.0F);
  6613. one = builder.makeFloatConstant(1.0F);
  6614. break;
  6615. case glslang::EOpConvBoolToInt:
  6616. case glslang::EOpConvBoolToInt64:
  6617. if (op == glslang::EOpConvBoolToInt64) {
  6618. zero = builder.makeInt64Constant(0);
  6619. one = builder.makeInt64Constant(1);
  6620. } else {
  6621. zero = builder.makeIntConstant(0);
  6622. one = builder.makeIntConstant(1);
  6623. }
  6624. convOp = spv::OpSelect;
  6625. break;
  6626. case glslang::EOpConvBoolToUint:
  6627. case glslang::EOpConvBoolToUint64:
  6628. if (op == glslang::EOpConvBoolToUint64) {
  6629. zero = builder.makeUint64Constant(0);
  6630. one = builder.makeUint64Constant(1);
  6631. } else {
  6632. zero = builder.makeUintConstant(0);
  6633. one = builder.makeUintConstant(1);
  6634. }
  6635. convOp = spv::OpSelect;
  6636. break;
  6637. case glslang::EOpConvInt8ToFloat16:
  6638. case glslang::EOpConvInt8ToFloat:
  6639. case glslang::EOpConvInt8ToDouble:
  6640. case glslang::EOpConvInt16ToFloat16:
  6641. case glslang::EOpConvInt16ToFloat:
  6642. case glslang::EOpConvInt16ToDouble:
  6643. case glslang::EOpConvIntToFloat16:
  6644. case glslang::EOpConvIntToFloat:
  6645. case glslang::EOpConvIntToDouble:
  6646. case glslang::EOpConvInt64ToFloat:
  6647. case glslang::EOpConvInt64ToDouble:
  6648. case glslang::EOpConvInt64ToFloat16:
  6649. convOp = spv::OpConvertSToF;
  6650. break;
  6651. case glslang::EOpConvUint8ToFloat16:
  6652. case glslang::EOpConvUint8ToFloat:
  6653. case glslang::EOpConvUint8ToDouble:
  6654. case glslang::EOpConvUint16ToFloat16:
  6655. case glslang::EOpConvUint16ToFloat:
  6656. case glslang::EOpConvUint16ToDouble:
  6657. case glslang::EOpConvUintToFloat16:
  6658. case glslang::EOpConvUintToFloat:
  6659. case glslang::EOpConvUintToDouble:
  6660. case glslang::EOpConvUint64ToFloat:
  6661. case glslang::EOpConvUint64ToDouble:
  6662. case glslang::EOpConvUint64ToFloat16:
  6663. convOp = spv::OpConvertUToF;
  6664. break;
  6665. case glslang::EOpConvFloat16ToInt8:
  6666. case glslang::EOpConvFloatToInt8:
  6667. case glslang::EOpConvDoubleToInt8:
  6668. case glslang::EOpConvFloat16ToInt16:
  6669. case glslang::EOpConvFloatToInt16:
  6670. case glslang::EOpConvDoubleToInt16:
  6671. case glslang::EOpConvFloat16ToInt:
  6672. case glslang::EOpConvFloatToInt:
  6673. case glslang::EOpConvDoubleToInt:
  6674. case glslang::EOpConvFloat16ToInt64:
  6675. case glslang::EOpConvFloatToInt64:
  6676. case glslang::EOpConvDoubleToInt64:
  6677. convOp = spv::OpConvertFToS;
  6678. break;
  6679. case glslang::EOpConvUint8ToInt8:
  6680. case glslang::EOpConvInt8ToUint8:
  6681. case glslang::EOpConvUint16ToInt16:
  6682. case glslang::EOpConvInt16ToUint16:
  6683. case glslang::EOpConvUintToInt:
  6684. case glslang::EOpConvIntToUint:
  6685. case glslang::EOpConvUint64ToInt64:
  6686. case glslang::EOpConvInt64ToUint64:
  6687. if (builder.isInSpecConstCodeGenMode()) {
  6688. // Build zero scalar or vector for OpIAdd.
  6689. if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
  6690. zero = builder.makeUint8Constant(0);
  6691. } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
  6692. zero = builder.makeUint16Constant(0);
  6693. } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
  6694. zero = builder.makeUint64Constant(0);
  6695. } else {
  6696. zero = builder.makeUintConstant(0);
  6697. }
  6698. zero = makeSmearedConstant(zero, vectorSize);
  6699. // Use OpIAdd, instead of OpBitcast to do the conversion when
  6700. // generating for OpSpecConstantOp instruction.
  6701. return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
  6702. }
  6703. // For normal run-time conversion instruction, use OpBitcast.
  6704. convOp = spv::OpBitcast;
  6705. break;
  6706. case glslang::EOpConvFloat16ToUint8:
  6707. case glslang::EOpConvFloatToUint8:
  6708. case glslang::EOpConvDoubleToUint8:
  6709. case glslang::EOpConvFloat16ToUint16:
  6710. case glslang::EOpConvFloatToUint16:
  6711. case glslang::EOpConvDoubleToUint16:
  6712. case glslang::EOpConvFloat16ToUint:
  6713. case glslang::EOpConvFloatToUint:
  6714. case glslang::EOpConvDoubleToUint:
  6715. case glslang::EOpConvFloatToUint64:
  6716. case glslang::EOpConvDoubleToUint64:
  6717. case glslang::EOpConvFloat16ToUint64:
  6718. convOp = spv::OpConvertFToU;
  6719. break;
  6720. case glslang::EOpConvInt8ToBool:
  6721. case glslang::EOpConvUint8ToBool:
  6722. zero = builder.makeUint8Constant(0);
  6723. zero = makeSmearedConstant(zero, vectorSize);
  6724. return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
  6725. case glslang::EOpConvInt16ToBool:
  6726. case glslang::EOpConvUint16ToBool:
  6727. zero = builder.makeUint16Constant(0);
  6728. zero = makeSmearedConstant(zero, vectorSize);
  6729. return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
  6730. case glslang::EOpConvInt64ToBool:
  6731. case glslang::EOpConvUint64ToBool:
  6732. zero = builder.makeUint64Constant(0);
  6733. zero = makeSmearedConstant(zero, vectorSize);
  6734. return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
  6735. case glslang::EOpConvDoubleToBool:
  6736. zero = builder.makeDoubleConstant(0.0);
  6737. zero = makeSmearedConstant(zero, vectorSize);
  6738. return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
  6739. case glslang::EOpConvFloat16ToBool:
  6740. zero = builder.makeFloat16Constant(0.0F);
  6741. zero = makeSmearedConstant(zero, vectorSize);
  6742. return builder.createBinOp(spv::OpFUnordNotEqual, destType, operand, zero);
  6743. case glslang::EOpConvBoolToDouble:
  6744. convOp = spv::OpSelect;
  6745. zero = builder.makeDoubleConstant(0.0);
  6746. one = builder.makeDoubleConstant(1.0);
  6747. break;
  6748. case glslang::EOpConvBoolToFloat16:
  6749. convOp = spv::OpSelect;
  6750. zero = builder.makeFloat16Constant(0.0F);
  6751. one = builder.makeFloat16Constant(1.0F);
  6752. break;
  6753. case glslang::EOpConvBoolToInt8:
  6754. zero = builder.makeInt8Constant(0);
  6755. one = builder.makeInt8Constant(1);
  6756. convOp = spv::OpSelect;
  6757. break;
  6758. case glslang::EOpConvBoolToUint8:
  6759. zero = builder.makeUint8Constant(0);
  6760. one = builder.makeUint8Constant(1);
  6761. convOp = spv::OpSelect;
  6762. break;
  6763. case glslang::EOpConvBoolToInt16:
  6764. zero = builder.makeInt16Constant(0);
  6765. one = builder.makeInt16Constant(1);
  6766. convOp = spv::OpSelect;
  6767. break;
  6768. case glslang::EOpConvBoolToUint16:
  6769. zero = builder.makeUint16Constant(0);
  6770. one = builder.makeUint16Constant(1);
  6771. convOp = spv::OpSelect;
  6772. break;
  6773. case glslang::EOpConvDoubleToFloat:
  6774. case glslang::EOpConvFloatToDouble:
  6775. case glslang::EOpConvDoubleToFloat16:
  6776. case glslang::EOpConvFloat16ToDouble:
  6777. case glslang::EOpConvFloatToFloat16:
  6778. case glslang::EOpConvFloat16ToFloat:
  6779. convOp = spv::OpFConvert;
  6780. if (builder.isMatrixType(destType))
  6781. return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
  6782. break;
  6783. case glslang::EOpConvInt8ToInt16:
  6784. case glslang::EOpConvInt8ToInt:
  6785. case glslang::EOpConvInt8ToInt64:
  6786. case glslang::EOpConvInt16ToInt8:
  6787. case glslang::EOpConvInt16ToInt:
  6788. case glslang::EOpConvInt16ToInt64:
  6789. case glslang::EOpConvIntToInt8:
  6790. case glslang::EOpConvIntToInt16:
  6791. case glslang::EOpConvIntToInt64:
  6792. case glslang::EOpConvInt64ToInt8:
  6793. case glslang::EOpConvInt64ToInt16:
  6794. case glslang::EOpConvInt64ToInt:
  6795. convOp = spv::OpSConvert;
  6796. break;
  6797. case glslang::EOpConvUint8ToUint16:
  6798. case glslang::EOpConvUint8ToUint:
  6799. case glslang::EOpConvUint8ToUint64:
  6800. case glslang::EOpConvUint16ToUint8:
  6801. case glslang::EOpConvUint16ToUint:
  6802. case glslang::EOpConvUint16ToUint64:
  6803. case glslang::EOpConvUintToUint8:
  6804. case glslang::EOpConvUintToUint16:
  6805. case glslang::EOpConvUintToUint64:
  6806. case glslang::EOpConvUint64ToUint8:
  6807. case glslang::EOpConvUint64ToUint16:
  6808. case glslang::EOpConvUint64ToUint:
  6809. convOp = spv::OpUConvert;
  6810. break;
  6811. case glslang::EOpConvInt8ToUint16:
  6812. case glslang::EOpConvInt8ToUint:
  6813. case glslang::EOpConvInt8ToUint64:
  6814. case glslang::EOpConvInt16ToUint8:
  6815. case glslang::EOpConvInt16ToUint:
  6816. case glslang::EOpConvInt16ToUint64:
  6817. case glslang::EOpConvIntToUint8:
  6818. case glslang::EOpConvIntToUint16:
  6819. case glslang::EOpConvIntToUint64:
  6820. case glslang::EOpConvInt64ToUint8:
  6821. case glslang::EOpConvInt64ToUint16:
  6822. case glslang::EOpConvInt64ToUint:
  6823. case glslang::EOpConvUint8ToInt16:
  6824. case glslang::EOpConvUint8ToInt:
  6825. case glslang::EOpConvUint8ToInt64:
  6826. case glslang::EOpConvUint16ToInt8:
  6827. case glslang::EOpConvUint16ToInt:
  6828. case glslang::EOpConvUint16ToInt64:
  6829. case glslang::EOpConvUintToInt8:
  6830. case glslang::EOpConvUintToInt16:
  6831. case glslang::EOpConvUintToInt64:
  6832. case glslang::EOpConvUint64ToInt8:
  6833. case glslang::EOpConvUint64ToInt16:
  6834. case glslang::EOpConvUint64ToInt:
  6835. // OpSConvert/OpUConvert + OpBitCast
  6836. operand = createIntWidthConversion(op, operand, vectorSize, destType);
  6837. if (builder.isInSpecConstCodeGenMode()) {
  6838. // Build zero scalar or vector for OpIAdd.
  6839. switch(op) {
  6840. case glslang::EOpConvInt16ToUint8:
  6841. case glslang::EOpConvIntToUint8:
  6842. case glslang::EOpConvInt64ToUint8:
  6843. case glslang::EOpConvUint16ToInt8:
  6844. case glslang::EOpConvUintToInt8:
  6845. case glslang::EOpConvUint64ToInt8:
  6846. zero = builder.makeUint8Constant(0);
  6847. break;
  6848. case glslang::EOpConvInt8ToUint16:
  6849. case glslang::EOpConvIntToUint16:
  6850. case glslang::EOpConvInt64ToUint16:
  6851. case glslang::EOpConvUint8ToInt16:
  6852. case glslang::EOpConvUintToInt16:
  6853. case glslang::EOpConvUint64ToInt16:
  6854. zero = builder.makeUint16Constant(0);
  6855. break;
  6856. case glslang::EOpConvInt8ToUint:
  6857. case glslang::EOpConvInt16ToUint:
  6858. case glslang::EOpConvInt64ToUint:
  6859. case glslang::EOpConvUint8ToInt:
  6860. case glslang::EOpConvUint16ToInt:
  6861. case glslang::EOpConvUint64ToInt:
  6862. zero = builder.makeUintConstant(0);
  6863. break;
  6864. case glslang::EOpConvInt8ToUint64:
  6865. case glslang::EOpConvInt16ToUint64:
  6866. case glslang::EOpConvIntToUint64:
  6867. case glslang::EOpConvUint8ToInt64:
  6868. case glslang::EOpConvUint16ToInt64:
  6869. case glslang::EOpConvUintToInt64:
  6870. zero = builder.makeUint64Constant(0);
  6871. break;
  6872. default:
  6873. assert(false && "Default missing");
  6874. break;
  6875. }
  6876. zero = makeSmearedConstant(zero, vectorSize);
  6877. // Use OpIAdd, instead of OpBitcast to do the conversion when
  6878. // generating for OpSpecConstantOp instruction.
  6879. return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
  6880. }
  6881. // For normal run-time conversion instruction, use OpBitcast.
  6882. convOp = spv::OpBitcast;
  6883. break;
  6884. case glslang::EOpConvUint64ToPtr:
  6885. convOp = spv::OpConvertUToPtr;
  6886. break;
  6887. case glslang::EOpConvPtrToUint64:
  6888. convOp = spv::OpConvertPtrToU;
  6889. break;
  6890. case glslang::EOpConvPtrToUvec2:
  6891. case glslang::EOpConvUvec2ToPtr:
  6892. convOp = spv::OpBitcast;
  6893. break;
  6894. default:
  6895. break;
  6896. }
  6897. spv::Id result = 0;
  6898. if (convOp == spv::OpNop)
  6899. return result;
  6900. if (convOp == spv::OpSelect) {
  6901. zero = makeSmearedConstant(zero, vectorSize);
  6902. one = makeSmearedConstant(one, vectorSize);
  6903. result = builder.createTriOp(convOp, destType, operand, one, zero);
  6904. } else
  6905. result = builder.createUnaryOp(convOp, destType, operand);
  6906. result = builder.setPrecision(result, decorations.precision);
  6907. decorations.addNonUniform(builder, result);
  6908. return result;
  6909. }
  6910. spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
  6911. {
  6912. if (vectorSize == 0)
  6913. return constant;
  6914. spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
  6915. std::vector<spv::Id> components;
  6916. for (int c = 0; c < vectorSize; ++c)
  6917. components.push_back(constant);
  6918. return builder.makeCompositeConstant(vectorTypeId, components);
  6919. }
  6920. // For glslang ops that map to SPV atomic opCodes
  6921. spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/,
  6922. spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy,
  6923. const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
  6924. {
  6925. spv::Op opCode = spv::OpNop;
  6926. switch (op) {
  6927. case glslang::EOpAtomicAdd:
  6928. case glslang::EOpImageAtomicAdd:
  6929. case glslang::EOpAtomicCounterAdd:
  6930. opCode = spv::OpAtomicIAdd;
  6931. if (typeProxy == glslang::EbtFloat16 || typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
  6932. opCode = spv::OpAtomicFAddEXT;
  6933. builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_add);
  6934. if (typeProxy == glslang::EbtFloat16) {
  6935. builder.addExtension(spv::E_SPV_EXT_shader_atomic_float16_add);
  6936. builder.addCapability(spv::CapabilityAtomicFloat16AddEXT);
  6937. } else if (typeProxy == glslang::EbtFloat) {
  6938. builder.addCapability(spv::CapabilityAtomicFloat32AddEXT);
  6939. } else {
  6940. builder.addCapability(spv::CapabilityAtomicFloat64AddEXT);
  6941. }
  6942. }
  6943. break;
  6944. case glslang::EOpAtomicSubtract:
  6945. case glslang::EOpAtomicCounterSubtract:
  6946. opCode = spv::OpAtomicISub;
  6947. break;
  6948. case glslang::EOpAtomicMin:
  6949. case glslang::EOpImageAtomicMin:
  6950. case glslang::EOpAtomicCounterMin:
  6951. if (typeProxy == glslang::EbtFloat16 || typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
  6952. opCode = spv::OpAtomicFMinEXT;
  6953. builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_min_max);
  6954. if (typeProxy == glslang::EbtFloat16)
  6955. builder.addCapability(spv::CapabilityAtomicFloat16MinMaxEXT);
  6956. else if (typeProxy == glslang::EbtFloat)
  6957. builder.addCapability(spv::CapabilityAtomicFloat32MinMaxEXT);
  6958. else
  6959. builder.addCapability(spv::CapabilityAtomicFloat64MinMaxEXT);
  6960. } else if (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) {
  6961. opCode = spv::OpAtomicUMin;
  6962. } else {
  6963. opCode = spv::OpAtomicSMin;
  6964. }
  6965. break;
  6966. case glslang::EOpAtomicMax:
  6967. case glslang::EOpImageAtomicMax:
  6968. case glslang::EOpAtomicCounterMax:
  6969. if (typeProxy == glslang::EbtFloat16 || typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble) {
  6970. opCode = spv::OpAtomicFMaxEXT;
  6971. builder.addExtension(spv::E_SPV_EXT_shader_atomic_float_min_max);
  6972. if (typeProxy == glslang::EbtFloat16)
  6973. builder.addCapability(spv::CapabilityAtomicFloat16MinMaxEXT);
  6974. else if (typeProxy == glslang::EbtFloat)
  6975. builder.addCapability(spv::CapabilityAtomicFloat32MinMaxEXT);
  6976. else
  6977. builder.addCapability(spv::CapabilityAtomicFloat64MinMaxEXT);
  6978. } else if (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) {
  6979. opCode = spv::OpAtomicUMax;
  6980. } else {
  6981. opCode = spv::OpAtomicSMax;
  6982. }
  6983. break;
  6984. case glslang::EOpAtomicAnd:
  6985. case glslang::EOpImageAtomicAnd:
  6986. case glslang::EOpAtomicCounterAnd:
  6987. opCode = spv::OpAtomicAnd;
  6988. break;
  6989. case glslang::EOpAtomicOr:
  6990. case glslang::EOpImageAtomicOr:
  6991. case glslang::EOpAtomicCounterOr:
  6992. opCode = spv::OpAtomicOr;
  6993. break;
  6994. case glslang::EOpAtomicXor:
  6995. case glslang::EOpImageAtomicXor:
  6996. case glslang::EOpAtomicCounterXor:
  6997. opCode = spv::OpAtomicXor;
  6998. break;
  6999. case glslang::EOpAtomicExchange:
  7000. case glslang::EOpImageAtomicExchange:
  7001. case glslang::EOpAtomicCounterExchange:
  7002. opCode = spv::OpAtomicExchange;
  7003. break;
  7004. case glslang::EOpAtomicCompSwap:
  7005. case glslang::EOpImageAtomicCompSwap:
  7006. case glslang::EOpAtomicCounterCompSwap:
  7007. opCode = spv::OpAtomicCompareExchange;
  7008. break;
  7009. case glslang::EOpAtomicCounterIncrement:
  7010. opCode = spv::OpAtomicIIncrement;
  7011. break;
  7012. case glslang::EOpAtomicCounterDecrement:
  7013. opCode = spv::OpAtomicIDecrement;
  7014. break;
  7015. case glslang::EOpAtomicCounter:
  7016. case glslang::EOpImageAtomicLoad:
  7017. case glslang::EOpAtomicLoad:
  7018. opCode = spv::OpAtomicLoad;
  7019. break;
  7020. case glslang::EOpAtomicStore:
  7021. case glslang::EOpImageAtomicStore:
  7022. opCode = spv::OpAtomicStore;
  7023. break;
  7024. default:
  7025. assert(0);
  7026. break;
  7027. }
  7028. if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
  7029. builder.addCapability(spv::CapabilityInt64Atomics);
  7030. // Sort out the operands
  7031. // - mapping from glslang -> SPV
  7032. // - there are extra SPV operands that are optional in glslang
  7033. // - compare-exchange swaps the value and comparator
  7034. // - compare-exchange has an extra memory semantics
  7035. // - EOpAtomicCounterDecrement needs a post decrement
  7036. spv::Id pointerId = 0, compareId = 0, valueId = 0;
  7037. // scope defaults to Device in the old model, QueueFamilyKHR in the new model
  7038. spv::Id scopeId;
  7039. if (glslangIntermediate->usingVulkanMemoryModel()) {
  7040. scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
  7041. } else {
  7042. scopeId = builder.makeUintConstant(spv::ScopeDevice);
  7043. }
  7044. // semantics default to relaxed
  7045. spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.isVolatile() &&
  7046. glslangIntermediate->usingVulkanMemoryModel() ?
  7047. spv::MemorySemanticsVolatileMask :
  7048. spv::MemorySemanticsMaskNone);
  7049. spv::Id semanticsId2 = semanticsId;
  7050. pointerId = operands[0];
  7051. if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
  7052. // no additional operands
  7053. } else if (opCode == spv::OpAtomicCompareExchange) {
  7054. compareId = operands[1];
  7055. valueId = operands[2];
  7056. if (operands.size() > 3) {
  7057. scopeId = operands[3];
  7058. semanticsId = builder.makeUintConstant(
  7059. builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
  7060. semanticsId2 = builder.makeUintConstant(
  7061. builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
  7062. }
  7063. } else if (opCode == spv::OpAtomicLoad) {
  7064. if (operands.size() > 1) {
  7065. scopeId = operands[1];
  7066. semanticsId = builder.makeUintConstant(
  7067. builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
  7068. }
  7069. } else {
  7070. // atomic store or RMW
  7071. valueId = operands[1];
  7072. if (operands.size() > 2) {
  7073. scopeId = operands[2];
  7074. semanticsId = builder.makeUintConstant
  7075. (builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
  7076. }
  7077. }
  7078. // Check for capabilities
  7079. unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
  7080. if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
  7081. spv::MemorySemanticsMakeVisibleKHRMask |
  7082. spv::MemorySemanticsOutputMemoryKHRMask |
  7083. spv::MemorySemanticsVolatileMask)) {
  7084. builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
  7085. }
  7086. if (builder.getConstantScalar(scopeId) == spv::ScopeQueueFamily) {
  7087. builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
  7088. }
  7089. if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
  7090. builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
  7091. }
  7092. std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
  7093. spvAtomicOperands.push_back(pointerId);
  7094. spvAtomicOperands.push_back(scopeId);
  7095. spvAtomicOperands.push_back(semanticsId);
  7096. if (opCode == spv::OpAtomicCompareExchange) {
  7097. spvAtomicOperands.push_back(semanticsId2);
  7098. spvAtomicOperands.push_back(valueId);
  7099. spvAtomicOperands.push_back(compareId);
  7100. } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
  7101. spvAtomicOperands.push_back(valueId);
  7102. }
  7103. if (opCode == spv::OpAtomicStore) {
  7104. builder.createNoResultOp(opCode, spvAtomicOperands);
  7105. return 0;
  7106. } else {
  7107. spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
  7108. // GLSL and HLSL atomic-counter decrement return post-decrement value,
  7109. // while SPIR-V returns pre-decrement value. Translate between these semantics.
  7110. if (op == glslang::EOpAtomicCounterDecrement)
  7111. resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
  7112. return resultId;
  7113. }
  7114. }
  7115. // Create group invocation operations.
  7116. spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId,
  7117. std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
  7118. {
  7119. bool isUnsigned = isTypeUnsignedInt(typeProxy);
  7120. bool isFloat = isTypeFloat(typeProxy);
  7121. spv::Op opCode = spv::OpNop;
  7122. std::vector<spv::IdImmediate> spvGroupOperands;
  7123. spv::GroupOperation groupOperation = spv::GroupOperationMax;
  7124. if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
  7125. op == glslang::EOpReadInvocation) {
  7126. builder.addExtension(spv::E_SPV_KHR_shader_ballot);
  7127. builder.addCapability(spv::CapabilitySubgroupBallotKHR);
  7128. } else if (op == glslang::EOpAnyInvocation ||
  7129. op == glslang::EOpAllInvocations ||
  7130. op == glslang::EOpAllInvocationsEqual) {
  7131. builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
  7132. builder.addCapability(spv::CapabilitySubgroupVoteKHR);
  7133. } else {
  7134. builder.addCapability(spv::CapabilityGroups);
  7135. if (op == glslang::EOpMinInvocationsNonUniform ||
  7136. op == glslang::EOpMaxInvocationsNonUniform ||
  7137. op == glslang::EOpAddInvocationsNonUniform ||
  7138. op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
  7139. op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
  7140. op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
  7141. op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
  7142. op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
  7143. op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
  7144. builder.addExtension(spv::E_SPV_AMD_shader_ballot);
  7145. switch (op) {
  7146. case glslang::EOpMinInvocations:
  7147. case glslang::EOpMaxInvocations:
  7148. case glslang::EOpAddInvocations:
  7149. case glslang::EOpMinInvocationsNonUniform:
  7150. case glslang::EOpMaxInvocationsNonUniform:
  7151. case glslang::EOpAddInvocationsNonUniform:
  7152. groupOperation = spv::GroupOperationReduce;
  7153. break;
  7154. case glslang::EOpMinInvocationsInclusiveScan:
  7155. case glslang::EOpMaxInvocationsInclusiveScan:
  7156. case glslang::EOpAddInvocationsInclusiveScan:
  7157. case glslang::EOpMinInvocationsInclusiveScanNonUniform:
  7158. case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
  7159. case glslang::EOpAddInvocationsInclusiveScanNonUniform:
  7160. groupOperation = spv::GroupOperationInclusiveScan;
  7161. break;
  7162. case glslang::EOpMinInvocationsExclusiveScan:
  7163. case glslang::EOpMaxInvocationsExclusiveScan:
  7164. case glslang::EOpAddInvocationsExclusiveScan:
  7165. case glslang::EOpMinInvocationsExclusiveScanNonUniform:
  7166. case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
  7167. case glslang::EOpAddInvocationsExclusiveScanNonUniform:
  7168. groupOperation = spv::GroupOperationExclusiveScan;
  7169. break;
  7170. default:
  7171. break;
  7172. }
  7173. spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
  7174. spvGroupOperands.push_back(scope);
  7175. if (groupOperation != spv::GroupOperationMax) {
  7176. spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
  7177. spvGroupOperands.push_back(groupOp);
  7178. }
  7179. }
  7180. for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
  7181. spv::IdImmediate op = { true, *opIt };
  7182. spvGroupOperands.push_back(op);
  7183. }
  7184. switch (op) {
  7185. case glslang::EOpAnyInvocation:
  7186. opCode = spv::OpSubgroupAnyKHR;
  7187. break;
  7188. case glslang::EOpAllInvocations:
  7189. opCode = spv::OpSubgroupAllKHR;
  7190. break;
  7191. case glslang::EOpAllInvocationsEqual:
  7192. opCode = spv::OpSubgroupAllEqualKHR;
  7193. break;
  7194. case glslang::EOpReadInvocation:
  7195. opCode = spv::OpSubgroupReadInvocationKHR;
  7196. if (builder.isVectorType(typeId))
  7197. return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
  7198. break;
  7199. case glslang::EOpReadFirstInvocation:
  7200. opCode = spv::OpSubgroupFirstInvocationKHR;
  7201. if (builder.isVectorType(typeId))
  7202. return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
  7203. break;
  7204. case glslang::EOpBallot:
  7205. {
  7206. // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
  7207. // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
  7208. // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
  7209. //
  7210. // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
  7211. //
  7212. spv::Id uintType = builder.makeUintType(32);
  7213. spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
  7214. spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
  7215. std::vector<spv::Id> components;
  7216. components.push_back(builder.createCompositeExtract(result, uintType, 0));
  7217. components.push_back(builder.createCompositeExtract(result, uintType, 1));
  7218. spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
  7219. return builder.createUnaryOp(spv::OpBitcast, typeId,
  7220. builder.createCompositeConstruct(uvec2Type, components));
  7221. }
  7222. case glslang::EOpMinInvocations:
  7223. case glslang::EOpMaxInvocations:
  7224. case glslang::EOpAddInvocations:
  7225. case glslang::EOpMinInvocationsInclusiveScan:
  7226. case glslang::EOpMaxInvocationsInclusiveScan:
  7227. case glslang::EOpAddInvocationsInclusiveScan:
  7228. case glslang::EOpMinInvocationsExclusiveScan:
  7229. case glslang::EOpMaxInvocationsExclusiveScan:
  7230. case glslang::EOpAddInvocationsExclusiveScan:
  7231. if (op == glslang::EOpMinInvocations ||
  7232. op == glslang::EOpMinInvocationsInclusiveScan ||
  7233. op == glslang::EOpMinInvocationsExclusiveScan) {
  7234. if (isFloat)
  7235. opCode = spv::OpGroupFMin;
  7236. else {
  7237. if (isUnsigned)
  7238. opCode = spv::OpGroupUMin;
  7239. else
  7240. opCode = spv::OpGroupSMin;
  7241. }
  7242. } else if (op == glslang::EOpMaxInvocations ||
  7243. op == glslang::EOpMaxInvocationsInclusiveScan ||
  7244. op == glslang::EOpMaxInvocationsExclusiveScan) {
  7245. if (isFloat)
  7246. opCode = spv::OpGroupFMax;
  7247. else {
  7248. if (isUnsigned)
  7249. opCode = spv::OpGroupUMax;
  7250. else
  7251. opCode = spv::OpGroupSMax;
  7252. }
  7253. } else {
  7254. if (isFloat)
  7255. opCode = spv::OpGroupFAdd;
  7256. else
  7257. opCode = spv::OpGroupIAdd;
  7258. }
  7259. if (builder.isVectorType(typeId))
  7260. return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
  7261. break;
  7262. case glslang::EOpMinInvocationsNonUniform:
  7263. case glslang::EOpMaxInvocationsNonUniform:
  7264. case glslang::EOpAddInvocationsNonUniform:
  7265. case glslang::EOpMinInvocationsInclusiveScanNonUniform:
  7266. case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
  7267. case glslang::EOpAddInvocationsInclusiveScanNonUniform:
  7268. case glslang::EOpMinInvocationsExclusiveScanNonUniform:
  7269. case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
  7270. case glslang::EOpAddInvocationsExclusiveScanNonUniform:
  7271. if (op == glslang::EOpMinInvocationsNonUniform ||
  7272. op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
  7273. op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
  7274. if (isFloat)
  7275. opCode = spv::OpGroupFMinNonUniformAMD;
  7276. else {
  7277. if (isUnsigned)
  7278. opCode = spv::OpGroupUMinNonUniformAMD;
  7279. else
  7280. opCode = spv::OpGroupSMinNonUniformAMD;
  7281. }
  7282. }
  7283. else if (op == glslang::EOpMaxInvocationsNonUniform ||
  7284. op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
  7285. op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
  7286. if (isFloat)
  7287. opCode = spv::OpGroupFMaxNonUniformAMD;
  7288. else {
  7289. if (isUnsigned)
  7290. opCode = spv::OpGroupUMaxNonUniformAMD;
  7291. else
  7292. opCode = spv::OpGroupSMaxNonUniformAMD;
  7293. }
  7294. }
  7295. else {
  7296. if (isFloat)
  7297. opCode = spv::OpGroupFAddNonUniformAMD;
  7298. else
  7299. opCode = spv::OpGroupIAddNonUniformAMD;
  7300. }
  7301. if (builder.isVectorType(typeId))
  7302. return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
  7303. break;
  7304. default:
  7305. logger->missingFunctionality("invocation operation");
  7306. return spv::NoResult;
  7307. }
  7308. assert(opCode != spv::OpNop);
  7309. return builder.createOp(opCode, typeId, spvGroupOperands);
  7310. }
  7311. // Create group invocation operations on a vector
  7312. spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
  7313. spv::Id typeId, std::vector<spv::Id>& operands)
  7314. {
  7315. assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
  7316. op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
  7317. op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
  7318. op == spv::OpSubgroupReadInvocationKHR || op == spv::OpSubgroupFirstInvocationKHR ||
  7319. op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD ||
  7320. op == spv::OpGroupSMinNonUniformAMD ||
  7321. op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD ||
  7322. op == spv::OpGroupSMaxNonUniformAMD ||
  7323. op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
  7324. // Handle group invocation operations scalar by scalar.
  7325. // The result type is the same type as the original type.
  7326. // The algorithm is to:
  7327. // - break the vector into scalars
  7328. // - apply the operation to each scalar
  7329. // - make a vector out the scalar results
  7330. // get the types sorted out
  7331. int numComponents = builder.getNumComponents(operands[0]);
  7332. spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
  7333. std::vector<spv::Id> results;
  7334. // do each scalar op
  7335. for (int comp = 0; comp < numComponents; ++comp) {
  7336. std::vector<unsigned int> indexes;
  7337. indexes.push_back(comp);
  7338. spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
  7339. std::vector<spv::IdImmediate> spvGroupOperands;
  7340. if (op == spv::OpSubgroupReadInvocationKHR) {
  7341. spvGroupOperands.push_back(scalar);
  7342. spv::IdImmediate operand = { true, operands[1] };
  7343. spvGroupOperands.push_back(operand);
  7344. } else if (op == spv::OpSubgroupFirstInvocationKHR) {
  7345. spvGroupOperands.push_back(scalar);
  7346. } else if (op == spv::OpGroupBroadcast) {
  7347. spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
  7348. spvGroupOperands.push_back(scope);
  7349. spvGroupOperands.push_back(scalar);
  7350. spv::IdImmediate operand = { true, operands[1] };
  7351. spvGroupOperands.push_back(operand);
  7352. } else {
  7353. spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
  7354. spvGroupOperands.push_back(scope);
  7355. spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
  7356. spvGroupOperands.push_back(groupOp);
  7357. spvGroupOperands.push_back(scalar);
  7358. }
  7359. results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
  7360. }
  7361. // put the pieces together
  7362. return builder.createCompositeConstruct(typeId, results);
  7363. }
  7364. // Create subgroup invocation operations.
  7365. spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
  7366. std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
  7367. {
  7368. // Add the required capabilities.
  7369. switch (op) {
  7370. case glslang::EOpSubgroupElect:
  7371. builder.addCapability(spv::CapabilityGroupNonUniform);
  7372. break;
  7373. case glslang::EOpSubgroupAll:
  7374. case glslang::EOpSubgroupAny:
  7375. case glslang::EOpSubgroupAllEqual:
  7376. builder.addCapability(spv::CapabilityGroupNonUniform);
  7377. builder.addCapability(spv::CapabilityGroupNonUniformVote);
  7378. break;
  7379. case glslang::EOpSubgroupBroadcast:
  7380. case glslang::EOpSubgroupBroadcastFirst:
  7381. case glslang::EOpSubgroupBallot:
  7382. case glslang::EOpSubgroupInverseBallot:
  7383. case glslang::EOpSubgroupBallotBitExtract:
  7384. case glslang::EOpSubgroupBallotBitCount:
  7385. case glslang::EOpSubgroupBallotInclusiveBitCount:
  7386. case glslang::EOpSubgroupBallotExclusiveBitCount:
  7387. case glslang::EOpSubgroupBallotFindLSB:
  7388. case glslang::EOpSubgroupBallotFindMSB:
  7389. builder.addCapability(spv::CapabilityGroupNonUniform);
  7390. builder.addCapability(spv::CapabilityGroupNonUniformBallot);
  7391. break;
  7392. case glslang::EOpSubgroupShuffle:
  7393. case glslang::EOpSubgroupShuffleXor:
  7394. builder.addCapability(spv::CapabilityGroupNonUniform);
  7395. builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
  7396. break;
  7397. case glslang::EOpSubgroupShuffleUp:
  7398. case glslang::EOpSubgroupShuffleDown:
  7399. builder.addCapability(spv::CapabilityGroupNonUniform);
  7400. builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
  7401. break;
  7402. case glslang::EOpSubgroupAdd:
  7403. case glslang::EOpSubgroupMul:
  7404. case glslang::EOpSubgroupMin:
  7405. case glslang::EOpSubgroupMax:
  7406. case glslang::EOpSubgroupAnd:
  7407. case glslang::EOpSubgroupOr:
  7408. case glslang::EOpSubgroupXor:
  7409. case glslang::EOpSubgroupInclusiveAdd:
  7410. case glslang::EOpSubgroupInclusiveMul:
  7411. case glslang::EOpSubgroupInclusiveMin:
  7412. case glslang::EOpSubgroupInclusiveMax:
  7413. case glslang::EOpSubgroupInclusiveAnd:
  7414. case glslang::EOpSubgroupInclusiveOr:
  7415. case glslang::EOpSubgroupInclusiveXor:
  7416. case glslang::EOpSubgroupExclusiveAdd:
  7417. case glslang::EOpSubgroupExclusiveMul:
  7418. case glslang::EOpSubgroupExclusiveMin:
  7419. case glslang::EOpSubgroupExclusiveMax:
  7420. case glslang::EOpSubgroupExclusiveAnd:
  7421. case glslang::EOpSubgroupExclusiveOr:
  7422. case glslang::EOpSubgroupExclusiveXor:
  7423. builder.addCapability(spv::CapabilityGroupNonUniform);
  7424. builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
  7425. break;
  7426. case glslang::EOpSubgroupClusteredAdd:
  7427. case glslang::EOpSubgroupClusteredMul:
  7428. case glslang::EOpSubgroupClusteredMin:
  7429. case glslang::EOpSubgroupClusteredMax:
  7430. case glslang::EOpSubgroupClusteredAnd:
  7431. case glslang::EOpSubgroupClusteredOr:
  7432. case glslang::EOpSubgroupClusteredXor:
  7433. builder.addCapability(spv::CapabilityGroupNonUniform);
  7434. builder.addCapability(spv::CapabilityGroupNonUniformClustered);
  7435. break;
  7436. case glslang::EOpSubgroupQuadBroadcast:
  7437. case glslang::EOpSubgroupQuadSwapHorizontal:
  7438. case glslang::EOpSubgroupQuadSwapVertical:
  7439. case glslang::EOpSubgroupQuadSwapDiagonal:
  7440. builder.addCapability(spv::CapabilityGroupNonUniform);
  7441. builder.addCapability(spv::CapabilityGroupNonUniformQuad);
  7442. break;
  7443. case glslang::EOpSubgroupPartitionedAdd:
  7444. case glslang::EOpSubgroupPartitionedMul:
  7445. case glslang::EOpSubgroupPartitionedMin:
  7446. case glslang::EOpSubgroupPartitionedMax:
  7447. case glslang::EOpSubgroupPartitionedAnd:
  7448. case glslang::EOpSubgroupPartitionedOr:
  7449. case glslang::EOpSubgroupPartitionedXor:
  7450. case glslang::EOpSubgroupPartitionedInclusiveAdd:
  7451. case glslang::EOpSubgroupPartitionedInclusiveMul:
  7452. case glslang::EOpSubgroupPartitionedInclusiveMin:
  7453. case glslang::EOpSubgroupPartitionedInclusiveMax:
  7454. case glslang::EOpSubgroupPartitionedInclusiveAnd:
  7455. case glslang::EOpSubgroupPartitionedInclusiveOr:
  7456. case glslang::EOpSubgroupPartitionedInclusiveXor:
  7457. case glslang::EOpSubgroupPartitionedExclusiveAdd:
  7458. case glslang::EOpSubgroupPartitionedExclusiveMul:
  7459. case glslang::EOpSubgroupPartitionedExclusiveMin:
  7460. case glslang::EOpSubgroupPartitionedExclusiveMax:
  7461. case glslang::EOpSubgroupPartitionedExclusiveAnd:
  7462. case glslang::EOpSubgroupPartitionedExclusiveOr:
  7463. case glslang::EOpSubgroupPartitionedExclusiveXor:
  7464. builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
  7465. builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
  7466. break;
  7467. default: assert(0 && "Unhandled subgroup operation!");
  7468. }
  7469. const bool isUnsigned = isTypeUnsignedInt(typeProxy);
  7470. const bool isFloat = isTypeFloat(typeProxy);
  7471. const bool isBool = typeProxy == glslang::EbtBool;
  7472. spv::Op opCode = spv::OpNop;
  7473. // Figure out which opcode to use.
  7474. switch (op) {
  7475. case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
  7476. case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
  7477. case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
  7478. case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
  7479. case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
  7480. case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
  7481. case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
  7482. case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
  7483. case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
  7484. case glslang::EOpSubgroupBallotBitCount:
  7485. case glslang::EOpSubgroupBallotInclusiveBitCount:
  7486. case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
  7487. case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
  7488. case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
  7489. case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
  7490. case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
  7491. case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
  7492. case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
  7493. case glslang::EOpSubgroupAdd:
  7494. case glslang::EOpSubgroupInclusiveAdd:
  7495. case glslang::EOpSubgroupExclusiveAdd:
  7496. case glslang::EOpSubgroupClusteredAdd:
  7497. case glslang::EOpSubgroupPartitionedAdd:
  7498. case glslang::EOpSubgroupPartitionedInclusiveAdd:
  7499. case glslang::EOpSubgroupPartitionedExclusiveAdd:
  7500. if (isFloat) {
  7501. opCode = spv::OpGroupNonUniformFAdd;
  7502. } else {
  7503. opCode = spv::OpGroupNonUniformIAdd;
  7504. }
  7505. break;
  7506. case glslang::EOpSubgroupMul:
  7507. case glslang::EOpSubgroupInclusiveMul:
  7508. case glslang::EOpSubgroupExclusiveMul:
  7509. case glslang::EOpSubgroupClusteredMul:
  7510. case glslang::EOpSubgroupPartitionedMul:
  7511. case glslang::EOpSubgroupPartitionedInclusiveMul:
  7512. case glslang::EOpSubgroupPartitionedExclusiveMul:
  7513. if (isFloat) {
  7514. opCode = spv::OpGroupNonUniformFMul;
  7515. } else {
  7516. opCode = spv::OpGroupNonUniformIMul;
  7517. }
  7518. break;
  7519. case glslang::EOpSubgroupMin:
  7520. case glslang::EOpSubgroupInclusiveMin:
  7521. case glslang::EOpSubgroupExclusiveMin:
  7522. case glslang::EOpSubgroupClusteredMin:
  7523. case glslang::EOpSubgroupPartitionedMin:
  7524. case glslang::EOpSubgroupPartitionedInclusiveMin:
  7525. case glslang::EOpSubgroupPartitionedExclusiveMin:
  7526. if (isFloat) {
  7527. opCode = spv::OpGroupNonUniformFMin;
  7528. } else if (isUnsigned) {
  7529. opCode = spv::OpGroupNonUniformUMin;
  7530. } else {
  7531. opCode = spv::OpGroupNonUniformSMin;
  7532. }
  7533. break;
  7534. case glslang::EOpSubgroupMax:
  7535. case glslang::EOpSubgroupInclusiveMax:
  7536. case glslang::EOpSubgroupExclusiveMax:
  7537. case glslang::EOpSubgroupClusteredMax:
  7538. case glslang::EOpSubgroupPartitionedMax:
  7539. case glslang::EOpSubgroupPartitionedInclusiveMax:
  7540. case glslang::EOpSubgroupPartitionedExclusiveMax:
  7541. if (isFloat) {
  7542. opCode = spv::OpGroupNonUniformFMax;
  7543. } else if (isUnsigned) {
  7544. opCode = spv::OpGroupNonUniformUMax;
  7545. } else {
  7546. opCode = spv::OpGroupNonUniformSMax;
  7547. }
  7548. break;
  7549. case glslang::EOpSubgroupAnd:
  7550. case glslang::EOpSubgroupInclusiveAnd:
  7551. case glslang::EOpSubgroupExclusiveAnd:
  7552. case glslang::EOpSubgroupClusteredAnd:
  7553. case glslang::EOpSubgroupPartitionedAnd:
  7554. case glslang::EOpSubgroupPartitionedInclusiveAnd:
  7555. case glslang::EOpSubgroupPartitionedExclusiveAnd:
  7556. if (isBool) {
  7557. opCode = spv::OpGroupNonUniformLogicalAnd;
  7558. } else {
  7559. opCode = spv::OpGroupNonUniformBitwiseAnd;
  7560. }
  7561. break;
  7562. case glslang::EOpSubgroupOr:
  7563. case glslang::EOpSubgroupInclusiveOr:
  7564. case glslang::EOpSubgroupExclusiveOr:
  7565. case glslang::EOpSubgroupClusteredOr:
  7566. case glslang::EOpSubgroupPartitionedOr:
  7567. case glslang::EOpSubgroupPartitionedInclusiveOr:
  7568. case glslang::EOpSubgroupPartitionedExclusiveOr:
  7569. if (isBool) {
  7570. opCode = spv::OpGroupNonUniformLogicalOr;
  7571. } else {
  7572. opCode = spv::OpGroupNonUniformBitwiseOr;
  7573. }
  7574. break;
  7575. case glslang::EOpSubgroupXor:
  7576. case glslang::EOpSubgroupInclusiveXor:
  7577. case glslang::EOpSubgroupExclusiveXor:
  7578. case glslang::EOpSubgroupClusteredXor:
  7579. case glslang::EOpSubgroupPartitionedXor:
  7580. case glslang::EOpSubgroupPartitionedInclusiveXor:
  7581. case glslang::EOpSubgroupPartitionedExclusiveXor:
  7582. if (isBool) {
  7583. opCode = spv::OpGroupNonUniformLogicalXor;
  7584. } else {
  7585. opCode = spv::OpGroupNonUniformBitwiseXor;
  7586. }
  7587. break;
  7588. case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
  7589. case glslang::EOpSubgroupQuadSwapHorizontal:
  7590. case glslang::EOpSubgroupQuadSwapVertical:
  7591. case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
  7592. default: assert(0 && "Unhandled subgroup operation!");
  7593. }
  7594. // get the right Group Operation
  7595. spv::GroupOperation groupOperation = spv::GroupOperationMax;
  7596. switch (op) {
  7597. default:
  7598. break;
  7599. case glslang::EOpSubgroupBallotBitCount:
  7600. case glslang::EOpSubgroupAdd:
  7601. case glslang::EOpSubgroupMul:
  7602. case glslang::EOpSubgroupMin:
  7603. case glslang::EOpSubgroupMax:
  7604. case glslang::EOpSubgroupAnd:
  7605. case glslang::EOpSubgroupOr:
  7606. case glslang::EOpSubgroupXor:
  7607. groupOperation = spv::GroupOperationReduce;
  7608. break;
  7609. case glslang::EOpSubgroupBallotInclusiveBitCount:
  7610. case glslang::EOpSubgroupInclusiveAdd:
  7611. case glslang::EOpSubgroupInclusiveMul:
  7612. case glslang::EOpSubgroupInclusiveMin:
  7613. case glslang::EOpSubgroupInclusiveMax:
  7614. case glslang::EOpSubgroupInclusiveAnd:
  7615. case glslang::EOpSubgroupInclusiveOr:
  7616. case glslang::EOpSubgroupInclusiveXor:
  7617. groupOperation = spv::GroupOperationInclusiveScan;
  7618. break;
  7619. case glslang::EOpSubgroupBallotExclusiveBitCount:
  7620. case glslang::EOpSubgroupExclusiveAdd:
  7621. case glslang::EOpSubgroupExclusiveMul:
  7622. case glslang::EOpSubgroupExclusiveMin:
  7623. case glslang::EOpSubgroupExclusiveMax:
  7624. case glslang::EOpSubgroupExclusiveAnd:
  7625. case glslang::EOpSubgroupExclusiveOr:
  7626. case glslang::EOpSubgroupExclusiveXor:
  7627. groupOperation = spv::GroupOperationExclusiveScan;
  7628. break;
  7629. case glslang::EOpSubgroupClusteredAdd:
  7630. case glslang::EOpSubgroupClusteredMul:
  7631. case glslang::EOpSubgroupClusteredMin:
  7632. case glslang::EOpSubgroupClusteredMax:
  7633. case glslang::EOpSubgroupClusteredAnd:
  7634. case glslang::EOpSubgroupClusteredOr:
  7635. case glslang::EOpSubgroupClusteredXor:
  7636. groupOperation = spv::GroupOperationClusteredReduce;
  7637. break;
  7638. case glslang::EOpSubgroupPartitionedAdd:
  7639. case glslang::EOpSubgroupPartitionedMul:
  7640. case glslang::EOpSubgroupPartitionedMin:
  7641. case glslang::EOpSubgroupPartitionedMax:
  7642. case glslang::EOpSubgroupPartitionedAnd:
  7643. case glslang::EOpSubgroupPartitionedOr:
  7644. case glslang::EOpSubgroupPartitionedXor:
  7645. groupOperation = spv::GroupOperationPartitionedReduceNV;
  7646. break;
  7647. case glslang::EOpSubgroupPartitionedInclusiveAdd:
  7648. case glslang::EOpSubgroupPartitionedInclusiveMul:
  7649. case glslang::EOpSubgroupPartitionedInclusiveMin:
  7650. case glslang::EOpSubgroupPartitionedInclusiveMax:
  7651. case glslang::EOpSubgroupPartitionedInclusiveAnd:
  7652. case glslang::EOpSubgroupPartitionedInclusiveOr:
  7653. case glslang::EOpSubgroupPartitionedInclusiveXor:
  7654. groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
  7655. break;
  7656. case glslang::EOpSubgroupPartitionedExclusiveAdd:
  7657. case glslang::EOpSubgroupPartitionedExclusiveMul:
  7658. case glslang::EOpSubgroupPartitionedExclusiveMin:
  7659. case glslang::EOpSubgroupPartitionedExclusiveMax:
  7660. case glslang::EOpSubgroupPartitionedExclusiveAnd:
  7661. case glslang::EOpSubgroupPartitionedExclusiveOr:
  7662. case glslang::EOpSubgroupPartitionedExclusiveXor:
  7663. groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
  7664. break;
  7665. }
  7666. // build the instruction
  7667. std::vector<spv::IdImmediate> spvGroupOperands;
  7668. // Every operation begins with the Execution Scope operand.
  7669. spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
  7670. spvGroupOperands.push_back(executionScope);
  7671. // Next, for all operations that use a Group Operation, push that as an operand.
  7672. if (groupOperation != spv::GroupOperationMax) {
  7673. spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
  7674. spvGroupOperands.push_back(groupOperand);
  7675. }
  7676. // Push back the operands next.
  7677. for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
  7678. spv::IdImmediate operand = { true, *opIt };
  7679. spvGroupOperands.push_back(operand);
  7680. }
  7681. // Some opcodes have additional operands.
  7682. spv::Id directionId = spv::NoResult;
  7683. switch (op) {
  7684. default: break;
  7685. case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
  7686. case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
  7687. case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
  7688. }
  7689. if (directionId != spv::NoResult) {
  7690. spv::IdImmediate direction = { true, directionId };
  7691. spvGroupOperands.push_back(direction);
  7692. }
  7693. return builder.createOp(opCode, typeId, spvGroupOperands);
  7694. }
  7695. spv::Id TGlslangToSpvTraverser::createMiscOperation(glslang::TOperator op, spv::Decoration precision,
  7696. spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
  7697. {
  7698. bool isUnsigned = isTypeUnsignedInt(typeProxy);
  7699. bool isFloat = isTypeFloat(typeProxy);
  7700. spv::Op opCode = spv::OpNop;
  7701. int extBuiltins = -1;
  7702. int libCall = -1;
  7703. size_t consumedOperands = operands.size();
  7704. spv::Id typeId0 = 0;
  7705. if (consumedOperands > 0)
  7706. typeId0 = builder.getTypeId(operands[0]);
  7707. spv::Id typeId1 = 0;
  7708. if (consumedOperands > 1)
  7709. typeId1 = builder.getTypeId(operands[1]);
  7710. spv::Id frexpIntType = 0;
  7711. switch (op) {
  7712. case glslang::EOpMin:
  7713. if (isFloat)
  7714. libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
  7715. else if (isUnsigned)
  7716. libCall = spv::GLSLstd450UMin;
  7717. else
  7718. libCall = spv::GLSLstd450SMin;
  7719. builder.promoteScalar(precision, operands.front(), operands.back());
  7720. break;
  7721. case glslang::EOpModf:
  7722. libCall = spv::GLSLstd450Modf;
  7723. break;
  7724. case glslang::EOpMax:
  7725. if (isFloat)
  7726. libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
  7727. else if (isUnsigned)
  7728. libCall = spv::GLSLstd450UMax;
  7729. else
  7730. libCall = spv::GLSLstd450SMax;
  7731. builder.promoteScalar(precision, operands.front(), operands.back());
  7732. break;
  7733. case glslang::EOpPow:
  7734. libCall = spv::GLSLstd450Pow;
  7735. break;
  7736. case glslang::EOpDot:
  7737. opCode = spv::OpDot;
  7738. break;
  7739. case glslang::EOpAtan:
  7740. libCall = spv::GLSLstd450Atan2;
  7741. break;
  7742. case glslang::EOpClamp:
  7743. if (isFloat)
  7744. libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
  7745. else if (isUnsigned)
  7746. libCall = spv::GLSLstd450UClamp;
  7747. else
  7748. libCall = spv::GLSLstd450SClamp;
  7749. builder.promoteScalar(precision, operands.front(), operands[1]);
  7750. builder.promoteScalar(precision, operands.front(), operands[2]);
  7751. break;
  7752. case glslang::EOpMix:
  7753. if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
  7754. assert(isFloat);
  7755. libCall = spv::GLSLstd450FMix;
  7756. } else {
  7757. opCode = spv::OpSelect;
  7758. std::swap(operands.front(), operands.back());
  7759. }
  7760. builder.promoteScalar(precision, operands.front(), operands.back());
  7761. break;
  7762. case glslang::EOpStep:
  7763. libCall = spv::GLSLstd450Step;
  7764. builder.promoteScalar(precision, operands.front(), operands.back());
  7765. break;
  7766. case glslang::EOpSmoothStep:
  7767. libCall = spv::GLSLstd450SmoothStep;
  7768. builder.promoteScalar(precision, operands[0], operands[2]);
  7769. builder.promoteScalar(precision, operands[1], operands[2]);
  7770. break;
  7771. case glslang::EOpDistance:
  7772. libCall = spv::GLSLstd450Distance;
  7773. break;
  7774. case glslang::EOpCross:
  7775. libCall = spv::GLSLstd450Cross;
  7776. break;
  7777. case glslang::EOpFaceForward:
  7778. libCall = spv::GLSLstd450FaceForward;
  7779. break;
  7780. case glslang::EOpReflect:
  7781. libCall = spv::GLSLstd450Reflect;
  7782. break;
  7783. case glslang::EOpRefract:
  7784. libCall = spv::GLSLstd450Refract;
  7785. break;
  7786. case glslang::EOpBarrier:
  7787. {
  7788. // This is for the extended controlBarrier function, with four operands.
  7789. // The unextended barrier() goes through createNoArgOperation.
  7790. assert(operands.size() == 4);
  7791. unsigned int executionScope = builder.getConstantScalar(operands[0]);
  7792. unsigned int memoryScope = builder.getConstantScalar(operands[1]);
  7793. unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
  7794. builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope,
  7795. (spv::MemorySemanticsMask)semantics);
  7796. if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
  7797. spv::MemorySemanticsMakeVisibleKHRMask |
  7798. spv::MemorySemanticsOutputMemoryKHRMask |
  7799. spv::MemorySemanticsVolatileMask)) {
  7800. builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
  7801. }
  7802. if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice ||
  7803. memoryScope == spv::ScopeDevice)) {
  7804. builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
  7805. }
  7806. return 0;
  7807. }
  7808. break;
  7809. case glslang::EOpMemoryBarrier:
  7810. {
  7811. // This is for the extended memoryBarrier function, with three operands.
  7812. // The unextended memoryBarrier() goes through createNoArgOperation.
  7813. assert(operands.size() == 3);
  7814. unsigned int memoryScope = builder.getConstantScalar(operands[0]);
  7815. unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
  7816. builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
  7817. if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
  7818. spv::MemorySemanticsMakeVisibleKHRMask |
  7819. spv::MemorySemanticsOutputMemoryKHRMask |
  7820. spv::MemorySemanticsVolatileMask)) {
  7821. builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
  7822. }
  7823. if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
  7824. builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
  7825. }
  7826. return 0;
  7827. }
  7828. break;
  7829. case glslang::EOpInterpolateAtSample:
  7830. if (typeProxy == glslang::EbtFloat16)
  7831. builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
  7832. libCall = spv::GLSLstd450InterpolateAtSample;
  7833. break;
  7834. case glslang::EOpInterpolateAtOffset:
  7835. if (typeProxy == glslang::EbtFloat16)
  7836. builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
  7837. libCall = spv::GLSLstd450InterpolateAtOffset;
  7838. break;
  7839. case glslang::EOpAddCarry:
  7840. opCode = spv::OpIAddCarry;
  7841. typeId = builder.makeStructResultType(typeId0, typeId0);
  7842. consumedOperands = 2;
  7843. break;
  7844. case glslang::EOpSubBorrow:
  7845. opCode = spv::OpISubBorrow;
  7846. typeId = builder.makeStructResultType(typeId0, typeId0);
  7847. consumedOperands = 2;
  7848. break;
  7849. case glslang::EOpUMulExtended:
  7850. opCode = spv::OpUMulExtended;
  7851. typeId = builder.makeStructResultType(typeId0, typeId0);
  7852. consumedOperands = 2;
  7853. break;
  7854. case glslang::EOpIMulExtended:
  7855. opCode = spv::OpSMulExtended;
  7856. typeId = builder.makeStructResultType(typeId0, typeId0);
  7857. consumedOperands = 2;
  7858. break;
  7859. case glslang::EOpBitfieldExtract:
  7860. if (isUnsigned)
  7861. opCode = spv::OpBitFieldUExtract;
  7862. else
  7863. opCode = spv::OpBitFieldSExtract;
  7864. break;
  7865. case glslang::EOpBitfieldInsert:
  7866. opCode = spv::OpBitFieldInsert;
  7867. break;
  7868. case glslang::EOpFma:
  7869. libCall = spv::GLSLstd450Fma;
  7870. break;
  7871. case glslang::EOpFrexp:
  7872. {
  7873. libCall = spv::GLSLstd450FrexpStruct;
  7874. assert(builder.isPointerType(typeId1));
  7875. typeId1 = builder.getContainedTypeId(typeId1);
  7876. int width = builder.getScalarTypeWidth(typeId1);
  7877. if (width == 16)
  7878. // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
  7879. builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
  7880. if (builder.getNumComponents(operands[0]) == 1)
  7881. frexpIntType = builder.makeIntegerType(width, true);
  7882. else
  7883. frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true),
  7884. builder.getNumComponents(operands[0]));
  7885. typeId = builder.makeStructResultType(typeId0, frexpIntType);
  7886. consumedOperands = 1;
  7887. }
  7888. break;
  7889. case glslang::EOpLdexp:
  7890. libCall = spv::GLSLstd450Ldexp;
  7891. break;
  7892. case glslang::EOpReadInvocation:
  7893. return createInvocationsOperation(op, typeId, operands, typeProxy);
  7894. case glslang::EOpSubgroupBroadcast:
  7895. case glslang::EOpSubgroupBallotBitExtract:
  7896. case glslang::EOpSubgroupShuffle:
  7897. case glslang::EOpSubgroupShuffleXor:
  7898. case glslang::EOpSubgroupShuffleUp:
  7899. case glslang::EOpSubgroupShuffleDown:
  7900. case glslang::EOpSubgroupClusteredAdd:
  7901. case glslang::EOpSubgroupClusteredMul:
  7902. case glslang::EOpSubgroupClusteredMin:
  7903. case glslang::EOpSubgroupClusteredMax:
  7904. case glslang::EOpSubgroupClusteredAnd:
  7905. case glslang::EOpSubgroupClusteredOr:
  7906. case glslang::EOpSubgroupClusteredXor:
  7907. case glslang::EOpSubgroupQuadBroadcast:
  7908. case glslang::EOpSubgroupPartitionedAdd:
  7909. case glslang::EOpSubgroupPartitionedMul:
  7910. case glslang::EOpSubgroupPartitionedMin:
  7911. case glslang::EOpSubgroupPartitionedMax:
  7912. case glslang::EOpSubgroupPartitionedAnd:
  7913. case glslang::EOpSubgroupPartitionedOr:
  7914. case glslang::EOpSubgroupPartitionedXor:
  7915. case glslang::EOpSubgroupPartitionedInclusiveAdd:
  7916. case glslang::EOpSubgroupPartitionedInclusiveMul:
  7917. case glslang::EOpSubgroupPartitionedInclusiveMin:
  7918. case glslang::EOpSubgroupPartitionedInclusiveMax:
  7919. case glslang::EOpSubgroupPartitionedInclusiveAnd:
  7920. case glslang::EOpSubgroupPartitionedInclusiveOr:
  7921. case glslang::EOpSubgroupPartitionedInclusiveXor:
  7922. case glslang::EOpSubgroupPartitionedExclusiveAdd:
  7923. case glslang::EOpSubgroupPartitionedExclusiveMul:
  7924. case glslang::EOpSubgroupPartitionedExclusiveMin:
  7925. case glslang::EOpSubgroupPartitionedExclusiveMax:
  7926. case glslang::EOpSubgroupPartitionedExclusiveAnd:
  7927. case glslang::EOpSubgroupPartitionedExclusiveOr:
  7928. case glslang::EOpSubgroupPartitionedExclusiveXor:
  7929. return createSubgroupOperation(op, typeId, operands, typeProxy);
  7930. case glslang::EOpSwizzleInvocations:
  7931. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
  7932. libCall = spv::SwizzleInvocationsAMD;
  7933. break;
  7934. case glslang::EOpSwizzleInvocationsMasked:
  7935. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
  7936. libCall = spv::SwizzleInvocationsMaskedAMD;
  7937. break;
  7938. case glslang::EOpWriteInvocation:
  7939. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
  7940. libCall = spv::WriteInvocationAMD;
  7941. break;
  7942. case glslang::EOpMin3:
  7943. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
  7944. if (isFloat)
  7945. libCall = spv::FMin3AMD;
  7946. else {
  7947. if (isUnsigned)
  7948. libCall = spv::UMin3AMD;
  7949. else
  7950. libCall = spv::SMin3AMD;
  7951. }
  7952. break;
  7953. case glslang::EOpMax3:
  7954. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
  7955. if (isFloat)
  7956. libCall = spv::FMax3AMD;
  7957. else {
  7958. if (isUnsigned)
  7959. libCall = spv::UMax3AMD;
  7960. else
  7961. libCall = spv::SMax3AMD;
  7962. }
  7963. break;
  7964. case glslang::EOpMid3:
  7965. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
  7966. if (isFloat)
  7967. libCall = spv::FMid3AMD;
  7968. else {
  7969. if (isUnsigned)
  7970. libCall = spv::UMid3AMD;
  7971. else
  7972. libCall = spv::SMid3AMD;
  7973. }
  7974. break;
  7975. case glslang::EOpInterpolateAtVertex:
  7976. if (typeProxy == glslang::EbtFloat16)
  7977. builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
  7978. extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
  7979. libCall = spv::InterpolateAtVertexAMD;
  7980. break;
  7981. case glslang::EOpReportIntersection:
  7982. typeId = builder.makeBoolType();
  7983. opCode = spv::OpReportIntersectionKHR;
  7984. break;
  7985. case glslang::EOpTraceNV:
  7986. builder.createNoResultOp(spv::OpTraceNV, operands);
  7987. return 0;
  7988. case glslang::EOpTraceRayMotionNV:
  7989. builder.addExtension(spv::E_SPV_NV_ray_tracing_motion_blur);
  7990. builder.addCapability(spv::CapabilityRayTracingMotionBlurNV);
  7991. builder.createNoResultOp(spv::OpTraceRayMotionNV, operands);
  7992. return 0;
  7993. case glslang::EOpTraceKHR:
  7994. builder.createNoResultOp(spv::OpTraceRayKHR, operands);
  7995. return 0;
  7996. case glslang::EOpExecuteCallableNV:
  7997. builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
  7998. return 0;
  7999. case glslang::EOpExecuteCallableKHR:
  8000. builder.createNoResultOp(spv::OpExecuteCallableKHR, operands);
  8001. return 0;
  8002. case glslang::EOpRayQueryInitialize:
  8003. builder.createNoResultOp(spv::OpRayQueryInitializeKHR, operands);
  8004. return 0;
  8005. case glslang::EOpRayQueryTerminate:
  8006. builder.createNoResultOp(spv::OpRayQueryTerminateKHR, operands);
  8007. return 0;
  8008. case glslang::EOpRayQueryGenerateIntersection:
  8009. builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR, operands);
  8010. return 0;
  8011. case glslang::EOpRayQueryConfirmIntersection:
  8012. builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR, operands);
  8013. return 0;
  8014. case glslang::EOpRayQueryProceed:
  8015. typeId = builder.makeBoolType();
  8016. opCode = spv::OpRayQueryProceedKHR;
  8017. break;
  8018. case glslang::EOpRayQueryGetIntersectionType:
  8019. typeId = builder.makeUintType(32);
  8020. opCode = spv::OpRayQueryGetIntersectionTypeKHR;
  8021. break;
  8022. case glslang::EOpRayQueryGetRayTMin:
  8023. typeId = builder.makeFloatType(32);
  8024. opCode = spv::OpRayQueryGetRayTMinKHR;
  8025. break;
  8026. case glslang::EOpRayQueryGetRayFlags:
  8027. typeId = builder.makeIntType(32);
  8028. opCode = spv::OpRayQueryGetRayFlagsKHR;
  8029. break;
  8030. case glslang::EOpRayQueryGetIntersectionT:
  8031. typeId = builder.makeFloatType(32);
  8032. opCode = spv::OpRayQueryGetIntersectionTKHR;
  8033. break;
  8034. case glslang::EOpRayQueryGetIntersectionInstanceCustomIndex:
  8035. typeId = builder.makeIntType(32);
  8036. opCode = spv::OpRayQueryGetIntersectionInstanceCustomIndexKHR;
  8037. break;
  8038. case glslang::EOpRayQueryGetIntersectionInstanceId:
  8039. typeId = builder.makeIntType(32);
  8040. opCode = spv::OpRayQueryGetIntersectionInstanceIdKHR;
  8041. break;
  8042. case glslang::EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
  8043. typeId = builder.makeUintType(32);
  8044. opCode = spv::OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR;
  8045. break;
  8046. case glslang::EOpRayQueryGetIntersectionGeometryIndex:
  8047. typeId = builder.makeIntType(32);
  8048. opCode = spv::OpRayQueryGetIntersectionGeometryIndexKHR;
  8049. break;
  8050. case glslang::EOpRayQueryGetIntersectionPrimitiveIndex:
  8051. typeId = builder.makeIntType(32);
  8052. opCode = spv::OpRayQueryGetIntersectionPrimitiveIndexKHR;
  8053. break;
  8054. case glslang::EOpRayQueryGetIntersectionBarycentrics:
  8055. typeId = builder.makeVectorType(builder.makeFloatType(32), 2);
  8056. opCode = spv::OpRayQueryGetIntersectionBarycentricsKHR;
  8057. break;
  8058. case glslang::EOpRayQueryGetIntersectionFrontFace:
  8059. typeId = builder.makeBoolType();
  8060. opCode = spv::OpRayQueryGetIntersectionFrontFaceKHR;
  8061. break;
  8062. case glslang::EOpRayQueryGetIntersectionCandidateAABBOpaque:
  8063. typeId = builder.makeBoolType();
  8064. opCode = spv::OpRayQueryGetIntersectionCandidateAABBOpaqueKHR;
  8065. break;
  8066. case glslang::EOpRayQueryGetIntersectionObjectRayDirection:
  8067. typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
  8068. opCode = spv::OpRayQueryGetIntersectionObjectRayDirectionKHR;
  8069. break;
  8070. case glslang::EOpRayQueryGetIntersectionObjectRayOrigin:
  8071. typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
  8072. opCode = spv::OpRayQueryGetIntersectionObjectRayOriginKHR;
  8073. break;
  8074. case glslang::EOpRayQueryGetWorldRayDirection:
  8075. typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
  8076. opCode = spv::OpRayQueryGetWorldRayDirectionKHR;
  8077. break;
  8078. case glslang::EOpRayQueryGetWorldRayOrigin:
  8079. typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
  8080. opCode = spv::OpRayQueryGetWorldRayOriginKHR;
  8081. break;
  8082. case glslang::EOpRayQueryGetIntersectionObjectToWorld:
  8083. typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
  8084. opCode = spv::OpRayQueryGetIntersectionObjectToWorldKHR;
  8085. break;
  8086. case glslang::EOpRayQueryGetIntersectionWorldToObject:
  8087. typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
  8088. opCode = spv::OpRayQueryGetIntersectionWorldToObjectKHR;
  8089. break;
  8090. case glslang::EOpWritePackedPrimitiveIndices4x8NV:
  8091. builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
  8092. return 0;
  8093. case glslang::EOpEmitMeshTasksEXT:
  8094. if (taskPayloadID)
  8095. operands.push_back(taskPayloadID);
  8096. // As per SPV_EXT_mesh_shader make it a terminating instruction in the current block
  8097. builder.makeStatementTerminator(spv::OpEmitMeshTasksEXT, operands, "post-OpEmitMeshTasksEXT");
  8098. return 0;
  8099. case glslang::EOpSetMeshOutputsEXT:
  8100. builder.createNoResultOp(spv::OpSetMeshOutputsEXT, operands);
  8101. return 0;
  8102. case glslang::EOpCooperativeMatrixMulAddNV:
  8103. opCode = spv::OpCooperativeMatrixMulAddNV;
  8104. break;
  8105. case glslang::EOpHitObjectTraceRayNV:
  8106. builder.createNoResultOp(spv::OpHitObjectTraceRayNV, operands);
  8107. return 0;
  8108. case glslang::EOpHitObjectTraceRayMotionNV:
  8109. builder.createNoResultOp(spv::OpHitObjectTraceRayMotionNV, operands);
  8110. return 0;
  8111. case glslang::EOpHitObjectRecordHitNV:
  8112. builder.createNoResultOp(spv::OpHitObjectRecordHitNV, operands);
  8113. return 0;
  8114. case glslang::EOpHitObjectRecordHitMotionNV:
  8115. builder.createNoResultOp(spv::OpHitObjectRecordHitMotionNV, operands);
  8116. return 0;
  8117. case glslang::EOpHitObjectRecordHitWithIndexNV:
  8118. builder.createNoResultOp(spv::OpHitObjectRecordHitWithIndexNV, operands);
  8119. return 0;
  8120. case glslang::EOpHitObjectRecordHitWithIndexMotionNV:
  8121. builder.createNoResultOp(spv::OpHitObjectRecordHitWithIndexMotionNV, operands);
  8122. return 0;
  8123. case glslang::EOpHitObjectRecordMissNV:
  8124. builder.createNoResultOp(spv::OpHitObjectRecordMissNV, operands);
  8125. return 0;
  8126. case glslang::EOpHitObjectRecordMissMotionNV:
  8127. builder.createNoResultOp(spv::OpHitObjectRecordMissMotionNV, operands);
  8128. return 0;
  8129. case glslang::EOpHitObjectExecuteShaderNV:
  8130. builder.createNoResultOp(spv::OpHitObjectExecuteShaderNV, operands);
  8131. return 0;
  8132. case glslang::EOpHitObjectIsEmptyNV:
  8133. typeId = builder.makeBoolType();
  8134. opCode = spv::OpHitObjectIsEmptyNV;
  8135. break;
  8136. case glslang::EOpHitObjectIsMissNV:
  8137. typeId = builder.makeBoolType();
  8138. opCode = spv::OpHitObjectIsMissNV;
  8139. break;
  8140. case glslang::EOpHitObjectIsHitNV:
  8141. typeId = builder.makeBoolType();
  8142. opCode = spv::OpHitObjectIsHitNV;
  8143. break;
  8144. case glslang::EOpHitObjectGetRayTMinNV:
  8145. typeId = builder.makeFloatType(32);
  8146. opCode = spv::OpHitObjectGetRayTMinNV;
  8147. break;
  8148. case glslang::EOpHitObjectGetRayTMaxNV:
  8149. typeId = builder.makeFloatType(32);
  8150. opCode = spv::OpHitObjectGetRayTMaxNV;
  8151. break;
  8152. case glslang::EOpHitObjectGetObjectRayOriginNV:
  8153. typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
  8154. opCode = spv::OpHitObjectGetObjectRayOriginNV;
  8155. break;
  8156. case glslang::EOpHitObjectGetObjectRayDirectionNV:
  8157. typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
  8158. opCode = spv::OpHitObjectGetObjectRayDirectionNV;
  8159. break;
  8160. case glslang::EOpHitObjectGetWorldRayOriginNV:
  8161. typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
  8162. opCode = spv::OpHitObjectGetWorldRayOriginNV;
  8163. break;
  8164. case glslang::EOpHitObjectGetWorldRayDirectionNV:
  8165. typeId = builder.makeVectorType(builder.makeFloatType(32), 3);
  8166. opCode = spv::OpHitObjectGetWorldRayDirectionNV;
  8167. break;
  8168. case glslang::EOpHitObjectGetWorldToObjectNV:
  8169. typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
  8170. opCode = spv::OpHitObjectGetWorldToObjectNV;
  8171. break;
  8172. case glslang::EOpHitObjectGetObjectToWorldNV:
  8173. typeId = builder.makeMatrixType(builder.makeFloatType(32), 4, 3);
  8174. opCode = spv::OpHitObjectGetObjectToWorldNV;
  8175. break;
  8176. case glslang::EOpHitObjectGetInstanceCustomIndexNV:
  8177. typeId = builder.makeIntegerType(32, 1);
  8178. opCode = spv::OpHitObjectGetInstanceCustomIndexNV;
  8179. break;
  8180. case glslang::EOpHitObjectGetInstanceIdNV:
  8181. typeId = builder.makeIntegerType(32, 1);
  8182. opCode = spv::OpHitObjectGetInstanceIdNV;
  8183. break;
  8184. case glslang::EOpHitObjectGetGeometryIndexNV:
  8185. typeId = builder.makeIntegerType(32, 1);
  8186. opCode = spv::OpHitObjectGetGeometryIndexNV;
  8187. break;
  8188. case glslang::EOpHitObjectGetPrimitiveIndexNV:
  8189. typeId = builder.makeIntegerType(32, 1);
  8190. opCode = spv::OpHitObjectGetPrimitiveIndexNV;
  8191. break;
  8192. case glslang::EOpHitObjectGetHitKindNV:
  8193. typeId = builder.makeIntegerType(32, 0);
  8194. opCode = spv::OpHitObjectGetHitKindNV;
  8195. break;
  8196. case glslang::EOpHitObjectGetCurrentTimeNV:
  8197. typeId = builder.makeFloatType(32);
  8198. opCode = spv::OpHitObjectGetCurrentTimeNV;
  8199. break;
  8200. case glslang::EOpHitObjectGetShaderBindingTableRecordIndexNV:
  8201. typeId = builder.makeIntegerType(32, 0);
  8202. opCode = spv::OpHitObjectGetShaderBindingTableRecordIndexNV;
  8203. return 0;
  8204. case glslang::EOpHitObjectGetAttributesNV:
  8205. builder.createNoResultOp(spv::OpHitObjectGetAttributesNV, operands);
  8206. return 0;
  8207. case glslang::EOpHitObjectGetShaderRecordBufferHandleNV:
  8208. typeId = builder.makeVectorType(builder.makeUintType(32), 2);
  8209. opCode = spv::OpHitObjectGetShaderRecordBufferHandleNV;
  8210. break;
  8211. case glslang::EOpReorderThreadNV: {
  8212. if (operands.size() == 2) {
  8213. builder.createNoResultOp(spv::OpReorderThreadWithHintNV, operands);
  8214. } else {
  8215. builder.createNoResultOp(spv::OpReorderThreadWithHitObjectNV, operands);
  8216. }
  8217. return 0;
  8218. }
  8219. break;
  8220. default:
  8221. return 0;
  8222. }
  8223. spv::Id id = 0;
  8224. if (libCall >= 0) {
  8225. // Use an extended instruction from the standard library.
  8226. // Construct the call arguments, without modifying the original operands vector.
  8227. // We might need the remaining arguments, e.g. in the EOpFrexp case.
  8228. std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
  8229. id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
  8230. } else if (opCode == spv::OpDot && !isFloat) {
  8231. // int dot(int, int)
  8232. // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
  8233. const int componentCount = builder.getNumComponents(operands[0]);
  8234. spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
  8235. builder.setPrecision(mulOp, precision);
  8236. id = builder.createCompositeExtract(mulOp, typeId, 0);
  8237. for (int i = 1; i < componentCount; ++i) {
  8238. builder.setPrecision(id, precision);
  8239. id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(mulOp, typeId, i));
  8240. }
  8241. } else {
  8242. switch (consumedOperands) {
  8243. case 0:
  8244. // should all be handled by visitAggregate and createNoArgOperation
  8245. assert(0);
  8246. return 0;
  8247. case 1:
  8248. // should all be handled by createUnaryOperation
  8249. assert(0);
  8250. return 0;
  8251. case 2:
  8252. id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
  8253. break;
  8254. default:
  8255. // anything 3 or over doesn't have l-value operands, so all should be consumed
  8256. assert(consumedOperands == operands.size());
  8257. id = builder.createOp(opCode, typeId, operands);
  8258. break;
  8259. }
  8260. }
  8261. // Decode the return types that were structures
  8262. switch (op) {
  8263. case glslang::EOpAddCarry:
  8264. case glslang::EOpSubBorrow:
  8265. builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
  8266. id = builder.createCompositeExtract(id, typeId0, 0);
  8267. break;
  8268. case glslang::EOpUMulExtended:
  8269. case glslang::EOpIMulExtended:
  8270. builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
  8271. builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
  8272. break;
  8273. case glslang::EOpFrexp:
  8274. {
  8275. assert(operands.size() == 2);
  8276. if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
  8277. // "exp" is floating-point type (from HLSL intrinsic)
  8278. spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
  8279. member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
  8280. builder.createStore(member1, operands[1]);
  8281. } else
  8282. // "exp" is integer type (from GLSL built-in function)
  8283. builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
  8284. id = builder.createCompositeExtract(id, typeId0, 0);
  8285. }
  8286. break;
  8287. default:
  8288. break;
  8289. }
  8290. return builder.setPrecision(id, precision);
  8291. }
  8292. // Intrinsics with no arguments (or no return value, and no precision).
  8293. spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
  8294. {
  8295. // GLSL memory barriers use queuefamily scope in new model, device scope in old model
  8296. spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ?
  8297. spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
  8298. switch (op) {
  8299. case glslang::EOpBarrier:
  8300. if (glslangIntermediate->getStage() == EShLangTessControl) {
  8301. if (glslangIntermediate->usingVulkanMemoryModel()) {
  8302. builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
  8303. spv::MemorySemanticsOutputMemoryKHRMask |
  8304. spv::MemorySemanticsAcquireReleaseMask);
  8305. builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
  8306. } else {
  8307. builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
  8308. }
  8309. } else {
  8310. builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
  8311. spv::MemorySemanticsWorkgroupMemoryMask |
  8312. spv::MemorySemanticsAcquireReleaseMask);
  8313. }
  8314. return 0;
  8315. case glslang::EOpMemoryBarrier:
  8316. builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
  8317. spv::MemorySemanticsAcquireReleaseMask);
  8318. return 0;
  8319. case glslang::EOpMemoryBarrierBuffer:
  8320. builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
  8321. spv::MemorySemanticsAcquireReleaseMask);
  8322. return 0;
  8323. case glslang::EOpMemoryBarrierShared:
  8324. builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
  8325. spv::MemorySemanticsAcquireReleaseMask);
  8326. return 0;
  8327. case glslang::EOpGroupMemoryBarrier:
  8328. builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
  8329. spv::MemorySemanticsAcquireReleaseMask);
  8330. return 0;
  8331. case glslang::EOpMemoryBarrierAtomicCounter:
  8332. builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
  8333. spv::MemorySemanticsAcquireReleaseMask);
  8334. return 0;
  8335. case glslang::EOpMemoryBarrierImage:
  8336. builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
  8337. spv::MemorySemanticsAcquireReleaseMask);
  8338. return 0;
  8339. case glslang::EOpAllMemoryBarrierWithGroupSync:
  8340. builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
  8341. spv::MemorySemanticsAllMemory |
  8342. spv::MemorySemanticsAcquireReleaseMask);
  8343. return 0;
  8344. case glslang::EOpDeviceMemoryBarrier:
  8345. builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
  8346. spv::MemorySemanticsImageMemoryMask |
  8347. spv::MemorySemanticsAcquireReleaseMask);
  8348. return 0;
  8349. case glslang::EOpDeviceMemoryBarrierWithGroupSync:
  8350. builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
  8351. spv::MemorySemanticsImageMemoryMask |
  8352. spv::MemorySemanticsAcquireReleaseMask);
  8353. return 0;
  8354. case glslang::EOpWorkgroupMemoryBarrier:
  8355. builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
  8356. spv::MemorySemanticsAcquireReleaseMask);
  8357. return 0;
  8358. case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
  8359. builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
  8360. spv::MemorySemanticsWorkgroupMemoryMask |
  8361. spv::MemorySemanticsAcquireReleaseMask);
  8362. return 0;
  8363. case glslang::EOpSubgroupBarrier:
  8364. builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
  8365. spv::MemorySemanticsAcquireReleaseMask);
  8366. return spv::NoResult;
  8367. case glslang::EOpSubgroupMemoryBarrier:
  8368. builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
  8369. spv::MemorySemanticsAcquireReleaseMask);
  8370. return spv::NoResult;
  8371. case glslang::EOpSubgroupMemoryBarrierBuffer:
  8372. builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
  8373. spv::MemorySemanticsAcquireReleaseMask);
  8374. return spv::NoResult;
  8375. case glslang::EOpSubgroupMemoryBarrierImage:
  8376. builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
  8377. spv::MemorySemanticsAcquireReleaseMask);
  8378. return spv::NoResult;
  8379. case glslang::EOpSubgroupMemoryBarrierShared:
  8380. builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
  8381. spv::MemorySemanticsAcquireReleaseMask);
  8382. return spv::NoResult;
  8383. case glslang::EOpEmitVertex:
  8384. builder.createNoResultOp(spv::OpEmitVertex);
  8385. return 0;
  8386. case glslang::EOpEndPrimitive:
  8387. builder.createNoResultOp(spv::OpEndPrimitive);
  8388. return 0;
  8389. case glslang::EOpSubgroupElect: {
  8390. std::vector<spv::Id> operands;
  8391. return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
  8392. }
  8393. case glslang::EOpTime:
  8394. {
  8395. std::vector<spv::Id> args; // Dummy arguments
  8396. spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
  8397. return builder.setPrecision(id, precision);
  8398. }
  8399. case glslang::EOpIgnoreIntersectionNV:
  8400. builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
  8401. return 0;
  8402. case glslang::EOpTerminateRayNV:
  8403. builder.createNoResultOp(spv::OpTerminateRayNV);
  8404. return 0;
  8405. case glslang::EOpRayQueryInitialize:
  8406. builder.createNoResultOp(spv::OpRayQueryInitializeKHR);
  8407. return 0;
  8408. case glslang::EOpRayQueryTerminate:
  8409. builder.createNoResultOp(spv::OpRayQueryTerminateKHR);
  8410. return 0;
  8411. case glslang::EOpRayQueryGenerateIntersection:
  8412. builder.createNoResultOp(spv::OpRayQueryGenerateIntersectionKHR);
  8413. return 0;
  8414. case glslang::EOpRayQueryConfirmIntersection:
  8415. builder.createNoResultOp(spv::OpRayQueryConfirmIntersectionKHR);
  8416. return 0;
  8417. case glslang::EOpBeginInvocationInterlock:
  8418. builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
  8419. return 0;
  8420. case glslang::EOpEndInvocationInterlock:
  8421. builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
  8422. return 0;
  8423. case glslang::EOpIsHelperInvocation:
  8424. {
  8425. std::vector<spv::Id> args; // Dummy arguments
  8426. builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
  8427. builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
  8428. return builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
  8429. }
  8430. case glslang::EOpReadClockSubgroupKHR: {
  8431. std::vector<spv::Id> args;
  8432. args.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
  8433. builder.addExtension(spv::E_SPV_KHR_shader_clock);
  8434. builder.addCapability(spv::CapabilityShaderClockKHR);
  8435. return builder.createOp(spv::OpReadClockKHR, typeId, args);
  8436. }
  8437. case glslang::EOpReadClockDeviceKHR: {
  8438. std::vector<spv::Id> args;
  8439. args.push_back(builder.makeUintConstant(spv::ScopeDevice));
  8440. builder.addExtension(spv::E_SPV_KHR_shader_clock);
  8441. builder.addCapability(spv::CapabilityShaderClockKHR);
  8442. return builder.createOp(spv::OpReadClockKHR, typeId, args);
  8443. }
  8444. case glslang::EOpStencilAttachmentReadEXT:
  8445. case glslang::EOpDepthAttachmentReadEXT:
  8446. {
  8447. builder.addExtension(spv::E_SPV_EXT_shader_tile_image);
  8448. spv::Decoration precision;
  8449. spv::Op spv_op;
  8450. if (op == glslang::EOpStencilAttachmentReadEXT)
  8451. {
  8452. precision = spv::DecorationRelaxedPrecision;
  8453. spv_op = spv::OpStencilAttachmentReadEXT;
  8454. builder.addCapability(spv::CapabilityTileImageStencilReadAccessEXT);
  8455. }
  8456. else
  8457. {
  8458. precision = spv::NoPrecision;
  8459. spv_op = spv::OpDepthAttachmentReadEXT;
  8460. builder.addCapability(spv::CapabilityTileImageDepthReadAccessEXT);
  8461. }
  8462. std::vector<spv::Id> args; // Dummy args
  8463. spv::Id result = builder.createOp(spv_op, typeId, args);
  8464. return builder.setPrecision(result, precision);
  8465. }
  8466. default:
  8467. break;
  8468. }
  8469. logger->missingFunctionality("unknown operation with no arguments");
  8470. return 0;
  8471. }
  8472. spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
  8473. {
  8474. auto iter = symbolValues.find(symbol->getId());
  8475. spv::Id id;
  8476. if (symbolValues.end() != iter) {
  8477. id = iter->second;
  8478. return id;
  8479. }
  8480. // it was not found, create it
  8481. spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
  8482. auto forcedType = getForcedType(symbol->getQualifier().builtIn, symbol->getType());
  8483. // There are pairs of symbols that map to the same SPIR-V built-in:
  8484. // gl_ObjectToWorldEXT and gl_ObjectToWorld3x4EXT, and gl_WorldToObjectEXT
  8485. // and gl_WorldToObject3x4EXT. SPIR-V forbids having two OpVariables
  8486. // with the same BuiltIn in the same storage class, so we must re-use one.
  8487. const bool mayNeedToReuseBuiltIn =
  8488. builtIn == spv::BuiltInObjectToWorldKHR ||
  8489. builtIn == spv::BuiltInWorldToObjectKHR;
  8490. if (mayNeedToReuseBuiltIn) {
  8491. auto iter = builtInVariableIds.find(uint32_t(builtIn));
  8492. if (builtInVariableIds.end() != iter) {
  8493. id = iter->second;
  8494. symbolValues[symbol->getId()] = id;
  8495. if (forcedType.second != spv::NoType)
  8496. forceType[id] = forcedType.second;
  8497. return id;
  8498. }
  8499. }
  8500. id = createSpvVariable(symbol, forcedType.first);
  8501. if (mayNeedToReuseBuiltIn) {
  8502. builtInVariableIds.insert({uint32_t(builtIn), id});
  8503. }
  8504. symbolValues[symbol->getId()] = id;
  8505. if (forcedType.second != spv::NoType)
  8506. forceType[id] = forcedType.second;
  8507. if (symbol->getBasicType() != glslang::EbtBlock) {
  8508. builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
  8509. builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
  8510. builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
  8511. addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
  8512. if (symbol->getQualifier().hasComponent())
  8513. builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
  8514. if (symbol->getQualifier().hasIndex())
  8515. builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
  8516. if (symbol->getType().getQualifier().hasSpecConstantId())
  8517. builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
  8518. // atomic counters use this:
  8519. if (symbol->getQualifier().hasOffset())
  8520. builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
  8521. }
  8522. if (symbol->getQualifier().hasLocation()) {
  8523. if (!(glslangIntermediate->isRayTracingStage() &&
  8524. (glslangIntermediate->IsRequestedExtension(glslang::E_GL_EXT_ray_tracing) ||
  8525. glslangIntermediate->IsRequestedExtension(glslang::E_GL_NV_shader_invocation_reorder))
  8526. && (builder.getStorageClass(id) == spv::StorageClassRayPayloadKHR ||
  8527. builder.getStorageClass(id) == spv::StorageClassIncomingRayPayloadKHR ||
  8528. builder.getStorageClass(id) == spv::StorageClassCallableDataKHR ||
  8529. builder.getStorageClass(id) == spv::StorageClassIncomingCallableDataKHR ||
  8530. builder.getStorageClass(id) == spv::StorageClassHitObjectAttributeNV))) {
  8531. // Location values are used to link TraceRayKHR/ExecuteCallableKHR/HitObjectGetAttributesNV
  8532. // to corresponding variables but are not valid in SPIRV since they are supported only
  8533. // for Input/Output Storage classes.
  8534. builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
  8535. }
  8536. }
  8537. builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
  8538. if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
  8539. builder.addCapability(spv::CapabilityGeometryStreams);
  8540. builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
  8541. }
  8542. if (symbol->getQualifier().hasSet())
  8543. builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
  8544. else if (IsDescriptorResource(symbol->getType())) {
  8545. // default to 0
  8546. builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
  8547. }
  8548. if (symbol->getQualifier().hasBinding())
  8549. builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
  8550. else if (IsDescriptorResource(symbol->getType())) {
  8551. // default to 0
  8552. builder.addDecoration(id, spv::DecorationBinding, 0);
  8553. }
  8554. if (symbol->getQualifier().hasAttachment())
  8555. builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
  8556. if (glslangIntermediate->getXfbMode()) {
  8557. builder.addCapability(spv::CapabilityTransformFeedback);
  8558. if (symbol->getQualifier().hasXfbBuffer()) {
  8559. builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
  8560. unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
  8561. if (stride != glslang::TQualifier::layoutXfbStrideEnd)
  8562. builder.addDecoration(id, spv::DecorationXfbStride, stride);
  8563. }
  8564. if (symbol->getQualifier().hasXfbOffset())
  8565. builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
  8566. }
  8567. // add built-in variable decoration
  8568. if (builtIn != spv::BuiltInMax) {
  8569. // WorkgroupSize deprecated in spirv1.6
  8570. if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_6 ||
  8571. builtIn != spv::BuiltInWorkgroupSize)
  8572. builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
  8573. }
  8574. // Add volatile decoration to HelperInvocation for spirv1.6 and beyond
  8575. if (builtIn == spv::BuiltInHelperInvocation &&
  8576. !glslangIntermediate->usingVulkanMemoryModel() &&
  8577. glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_6) {
  8578. builder.addDecoration(id, spv::DecorationVolatile);
  8579. }
  8580. // Subgroup builtins which have input storage class are volatile for ray tracing stages.
  8581. if (symbol->getType().isImage() || symbol->getQualifier().isPipeInput()) {
  8582. std::vector<spv::Decoration> memory;
  8583. TranslateMemoryDecoration(symbol->getType().getQualifier(), memory,
  8584. glslangIntermediate->usingVulkanMemoryModel());
  8585. for (unsigned int i = 0; i < memory.size(); ++i)
  8586. builder.addDecoration(id, memory[i]);
  8587. }
  8588. if (builtIn == spv::BuiltInSampleMask) {
  8589. spv::Decoration decoration;
  8590. // GL_NV_sample_mask_override_coverage extension
  8591. if (glslangIntermediate->getLayoutOverrideCoverage())
  8592. decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
  8593. else
  8594. decoration = (spv::Decoration)spv::DecorationMax;
  8595. builder.addDecoration(id, decoration);
  8596. if (decoration != spv::DecorationMax) {
  8597. builder.addCapability(spv::CapabilitySampleMaskOverrideCoverageNV);
  8598. builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
  8599. }
  8600. }
  8601. else if (builtIn == spv::BuiltInLayer) {
  8602. // SPV_NV_viewport_array2 extension
  8603. if (symbol->getQualifier().layoutViewportRelative) {
  8604. builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
  8605. builder.addCapability(spv::CapabilityShaderViewportMaskNV);
  8606. builder.addExtension(spv::E_SPV_NV_viewport_array2);
  8607. }
  8608. if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
  8609. builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
  8610. symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
  8611. builder.addCapability(spv::CapabilityShaderStereoViewNV);
  8612. builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
  8613. }
  8614. }
  8615. if (symbol->getQualifier().layoutPassthrough) {
  8616. builder.addDecoration(id, spv::DecorationPassthroughNV);
  8617. builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
  8618. builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
  8619. }
  8620. if (symbol->getQualifier().pervertexNV) {
  8621. builder.addDecoration(id, spv::DecorationPerVertexNV);
  8622. builder.addCapability(spv::CapabilityFragmentBarycentricNV);
  8623. builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
  8624. }
  8625. if (symbol->getQualifier().pervertexEXT) {
  8626. builder.addDecoration(id, spv::DecorationPerVertexKHR);
  8627. builder.addCapability(spv::CapabilityFragmentBarycentricKHR);
  8628. builder.addExtension(spv::E_SPV_KHR_fragment_shader_barycentric);
  8629. }
  8630. if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
  8631. builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
  8632. builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
  8633. symbol->getType().getQualifier().semanticName);
  8634. }
  8635. if (symbol->isReference()) {
  8636. builder.addDecoration(id, symbol->getType().getQualifier().restrict ?
  8637. spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
  8638. }
  8639. //
  8640. // Add SPIR-V decorations for structure (GL_EXT_spirv_intrinsics)
  8641. //
  8642. if (symbol->getType().getQualifier().hasSprivDecorate()) {
  8643. const glslang::TSpirvDecorate& spirvDecorate = symbol->getType().getQualifier().getSpirvDecorate();
  8644. // Add spirv_decorate
  8645. for (auto& decorate : spirvDecorate.decorates) {
  8646. if (!decorate.second.empty()) {
  8647. std::vector<unsigned> literals;
  8648. TranslateLiterals(decorate.second, literals);
  8649. builder.addDecoration(id, static_cast<spv::Decoration>(decorate.first), literals);
  8650. }
  8651. else
  8652. builder.addDecoration(id, static_cast<spv::Decoration>(decorate.first));
  8653. }
  8654. // Add spirv_decorate_id
  8655. for (auto& decorateId : spirvDecorate.decorateIds) {
  8656. std::vector<spv::Id> operandIds;
  8657. assert(!decorateId.second.empty());
  8658. for (auto extraOperand : decorateId.second) {
  8659. if (extraOperand->getQualifier().isFrontEndConstant())
  8660. operandIds.push_back(createSpvConstant(*extraOperand));
  8661. else
  8662. operandIds.push_back(getSymbolId(extraOperand->getAsSymbolNode()));
  8663. }
  8664. builder.addDecorationId(id, static_cast<spv::Decoration>(decorateId.first), operandIds);
  8665. }
  8666. // Add spirv_decorate_string
  8667. for (auto& decorateString : spirvDecorate.decorateStrings) {
  8668. std::vector<const char*> strings;
  8669. assert(!decorateString.second.empty());
  8670. for (auto extraOperand : decorateString.second) {
  8671. const char* string = extraOperand->getConstArray()[0].getSConst()->c_str();
  8672. strings.push_back(string);
  8673. }
  8674. builder.addDecoration(id, static_cast<spv::Decoration>(decorateString.first), strings);
  8675. }
  8676. }
  8677. return id;
  8678. }
  8679. // add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
  8680. void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
  8681. {
  8682. bool isMeshShaderExt = (glslangIntermediate->getRequestedExtensions().find(glslang::E_GL_EXT_mesh_shader) !=
  8683. glslangIntermediate->getRequestedExtensions().end());
  8684. if (member >= 0) {
  8685. if (qualifier.perPrimitiveNV) {
  8686. // Need to add capability/extension for fragment shader.
  8687. // Mesh shader already adds this by default.
  8688. if (glslangIntermediate->getStage() == EShLangFragment) {
  8689. if(isMeshShaderExt) {
  8690. builder.addCapability(spv::CapabilityMeshShadingEXT);
  8691. builder.addExtension(spv::E_SPV_EXT_mesh_shader);
  8692. } else {
  8693. builder.addCapability(spv::CapabilityMeshShadingNV);
  8694. builder.addExtension(spv::E_SPV_NV_mesh_shader);
  8695. }
  8696. }
  8697. builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
  8698. }
  8699. if (qualifier.perViewNV)
  8700. builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
  8701. if (qualifier.perTaskNV)
  8702. builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
  8703. } else {
  8704. if (qualifier.perPrimitiveNV) {
  8705. // Need to add capability/extension for fragment shader.
  8706. // Mesh shader already adds this by default.
  8707. if (glslangIntermediate->getStage() == EShLangFragment) {
  8708. if(isMeshShaderExt) {
  8709. builder.addCapability(spv::CapabilityMeshShadingEXT);
  8710. builder.addExtension(spv::E_SPV_EXT_mesh_shader);
  8711. } else {
  8712. builder.addCapability(spv::CapabilityMeshShadingNV);
  8713. builder.addExtension(spv::E_SPV_NV_mesh_shader);
  8714. }
  8715. }
  8716. builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
  8717. }
  8718. if (qualifier.perViewNV)
  8719. builder.addDecoration(id, spv::DecorationPerViewNV);
  8720. if (qualifier.perTaskNV)
  8721. builder.addDecoration(id, spv::DecorationPerTaskNV);
  8722. }
  8723. }
  8724. // Make a full tree of instructions to build a SPIR-V specialization constant,
  8725. // or regular constant if possible.
  8726. //
  8727. // TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
  8728. //
  8729. // Recursively walk the nodes. The nodes form a tree whose leaves are
  8730. // regular constants, which themselves are trees that createSpvConstant()
  8731. // recursively walks. So, this function walks the "top" of the tree:
  8732. // - emit specialization constant-building instructions for specConstant
  8733. // - when running into a non-spec-constant, switch to createSpvConstant()
  8734. spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
  8735. {
  8736. assert(node.getQualifier().isConstant());
  8737. // Handle front-end constants first (non-specialization constants).
  8738. if (! node.getQualifier().specConstant) {
  8739. // hand off to the non-spec-constant path
  8740. assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
  8741. int nextConst = 0;
  8742. return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ?
  8743. node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
  8744. nextConst, false);
  8745. }
  8746. // We now know we have a specialization constant to build
  8747. // Extra capabilities may be needed.
  8748. if (node.getType().contains8BitInt())
  8749. builder.addCapability(spv::CapabilityInt8);
  8750. if (node.getType().contains16BitFloat())
  8751. builder.addCapability(spv::CapabilityFloat16);
  8752. if (node.getType().contains16BitInt())
  8753. builder.addCapability(spv::CapabilityInt16);
  8754. if (node.getType().contains64BitInt())
  8755. builder.addCapability(spv::CapabilityInt64);
  8756. if (node.getType().containsDouble())
  8757. builder.addCapability(spv::CapabilityFloat64);
  8758. // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
  8759. // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
  8760. if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
  8761. std::vector<spv::Id> dimConstId;
  8762. for (int dim = 0; dim < 3; ++dim) {
  8763. bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
  8764. dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
  8765. if (specConst) {
  8766. builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
  8767. glslangIntermediate->getLocalSizeSpecId(dim));
  8768. }
  8769. }
  8770. return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
  8771. }
  8772. // An AST node labelled as specialization constant should be a symbol node.
  8773. // Its initializer should either be a sub tree with constant nodes, or a constant union array.
  8774. if (auto* sn = node.getAsSymbolNode()) {
  8775. spv::Id result;
  8776. if (auto* sub_tree = sn->getConstSubtree()) {
  8777. // Traverse the constant constructor sub tree like generating normal run-time instructions.
  8778. // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
  8779. // will set the builder into spec constant op instruction generating mode.
  8780. sub_tree->traverse(this);
  8781. result = accessChainLoad(sub_tree->getType());
  8782. } else if (auto* const_union_array = &sn->getConstArray()) {
  8783. int nextConst = 0;
  8784. result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
  8785. } else {
  8786. logger->missingFunctionality("Invalid initializer for spec onstant.");
  8787. return spv::NoResult;
  8788. }
  8789. builder.addName(result, sn->getName().c_str());
  8790. return result;
  8791. }
  8792. // Neither a front-end constant node, nor a specialization constant node with constant union array or
  8793. // constant sub tree as initializer.
  8794. logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
  8795. return spv::NoResult;
  8796. }
  8797. // Use 'consts' as the flattened glslang source of scalar constants to recursively
  8798. // build the aggregate SPIR-V constant.
  8799. //
  8800. // If there are not enough elements present in 'consts', 0 will be substituted;
  8801. // an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
  8802. //
  8803. spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType,
  8804. const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
  8805. {
  8806. // vector of constants for SPIR-V
  8807. std::vector<spv::Id> spvConsts;
  8808. // Type is used for struct and array constants
  8809. spv::Id typeId = convertGlslangToSpvType(glslangType);
  8810. if (glslangType.isArray()) {
  8811. glslang::TType elementType(glslangType, 0);
  8812. for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
  8813. spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
  8814. } else if (glslangType.isMatrix()) {
  8815. glslang::TType vectorType(glslangType, 0);
  8816. for (int col = 0; col < glslangType.getMatrixCols(); ++col)
  8817. spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
  8818. } else if (glslangType.isCoopMat()) {
  8819. glslang::TType componentType(glslangType.getBasicType());
  8820. spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
  8821. } else if (glslangType.isStruct()) {
  8822. glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
  8823. for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
  8824. spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
  8825. } else if (glslangType.getVectorSize() > 1) {
  8826. for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
  8827. bool zero = nextConst >= consts.size();
  8828. switch (glslangType.getBasicType()) {
  8829. case glslang::EbtInt:
  8830. spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
  8831. break;
  8832. case glslang::EbtUint:
  8833. spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
  8834. break;
  8835. case glslang::EbtFloat:
  8836. spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
  8837. break;
  8838. case glslang::EbtBool:
  8839. spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
  8840. break;
  8841. case glslang::EbtInt8:
  8842. builder.addCapability(spv::CapabilityInt8);
  8843. spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
  8844. break;
  8845. case glslang::EbtUint8:
  8846. builder.addCapability(spv::CapabilityInt8);
  8847. spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
  8848. break;
  8849. case glslang::EbtInt16:
  8850. builder.addCapability(spv::CapabilityInt16);
  8851. spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
  8852. break;
  8853. case glslang::EbtUint16:
  8854. builder.addCapability(spv::CapabilityInt16);
  8855. spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
  8856. break;
  8857. case glslang::EbtInt64:
  8858. spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
  8859. break;
  8860. case glslang::EbtUint64:
  8861. spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
  8862. break;
  8863. case glslang::EbtDouble:
  8864. spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
  8865. break;
  8866. case glslang::EbtFloat16:
  8867. builder.addCapability(spv::CapabilityFloat16);
  8868. spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
  8869. break;
  8870. default:
  8871. assert(0);
  8872. break;
  8873. }
  8874. ++nextConst;
  8875. }
  8876. } else {
  8877. // we have a non-aggregate (scalar) constant
  8878. bool zero = nextConst >= consts.size();
  8879. spv::Id scalar = 0;
  8880. switch (glslangType.getBasicType()) {
  8881. case glslang::EbtInt:
  8882. scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
  8883. break;
  8884. case glslang::EbtUint:
  8885. scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
  8886. break;
  8887. case glslang::EbtFloat:
  8888. scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
  8889. break;
  8890. case glslang::EbtBool:
  8891. scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
  8892. break;
  8893. case glslang::EbtInt8:
  8894. builder.addCapability(spv::CapabilityInt8);
  8895. scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
  8896. break;
  8897. case glslang::EbtUint8:
  8898. builder.addCapability(spv::CapabilityInt8);
  8899. scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
  8900. break;
  8901. case glslang::EbtInt16:
  8902. builder.addCapability(spv::CapabilityInt16);
  8903. scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
  8904. break;
  8905. case glslang::EbtUint16:
  8906. builder.addCapability(spv::CapabilityInt16);
  8907. scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
  8908. break;
  8909. case glslang::EbtInt64:
  8910. scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
  8911. break;
  8912. case glslang::EbtUint64:
  8913. scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
  8914. break;
  8915. case glslang::EbtDouble:
  8916. scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
  8917. break;
  8918. case glslang::EbtFloat16:
  8919. builder.addCapability(spv::CapabilityFloat16);
  8920. scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
  8921. break;
  8922. case glslang::EbtReference:
  8923. scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
  8924. scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
  8925. break;
  8926. case glslang::EbtString:
  8927. scalar = builder.getStringId(consts[nextConst].getSConst()->c_str());
  8928. break;
  8929. default:
  8930. assert(0);
  8931. break;
  8932. }
  8933. ++nextConst;
  8934. return scalar;
  8935. }
  8936. return builder.makeCompositeConstant(typeId, spvConsts);
  8937. }
  8938. // Return true if the node is a constant or symbol whose reading has no
  8939. // non-trivial observable cost or effect.
  8940. bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
  8941. {
  8942. // don't know what this is
  8943. if (node == nullptr)
  8944. return false;
  8945. // a constant is safe
  8946. if (node->getAsConstantUnion() != nullptr)
  8947. return true;
  8948. // not a symbol means non-trivial
  8949. if (node->getAsSymbolNode() == nullptr)
  8950. return false;
  8951. // a symbol, depends on what's being read
  8952. switch (node->getType().getQualifier().storage) {
  8953. case glslang::EvqTemporary:
  8954. case glslang::EvqGlobal:
  8955. case glslang::EvqIn:
  8956. case glslang::EvqInOut:
  8957. case glslang::EvqConst:
  8958. case glslang::EvqConstReadOnly:
  8959. case glslang::EvqUniform:
  8960. return true;
  8961. default:
  8962. return false;
  8963. }
  8964. }
  8965. // A node is trivial if it is a single operation with no side effects.
  8966. // HLSL (and/or vectors) are always trivial, as it does not short circuit.
  8967. // Otherwise, error on the side of saying non-trivial.
  8968. // Return true if trivial.
  8969. bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
  8970. {
  8971. if (node == nullptr)
  8972. return false;
  8973. // count non scalars as trivial, as well as anything coming from HLSL
  8974. if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
  8975. return true;
  8976. // symbols and constants are trivial
  8977. if (isTrivialLeaf(node))
  8978. return true;
  8979. // otherwise, it needs to be a simple operation or one or two leaf nodes
  8980. // not a simple operation
  8981. const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
  8982. const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
  8983. if (binaryNode == nullptr && unaryNode == nullptr)
  8984. return false;
  8985. // not on leaf nodes
  8986. if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
  8987. return false;
  8988. if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
  8989. return false;
  8990. }
  8991. switch (node->getAsOperator()->getOp()) {
  8992. case glslang::EOpLogicalNot:
  8993. case glslang::EOpConvIntToBool:
  8994. case glslang::EOpConvUintToBool:
  8995. case glslang::EOpConvFloatToBool:
  8996. case glslang::EOpConvDoubleToBool:
  8997. case glslang::EOpEqual:
  8998. case glslang::EOpNotEqual:
  8999. case glslang::EOpLessThan:
  9000. case glslang::EOpGreaterThan:
  9001. case glslang::EOpLessThanEqual:
  9002. case glslang::EOpGreaterThanEqual:
  9003. case glslang::EOpIndexDirect:
  9004. case glslang::EOpIndexDirectStruct:
  9005. case glslang::EOpLogicalXor:
  9006. case glslang::EOpAny:
  9007. case glslang::EOpAll:
  9008. return true;
  9009. default:
  9010. return false;
  9011. }
  9012. }
  9013. // Emit short-circuiting code, where 'right' is never evaluated unless
  9014. // the left side is true (for &&) or false (for ||).
  9015. spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left,
  9016. glslang::TIntermTyped& right)
  9017. {
  9018. spv::Id boolTypeId = builder.makeBoolType();
  9019. // emit left operand
  9020. builder.clearAccessChain();
  9021. left.traverse(this);
  9022. spv::Id leftId = accessChainLoad(left.getType());
  9023. // Operands to accumulate OpPhi operands
  9024. std::vector<spv::Id> phiOperands;
  9025. // accumulate left operand's phi information
  9026. phiOperands.push_back(leftId);
  9027. phiOperands.push_back(builder.getBuildPoint()->getId());
  9028. // Make the two kinds of operation symmetric with a "!"
  9029. // || => emit "if (! left) result = right"
  9030. // && => emit "if ( left) result = right"
  9031. //
  9032. // TODO: this runtime "not" for || could be avoided by adding functionality
  9033. // to 'builder' to have an "else" without an "then"
  9034. if (op == glslang::EOpLogicalOr)
  9035. leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
  9036. // make an "if" based on the left value
  9037. spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
  9038. // emit right operand as the "then" part of the "if"
  9039. builder.clearAccessChain();
  9040. right.traverse(this);
  9041. spv::Id rightId = accessChainLoad(right.getType());
  9042. // accumulate left operand's phi information
  9043. phiOperands.push_back(rightId);
  9044. phiOperands.push_back(builder.getBuildPoint()->getId());
  9045. // finish the "if"
  9046. ifBuilder.makeEndIf();
  9047. // phi together the two results
  9048. return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
  9049. }
  9050. // Return type Id of the imported set of extended instructions corresponds to the name.
  9051. // Import this set if it has not been imported yet.
  9052. spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
  9053. {
  9054. if (extBuiltinMap.find(name) != extBuiltinMap.end())
  9055. return extBuiltinMap[name];
  9056. else {
  9057. builder.addExtension(name);
  9058. spv::Id extBuiltins = builder.import(name);
  9059. extBuiltinMap[name] = extBuiltins;
  9060. return extBuiltins;
  9061. }
  9062. }
  9063. }; // end anonymous namespace
  9064. namespace glslang {
  9065. void GetSpirvVersion(std::string& version)
  9066. {
  9067. const int bufSize = 100;
  9068. char buf[bufSize];
  9069. snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
  9070. version = buf;
  9071. }
  9072. // For low-order part of the generator's magic number. Bump up
  9073. // when there is a change in the style (e.g., if SSA form changes,
  9074. // or a different instruction sequence to do something gets used).
  9075. int GetSpirvGeneratorVersion()
  9076. {
  9077. // return 1; // start
  9078. // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
  9079. // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
  9080. // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
  9081. // return 5; // make OpArrayLength result type be an int with signedness of 0
  9082. // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
  9083. // versions 4 and 6 each generate OpArrayLength as it has long been done
  9084. // return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
  9085. // return 8; // switch to new dead block eliminator; use OpUnreachable
  9086. // return 9; // don't include opaque function parameters in OpEntryPoint global's operand list
  9087. // return 10; // Generate OpFUnordNotEqual for != comparisons
  9088. return 11; // Make OpEmitMeshTasksEXT a terminal instruction
  9089. }
  9090. // Write SPIR-V out to a binary file
  9091. bool OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
  9092. {
  9093. std::ofstream out;
  9094. out.open(baseName, std::ios::binary | std::ios::out);
  9095. if (out.fail()) {
  9096. printf("ERROR: Failed to open file: %s\n", baseName);
  9097. return false;
  9098. }
  9099. for (int i = 0; i < (int)spirv.size(); ++i) {
  9100. unsigned int word = spirv[i];
  9101. out.write((const char*)&word, 4);
  9102. }
  9103. out.close();
  9104. return true;
  9105. }
  9106. // Write SPIR-V out to a text file with 32-bit hexadecimal words
  9107. bool OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
  9108. {
  9109. std::ofstream out;
  9110. out.open(baseName, std::ios::binary | std::ios::out);
  9111. if (out.fail()) {
  9112. printf("ERROR: Failed to open file: %s\n", baseName);
  9113. return false;
  9114. }
  9115. out << "\t// " <<
  9116. GetSpirvGeneratorVersion() <<
  9117. GLSLANG_VERSION_MAJOR << "." << GLSLANG_VERSION_MINOR << "." << GLSLANG_VERSION_PATCH <<
  9118. GLSLANG_VERSION_FLAVOR << std::endl;
  9119. if (varName != nullptr) {
  9120. out << "\t #pragma once" << std::endl;
  9121. out << "const uint32_t " << varName << "[] = {" << std::endl;
  9122. }
  9123. const int WORDS_PER_LINE = 8;
  9124. for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
  9125. out << "\t";
  9126. for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
  9127. const unsigned int word = spirv[i + j];
  9128. out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
  9129. if (i + j + 1 < (int)spirv.size()) {
  9130. out << ",";
  9131. }
  9132. }
  9133. out << std::endl;
  9134. }
  9135. if (varName != nullptr) {
  9136. out << "};";
  9137. out << std::endl;
  9138. }
  9139. out.close();
  9140. return true;
  9141. }
  9142. //
  9143. // Set up the glslang traversal
  9144. //
  9145. void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
  9146. {
  9147. spv::SpvBuildLogger logger;
  9148. GlslangToSpv(intermediate, spirv, &logger, options);
  9149. }
  9150. void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
  9151. spv::SpvBuildLogger* logger, SpvOptions* options)
  9152. {
  9153. TIntermNode* root = intermediate.getTreeRoot();
  9154. if (root == nullptr)
  9155. return;
  9156. SpvOptions defaultOptions;
  9157. if (options == nullptr)
  9158. options = &defaultOptions;
  9159. GetThreadPoolAllocator().push();
  9160. TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
  9161. root->traverse(&it);
  9162. it.finishSpv();
  9163. it.dumpSpv(spirv);
  9164. #if ENABLE_OPT
  9165. // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
  9166. // eg. forward and remove memory writes of opaque types.
  9167. bool prelegalization = intermediate.getSource() == EShSourceHlsl;
  9168. if ((prelegalization || options->optimizeSize) && !options->disableOptimizer) {
  9169. SpirvToolsTransform(intermediate, spirv, logger, options);
  9170. prelegalization = false;
  9171. }
  9172. else if (options->stripDebugInfo) {
  9173. // Strip debug info even if optimization is disabled.
  9174. SpirvToolsStripDebugInfo(intermediate, spirv, logger);
  9175. }
  9176. if (options->validate)
  9177. SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
  9178. if (options->disassemble)
  9179. SpirvToolsDisassemble(std::cout, spirv);
  9180. #endif
  9181. GetThreadPoolAllocator().pop();
  9182. }
  9183. }; // end namespace glslang