hlslParseHelper.cpp 420 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032
  1. //
  2. // Copyright (C) 2017-2018 Google, Inc.
  3. // Copyright (C) 2017 LunarG, Inc.
  4. //
  5. // All rights reserved.
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions
  9. // are met:
  10. //
  11. // Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. //
  14. // Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following
  16. // disclaimer in the documentation and/or other materials provided
  17. // with the distribution.
  18. //
  19. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  20. // contributors may be used to endorse or promote products derived
  21. // from this software without specific prior written permission.
  22. //
  23. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  26. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  27. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  28. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  29. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  30. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  31. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  33. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  34. // POSSIBILITY OF SUCH DAMAGE.
  35. //
  36. #include "hlslParseHelper.h"
  37. #include "hlslScanContext.h"
  38. #include "hlslGrammar.h"
  39. #include "hlslAttributes.h"
  40. #include "../glslang/Include/Common.h"
  41. #include "../glslang/MachineIndependent/Scan.h"
  42. #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
  43. #include "../glslang/OSDependent/osinclude.h"
  44. #include <algorithm>
  45. #include <functional>
  46. #include <cctype>
  47. #include <array>
  48. #include <set>
  49. namespace glslang {
  50. HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
  51. int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
  52. TInfoSink& infoSink,
  53. const TString sourceEntryPointName,
  54. bool forwardCompatible, EShMessages messages) :
  55. TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language, infoSink,
  56. forwardCompatible, messages, &sourceEntryPointName),
  57. annotationNestingLevel(0),
  58. inputPatch(nullptr),
  59. nextInLocation(0), nextOutLocation(0),
  60. entryPointFunction(nullptr),
  61. entryPointFunctionBody(nullptr),
  62. gsStreamOutput(nullptr),
  63. clipDistanceOutput(nullptr),
  64. cullDistanceOutput(nullptr),
  65. clipDistanceInput(nullptr),
  66. cullDistanceInput(nullptr)
  67. {
  68. globalUniformDefaults.clear();
  69. globalUniformDefaults.layoutMatrix = ElmRowMajor;
  70. globalUniformDefaults.layoutPacking = ElpStd140;
  71. globalBufferDefaults.clear();
  72. globalBufferDefaults.layoutMatrix = ElmRowMajor;
  73. globalBufferDefaults.layoutPacking = ElpStd430;
  74. globalInputDefaults.clear();
  75. globalOutputDefaults.clear();
  76. clipSemanticNSizeIn.fill(0);
  77. cullSemanticNSizeIn.fill(0);
  78. clipSemanticNSizeOut.fill(0);
  79. cullSemanticNSizeOut.fill(0);
  80. // "Shaders in the transform
  81. // feedback capturing mode have an initial global default of
  82. // layout(xfb_buffer = 0) out;"
  83. if (language == EShLangVertex ||
  84. language == EShLangTessControl ||
  85. language == EShLangTessEvaluation ||
  86. language == EShLangGeometry)
  87. globalOutputDefaults.layoutXfbBuffer = 0;
  88. if (language == EShLangGeometry)
  89. globalOutputDefaults.layoutStream = 0;
  90. }
  91. HlslParseContext::~HlslParseContext()
  92. {
  93. }
  94. void HlslParseContext::initializeExtensionBehavior()
  95. {
  96. TParseContextBase::initializeExtensionBehavior();
  97. // HLSL allows #line by default.
  98. extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
  99. }
  100. void HlslParseContext::setLimits(const TBuiltInResource& r)
  101. {
  102. resources = r;
  103. intermediate.setLimits(resources);
  104. }
  105. //
  106. // Parse an array of strings using the parser in HlslRules.
  107. //
  108. // Returns true for successful acceptance of the shader, false if any errors.
  109. //
  110. bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
  111. {
  112. currentScanner = &input;
  113. ppContext.setInput(input, versionWillBeError);
  114. HlslScanContext scanContext(*this, ppContext);
  115. HlslGrammar grammar(scanContext, *this);
  116. if (!grammar.parse()) {
  117. // Print a message formated such that if you click on the message it will take you right to
  118. // the line through most UIs.
  119. const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
  120. infoSink.info << sourceLoc.getFilenameStr() << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
  121. << ", HLSL parsing failed.\n";
  122. ++numErrors;
  123. return false;
  124. }
  125. finish();
  126. return numErrors == 0;
  127. }
  128. //
  129. // Return true if this l-value node should be converted in some manner.
  130. // For instance: turning a load aggregate into a store in an l-value.
  131. //
  132. bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
  133. {
  134. if (node == nullptr || node->getAsTyped() == nullptr)
  135. return false;
  136. const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  137. const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
  138. // If it's a swizzled/indexed aggregate, look at the left node instead.
  139. if (lhsAsBinary != nullptr &&
  140. (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
  141. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  142. if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
  143. return true;
  144. return false;
  145. }
  146. void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
  147. TTypeList* newTypeList)
  148. {
  149. newTypeList = nullptr;
  150. correctUniform(memberType.getQualifier());
  151. if (memberType.isStruct()) {
  152. auto it = ioTypeMap.find(memberType.getStruct());
  153. if (it != ioTypeMap.end() && it->second.uniform)
  154. newTypeList = it->second.uniform;
  155. }
  156. TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
  157. }
  158. //
  159. // Return a TLayoutFormat corresponding to the given texture type.
  160. //
  161. TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
  162. {
  163. if (txType.isStruct()) {
  164. // TODO: implement.
  165. error(loc, "unimplemented: structure type in image or buffer", "", "");
  166. return ElfNone;
  167. }
  168. const int components = txType.getVectorSize();
  169. const TBasicType txBasicType = txType.getBasicType();
  170. const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
  171. if (intermediate.getNoStorageFormat())
  172. return ElfNone;
  173. return components == 1 ? v1 :
  174. components == 2 ? v2 : v4;
  175. };
  176. switch (txBasicType) {
  177. case EbtFloat: return selectFormat(ElfR32f, ElfRg32f, ElfRgba32f);
  178. case EbtInt: return selectFormat(ElfR32i, ElfRg32i, ElfRgba32i);
  179. case EbtUint: return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
  180. default:
  181. error(loc, "unknown basic type in image format", "", "");
  182. return ElfNone;
  183. }
  184. }
  185. //
  186. // Both test and if necessary, spit out an error, to see if the node is really
  187. // an l-value that can be operated on this way.
  188. //
  189. // Returns true if there was an error.
  190. //
  191. bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
  192. {
  193. if (shouldConvertLValue(node)) {
  194. // if we're writing to a texture, it must be an RW form.
  195. TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  196. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  197. if (!object->getType().getSampler().isImage()) {
  198. error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
  199. return true;
  200. }
  201. }
  202. // We tolerate samplers as l-values, even though they are nominally
  203. // illegal, because we expect a later optimization to eliminate them.
  204. if (node->getType().getBasicType() == EbtSampler) {
  205. intermediate.setNeedsLegalization();
  206. return false;
  207. }
  208. // Let the base class check errors
  209. return TParseContextBase::lValueErrorCheck(loc, op, node);
  210. }
  211. //
  212. // This function handles l-value conversions and verifications. It uses, but is not synonymous
  213. // with lValueErrorCheck. That function accepts an l-value directly, while this one must be
  214. // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
  215. // series of other image operations.
  216. //
  217. // Most things are passed through unmodified, except for error checking.
  218. //
  219. TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
  220. {
  221. if (node == nullptr)
  222. return nullptr;
  223. TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
  224. TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
  225. TIntermAggregate* sequence = nullptr;
  226. TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
  227. nodeAsBinary ? nodeAsBinary->getLeft() :
  228. nullptr;
  229. // Early bail out if there is no conversion to apply
  230. if (!shouldConvertLValue(lhs)) {
  231. if (lhs != nullptr)
  232. if (lValueErrorCheck(loc, op, lhs))
  233. return nullptr;
  234. return node;
  235. }
  236. // *** If we get here, we're going to apply some conversion to an l-value.
  237. // Helper to create a load.
  238. const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
  239. TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
  240. loadOp->setLoc(loc);
  241. loadOp->getSequence().push_back(object);
  242. loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
  243. loadOp->setType(derefType);
  244. sequence = intermediate.growAggregate(sequence,
  245. intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
  246. loc);
  247. };
  248. // Helper to create a store.
  249. const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
  250. TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
  251. storeOp->getSequence().push_back(object);
  252. storeOp->getSequence().push_back(coord);
  253. storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
  254. storeOp->setLoc(loc);
  255. storeOp->setType(TType(EbtVoid));
  256. sequence = intermediate.growAggregate(sequence, storeOp);
  257. };
  258. // Helper to create an assign.
  259. const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
  260. sequence = intermediate.growAggregate(sequence,
  261. intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
  262. loc);
  263. };
  264. // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
  265. const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
  266. // Add a trailing use of the temp, so the sequence returns the proper value.
  267. sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
  268. sequence->setOperator(EOpSequence);
  269. sequence->setLoc(loc);
  270. sequence->setType(derefType);
  271. return sequence;
  272. };
  273. // Helper to add unary op
  274. const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
  275. sequence = intermediate.growAggregate(sequence,
  276. intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
  277. rhsTmp->getType()),
  278. loc);
  279. };
  280. // Return true if swizzle or index writes all components of the given variable.
  281. const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
  282. if (swizzle == nullptr) // not a swizzle or index
  283. return true;
  284. // Track which components are being set.
  285. std::array<bool, 4> compIsSet;
  286. compIsSet.fill(false);
  287. const TIntermConstantUnion* asConst = swizzle->getRight()->getAsConstantUnion();
  288. const TIntermAggregate* asAggregate = swizzle->getRight()->getAsAggregate();
  289. // This could be either a direct index, or a swizzle.
  290. if (asConst) {
  291. compIsSet[asConst->getConstArray()[0].getIConst()] = true;
  292. } else if (asAggregate) {
  293. const TIntermSequence& seq = asAggregate->getSequence();
  294. for (int comp=0; comp<int(seq.size()); ++comp)
  295. compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
  296. } else {
  297. assert(0);
  298. }
  299. // Return true if all components are being set by the index or swizzle
  300. return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
  301. [](bool isSet) { return isSet; } );
  302. };
  303. // Create swizzle matching input swizzle
  304. const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
  305. if (swizzle)
  306. return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
  307. else
  308. return var;
  309. };
  310. TIntermBinary* lhsAsBinary = lhs->getAsBinaryNode();
  311. TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
  312. bool lhsIsSwizzle = false;
  313. // If it's a swizzled L-value, remember the swizzle, and use the LHS.
  314. if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
  315. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  316. lhsIsSwizzle = true;
  317. }
  318. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  319. TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
  320. const TSampler& texSampler = object->getType().getSampler();
  321. TType objDerefType;
  322. getTextureReturnType(texSampler, objDerefType);
  323. if (nodeAsBinary) {
  324. TIntermTyped* rhs = nodeAsBinary->getRight();
  325. const TOperator assignOp = nodeAsBinary->getOp();
  326. bool isModifyOp = false;
  327. switch (assignOp) {
  328. case EOpAddAssign:
  329. case EOpSubAssign:
  330. case EOpMulAssign:
  331. case EOpVectorTimesMatrixAssign:
  332. case EOpVectorTimesScalarAssign:
  333. case EOpMatrixTimesScalarAssign:
  334. case EOpMatrixTimesMatrixAssign:
  335. case EOpDivAssign:
  336. case EOpModAssign:
  337. case EOpAndAssign:
  338. case EOpInclusiveOrAssign:
  339. case EOpExclusiveOrAssign:
  340. case EOpLeftShiftAssign:
  341. case EOpRightShiftAssign:
  342. isModifyOp = true;
  343. // fall through...
  344. case EOpAssign:
  345. {
  346. // Since this is an lvalue, we'll convert an image load to a sequence like this
  347. // (to still provide the value):
  348. // OpSequence
  349. // OpImageStore(object, lhs, rhs)
  350. // rhs
  351. // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
  352. // so we'll convert instead to this:
  353. // OpSequence
  354. // rhsTmp = rhs
  355. // OpImageStore(object, coord, rhsTmp)
  356. // rhsTmp
  357. // If this is a read-modify-write op, like +=, we issue:
  358. // OpSequence
  359. // coordtmp = load's param1
  360. // rhsTmp = OpImageLoad(object, coordTmp)
  361. // rhsTmp op= rhs
  362. // OpImageStore(object, coordTmp, rhsTmp)
  363. // rhsTmp
  364. //
  365. // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
  366. // ...
  367. // rhsTmp.some_swizzle = ...
  368. // For partial writes, an error is generated.
  369. TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
  370. TIntermTyped* coordTmp = coord;
  371. if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
  372. rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  373. // Partial updates not yet supported
  374. if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
  375. error(loc, "unimplemented: partial image updates", "", "");
  376. }
  377. // Assign storeTemp = rhs
  378. if (isModifyOp) {
  379. // We have to make a temp var for the coordinate, to avoid evaluating it twice.
  380. coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  381. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  382. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  383. }
  384. // rhsTmp op= rhs.
  385. makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
  386. }
  387. makeStore(object, coordTmp, rhsTmp); // add a store
  388. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  389. }
  390. default:
  391. break;
  392. }
  393. }
  394. if (nodeAsUnary) {
  395. const TOperator assignOp = nodeAsUnary->getOp();
  396. switch (assignOp) {
  397. case EOpPreIncrement:
  398. case EOpPreDecrement:
  399. {
  400. // We turn this into:
  401. // OpSequence
  402. // coordtmp = load's param1
  403. // rhsTmp = OpImageLoad(object, coordTmp)
  404. // rhsTmp op
  405. // OpImageStore(object, coordTmp, rhsTmp)
  406. // rhsTmp
  407. TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  408. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  409. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  410. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  411. makeUnary(assignOp, rhsTmp); // op rhsTmp
  412. makeStore(object, coordTmp, rhsTmp); // OpImageStore(object, coordTmp, rhsTmp)
  413. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  414. }
  415. case EOpPostIncrement:
  416. case EOpPostDecrement:
  417. {
  418. // We turn this into:
  419. // OpSequence
  420. // coordtmp = load's param1
  421. // rhsTmp1 = OpImageLoad(object, coordTmp)
  422. // rhsTmp2 = rhsTmp1
  423. // rhsTmp2 op
  424. // OpImageStore(object, coordTmp, rhsTmp2)
  425. // rhsTmp1 (pre-op value)
  426. TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre", objDerefType);
  427. TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
  428. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  429. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  430. makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
  431. makeBinary(EOpAssign, rhsTmp2, rhsTmp1); // rhsTmp2 = rhsTmp1
  432. makeUnary(assignOp, rhsTmp2); // rhsTmp op
  433. makeStore(object, coordTmp, rhsTmp2); // OpImageStore(object, coordTmp, rhsTmp2)
  434. return finishSequence(rhsTmp1, objDerefType); // return rhsTmp from sequence
  435. }
  436. default:
  437. break;
  438. }
  439. }
  440. if (lhs)
  441. if (lValueErrorCheck(loc, op, lhs))
  442. return nullptr;
  443. return node;
  444. }
  445. void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
  446. {
  447. if (pragmaCallback)
  448. pragmaCallback(loc.line, tokens);
  449. if (tokens.size() == 0)
  450. return;
  451. // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
  452. TVector<TString> lowerTokens = tokens;
  453. for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
  454. std::transform(it->begin(), it->end(), it->begin(), ::tolower);
  455. // Handle pack_matrix
  456. if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
  457. // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
  458. // Row major becomes column major and vice versa.
  459. if (lowerTokens[2] == "row_major") {
  460. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
  461. } else if (lowerTokens[2] == "column_major") {
  462. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  463. } else {
  464. // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
  465. warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
  466. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  467. }
  468. return;
  469. }
  470. // Handle once
  471. if (lowerTokens[0] == "once") {
  472. warn(loc, "not implemented", "#pragma once", "");
  473. return;
  474. }
  475. }
  476. //
  477. // Look at a '.' matrix selector string and change it into components
  478. // for a matrix. There are two types:
  479. //
  480. // _21 second row, first column (one based)
  481. // _m21 third row, second column (zero based)
  482. //
  483. // Returns true if there is no error.
  484. //
  485. bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
  486. TSwizzleSelectors<TMatrixSelector>& components)
  487. {
  488. int startPos[MaxSwizzleSelectors];
  489. int numComps = 0;
  490. TString compString = fields;
  491. // Find where each component starts,
  492. // recording the first character position after the '_'.
  493. for (size_t c = 0; c < compString.size(); ++c) {
  494. if (compString[c] == '_') {
  495. if (numComps >= MaxSwizzleSelectors) {
  496. error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
  497. return false;
  498. }
  499. if (c > compString.size() - 3 ||
  500. ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
  501. error(loc, "matrix component swizzle missing", compString.c_str(), "");
  502. return false;
  503. }
  504. startPos[numComps++] = (int)c + 1;
  505. }
  506. }
  507. // Process each component
  508. for (int i = 0; i < numComps; ++i) {
  509. int pos = startPos[i];
  510. int bias = -1;
  511. if (compString[pos] == 'm' || compString[pos] == 'M') {
  512. bias = 0;
  513. ++pos;
  514. }
  515. TMatrixSelector comp;
  516. comp.coord1 = compString[pos+0] - '0' + bias;
  517. comp.coord2 = compString[pos+1] - '0' + bias;
  518. if (comp.coord1 < 0 || comp.coord1 >= cols) {
  519. error(loc, "matrix row component out of range", compString.c_str(), "");
  520. return false;
  521. }
  522. if (comp.coord2 < 0 || comp.coord2 >= rows) {
  523. error(loc, "matrix column component out of range", compString.c_str(), "");
  524. return false;
  525. }
  526. components.push_back(comp);
  527. }
  528. return true;
  529. }
  530. // If the 'comps' express a column of a matrix,
  531. // return the column. Column means the first coords all match.
  532. //
  533. // Otherwise, return -1.
  534. //
  535. int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
  536. {
  537. int col = -1;
  538. // right number of comps?
  539. if (selector.size() != rows)
  540. return -1;
  541. // all comps in the same column?
  542. // rows in order?
  543. col = selector[0].coord1;
  544. for (int i = 0; i < rows; ++i) {
  545. if (col != selector[i].coord1)
  546. return -1;
  547. if (i != selector[i].coord2)
  548. return -1;
  549. }
  550. return col;
  551. }
  552. //
  553. // Handle seeing a variable identifier in the grammar.
  554. //
  555. TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
  556. {
  557. int thisDepth;
  558. TSymbol* symbol = symbolTable.find(*string, thisDepth);
  559. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  560. error(loc, "expected symbol, not user-defined type", string->c_str(), "");
  561. return nullptr;
  562. }
  563. const TVariable* variable = nullptr;
  564. const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
  565. TIntermTyped* node = nullptr;
  566. if (anon) {
  567. // It was a member of an anonymous container, which could be a 'this' structure.
  568. // Create a subtree for its dereference.
  569. if (thisDepth > 0) {
  570. variable = getImplicitThis(thisDepth);
  571. if (variable == nullptr)
  572. error(loc, "cannot access member variables (static member function?)", "this", "");
  573. }
  574. if (variable == nullptr)
  575. variable = anon->getAnonContainer().getAsVariable();
  576. TIntermTyped* container = intermediate.addSymbol(*variable, loc);
  577. TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
  578. node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
  579. node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
  580. if (node->getType().hiddenMember())
  581. error(loc, "member of nameless block was not redeclared", string->c_str(), "");
  582. } else {
  583. // Not a member of an anonymous container.
  584. // The symbol table search was done in the lexical phase.
  585. // See if it was a variable.
  586. variable = symbol ? symbol->getAsVariable() : nullptr;
  587. if (variable) {
  588. if ((variable->getType().getBasicType() == EbtBlock ||
  589. variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
  590. error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
  591. variable = nullptr;
  592. }
  593. } else {
  594. if (symbol)
  595. error(loc, "variable name expected", string->c_str(), "");
  596. }
  597. // Recovery, if it wasn't found or was not a variable.
  598. if (variable == nullptr) {
  599. error(loc, "unknown variable", string->c_str(), "");
  600. variable = new TVariable(string, TType(EbtVoid));
  601. }
  602. if (variable->getType().getQualifier().isFrontEndConstant())
  603. node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
  604. else
  605. node = intermediate.addSymbol(*variable, loc);
  606. }
  607. if (variable->getType().getQualifier().isIo())
  608. intermediate.addIoAccessed(*string);
  609. return node;
  610. }
  611. //
  612. // Handle operator[] on any objects it applies to. Currently:
  613. // Textures
  614. // Buffers
  615. //
  616. TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  617. {
  618. // handle r-value operator[] on textures and images. l-values will be processed later.
  619. if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
  620. const TSampler& sampler = base->getType().getSampler();
  621. if (sampler.isImage() || sampler.isTexture()) {
  622. if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
  623. // The first operator[] to a .mips[] sequence is the mip level. We'll remember it.
  624. mipsOperatorMipArg.back().mipLevel = index;
  625. return base; // next [] index is to the same base.
  626. } else {
  627. TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
  628. TType sampReturnType;
  629. getTextureReturnType(sampler, sampReturnType);
  630. load->setType(sampReturnType);
  631. load->setLoc(loc);
  632. load->getSequence().push_back(base);
  633. load->getSequence().push_back(index);
  634. // Textures need a MIP. If we saw one go by, use it. Otherwise, use zero.
  635. if (sampler.isTexture()) {
  636. if (! mipsOperatorMipArg.empty()) {
  637. load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
  638. mipsOperatorMipArg.pop_back();
  639. } else {
  640. load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
  641. }
  642. }
  643. return load;
  644. }
  645. }
  646. }
  647. // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
  648. // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
  649. TIntermTyped* sbArray = indexStructBufferContent(loc, base);
  650. if (sbArray != nullptr) {
  651. if (sbArray == nullptr)
  652. return nullptr;
  653. // Now we'll apply the [] index to that array
  654. const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  655. TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
  656. const TType derefType(sbArray->getType(), 0);
  657. element->setType(derefType);
  658. return element;
  659. }
  660. return nullptr;
  661. }
  662. //
  663. // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
  664. TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
  665. {
  666. const TBasicType indexBasicType = index->getType().getBasicType();
  667. const int vecSize = index->getType().getVectorSize();
  668. // We can use int types directly as the index
  669. if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
  670. indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
  671. return index;
  672. // Cast index to unsigned integer if it isn't one.
  673. return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
  674. }
  675. //
  676. // Handle seeing a base[index] dereference in the grammar.
  677. //
  678. TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  679. {
  680. index = makeIntegerIndex(index);
  681. if (index == nullptr) {
  682. error(loc, " unknown index type ", "", "");
  683. return nullptr;
  684. }
  685. TIntermTyped* result = handleBracketOperator(loc, base, index);
  686. if (result != nullptr)
  687. return result; // it was handled as an operator[]
  688. bool flattened = false;
  689. int indexValue = 0;
  690. if (index->getQualifier().isFrontEndConstant())
  691. indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
  692. variableCheck(base);
  693. if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
  694. if (base->getAsSymbolNode())
  695. error(loc, " left of '[' is not of type array, matrix, or vector ",
  696. base->getAsSymbolNode()->getName().c_str(), "");
  697. else
  698. error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
  699. } else if (base->getType().getQualifier().isFrontEndConstant() &&
  700. index->getQualifier().isFrontEndConstant()) {
  701. // both base and index are front-end constants
  702. checkIndex(loc, base->getType(), indexValue);
  703. return intermediate.foldDereference(base, indexValue, loc);
  704. } else {
  705. // at least one of base and index is variable...
  706. if (index->getQualifier().isFrontEndConstant())
  707. checkIndex(loc, base->getType(), indexValue);
  708. if (base->getType().isScalarOrVec1())
  709. result = base;
  710. else if (base->getAsSymbolNode() && wasFlattened(base)) {
  711. if (index->getQualifier().storage != EvqConst)
  712. error(loc, "Invalid variable index to flattened array", base->getAsSymbolNode()->getName().c_str(), "");
  713. result = flattenAccess(base, indexValue);
  714. flattened = (result != base);
  715. } else {
  716. if (index->getQualifier().isFrontEndConstant()) {
  717. if (base->getType().isUnsizedArray())
  718. base->getWritableType().updateImplicitArraySize(indexValue + 1);
  719. else
  720. checkIndex(loc, base->getType(), indexValue);
  721. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  722. } else
  723. result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
  724. }
  725. }
  726. if (result == nullptr) {
  727. // Insert dummy error-recovery result
  728. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  729. } else {
  730. // If the array reference was flattened, it has the correct type. E.g, if it was
  731. // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
  732. // In that case, we preserve the qualifiers.
  733. if (!flattened) {
  734. // Insert valid dereferenced result
  735. TType newType(base->getType(), 0); // dereferenced type
  736. if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
  737. newType.getQualifier().storage = EvqConst;
  738. else
  739. newType.getQualifier().storage = EvqTemporary;
  740. result->setType(newType);
  741. }
  742. }
  743. return result;
  744. }
  745. // Handle seeing a binary node with a math operation.
  746. TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  747. TIntermTyped* left, TIntermTyped* right)
  748. {
  749. TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
  750. if (result == nullptr)
  751. binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
  752. return result;
  753. }
  754. // Handle seeing a unary node with a math operation.
  755. TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  756. TIntermTyped* childNode)
  757. {
  758. TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
  759. if (result)
  760. return result;
  761. else
  762. unaryOpError(loc, str, childNode->getCompleteString());
  763. return childNode;
  764. }
  765. //
  766. // Return true if the name is a struct buffer method
  767. //
  768. bool HlslParseContext::isStructBufferMethod(const TString& name) const
  769. {
  770. return
  771. name == "GetDimensions" ||
  772. name == "Load" ||
  773. name == "Load2" ||
  774. name == "Load3" ||
  775. name == "Load4" ||
  776. name == "Store" ||
  777. name == "Store2" ||
  778. name == "Store3" ||
  779. name == "Store4" ||
  780. name == "InterlockedAdd" ||
  781. name == "InterlockedAnd" ||
  782. name == "InterlockedCompareExchange" ||
  783. name == "InterlockedCompareStore" ||
  784. name == "InterlockedExchange" ||
  785. name == "InterlockedMax" ||
  786. name == "InterlockedMin" ||
  787. name == "InterlockedOr" ||
  788. name == "InterlockedXor" ||
  789. name == "IncrementCounter" ||
  790. name == "DecrementCounter" ||
  791. name == "Append" ||
  792. name == "Consume";
  793. }
  794. //
  795. // Handle seeing a base.field dereference in the grammar, where 'field' is a
  796. // swizzle or member variable.
  797. //
  798. TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
  799. {
  800. variableCheck(base);
  801. if (base->isArray()) {
  802. error(loc, "cannot apply to an array:", ".", field.c_str());
  803. return base;
  804. }
  805. TIntermTyped* result = base;
  806. if (base->getType().getBasicType() == EbtSampler) {
  807. // Handle .mips[mipid][pos] operation on textures
  808. const TSampler& sampler = base->getType().getSampler();
  809. if (sampler.isTexture() && field == "mips") {
  810. // Push a null to signify that we expect a mip level under operator[] next.
  811. mipsOperatorMipArg.push_back(tMipsOperatorData(loc, nullptr));
  812. // Keep 'result' pointing to 'base', since we expect an operator[] to go by next.
  813. } else {
  814. if (field == "mips")
  815. error(loc, "unexpected texture type for .mips[][] operator:",
  816. base->getType().getCompleteString().c_str(), "");
  817. else
  818. error(loc, "unexpected operator on texture type:", field.c_str(),
  819. base->getType().getCompleteString().c_str());
  820. }
  821. } else if (base->isVector() || base->isScalar()) {
  822. TSwizzleSelectors<TVectorSelector> selectors;
  823. parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
  824. if (base->isScalar()) {
  825. if (selectors.size() == 1)
  826. return result;
  827. else {
  828. TType type(base->getBasicType(), EvqTemporary, selectors.size());
  829. return addConstructor(loc, base, type);
  830. }
  831. }
  832. if (base->getVectorSize() == 1) {
  833. TType scalarType(base->getBasicType(), EvqTemporary, 1);
  834. if (selectors.size() == 1)
  835. return addConstructor(loc, base, scalarType);
  836. else {
  837. TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
  838. return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
  839. }
  840. }
  841. if (base->getType().getQualifier().isFrontEndConstant())
  842. result = intermediate.foldSwizzle(base, selectors, loc);
  843. else {
  844. if (selectors.size() == 1) {
  845. TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
  846. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  847. result->setType(TType(base->getBasicType(), EvqTemporary));
  848. } else {
  849. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  850. result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
  851. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  852. selectors.size()));
  853. }
  854. }
  855. } else if (base->isMatrix()) {
  856. TSwizzleSelectors<TMatrixSelector> selectors;
  857. if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
  858. return result;
  859. if (selectors.size() == 1) {
  860. // Representable by m[c][r]
  861. if (base->getType().getQualifier().isFrontEndConstant()) {
  862. result = intermediate.foldDereference(base, selectors[0].coord1, loc);
  863. result = intermediate.foldDereference(result, selectors[0].coord2, loc);
  864. } else {
  865. result = intermediate.addIndex(EOpIndexDirect, base,
  866. intermediate.addConstantUnion(selectors[0].coord1, loc),
  867. loc);
  868. TType dereferencedCol(base->getType(), 0);
  869. result->setType(dereferencedCol);
  870. result = intermediate.addIndex(EOpIndexDirect, result,
  871. intermediate.addConstantUnion(selectors[0].coord2, loc),
  872. loc);
  873. TType dereferenced(dereferencedCol, 0);
  874. result->setType(dereferenced);
  875. }
  876. } else {
  877. int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
  878. if (column >= 0) {
  879. // Representable by m[c]
  880. if (base->getType().getQualifier().isFrontEndConstant())
  881. result = intermediate.foldDereference(base, column, loc);
  882. else {
  883. result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
  884. loc);
  885. TType dereferenced(base->getType(), 0);
  886. result->setType(dereferenced);
  887. }
  888. } else {
  889. // general case, not a column, not a single component
  890. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  891. result = intermediate.addIndex(EOpMatrixSwizzle, base, index, loc);
  892. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  893. selectors.size()));
  894. }
  895. }
  896. } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
  897. const TTypeList* fields = base->getType().getStruct();
  898. bool fieldFound = false;
  899. int member;
  900. for (member = 0; member < (int)fields->size(); ++member) {
  901. if ((*fields)[member].type->getFieldName() == field) {
  902. fieldFound = true;
  903. break;
  904. }
  905. }
  906. if (fieldFound) {
  907. if (base->getAsSymbolNode() && wasFlattened(base)) {
  908. result = flattenAccess(base, member);
  909. } else {
  910. if (base->getType().getQualifier().storage == EvqConst)
  911. result = intermediate.foldDereference(base, member, loc);
  912. else {
  913. TIntermTyped* index = intermediate.addConstantUnion(member, loc);
  914. result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
  915. result->setType(*(*fields)[member].type);
  916. }
  917. }
  918. } else
  919. error(loc, "no such field in structure", field.c_str(), "");
  920. } else
  921. error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
  922. return result;
  923. }
  924. //
  925. // Return true if the field should be treated as a built-in method.
  926. // Return false otherwise.
  927. //
  928. bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
  929. {
  930. if (base == nullptr)
  931. return false;
  932. variableCheck(base);
  933. if (base->getType().getBasicType() == EbtSampler) {
  934. return true;
  935. } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
  936. return true;
  937. } else if (field == "Append" ||
  938. field == "RestartStrip") {
  939. // We cannot check the type here: it may be sanitized if we're not compiling a geometry shader, but
  940. // the code is around in the shader source.
  941. return true;
  942. } else
  943. return false;
  944. }
  945. // Independently establish a built-in that is a member of a structure.
  946. // 'arraySizes' are what's desired for the independent built-in, whatever
  947. // the higher-level source/expression of them was.
  948. void HlslParseContext::splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes* arraySizes,
  949. const TQualifier& outerQualifier)
  950. {
  951. // Because of arrays of structs, we might be asked more than once,
  952. // but the arraySizes passed in should have captured the whole thing
  953. // the first time.
  954. // However, clip/cull rely on multiple updates.
  955. if (!isClipOrCullDistance(memberType))
  956. if (splitBuiltIns.find(tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)) !=
  957. splitBuiltIns.end())
  958. return;
  959. TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
  960. if (arraySizes != nullptr && !memberType.isArray())
  961. ioVar->getWritableType().copyArraySizes(*arraySizes);
  962. splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
  963. if (!isClipOrCullDistance(ioVar->getType()))
  964. trackLinkage(*ioVar);
  965. // Merge qualifier from the user structure
  966. mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
  967. // Fix the builtin type if needed (e.g, some types require fixed array sizes, no matter how the
  968. // shader declared them). This is done after mergeQualifiers(), in case fixBuiltInIoType looks
  969. // at the qualifier to determine e.g, in or out qualifications.
  970. fixBuiltInIoType(ioVar->getWritableType());
  971. // But, not location, we're losing that
  972. ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  973. }
  974. // Split a type into
  975. // 1. a struct of non-I/O members
  976. // 2. a collection of independent I/O variables
  977. void HlslParseContext::split(const TVariable& variable)
  978. {
  979. // Create a new variable:
  980. const TType& clonedType = *variable.getType().clone();
  981. const TType& splitType = split(clonedType, variable.getName(), clonedType.getQualifier());
  982. splitNonIoVars[variable.getUniqueId()] = makeInternalVariable(variable.getName(), splitType);
  983. }
  984. // Recursive implementation of split().
  985. // Returns reference to the modified type.
  986. const TType& HlslParseContext::split(const TType& type, const TString& name, const TQualifier& outerQualifier)
  987. {
  988. if (type.isStruct()) {
  989. TTypeList* userStructure = type.getWritableStruct();
  990. for (auto ioType = userStructure->begin(); ioType != userStructure->end(); ) {
  991. if (ioType->type->isBuiltIn()) {
  992. // move out the built-in
  993. splitBuiltIn(name, *ioType->type, type.getArraySizes(), outerQualifier);
  994. ioType = userStructure->erase(ioType);
  995. } else {
  996. split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
  997. ++ioType;
  998. }
  999. }
  1000. }
  1001. return type;
  1002. }
  1003. // Is this an aggregate that should be flattened?
  1004. // Can be applied to intermediate levels of type in a hierarchy.
  1005. // Some things like flattening uniform arrays are only about the top level
  1006. // of the aggregate, triggered on 'topLevel'.
  1007. bool HlslParseContext::shouldFlatten(const TType& type, TStorageQualifier qualifier, bool topLevel) const
  1008. {
  1009. switch (qualifier) {
  1010. case EvqVaryingIn:
  1011. case EvqVaryingOut:
  1012. return type.isStruct() || type.isArray();
  1013. case EvqUniform:
  1014. return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
  1015. (type.isStruct() && type.containsOpaque());
  1016. default:
  1017. return false;
  1018. };
  1019. }
  1020. // Top level variable flattening: construct data
  1021. void HlslParseContext::flatten(const TVariable& variable, bool linkage)
  1022. {
  1023. const TType& type = variable.getType();
  1024. // If it's a standalone built-in, there is nothing to flatten
  1025. if (type.isBuiltIn() && !type.isStruct())
  1026. return;
  1027. auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
  1028. TFlattenData(type.getQualifier().layoutBinding,
  1029. type.getQualifier().layoutLocation)));
  1030. // the item is a map pair, so first->second is the TFlattenData itself.
  1031. flatten(variable, type, entry.first->second, variable.getName(), linkage, type.getQualifier(), nullptr);
  1032. }
  1033. // Recursively flatten the given variable at the provided type, building the flattenData as we go.
  1034. //
  1035. // This is mutually recursive with flattenStruct and flattenArray.
  1036. // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
  1037. // members, and later on, we want to turn a path through the tree structure into a final
  1038. // location in this linear sequence.
  1039. //
  1040. // If the tree was N-ary, that can be directly calculated. However, we are dealing with
  1041. // arbitrary numbers - perhaps a struct of 7 members containing an array of 3. Thus, we must
  1042. // build a data structure to allow the sequence of bracket and dot operators on arrays and
  1043. // structs to arrive at the proper member.
  1044. //
  1045. // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
  1046. // The leaves are the indexes into the flattened member array.
  1047. // Each level will have the next location for the Nth item stored sequentially, so for instance:
  1048. //
  1049. // struct { float2 a[2]; int b; float4 c[3] };
  1050. //
  1051. // This will produce the following flattened tree:
  1052. // Pos: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  1053. // (3, 7, 8, 5, 6, 0, 1, 2, 11, 12, 13, 3, 4, 5}
  1054. //
  1055. // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
  1056. // (0+2) = 8 --> (8+1) = 12 --> 12 = 4
  1057. //
  1058. // so the 4th flattened member in traversal order is ours.
  1059. //
  1060. int HlslParseContext::flatten(const TVariable& variable, const TType& type,
  1061. TFlattenData& flattenData, TString name, bool linkage,
  1062. const TQualifier& outerQualifier,
  1063. const TArraySizes* builtInArraySizes)
  1064. {
  1065. // If something is an arrayed struct, the array flattener will recursively call flatten()
  1066. // to then flatten the struct, so this is an "if else": we don't do both.
  1067. if (type.isArray())
  1068. return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
  1069. else if (type.isStruct())
  1070. return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
  1071. else {
  1072. assert(0); // should never happen
  1073. return -1;
  1074. }
  1075. }
  1076. // Add a single flattened member to the flattened data being tracked for the composite
  1077. // Returns true for the final flattening level.
  1078. int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
  1079. const TString& memberName, bool linkage,
  1080. const TQualifier& outerQualifier,
  1081. const TArraySizes* builtInArraySizes)
  1082. {
  1083. if (!shouldFlatten(type, outerQualifier.storage, false)) {
  1084. // This is as far as we flatten. Insert the variable.
  1085. TVariable* memberVariable = makeInternalVariable(memberName, type);
  1086. mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
  1087. if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
  1088. memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
  1089. if (memberVariable->getType().isBuiltIn()) {
  1090. // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
  1091. memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  1092. } else {
  1093. // inherited locations must be auto bumped, not replicated
  1094. if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
  1095. memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
  1096. flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
  1097. nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
  1098. }
  1099. }
  1100. flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
  1101. flattenData.members.push_back(memberVariable);
  1102. if (linkage)
  1103. trackLinkage(*memberVariable);
  1104. return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
  1105. } else {
  1106. // Further recursion required
  1107. return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
  1108. }
  1109. }
  1110. // Figure out the mapping between an aggregate's top members and an
  1111. // equivalent set of individual variables.
  1112. //
  1113. // Assumes shouldFlatten() or equivalent was called first.
  1114. int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
  1115. TFlattenData& flattenData, TString name, bool linkage,
  1116. const TQualifier& outerQualifier,
  1117. const TArraySizes* builtInArraySizes)
  1118. {
  1119. assert(type.isStruct());
  1120. auto members = *type.getStruct();
  1121. // Reserve space for this tree level.
  1122. int start = static_cast<int>(flattenData.offsets.size());
  1123. int pos = start;
  1124. flattenData.offsets.resize(int(pos + members.size()), -1);
  1125. for (int member = 0; member < (int)members.size(); ++member) {
  1126. TType& dereferencedType = *members[member].type;
  1127. if (dereferencedType.isBuiltIn())
  1128. splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
  1129. else {
  1130. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1131. name + "." + dereferencedType.getFieldName(),
  1132. linkage, outerQualifier,
  1133. builtInArraySizes == nullptr && dereferencedType.isArray()
  1134. ? dereferencedType.getArraySizes()
  1135. : builtInArraySizes);
  1136. flattenData.offsets[pos++] = mpos;
  1137. }
  1138. }
  1139. return start;
  1140. }
  1141. // Figure out mapping between an array's members and an
  1142. // equivalent set of individual variables.
  1143. //
  1144. // Assumes shouldFlatten() or equivalent was called first.
  1145. int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
  1146. TFlattenData& flattenData, TString name, bool linkage,
  1147. const TQualifier& outerQualifier)
  1148. {
  1149. assert(type.isSizedArray());
  1150. const int size = type.getOuterArraySize();
  1151. const TType dereferencedType(type, 0);
  1152. if (name.empty())
  1153. name = variable.getName();
  1154. // Reserve space for this tree level.
  1155. int start = static_cast<int>(flattenData.offsets.size());
  1156. int pos = start;
  1157. flattenData.offsets.resize(int(pos + size), -1);
  1158. for (int element=0; element < size; ++element) {
  1159. char elementNumBuf[20]; // sufficient for MAXINT
  1160. snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
  1161. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1162. name + elementNumBuf, linkage, outerQualifier,
  1163. type.getArraySizes());
  1164. flattenData.offsets[pos++] = mpos;
  1165. }
  1166. return start;
  1167. }
  1168. // Return true if we have flattened this node.
  1169. bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
  1170. {
  1171. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1172. wasFlattened(node->getAsSymbolNode()->getId());
  1173. }
  1174. // Return true if we have split this structure
  1175. bool HlslParseContext::wasSplit(const TIntermTyped* node) const
  1176. {
  1177. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1178. wasSplit(node->getAsSymbolNode()->getId());
  1179. }
  1180. // Turn an access into an aggregate that was flattened to instead be
  1181. // an access to the individual variable the member was flattened to.
  1182. // Assumes wasFlattened() or equivalent was called first.
  1183. TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
  1184. {
  1185. const TType dereferencedType(base->getType(), member); // dereferenced type
  1186. const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
  1187. TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
  1188. dereferencedType, symbolNode.getFlattenSubset());
  1189. return flattened ? flattened : base;
  1190. }
  1191. TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
  1192. const TType& dereferencedType, int subset)
  1193. {
  1194. const auto flattenData = flattenMap.find(uniqueId);
  1195. if (flattenData == flattenMap.end())
  1196. return nullptr;
  1197. // Calculate new cumulative offset from the packed tree
  1198. int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
  1199. TIntermSymbol* subsetSymbol;
  1200. if (!shouldFlatten(dereferencedType, outerStorage, false)) {
  1201. // Finished flattening: create symbol for variable
  1202. member = flattenData->second.offsets[newSubset];
  1203. const TVariable* memberVariable = flattenData->second.members[member];
  1204. subsetSymbol = intermediate.addSymbol(*memberVariable);
  1205. subsetSymbol->setFlattenSubset(-1);
  1206. } else {
  1207. // If this is not the final flattening, accumulate the position and return
  1208. // an object of the partially dereferenced type.
  1209. subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
  1210. subsetSymbol->setFlattenSubset(newSubset);
  1211. }
  1212. return subsetSymbol;
  1213. }
  1214. // For finding where the first leaf is in a subtree of a multi-level aggregate
  1215. // that is just getting a subset assigned. Follows the same logic as flattenAccess,
  1216. // but logically going down the "left-most" tree branch each step of the way.
  1217. //
  1218. // Returns the offset into the first leaf of the subset.
  1219. int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
  1220. {
  1221. const TIntermSymbol* sym = node.getAsSymbolNode();
  1222. if (sym == nullptr)
  1223. return 0;
  1224. if (!sym->isArray() && !sym->isStruct())
  1225. return 0;
  1226. int subset = sym->getFlattenSubset();
  1227. if (subset == -1)
  1228. return 0;
  1229. // Getting this far means a partial aggregate is identified by the flatten subset.
  1230. // Find the first leaf of the subset.
  1231. const auto flattenData = flattenMap.find(sym->getId());
  1232. if (flattenData == flattenMap.end())
  1233. return 0;
  1234. return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
  1235. do {
  1236. subset = flattenData->second.offsets[subset];
  1237. } while (true);
  1238. }
  1239. // Recursively do the desent
  1240. int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
  1241. {
  1242. if (!type.isArray() && !type.isStruct())
  1243. return offsets[subset];
  1244. TType derefType(type, 0);
  1245. return findSubtreeOffset(derefType, offsets[subset], offsets);
  1246. };
  1247. // Find and return the split IO TVariable for id, or nullptr if none.
  1248. TVariable* HlslParseContext::getSplitNonIoVar(int id) const
  1249. {
  1250. const auto splitNonIoVar = splitNonIoVars.find(id);
  1251. if (splitNonIoVar == splitNonIoVars.end())
  1252. return nullptr;
  1253. return splitNonIoVar->second;
  1254. }
  1255. // Pass through to base class after remembering built-in mappings.
  1256. void HlslParseContext::trackLinkage(TSymbol& symbol)
  1257. {
  1258. TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
  1259. if (biType != EbvNone)
  1260. builtInTessLinkageSymbols[biType] = symbol.clone();
  1261. TParseContextBase::trackLinkage(symbol);
  1262. }
  1263. // Returns true if the built-in is a clip or cull distance variable.
  1264. bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
  1265. {
  1266. return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
  1267. }
  1268. // Some types require fixed array sizes in SPIR-V, but can be scalars or
  1269. // arrays of sizes SPIR-V doesn't allow. For example, tessellation factors.
  1270. // This creates the right size. A conversion is performed when the internal
  1271. // type is copied to or from the external type. This corrects the externally
  1272. // facing input or output type to abide downstream semantics.
  1273. void HlslParseContext::fixBuiltInIoType(TType& type)
  1274. {
  1275. int requiredArraySize = 0;
  1276. int requiredVectorSize = 0;
  1277. switch (type.getQualifier().builtIn) {
  1278. case EbvTessLevelOuter: requiredArraySize = 4; break;
  1279. case EbvTessLevelInner: requiredArraySize = 2; break;
  1280. case EbvSampleMask:
  1281. {
  1282. // Promote scalar to array of size 1. Leave existing arrays alone.
  1283. if (!type.isArray())
  1284. requiredArraySize = 1;
  1285. break;
  1286. }
  1287. case EbvWorkGroupId: requiredVectorSize = 3; break;
  1288. case EbvGlobalInvocationId: requiredVectorSize = 3; break;
  1289. case EbvLocalInvocationId: requiredVectorSize = 3; break;
  1290. case EbvTessCoord: requiredVectorSize = 3; break;
  1291. default:
  1292. if (isClipOrCullDistance(type)) {
  1293. const int loc = type.getQualifier().layoutLocation;
  1294. if (type.getQualifier().builtIn == EbvClipDistance) {
  1295. if (type.getQualifier().storage == EvqVaryingIn)
  1296. clipSemanticNSizeIn[loc] = type.getVectorSize();
  1297. else
  1298. clipSemanticNSizeOut[loc] = type.getVectorSize();
  1299. } else {
  1300. if (type.getQualifier().storage == EvqVaryingIn)
  1301. cullSemanticNSizeIn[loc] = type.getVectorSize();
  1302. else
  1303. cullSemanticNSizeOut[loc] = type.getVectorSize();
  1304. }
  1305. }
  1306. return;
  1307. }
  1308. // Alter or set vector size as needed.
  1309. if (requiredVectorSize > 0) {
  1310. TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
  1311. newType.getQualifier() = type.getQualifier();
  1312. type.shallowCopy(newType);
  1313. }
  1314. // Alter or set array size as needed.
  1315. if (requiredArraySize > 0) {
  1316. if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
  1317. TArraySizes* arraySizes = new TArraySizes;
  1318. arraySizes->addInnerSize(requiredArraySize);
  1319. type.transferArraySizes(arraySizes);
  1320. }
  1321. }
  1322. }
  1323. // Variables that correspond to the user-interface in and out of a stage
  1324. // (not the built-in interface) are
  1325. // - assigned locations
  1326. // - registered as a linkage node (part of the stage's external interface).
  1327. // Assumes it is called in the order in which locations should be assigned.
  1328. void HlslParseContext::assignToInterface(TVariable& variable)
  1329. {
  1330. const auto assignLocation = [&](TVariable& variable) {
  1331. TType& type = variable.getWritableType();
  1332. if (!type.isStruct() || type.getStruct()->size() > 0) {
  1333. TQualifier& qualifier = type.getQualifier();
  1334. if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
  1335. if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
  1336. // Strip off the outer array dimension for those having an extra one.
  1337. int size;
  1338. if (type.isArray() && qualifier.isArrayedIo(language)) {
  1339. TType elementType(type, 0);
  1340. size = intermediate.computeTypeLocationSize(elementType, language);
  1341. } else
  1342. size = intermediate.computeTypeLocationSize(type, language);
  1343. if (qualifier.storage == EvqVaryingIn) {
  1344. variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
  1345. nextInLocation += size;
  1346. } else {
  1347. variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
  1348. nextOutLocation += size;
  1349. }
  1350. }
  1351. trackLinkage(variable);
  1352. }
  1353. }
  1354. };
  1355. if (wasFlattened(variable.getUniqueId())) {
  1356. auto& memberList = flattenMap[variable.getUniqueId()].members;
  1357. for (auto member = memberList.begin(); member != memberList.end(); ++member)
  1358. assignLocation(**member);
  1359. } else if (wasSplit(variable.getUniqueId())) {
  1360. TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
  1361. assignLocation(*splitIoVar);
  1362. } else {
  1363. assignLocation(variable);
  1364. }
  1365. }
  1366. //
  1367. // Handle seeing a function declarator in the grammar. This is the precursor
  1368. // to recognizing a function prototype or function definition.
  1369. //
  1370. void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
  1371. {
  1372. //
  1373. // Multiple declarations of the same function name are allowed.
  1374. //
  1375. // If this is a definition, the definition production code will check for redefinitions
  1376. // (we don't know at this point if it's a definition or not).
  1377. //
  1378. bool builtIn;
  1379. TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
  1380. const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
  1381. if (prototype) {
  1382. // All built-in functions are defined, even though they don't have a body.
  1383. // Count their prototype as a definition instead.
  1384. if (symbolTable.atBuiltInLevel())
  1385. function.setDefined();
  1386. else {
  1387. if (prevDec && ! builtIn)
  1388. symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
  1389. function.setPrototyped();
  1390. }
  1391. }
  1392. // This insert won't actually insert it if it's a duplicate signature, but it will still check for
  1393. // other forms of name collisions.
  1394. if (! symbolTable.insert(function))
  1395. error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
  1396. }
  1397. // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
  1398. // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
  1399. // Otherwise, it's a no-op
  1400. void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
  1401. TIntermAggregate*& paramNodes)
  1402. {
  1403. if (! hasStructBuffCounter(*param.type))
  1404. return;
  1405. const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
  1406. TType counterType;
  1407. counterBufferType(loc, counterType);
  1408. TVariable *variable = makeInternalVariable(counterBlockName, counterType);
  1409. if (! symbolTable.insert(*variable))
  1410. error(loc, "redefinition", variable->getName().c_str(), "");
  1411. paramNodes = intermediate.growAggregate(paramNodes,
  1412. intermediate.addSymbol(*variable, loc),
  1413. loc);
  1414. }
  1415. //
  1416. // Handle seeing the function prototype in front of a function definition in the grammar.
  1417. // The body is handled after this function returns.
  1418. //
  1419. // Returns an aggregate of parameter-symbol nodes.
  1420. //
  1421. TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
  1422. const TAttributes& attributes,
  1423. TIntermNode*& entryPointTree)
  1424. {
  1425. currentCaller = function.getMangledName();
  1426. TSymbol* symbol = symbolTable.find(function.getMangledName());
  1427. TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
  1428. if (prevDec == nullptr)
  1429. error(loc, "can't find function", function.getName().c_str(), "");
  1430. // Note: 'prevDec' could be 'function' if this is the first time we've seen function
  1431. // as it would have just been put in the symbol table. Otherwise, we're looking up
  1432. // an earlier occurrence.
  1433. if (prevDec && prevDec->isDefined()) {
  1434. // Then this function already has a body.
  1435. error(loc, "function already has a body", function.getName().c_str(), "");
  1436. }
  1437. if (prevDec && ! prevDec->isDefined()) {
  1438. prevDec->setDefined();
  1439. // Remember the return type for later checking for RETURN statements.
  1440. currentFunctionType = &(prevDec->getType());
  1441. } else
  1442. currentFunctionType = new TType(EbtVoid);
  1443. functionReturnsValue = false;
  1444. // Entry points need different I/O and other handling, transform it so the
  1445. // rest of this function doesn't care.
  1446. entryPointTree = transformEntryPoint(loc, function, attributes);
  1447. //
  1448. // New symbol table scope for body of function plus its arguments
  1449. //
  1450. pushScope();
  1451. //
  1452. // Insert parameters into the symbol table.
  1453. // If the parameter has no name, it's not an error, just don't insert it
  1454. // (could be used for unused args).
  1455. //
  1456. // Also, accumulate the list of parameters into the AST, so lower level code
  1457. // knows where to find parameters.
  1458. //
  1459. TIntermAggregate* paramNodes = new TIntermAggregate;
  1460. for (int i = 0; i < function.getParamCount(); i++) {
  1461. TParameter& param = function[i];
  1462. if (param.name != nullptr) {
  1463. TVariable *variable = new TVariable(param.name, *param.type);
  1464. if (i == 0 && function.hasImplicitThis()) {
  1465. // Anonymous 'this' members are already in a symbol-table level,
  1466. // and we need to know what function parameter to map them to.
  1467. symbolTable.makeInternalVariable(*variable);
  1468. pushImplicitThis(variable);
  1469. }
  1470. // Insert the parameters with name in the symbol table.
  1471. if (! symbolTable.insert(*variable))
  1472. error(loc, "redefinition", variable->getName().c_str(), "");
  1473. // Add parameters to the AST list.
  1474. if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
  1475. // Expand the AST parameter nodes (but not the name mangling or symbol table view)
  1476. // for structures that need to be flattened.
  1477. flatten(*variable, false);
  1478. const TTypeList* structure = variable->getType().getStruct();
  1479. for (int mem = 0; mem < (int)structure->size(); ++mem) {
  1480. paramNodes = intermediate.growAggregate(paramNodes,
  1481. flattenAccess(variable->getUniqueId(), mem,
  1482. variable->getType().getQualifier().storage,
  1483. *(*structure)[mem].type),
  1484. loc);
  1485. }
  1486. } else {
  1487. // Add the parameter to the AST
  1488. paramNodes = intermediate.growAggregate(paramNodes,
  1489. intermediate.addSymbol(*variable, loc),
  1490. loc);
  1491. }
  1492. // Add hidden AST parameter for struct buffer counters, if needed.
  1493. addStructBufferHiddenCounterParam(loc, param, paramNodes);
  1494. } else
  1495. paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
  1496. }
  1497. if (function.hasIllegalImplicitThis())
  1498. pushImplicitThis(nullptr);
  1499. intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
  1500. loopNestingLevel = 0;
  1501. controlFlowNestingLevel = 0;
  1502. postEntryPointReturn = false;
  1503. return paramNodes;
  1504. }
  1505. // Handle all [attrib] attribute for the shader entry point
  1506. void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
  1507. {
  1508. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1509. switch (it->name) {
  1510. case EatNumThreads:
  1511. {
  1512. const TIntermSequence& sequence = it->args->getSequence();
  1513. for (int lid = 0; lid < int(sequence.size()); ++lid)
  1514. intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
  1515. break;
  1516. }
  1517. case EatMaxVertexCount:
  1518. {
  1519. int maxVertexCount;
  1520. if (! it->getInt(maxVertexCount)) {
  1521. error(loc, "invalid maxvertexcount", "", "");
  1522. } else {
  1523. if (! intermediate.setVertices(maxVertexCount))
  1524. error(loc, "cannot change previously set maxvertexcount attribute", "", "");
  1525. }
  1526. break;
  1527. }
  1528. case EatPatchConstantFunc:
  1529. {
  1530. TString pcfName;
  1531. if (! it->getString(pcfName, 0, false)) {
  1532. error(loc, "invalid patch constant function", "", "");
  1533. } else {
  1534. patchConstantFunctionName = pcfName;
  1535. }
  1536. break;
  1537. }
  1538. case EatDomain:
  1539. {
  1540. // Handle [domain("...")]
  1541. TString domainStr;
  1542. if (! it->getString(domainStr)) {
  1543. error(loc, "invalid domain", "", "");
  1544. } else {
  1545. TLayoutGeometry domain = ElgNone;
  1546. if (domainStr == "tri") {
  1547. domain = ElgTriangles;
  1548. } else if (domainStr == "quad") {
  1549. domain = ElgQuads;
  1550. } else if (domainStr == "isoline") {
  1551. domain = ElgIsolines;
  1552. } else {
  1553. error(loc, "unsupported domain type", domainStr.c_str(), "");
  1554. }
  1555. if (language == EShLangTessEvaluation) {
  1556. if (! intermediate.setInputPrimitive(domain))
  1557. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1558. } else {
  1559. if (! intermediate.setOutputPrimitive(domain))
  1560. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1561. }
  1562. }
  1563. break;
  1564. }
  1565. case EatOutputTopology:
  1566. {
  1567. // Handle [outputtopology("...")]
  1568. TString topologyStr;
  1569. if (! it->getString(topologyStr)) {
  1570. error(loc, "invalid outputtopology", "", "");
  1571. } else {
  1572. TVertexOrder vertexOrder = EvoNone;
  1573. TLayoutGeometry primitive = ElgNone;
  1574. if (topologyStr == "point") {
  1575. intermediate.setPointMode();
  1576. } else if (topologyStr == "line") {
  1577. primitive = ElgIsolines;
  1578. } else if (topologyStr == "triangle_cw") {
  1579. vertexOrder = EvoCw;
  1580. primitive = ElgTriangles;
  1581. } else if (topologyStr == "triangle_ccw") {
  1582. vertexOrder = EvoCcw;
  1583. primitive = ElgTriangles;
  1584. } else {
  1585. error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
  1586. }
  1587. if (vertexOrder != EvoNone) {
  1588. if (! intermediate.setVertexOrder(vertexOrder)) {
  1589. error(loc, "cannot change previously set outputtopology",
  1590. TQualifier::getVertexOrderString(vertexOrder), "");
  1591. }
  1592. }
  1593. if (primitive != ElgNone)
  1594. intermediate.setOutputPrimitive(primitive);
  1595. }
  1596. break;
  1597. }
  1598. case EatPartitioning:
  1599. {
  1600. // Handle [partitioning("...")]
  1601. TString partitionStr;
  1602. if (! it->getString(partitionStr)) {
  1603. error(loc, "invalid partitioning", "", "");
  1604. } else {
  1605. TVertexSpacing partitioning = EvsNone;
  1606. if (partitionStr == "integer") {
  1607. partitioning = EvsEqual;
  1608. } else if (partitionStr == "fractional_even") {
  1609. partitioning = EvsFractionalEven;
  1610. } else if (partitionStr == "fractional_odd") {
  1611. partitioning = EvsFractionalOdd;
  1612. //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
  1613. } else {
  1614. error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
  1615. }
  1616. if (! intermediate.setVertexSpacing(partitioning))
  1617. error(loc, "cannot change previously set partitioning",
  1618. TQualifier::getVertexSpacingString(partitioning), "");
  1619. }
  1620. break;
  1621. }
  1622. case EatOutputControlPoints:
  1623. {
  1624. // Handle [outputcontrolpoints("...")]
  1625. int ctrlPoints;
  1626. if (! it->getInt(ctrlPoints)) {
  1627. error(loc, "invalid outputcontrolpoints", "", "");
  1628. } else {
  1629. if (! intermediate.setVertices(ctrlPoints)) {
  1630. error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
  1631. }
  1632. }
  1633. break;
  1634. }
  1635. case EatEarlyDepthStencil:
  1636. intermediate.setEarlyFragmentTests();
  1637. break;
  1638. case EatBuiltIn:
  1639. case EatLocation:
  1640. // tolerate these because of dual use of entrypoint and type attributes
  1641. break;
  1642. default:
  1643. warn(loc, "attribute does not apply to entry point", "", "");
  1644. break;
  1645. }
  1646. }
  1647. }
  1648. // Update the given type with any type-like attribute information in the
  1649. // attributes.
  1650. void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
  1651. bool allowEntry)
  1652. {
  1653. if (attributes.size() == 0)
  1654. return;
  1655. int value;
  1656. TString builtInString;
  1657. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1658. switch (it->name) {
  1659. case EatLocation:
  1660. // location
  1661. if (it->getInt(value))
  1662. type.getQualifier().layoutLocation = value;
  1663. else
  1664. error(loc, "needs a literal integer", "location", "");
  1665. break;
  1666. case EatBinding:
  1667. // binding
  1668. if (it->getInt(value)) {
  1669. type.getQualifier().layoutBinding = value;
  1670. type.getQualifier().layoutSet = 0;
  1671. } else
  1672. error(loc, "needs a literal integer", "binding", "");
  1673. // set
  1674. if (it->getInt(value, 1))
  1675. type.getQualifier().layoutSet = value;
  1676. break;
  1677. case EatGlobalBinding:
  1678. // global cbuffer binding
  1679. if (it->getInt(value))
  1680. globalUniformBinding = value;
  1681. else
  1682. error(loc, "needs a literal integer", "global binding", "");
  1683. // global cbuffer set
  1684. if (it->getInt(value, 1))
  1685. globalUniformSet = value;
  1686. break;
  1687. case EatInputAttachment:
  1688. // input attachment
  1689. if (it->getInt(value))
  1690. type.getQualifier().layoutAttachment = value;
  1691. else
  1692. error(loc, "needs a literal integer", "input attachment", "");
  1693. break;
  1694. case EatBuiltIn:
  1695. // PointSize built-in
  1696. if (it->getString(builtInString, 0, false)) {
  1697. if (builtInString == "PointSize")
  1698. type.getQualifier().builtIn = EbvPointSize;
  1699. }
  1700. break;
  1701. case EatPushConstant:
  1702. // push_constant
  1703. type.getQualifier().layoutPushConstant = true;
  1704. break;
  1705. case EatConstantId:
  1706. // specialization constant
  1707. if (it->getInt(value)) {
  1708. TSourceLoc loc;
  1709. loc.init();
  1710. setSpecConstantId(loc, type.getQualifier(), value);
  1711. }
  1712. break;
  1713. // image formats
  1714. case EatFormatRgba32f: type.getQualifier().layoutFormat = ElfRgba32f; break;
  1715. case EatFormatRgba16f: type.getQualifier().layoutFormat = ElfRgba16f; break;
  1716. case EatFormatR32f: type.getQualifier().layoutFormat = ElfR32f; break;
  1717. case EatFormatRgba8: type.getQualifier().layoutFormat = ElfRgba8; break;
  1718. case EatFormatRgba8Snorm: type.getQualifier().layoutFormat = ElfRgba8Snorm; break;
  1719. case EatFormatRg32f: type.getQualifier().layoutFormat = ElfRg32f; break;
  1720. case EatFormatRg16f: type.getQualifier().layoutFormat = ElfRg16f; break;
  1721. case EatFormatR11fG11fB10f: type.getQualifier().layoutFormat = ElfR11fG11fB10f; break;
  1722. case EatFormatR16f: type.getQualifier().layoutFormat = ElfR16f; break;
  1723. case EatFormatRgba16: type.getQualifier().layoutFormat = ElfRgba16; break;
  1724. case EatFormatRgb10A2: type.getQualifier().layoutFormat = ElfRgb10A2; break;
  1725. case EatFormatRg16: type.getQualifier().layoutFormat = ElfRg16; break;
  1726. case EatFormatRg8: type.getQualifier().layoutFormat = ElfRg8; break;
  1727. case EatFormatR16: type.getQualifier().layoutFormat = ElfR16; break;
  1728. case EatFormatR8: type.getQualifier().layoutFormat = ElfR8; break;
  1729. case EatFormatRgba16Snorm: type.getQualifier().layoutFormat = ElfRgba16Snorm; break;
  1730. case EatFormatRg16Snorm: type.getQualifier().layoutFormat = ElfRg16Snorm; break;
  1731. case EatFormatRg8Snorm: type.getQualifier().layoutFormat = ElfRg8Snorm; break;
  1732. case EatFormatR16Snorm: type.getQualifier().layoutFormat = ElfR16Snorm; break;
  1733. case EatFormatR8Snorm: type.getQualifier().layoutFormat = ElfR8Snorm; break;
  1734. case EatFormatRgba32i: type.getQualifier().layoutFormat = ElfRgba32i; break;
  1735. case EatFormatRgba16i: type.getQualifier().layoutFormat = ElfRgba16i; break;
  1736. case EatFormatRgba8i: type.getQualifier().layoutFormat = ElfRgba8i; break;
  1737. case EatFormatR32i: type.getQualifier().layoutFormat = ElfR32i; break;
  1738. case EatFormatRg32i: type.getQualifier().layoutFormat = ElfRg32i; break;
  1739. case EatFormatRg16i: type.getQualifier().layoutFormat = ElfRg16i; break;
  1740. case EatFormatRg8i: type.getQualifier().layoutFormat = ElfRg8i; break;
  1741. case EatFormatR16i: type.getQualifier().layoutFormat = ElfR16i; break;
  1742. case EatFormatR8i: type.getQualifier().layoutFormat = ElfR8i; break;
  1743. case EatFormatRgba32ui: type.getQualifier().layoutFormat = ElfRgba32ui; break;
  1744. case EatFormatRgba16ui: type.getQualifier().layoutFormat = ElfRgba16ui; break;
  1745. case EatFormatRgba8ui: type.getQualifier().layoutFormat = ElfRgba8ui; break;
  1746. case EatFormatR32ui: type.getQualifier().layoutFormat = ElfR32ui; break;
  1747. case EatFormatRgb10a2ui: type.getQualifier().layoutFormat = ElfRgb10a2ui; break;
  1748. case EatFormatRg32ui: type.getQualifier().layoutFormat = ElfRg32ui; break;
  1749. case EatFormatRg16ui: type.getQualifier().layoutFormat = ElfRg16ui; break;
  1750. case EatFormatRg8ui: type.getQualifier().layoutFormat = ElfRg8ui; break;
  1751. case EatFormatR16ui: type.getQualifier().layoutFormat = ElfR16ui; break;
  1752. case EatFormatR8ui: type.getQualifier().layoutFormat = ElfR8ui; break;
  1753. case EatFormatUnknown: type.getQualifier().layoutFormat = ElfNone; break;
  1754. case EatNonWritable: type.getQualifier().readonly = true; break;
  1755. case EatNonReadable: type.getQualifier().writeonly = true; break;
  1756. default:
  1757. if (! allowEntry)
  1758. warn(loc, "attribute does not apply to a type", "", "");
  1759. break;
  1760. }
  1761. }
  1762. }
  1763. //
  1764. // Do all special handling for the entry point, including wrapping
  1765. // the shader's entry point with the official entry point that will call it.
  1766. //
  1767. // The following:
  1768. //
  1769. // retType shaderEntryPoint(args...) // shader declared entry point
  1770. // { body }
  1771. //
  1772. // Becomes
  1773. //
  1774. // out retType ret;
  1775. // in iargs<that are input>...;
  1776. // out oargs<that are output> ...;
  1777. //
  1778. // void shaderEntryPoint() // synthesized, but official, entry point
  1779. // {
  1780. // args<that are input> = iargs...;
  1781. // ret = @shaderEntryPoint(args...);
  1782. // oargs = args<that are output>...;
  1783. // }
  1784. // retType @shaderEntryPoint(args...)
  1785. // { body }
  1786. //
  1787. // The symbol table will still map the original entry point name to the
  1788. // the modified function and its new name:
  1789. //
  1790. // symbol table: shaderEntryPoint -> @shaderEntryPoint
  1791. //
  1792. // Returns nullptr if no entry-point tree was built, otherwise, returns
  1793. // a subtree that creates the entry point.
  1794. //
  1795. TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
  1796. const TAttributes& attributes)
  1797. {
  1798. // Return true if this is a tessellation patch constant function input to a domain shader.
  1799. const auto isDsPcfInput = [this](const TType& type) {
  1800. return language == EShLangTessEvaluation &&
  1801. type.contains([](const TType* t) {
  1802. return t->getQualifier().builtIn == EbvTessLevelOuter ||
  1803. t->getQualifier().builtIn == EbvTessLevelInner;
  1804. });
  1805. };
  1806. // if we aren't in the entry point, fix the IO as such and exit
  1807. if (userFunction.getName().compare(intermediate.getEntryPointName().c_str()) != 0) {
  1808. remapNonEntryPointIO(userFunction);
  1809. return nullptr;
  1810. }
  1811. entryPointFunction = &userFunction; // needed in finish()
  1812. // Handle entry point attributes
  1813. handleEntryPointAttributes(loc, attributes);
  1814. // entry point logic...
  1815. // Move parameters and return value to shader in/out
  1816. TVariable* entryPointOutput; // gets created in remapEntryPointIO
  1817. TVector<TVariable*> inputs;
  1818. TVector<TVariable*> outputs;
  1819. remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
  1820. // Further this return/in/out transform by flattening, splitting, and assigning locations
  1821. const auto makeVariableInOut = [&](TVariable& variable) {
  1822. if (variable.getType().isStruct()) {
  1823. if (variable.getType().getQualifier().isArrayedIo(language)) {
  1824. if (variable.getType().containsBuiltIn())
  1825. split(variable);
  1826. } else if (shouldFlatten(variable.getType(), EvqVaryingIn /* not assigned yet, but close enough */, true))
  1827. flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */);
  1828. }
  1829. // TODO: flatten arrays too
  1830. // TODO: flatten everything in I/O
  1831. // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
  1832. // For clip and cull distance, multiple output variables potentially get merged
  1833. // into one in assignClipCullDistance. That code in assignClipCullDistance
  1834. // handles the interface logic, so we avoid it here in that case.
  1835. if (!isClipOrCullDistance(variable.getType()))
  1836. assignToInterface(variable);
  1837. };
  1838. if (entryPointOutput != nullptr)
  1839. makeVariableInOut(*entryPointOutput);
  1840. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1841. if (!isDsPcfInput((*it)->getType())) // wait until the end for PCF input (see comment below)
  1842. makeVariableInOut(*(*it));
  1843. for (auto it = outputs.begin(); it != outputs.end(); ++it)
  1844. makeVariableInOut(*(*it));
  1845. // In the domain shader, PCF input must be at the end of the linkage. That's because in the
  1846. // hull shader there is no ordering: the output comes from the separate PCF, which does not
  1847. // participate in the argument list. That is always put at the end of the HS linkage, so the
  1848. // input side of the DS must match. The argument may be in any position in the DS argument list
  1849. // however, so this ensures the linkage is built in the correct order regardless of argument order.
  1850. if (language == EShLangTessEvaluation) {
  1851. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1852. if (isDsPcfInput((*it)->getType()))
  1853. makeVariableInOut(*(*it));
  1854. }
  1855. // Synthesize the call
  1856. pushScope(); // matches the one in handleFunctionBody()
  1857. // new signature
  1858. TType voidType(EbtVoid);
  1859. TFunction synthEntryPoint(&userFunction.getName(), voidType);
  1860. TIntermAggregate* synthParams = new TIntermAggregate();
  1861. intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
  1862. intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
  1863. intermediate.incrementEntryPointCount();
  1864. TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
  1865. // change original name
  1866. userFunction.addPrefix("@"); // change the name in the function, but not in the symbol table
  1867. // Copy inputs (shader-in -> calling arg), while building up the call node
  1868. TVector<TVariable*> argVars;
  1869. TIntermAggregate* synthBody = new TIntermAggregate();
  1870. auto inputIt = inputs.begin();
  1871. TIntermTyped* callingArgs = nullptr;
  1872. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1873. TParameter& param = userFunction[i];
  1874. argVars.push_back(makeInternalVariable(*param.name, *param.type));
  1875. argVars.back()->getWritableType().getQualifier().makeTemporary();
  1876. // Track the input patch, which is the only non-builtin supported by hull shader PCF.
  1877. if (param.getDeclaredBuiltIn() == EbvInputPatch)
  1878. inputPatch = argVars.back();
  1879. TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
  1880. handleFunctionArgument(&callee, callingArgs, arg);
  1881. if (param.type->getQualifier().isParamInput()) {
  1882. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
  1883. intermediate.addSymbol(**inputIt)));
  1884. inputIt++;
  1885. }
  1886. }
  1887. // Call
  1888. currentCaller = synthEntryPoint.getMangledName();
  1889. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  1890. currentCaller = userFunction.getMangledName();
  1891. // Return value
  1892. if (entryPointOutput) {
  1893. TIntermTyped* returnAssign;
  1894. // For hull shaders, the wrapped entry point return value is written to
  1895. // an array element as indexed by invocation ID, which we might have to make up.
  1896. // This is required to match SPIR-V semantics.
  1897. if (language == EShLangTessControl) {
  1898. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  1899. // If there is no user declared invocation ID, we must make one.
  1900. if (invocationIdSym == nullptr) {
  1901. TType invocationIdType(EbtUint, EvqIn, 1);
  1902. TString* invocationIdName = NewPoolTString("InvocationId");
  1903. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  1904. TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
  1905. globalQualifierFix(loc, variable->getWritableType().getQualifier());
  1906. trackLinkage(*variable);
  1907. invocationIdSym = intermediate.addSymbol(*variable);
  1908. }
  1909. TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
  1910. invocationIdSym, loc);
  1911. // Set the type of the array element being dereferenced
  1912. const TType derefElementType(entryPointOutput->getType(), 0);
  1913. element->setType(derefElementType);
  1914. returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
  1915. } else {
  1916. returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
  1917. }
  1918. intermediate.growAggregate(synthBody, returnAssign);
  1919. } else
  1920. intermediate.growAggregate(synthBody, callReturn);
  1921. // Output copies
  1922. auto outputIt = outputs.begin();
  1923. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1924. TParameter& param = userFunction[i];
  1925. // GS outputs are via emit, so we do not copy them here.
  1926. if (param.type->getQualifier().isParamOutput()) {
  1927. if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
  1928. // GS output stream does not assign outputs here: it's the Append() method
  1929. // which writes to the output, probably multiple times separated by Emit.
  1930. // We merely remember the output to use, here.
  1931. gsStreamOutput = *outputIt;
  1932. } else {
  1933. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
  1934. intermediate.addSymbol(**outputIt),
  1935. intermediate.addSymbol(*argVars[i])));
  1936. }
  1937. outputIt++;
  1938. }
  1939. }
  1940. // Put the pieces together to form a full function subtree
  1941. // for the synthesized entry point.
  1942. synthBody->setOperator(EOpSequence);
  1943. TIntermNode* synthFunctionDef = synthParams;
  1944. handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
  1945. entryPointFunctionBody = synthBody;
  1946. return synthFunctionDef;
  1947. }
  1948. void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
  1949. TIntermNode*& node)
  1950. {
  1951. node = intermediate.growAggregate(node, functionBody);
  1952. intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
  1953. node->getAsAggregate()->setName(function.getMangledName().c_str());
  1954. popScope();
  1955. if (function.hasImplicitThis())
  1956. popImplicitThis();
  1957. if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
  1958. error(loc, "function does not return a value:", "", function.getName().c_str());
  1959. }
  1960. // AST I/O is done through shader globals declared in the 'in' or 'out'
  1961. // storage class. An HLSL entry point has a return value, input parameters
  1962. // and output parameters. These need to get remapped to the AST I/O.
  1963. void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
  1964. TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
  1965. {
  1966. // We might have in input structure type with no decorations that caused it
  1967. // to look like an input type, yet it has (e.g.) interpolation types that
  1968. // must be modified that turn it into an input type.
  1969. // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
  1970. const auto synthesizeEditedInput = [this](TType& type) {
  1971. // True if a type needs to be 'flat'
  1972. const auto needsFlat = [](const TType& type) {
  1973. return type.containsBasicType(EbtInt) ||
  1974. type.containsBasicType(EbtUint) ||
  1975. type.containsBasicType(EbtInt64) ||
  1976. type.containsBasicType(EbtUint64) ||
  1977. type.containsBasicType(EbtBool) ||
  1978. type.containsBasicType(EbtDouble);
  1979. };
  1980. if (language == EShLangFragment && needsFlat(type)) {
  1981. if (type.isStruct()) {
  1982. TTypeList* finalList = nullptr;
  1983. auto it = ioTypeMap.find(type.getStruct());
  1984. if (it == ioTypeMap.end() || it->second.input == nullptr) {
  1985. // Getting here means we have no input struct, but we need one.
  1986. auto list = new TTypeList;
  1987. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  1988. TType* newType = new TType;
  1989. newType->shallowCopy(*member->type);
  1990. TTypeLoc typeLoc = { newType, member->loc };
  1991. list->push_back(typeLoc);
  1992. }
  1993. // install the new input type
  1994. if (it == ioTypeMap.end()) {
  1995. tIoKinds newLists = { list, nullptr, nullptr };
  1996. ioTypeMap[type.getStruct()] = newLists;
  1997. } else
  1998. it->second.input = list;
  1999. finalList = list;
  2000. } else
  2001. finalList = it->second.input;
  2002. // edit for 'flat'
  2003. for (auto member = finalList->begin(); member != finalList->end(); ++member) {
  2004. if (needsFlat(*member->type)) {
  2005. member->type->getQualifier().clearInterpolation();
  2006. member->type->getQualifier().flat = true;
  2007. }
  2008. }
  2009. } else {
  2010. type.getQualifier().clearInterpolation();
  2011. type.getQualifier().flat = true;
  2012. }
  2013. }
  2014. };
  2015. // Do the actual work to make a type be a shader input or output variable,
  2016. // and clear the original to be non-IO (for use as a normal function parameter/return).
  2017. const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
  2018. TVariable* ioVariable = makeInternalVariable(name, type);
  2019. clearUniformInputOutput(type.getQualifier());
  2020. if (type.isStruct()) {
  2021. auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
  2022. if (newLists != ioTypeMap.end()) {
  2023. if (storage == EvqVaryingIn && newLists->second.input)
  2024. ioVariable->getWritableType().setStruct(newLists->second.input);
  2025. else if (storage == EvqVaryingOut && newLists->second.output)
  2026. ioVariable->getWritableType().setStruct(newLists->second.output);
  2027. }
  2028. }
  2029. if (storage == EvqVaryingIn) {
  2030. correctInput(ioVariable->getWritableType().getQualifier());
  2031. if (language == EShLangTessEvaluation)
  2032. if (!ioVariable->getType().isArray())
  2033. ioVariable->getWritableType().getQualifier().patch = true;
  2034. } else {
  2035. correctOutput(ioVariable->getWritableType().getQualifier());
  2036. }
  2037. ioVariable->getWritableType().getQualifier().storage = storage;
  2038. fixBuiltInIoType(ioVariable->getWritableType());
  2039. return ioVariable;
  2040. };
  2041. // return value is actually a shader-scoped output (out)
  2042. if (function.getType().getBasicType() == EbtVoid) {
  2043. returnValue = nullptr;
  2044. } else {
  2045. if (language == EShLangTessControl) {
  2046. // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
  2047. // array in SPIR-V semantics. We'll write to it indexed by invocation ID.
  2048. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2049. TType outputType;
  2050. outputType.shallowCopy(function.getType());
  2051. // vertices has necessarily already been set when handling entry point attributes.
  2052. TArraySizes* arraySizes = new TArraySizes;
  2053. arraySizes->addInnerSize(intermediate.getVertices());
  2054. outputType.transferArraySizes(arraySizes);
  2055. clearUniformInputOutput(function.getWritableType().getQualifier());
  2056. returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
  2057. } else {
  2058. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2059. }
  2060. }
  2061. // parameters are actually shader-scoped inputs and outputs (in or out)
  2062. for (int i = 0; i < function.getParamCount(); i++) {
  2063. TType& paramType = *function[i].type;
  2064. if (paramType.getQualifier().isParamInput()) {
  2065. synthesizeEditedInput(paramType);
  2066. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
  2067. inputs.push_back(argAsGlobal);
  2068. }
  2069. if (paramType.getQualifier().isParamOutput()) {
  2070. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
  2071. outputs.push_back(argAsGlobal);
  2072. }
  2073. }
  2074. }
  2075. // An HLSL function that looks like an entry point, but is not,
  2076. // declares entry point IO built-ins, but these have to be undone.
  2077. void HlslParseContext::remapNonEntryPointIO(TFunction& function)
  2078. {
  2079. // return value
  2080. if (function.getType().getBasicType() != EbtVoid)
  2081. clearUniformInputOutput(function.getWritableType().getQualifier());
  2082. // parameters.
  2083. // References to structuredbuffer types are left unmodified
  2084. for (int i = 0; i < function.getParamCount(); i++)
  2085. if (!isReference(*function[i].type))
  2086. clearUniformInputOutput(function[i].type->getQualifier());
  2087. }
  2088. // Handle function returns, including type conversions to the function return type
  2089. // if necessary.
  2090. TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
  2091. {
  2092. functionReturnsValue = true;
  2093. if (currentFunctionType->getBasicType() == EbtVoid) {
  2094. error(loc, "void function cannot return a value", "return", "");
  2095. return intermediate.addBranch(EOpReturn, loc);
  2096. } else if (*currentFunctionType != value->getType()) {
  2097. value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
  2098. if (value && *currentFunctionType != value->getType())
  2099. value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
  2100. if (value == nullptr || *currentFunctionType != value->getType()) {
  2101. error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
  2102. return value;
  2103. }
  2104. }
  2105. return intermediate.addBranch(EOpReturn, value, loc);
  2106. }
  2107. void HlslParseContext::handleFunctionArgument(TFunction* function,
  2108. TIntermTyped*& arguments, TIntermTyped* newArg)
  2109. {
  2110. TParameter param = { 0, new TType, nullptr };
  2111. param.type->shallowCopy(newArg->getType());
  2112. function->addParameter(param);
  2113. if (arguments)
  2114. arguments = intermediate.growAggregate(arguments, newArg);
  2115. else
  2116. arguments = newArg;
  2117. }
  2118. // Position may require special handling: we can optionally invert Y.
  2119. // See: https://github.com/KhronosGroup/glslang/issues/1173
  2120. // https://github.com/KhronosGroup/glslang/issues/494
  2121. TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
  2122. TIntermTyped* left, TIntermTyped* right)
  2123. {
  2124. // If we are not asked for Y inversion, use a plain old assign.
  2125. if (!intermediate.getInvertY())
  2126. return intermediate.addAssign(op, left, right, loc);
  2127. // If we get here, we should invert Y.
  2128. TIntermAggregate* assignList = nullptr;
  2129. // If this is a complex rvalue, we don't want to dereference it many times. Create a temporary.
  2130. TVariable* rhsTempVar = nullptr;
  2131. rhsTempVar = makeInternalVariable("@position", right->getType());
  2132. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2133. {
  2134. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2135. assignList = intermediate.growAggregate(assignList,
  2136. intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
  2137. }
  2138. // pos.y = -pos.y
  2139. {
  2140. const int Y = 1;
  2141. TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
  2142. TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
  2143. TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
  2144. TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
  2145. TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
  2146. const TType derefType(right->getType(), 0);
  2147. lhsElement->setType(derefType);
  2148. rhsElement->setType(derefType);
  2149. TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
  2150. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
  2151. }
  2152. // Assign the rhs temp (now with Y inversion) to the final output
  2153. {
  2154. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2155. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
  2156. }
  2157. assert(assignList != nullptr);
  2158. assignList->setOperator(EOpSequence);
  2159. return assignList;
  2160. }
  2161. // Clip and cull distance require special handling due to a semantic mismatch. In HLSL,
  2162. // these can be float scalar, float vector, or arrays of float scalar or float vector.
  2163. // In SPIR-V, they are arrays of scalar floats in all cases. We must copy individual components
  2164. // (e.g, both x and y components of a float2) out into the destination float array.
  2165. //
  2166. // The values are assigned to sequential members of the output array. The inner dimension
  2167. // is vector components. The outer dimension is array elements.
  2168. TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
  2169. TIntermTyped* left, TIntermTyped* right)
  2170. {
  2171. switch (language) {
  2172. case EShLangFragment:
  2173. case EShLangVertex:
  2174. case EShLangGeometry:
  2175. break;
  2176. default:
  2177. error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
  2178. return nullptr;
  2179. }
  2180. TVariable** clipCullVar = nullptr;
  2181. // Figure out if we are assigning to, or from, clip or cull distance.
  2182. const bool isOutput = isClipOrCullDistance(left->getType());
  2183. // This is the rvalue or lvalue holding the clip or cull distance.
  2184. TIntermTyped* clipCullNode = isOutput ? left : right;
  2185. // This is the value going into or out of the clip or cull distance.
  2186. TIntermTyped* internalNode = isOutput ? right : left;
  2187. const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
  2188. decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
  2189. // Refer to either the clip or the cull distance, depending on semantic.
  2190. switch (builtInType) {
  2191. case EbvClipDistance:
  2192. clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
  2193. semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
  2194. break;
  2195. case EbvCullDistance:
  2196. clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
  2197. semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
  2198. break;
  2199. // called invalidly: we expected a clip or a cull distance.
  2200. // static compile time problem: should not happen.
  2201. default: assert(0); return nullptr;
  2202. }
  2203. // This is the offset in the destination array of a given semantic's data
  2204. std::array<int, maxClipCullRegs> semanticOffset;
  2205. // Calculate offset of variable of semantic N in destination array
  2206. int arrayLoc = 0;
  2207. int vecItems = 0;
  2208. for (int x = 0; x < maxClipCullRegs; ++x) {
  2209. // See if we overflowed the vec4 packing
  2210. if ((vecItems + (*semanticNSize)[x]) > 4) {
  2211. arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
  2212. vecItems = 0;
  2213. }
  2214. semanticOffset[x] = arrayLoc;
  2215. vecItems += (*semanticNSize)[x];
  2216. arrayLoc += (*semanticNSize)[x];
  2217. }
  2218. // It can have up to 2 array dimensions (in the case of geometry shader inputs)
  2219. const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
  2220. const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
  2221. // vector sizes:
  2222. const int internalVectorSize = internalNode->getType().getVectorSize();
  2223. // array sizes, or 1 if it's not an array:
  2224. const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
  2225. const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
  2226. // The created type may be an array of arrays, e.g, for geometry shader inputs.
  2227. const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
  2228. // If we haven't created the output already, create it now.
  2229. if (*clipCullVar == nullptr) {
  2230. // ClipDistance and CullDistance are handled specially in the entry point input/output copy
  2231. // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
  2232. // into a float array, or vice versa. Here, we make the array the right size and type,
  2233. // which depends on the incoming data, which has several potential dimensions:
  2234. // * Semantic ID
  2235. // * vector size
  2236. // * array size
  2237. // Of those, semantic ID and array size cannot appear simultaneously.
  2238. //
  2239. // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
  2240. // array dimensions. The shader's declaration may have one or two array dimensions. One is always
  2241. // the geometry's dimension.
  2242. const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
  2243. const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
  2244. const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
  2245. TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
  2246. clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
  2247. // Create required array dimension
  2248. TArraySizes* arraySizes = new TArraySizes;
  2249. if (isImplicitlyArrayed)
  2250. arraySizes->addInnerSize(requiredOuterArraySize);
  2251. arraySizes->addInnerSize(requiredInnerArraySize);
  2252. clipCullType.transferArraySizes(arraySizes);
  2253. // Obtain symbol name: we'll use that for the symbol we introduce.
  2254. TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
  2255. assert(sym != nullptr);
  2256. // We are moving the semantic ID from the layout location, so it is no longer needed or
  2257. // desired there.
  2258. clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  2259. // Create variable and track its linkage
  2260. *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
  2261. trackLinkage(**clipCullVar);
  2262. }
  2263. // Create symbol for the clip or cull variable.
  2264. TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
  2265. // vector sizes:
  2266. const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
  2267. // array sizes, or 1 if it's not an array:
  2268. const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
  2269. const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
  2270. const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
  2271. // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
  2272. // fixBuiltInIoType() should have handled that upstream.
  2273. assert(clipCullSym->getType().isArray());
  2274. assert(clipCullSym->getType().getVectorSize() == 1);
  2275. assert(clipCullSym->getType().getBasicType() == EbtFloat);
  2276. // We may be creating multiple sub-assignments. This is an aggregate to hold them.
  2277. // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
  2278. TIntermAggregate* assignList = nullptr;
  2279. // Holds individual component assignments as we make them.
  2280. TIntermTyped* clipCullAssign = nullptr;
  2281. // If the types are homomorphic, use a simple assign. No need to mess about with
  2282. // individual components.
  2283. if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
  2284. clipCullInnerArraySize == internalInnerArraySize &&
  2285. clipCullOuterArraySize == internalOuterArraySize &&
  2286. clipCullVectorSize == internalVectorSize) {
  2287. if (isOutput)
  2288. clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
  2289. else
  2290. clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
  2291. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2292. assignList->setOperator(EOpSequence);
  2293. return assignList;
  2294. }
  2295. // We are going to copy each component of the internal (per array element if indicated) to sequential
  2296. // array elements of the clipCullSym. This tracks the lhs element we're writing to as we go along.
  2297. // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
  2298. int clipCullInnerArrayPos = semanticOffset[semanticId];
  2299. int clipCullOuterArrayPos = 0;
  2300. // Lambda to add an index to a node, set the type of the result, and return the new node.
  2301. const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
  2302. const TType derefType(node->getType(), 0);
  2303. node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
  2304. node->setType(derefType);
  2305. return node;
  2306. };
  2307. // Loop through every component of every element of the internal, and copy to or from the matching external.
  2308. for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
  2309. for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
  2310. for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
  2311. // clip/cull array member to read from / write to:
  2312. TIntermTyped* clipCullMember = clipCullSym;
  2313. // If implicitly arrayed, there is an outer array dimension involved
  2314. if (isImplicitlyArrayed)
  2315. clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
  2316. // Index into proper array position for clip cull member
  2317. clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
  2318. // if needed, start over with next outer array slice.
  2319. if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
  2320. clipCullInnerArrayPos = semanticOffset[semanticId];
  2321. ++clipCullOuterArrayPos;
  2322. }
  2323. // internal member to read from / write to:
  2324. TIntermTyped* internalMember = internalNode;
  2325. // If internal node has outer array dimension, index appropriately.
  2326. if (internalArrayDims > 1)
  2327. internalMember = addIndex(internalMember, internalOuterArrayPos);
  2328. // If internal node has inner array dimension, index appropriately.
  2329. if (internalArrayDims > 0)
  2330. internalMember = addIndex(internalMember, internalInnerArrayPos);
  2331. // If internal node is a vector, extract the component of interest.
  2332. if (internalNode->getType().isVector())
  2333. internalMember = addIndex(internalMember, internalComponent);
  2334. // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
  2335. if (isOutput)
  2336. clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
  2337. else
  2338. clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
  2339. // Track assignment in the sequence.
  2340. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2341. }
  2342. }
  2343. }
  2344. assert(assignList != nullptr);
  2345. assignList->setOperator(EOpSequence);
  2346. return assignList;
  2347. }
  2348. // Some simple source assignments need to be flattened to a sequence
  2349. // of AST assignments. Catch these and flatten, otherwise, pass through
  2350. // to intermediate.addAssign().
  2351. //
  2352. // Also, assignment to matrix swizzles requires multiple component assignments,
  2353. // intercept those as well.
  2354. TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2355. TIntermTyped* right)
  2356. {
  2357. if (left == nullptr || right == nullptr)
  2358. return nullptr;
  2359. // writing to opaques will require fixing transforms
  2360. if (left->getType().containsOpaque())
  2361. intermediate.setNeedsLegalization();
  2362. if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
  2363. return handleAssignToMatrixSwizzle(loc, op, left, right);
  2364. // Return true if the given node is an index operation into a split variable.
  2365. const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
  2366. const TIntermBinary* binaryNode = node->getAsBinaryNode();
  2367. if (binaryNode == nullptr)
  2368. return false;
  2369. return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) &&
  2370. wasSplit(binaryNode->getLeft());
  2371. };
  2372. // Return true if this stage assigns clip position with potentially inverted Y
  2373. const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
  2374. return node->getType().getQualifier().builtIn == EbvPosition &&
  2375. (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
  2376. };
  2377. const bool isSplitLeft = wasSplit(left) || indexesSplit(left);
  2378. const bool isSplitRight = wasSplit(right) || indexesSplit(right);
  2379. const bool isFlattenLeft = wasFlattened(left);
  2380. const bool isFlattenRight = wasFlattened(right);
  2381. // OK to do a single assign if neither side is split or flattened. Otherwise,
  2382. // fall through to a member-wise copy.
  2383. if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
  2384. // Clip and cull distance requires more processing. See comment above assignClipCullDistance.
  2385. if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
  2386. const bool isOutput = isClipOrCullDistance(left->getType());
  2387. const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
  2388. return assignClipCullDistance(loc, op, semanticId, left, right);
  2389. } else if (assignsClipPos(left)) {
  2390. // Position can require special handling: see comment above assignPosition
  2391. return assignPosition(loc, op, left, right);
  2392. } else if (left->getQualifier().builtIn == EbvSampleMask) {
  2393. // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
  2394. // in the shader. Copy the scalar RHS into the LHS array element zero, if that happens.
  2395. if (left->isArray() && !right->isArray()) {
  2396. const TType derefType(left->getType(), 0);
  2397. left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
  2398. left->setType(derefType);
  2399. // Fall through to add assign.
  2400. }
  2401. }
  2402. return intermediate.addAssign(op, left, right, loc);
  2403. }
  2404. TIntermAggregate* assignList = nullptr;
  2405. const TVector<TVariable*>* leftVariables = nullptr;
  2406. const TVector<TVariable*>* rightVariables = nullptr;
  2407. // A temporary to store the right node's value, so we don't keep indirecting into it
  2408. // if it's not a simple symbol.
  2409. TVariable* rhsTempVar = nullptr;
  2410. // If the RHS is a simple symbol node, we'll copy it for each member.
  2411. TIntermSymbol* cloneSymNode = nullptr;
  2412. int memberCount = 0;
  2413. // Track how many items there are to copy.
  2414. if (left->getType().isStruct())
  2415. memberCount = (int)left->getType().getStruct()->size();
  2416. if (left->getType().isArray())
  2417. memberCount = left->getType().getCumulativeArraySize();
  2418. if (isFlattenLeft)
  2419. leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
  2420. if (isFlattenRight) {
  2421. rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
  2422. } else {
  2423. // The RHS is not flattened. There are several cases:
  2424. // 1. 1 item to copy: Use the RHS directly.
  2425. // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
  2426. // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
  2427. if (memberCount <= 1) {
  2428. // case 1: we'll use the symbol directly below. Nothing to do.
  2429. } else {
  2430. if (right->getAsSymbolNode() != nullptr) {
  2431. // case 2: we'll copy the symbol per iteration below.
  2432. cloneSymNode = right->getAsSymbolNode();
  2433. } else {
  2434. // case 3: assign to a temp, and indirect into that.
  2435. rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
  2436. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2437. TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
  2438. // Add this to the aggregate being built.
  2439. assignList = intermediate.growAggregate(assignList,
  2440. intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
  2441. }
  2442. }
  2443. }
  2444. // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
  2445. // variables, which is awkward when copying between split and unsplit structures. This variable tracks
  2446. // array indirections so they can be percolated from outer structs to inner variables.
  2447. std::vector <int> arrayElement;
  2448. TStorageQualifier leftStorage = left->getType().getQualifier().storage;
  2449. TStorageQualifier rightStorage = right->getType().getQualifier().storage;
  2450. int leftOffset = findSubtreeOffset(*left);
  2451. int rightOffset = findSubtreeOffset(*right);
  2452. const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
  2453. bool flattened)
  2454. -> TIntermTyped * {
  2455. const bool split = isLeft ? isSplitLeft : isSplitRight;
  2456. TIntermTyped* subTree;
  2457. const TType derefType(type, member);
  2458. const TVariable* builtInVar = nullptr;
  2459. if ((flattened || split) && derefType.isBuiltIn()) {
  2460. auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
  2461. derefType.getQualifier().builtIn,
  2462. isLeft ? leftStorage : rightStorage));
  2463. if (splitPair != splitBuiltIns.end())
  2464. builtInVar = splitPair->second;
  2465. }
  2466. if (builtInVar != nullptr) {
  2467. // copy from interstage IO built-in if needed
  2468. subTree = intermediate.addSymbol(*builtInVar);
  2469. if (subTree->getType().isArray()) {
  2470. // Arrayness of builtIn symbols isn't handled by the normal recursion:
  2471. // it's been extracted and moved to the built-in.
  2472. if (!arrayElement.empty()) {
  2473. const TType splitDerefType(subTree->getType(), arrayElement.back());
  2474. subTree = intermediate.addIndex(EOpIndexDirect, subTree,
  2475. intermediate.addConstantUnion(arrayElement.back(), loc), loc);
  2476. subTree->setType(splitDerefType);
  2477. } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
  2478. // This might also be a stage with arrayed outputs, in which case there's an index
  2479. // operation we should transfer to the output builtin.
  2480. const TType splitDerefType(subTree->getType(), 0);
  2481. subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
  2482. splitNode->getAsBinaryNode()->getRight(), loc);
  2483. subTree->setType(splitDerefType);
  2484. }
  2485. }
  2486. } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
  2487. if (isLeft)
  2488. subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
  2489. else
  2490. subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
  2491. } else {
  2492. // Index operator if it's an aggregate, else EOpNull
  2493. const TOperator accessOp = type.isArray() ? EOpIndexDirect
  2494. : type.isStruct() ? EOpIndexDirectStruct
  2495. : EOpNull;
  2496. if (accessOp == EOpNull) {
  2497. subTree = splitNode;
  2498. } else {
  2499. subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
  2500. loc);
  2501. const TType splitDerefType(splitNode->getType(), splitMember);
  2502. subTree->setType(splitDerefType);
  2503. }
  2504. }
  2505. return subTree;
  2506. };
  2507. // Use the proper RHS node: a new symbol from a TVariable, copy
  2508. // of an TIntermSymbol node, or sometimes the right node directly.
  2509. right = rhsTempVar != nullptr ? intermediate.addSymbol(*rhsTempVar, loc) :
  2510. cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
  2511. right;
  2512. // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
  2513. // whole thing. So, we'll resort to an explicit type via std::function.
  2514. const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2515. bool topLevel)>
  2516. traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2517. bool topLevel) -> void {
  2518. // If we get here, we are assigning to or from a whole array or struct that must be
  2519. // flattened, so have to do member-by-member assignment:
  2520. bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
  2521. bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
  2522. if ((left->getType().isArray() || right->getType().isArray()) &&
  2523. (shouldFlattenSubsetLeft || isSplitLeft ||
  2524. shouldFlattenSubsetRight || isSplitRight)) {
  2525. const int elementsL = left->getType().isArray() ? left->getType().getOuterArraySize() : 1;
  2526. const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
  2527. // The arrays might not be the same size,
  2528. // e.g., if the size has been forced for EbvTessLevelInner/Outer.
  2529. const int elementsToCopy = std::min(elementsL, elementsR);
  2530. // array case
  2531. for (int element = 0; element < elementsToCopy; ++element) {
  2532. arrayElement.push_back(element);
  2533. // Add a new AST symbol node if we have a temp variable holding a complex RHS.
  2534. TIntermTyped* subLeft = getMember(true, left->getType(), element, left, element,
  2535. shouldFlattenSubsetLeft);
  2536. TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
  2537. shouldFlattenSubsetRight);
  2538. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), element, splitLeft,
  2539. element, shouldFlattenSubsetLeft)
  2540. : subLeft;
  2541. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
  2542. element, shouldFlattenSubsetRight)
  2543. : subRight;
  2544. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2545. arrayElement.pop_back();
  2546. }
  2547. } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft || isSplitLeft ||
  2548. shouldFlattenSubsetRight || isSplitRight)) {
  2549. // struct case
  2550. const auto& membersL = *left->getType().getStruct();
  2551. const auto& membersR = *right->getType().getStruct();
  2552. // These track the members in the split structures corresponding to the same in the unsplit structures,
  2553. // which we traverse in parallel.
  2554. int memberL = 0;
  2555. int memberR = 0;
  2556. // Handle empty structure assignment
  2557. if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
  2558. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2559. for (int member = 0; member < int(membersL.size()); ++member) {
  2560. const TType& typeL = *membersL[member].type;
  2561. const TType& typeR = *membersR[member].type;
  2562. TIntermTyped* subLeft = getMember(true, left->getType(), member, left, member,
  2563. shouldFlattenSubsetLeft);
  2564. TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
  2565. shouldFlattenSubsetRight);
  2566. // If there is no splitting, use the same values to avoid inefficiency.
  2567. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), member, splitLeft,
  2568. memberL, shouldFlattenSubsetLeft)
  2569. : subLeft;
  2570. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
  2571. memberR, shouldFlattenSubsetRight)
  2572. : subRight;
  2573. if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
  2574. // Clip and cull distance built-in assignment is complex in its own right, and is handled in
  2575. // a separate function dedicated to that task. See comment above assignClipCullDistance;
  2576. const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
  2577. // Since all clip/cull semantics boil down to the same built-in type, we need to get the
  2578. // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
  2579. const TType derefType((isOutput ? left : right)->getType(), member);
  2580. const int semanticId = derefType.getQualifier().layoutLocation;
  2581. TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
  2582. subSplitLeft, subSplitRight);
  2583. assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
  2584. } else if (assignsClipPos(subSplitLeft)) {
  2585. // Position can require special handling: see comment above assignPosition
  2586. TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
  2587. assignList = intermediate.growAggregate(assignList, positionAssign, loc);
  2588. } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
  2589. !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
  2590. // If this is the final flattening (no nested types below to flatten)
  2591. // we'll copy the member, else recurse into the type hierarchy.
  2592. // However, if splitting the struct, that means we can copy a whole
  2593. // subtree here IFF it does not itself contain any interstage built-in
  2594. // IO variables, so we only have to recurse into it if there's something
  2595. // for splitting to do. That can save a lot of AST verbosity for
  2596. // a bunch of memberwise copies.
  2597. assignList = intermediate.growAggregate(assignList,
  2598. intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
  2599. loc);
  2600. } else {
  2601. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2602. }
  2603. memberL += (typeL.isBuiltIn() ? 0 : 1);
  2604. memberR += (typeR.isBuiltIn() ? 0 : 1);
  2605. }
  2606. } else {
  2607. // Member copy
  2608. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2609. }
  2610. };
  2611. TIntermTyped* splitLeft = left;
  2612. TIntermTyped* splitRight = right;
  2613. // If either left or right was a split structure, we must read or write it, but still have to
  2614. // parallel-recurse through the unsplit structure to identify the built-in IO vars.
  2615. // The left can be either a symbol, or an index into a symbol (e.g, array reference)
  2616. if (isSplitLeft) {
  2617. if (indexesSplit(left)) {
  2618. // Index case: Refer to the indexed symbol, if the left is an index operator.
  2619. const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2620. TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2621. splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
  2622. left->getAsBinaryNode()->getRight(), loc);
  2623. const TType derefType(splitLeftNonIo->getType(), 0);
  2624. splitLeft->setType(derefType);
  2625. } else {
  2626. // Symbol case: otherwise, if not indexed, we have the symbol directly.
  2627. const TIntermSymbol* symNode = left->getAsSymbolNode();
  2628. splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2629. }
  2630. }
  2631. if (isSplitRight)
  2632. splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
  2633. // This makes the whole assignment, recursing through subtypes as needed.
  2634. traverse(left, right, splitLeft, splitRight, true);
  2635. assert(assignList != nullptr);
  2636. assignList->setOperator(EOpSequence);
  2637. return assignList;
  2638. }
  2639. // An assignment to matrix swizzle must be decomposed into individual assignments.
  2640. // These must be selected component-wise from the RHS and stored component-wise
  2641. // into the LHS.
  2642. TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2643. TIntermTyped* right)
  2644. {
  2645. assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
  2646. if (op != EOpAssign)
  2647. error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
  2648. // isolate the matrix and swizzle nodes
  2649. TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
  2650. const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
  2651. // if the RHS isn't already a simple vector, let's store into one
  2652. TIntermSymbol* vector = right->getAsSymbolNode();
  2653. TIntermTyped* vectorAssign = nullptr;
  2654. if (vector == nullptr) {
  2655. // create a new intermediate vector variable to assign to
  2656. TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
  2657. vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
  2658. // assign the right to the new vector
  2659. vectorAssign = handleAssign(loc, op, vector, right);
  2660. }
  2661. // Assign the vector components to the matrix components.
  2662. // Store this as a sequence, so a single aggregate node represents this
  2663. // entire operation.
  2664. TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
  2665. TType columnType(matrix->getType(), 0);
  2666. TType componentType(columnType, 0);
  2667. TType indexType(EbtInt);
  2668. for (int i = 0; i < (int)swizzle.size(); i += 2) {
  2669. // the right component, single index into the RHS vector
  2670. TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
  2671. intermediate.addConstantUnion(i/2, loc), loc);
  2672. // the left component, double index into the LHS matrix
  2673. TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
  2674. intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
  2675. indexType, loc),
  2676. loc);
  2677. leftComp->setType(columnType);
  2678. leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
  2679. intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
  2680. indexType, loc),
  2681. loc);
  2682. leftComp->setType(componentType);
  2683. // Add the assignment to the aggregate
  2684. result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
  2685. }
  2686. result->setOp(EOpSequence);
  2687. return result;
  2688. }
  2689. //
  2690. // HLSL atomic operations have slightly different arguments than
  2691. // GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
  2692. // This provides the post-decomposition equivalent opcode.
  2693. //
  2694. TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
  2695. {
  2696. switch (op) {
  2697. case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
  2698. case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
  2699. case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
  2700. case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
  2701. case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
  2702. case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
  2703. case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
  2704. case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
  2705. case EOpInterlockedCompareStore: // TODO: ...
  2706. default:
  2707. error(loc, "unknown atomic operation", "unknown op", "");
  2708. return EOpNull;
  2709. }
  2710. }
  2711. //
  2712. // Create a combined sampler/texture from separate sampler and texture.
  2713. //
  2714. TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
  2715. TIntermTyped* argSampler)
  2716. {
  2717. TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
  2718. txcombine->getSequence().push_back(argTex);
  2719. txcombine->getSequence().push_back(argSampler);
  2720. TSampler samplerType = argTex->getType().getSampler();
  2721. samplerType.combined = true;
  2722. // TODO:
  2723. // This block exists until the spec no longer requires shadow modes on texture objects.
  2724. // It can be deleted after that, along with the shadowTextureVariant member.
  2725. {
  2726. const bool shadowMode = argSampler->getType().getSampler().shadow;
  2727. TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
  2728. if (texSymbol == nullptr)
  2729. texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2730. if (texSymbol == nullptr) {
  2731. error(loc, "unable to find texture symbol", "", "");
  2732. return nullptr;
  2733. }
  2734. // This forces the texture's shadow state to be the sampler's
  2735. // shadow state. This depends on downstream optimization to
  2736. // DCE one variant in [shadow, nonshadow] if both are present,
  2737. // or the SPIR-V module would be invalid.
  2738. int newId = texSymbol->getId();
  2739. // Check to see if this texture has been given a shadow mode already.
  2740. // If so, look up the one we already have.
  2741. const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
  2742. if (textureShadowEntry != textureShadowVariant.end())
  2743. newId = textureShadowEntry->second->get(shadowMode);
  2744. else
  2745. textureShadowVariant[texSymbol->getId()] = NewPoolObject(tShadowTextureSymbols(), 1);
  2746. // Sometimes we have to create another symbol (if this texture has been seen before,
  2747. // and we haven't created the form for this shadow mode).
  2748. if (newId == -1) {
  2749. TType texType;
  2750. texType.shallowCopy(argTex->getType());
  2751. texType.getSampler().shadow = shadowMode; // set appropriate shadow mode.
  2752. globalQualifierFix(loc, texType.getQualifier());
  2753. TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
  2754. trackLinkage(*newTexture);
  2755. newId = newTexture->getUniqueId();
  2756. }
  2757. assert(newId != -1);
  2758. if (textureShadowVariant.find(newId) == textureShadowVariant.end())
  2759. textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
  2760. textureShadowVariant[newId]->set(shadowMode, newId);
  2761. // Remember this shadow mode in the texture and the merged type.
  2762. argTex->getWritableType().getSampler().shadow = shadowMode;
  2763. samplerType.shadow = shadowMode;
  2764. texSymbol->switchId(newId);
  2765. }
  2766. txcombine->setType(TType(samplerType, EvqTemporary));
  2767. txcombine->setLoc(loc);
  2768. return txcombine;
  2769. }
  2770. // Return true if this a buffer type that has an associated counter buffer.
  2771. bool HlslParseContext::hasStructBuffCounter(const TType& type) const
  2772. {
  2773. switch (type.getQualifier().declaredBuiltIn) {
  2774. case EbvAppendConsume: // fall through...
  2775. case EbvRWStructuredBuffer: // ...
  2776. return true;
  2777. default:
  2778. return false; // the other structuredbuffer types do not have a counter.
  2779. }
  2780. }
  2781. void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
  2782. {
  2783. // Counter type
  2784. TType* counterType = new TType(EbtUint, EvqBuffer);
  2785. counterType->setFieldName(intermediate.implicitCounterName);
  2786. TTypeList* blockStruct = new TTypeList;
  2787. TTypeLoc member = { counterType, loc };
  2788. blockStruct->push_back(member);
  2789. TType blockType(blockStruct, "", counterType->getQualifier());
  2790. blockType.getQualifier().storage = EvqBuffer;
  2791. type.shallowCopy(blockType);
  2792. shareStructBufferType(type);
  2793. }
  2794. // declare counter for a structured buffer type
  2795. void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
  2796. {
  2797. // Bail out if not a struct buffer
  2798. if (! isStructBufferType(bufferType))
  2799. return;
  2800. if (! hasStructBuffCounter(bufferType))
  2801. return;
  2802. TType blockType;
  2803. counterBufferType(loc, blockType);
  2804. TString* blockName = NewPoolTString(intermediate.addCounterBufferName(name).c_str());
  2805. // Counter buffer is not yet in use
  2806. structBufferCounter[*blockName] = false;
  2807. shareStructBufferType(blockType);
  2808. declareBlock(loc, blockType, blockName);
  2809. }
  2810. // return the counter that goes with a given structuredbuffer
  2811. TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
  2812. {
  2813. // Bail out if not a struct buffer
  2814. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  2815. return nullptr;
  2816. const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
  2817. // Mark the counter as being used
  2818. structBufferCounter[counterBlockName] = true;
  2819. TIntermTyped* counterVar = handleVariable(loc, &counterBlockName); // find the block structure
  2820. TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
  2821. TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
  2822. counterMember->setType(TType(EbtUint));
  2823. return counterMember;
  2824. }
  2825. //
  2826. // Decompose structure buffer methods into AST
  2827. //
  2828. void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  2829. {
  2830. if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
  2831. return;
  2832. const TOperator op = node->getAsOperator()->getOp();
  2833. TIntermAggregate* argAggregate = arguments->getAsAggregate();
  2834. // Buffer is the object upon which method is called, so always arg 0
  2835. TIntermTyped* bufferObj = nullptr;
  2836. // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
  2837. if (argAggregate) {
  2838. if (argAggregate->getSequence().empty())
  2839. return;
  2840. if (argAggregate->getSequence()[0])
  2841. bufferObj = argAggregate->getSequence()[0]->getAsTyped();
  2842. } else {
  2843. bufferObj = arguments->getAsSymbolNode();
  2844. }
  2845. if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
  2846. return;
  2847. // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
  2848. // This lambda adds something to it and returns the old value.
  2849. const auto incDecCounter = [&](int incval) -> TIntermTyped* {
  2850. TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
  2851. TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
  2852. if (counter == nullptr)
  2853. return nullptr;
  2854. TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
  2855. counterIncrement->setType(TType(EbtUint, EvqTemporary));
  2856. counterIncrement->setLoc(loc);
  2857. counterIncrement->getSequence().push_back(counter);
  2858. counterIncrement->getSequence().push_back(incrementValue);
  2859. return counterIncrement;
  2860. };
  2861. // Index to obtain the runtime sized array out of the buffer.
  2862. TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
  2863. if (argArray == nullptr)
  2864. return; // It might not be a struct buffer method.
  2865. switch (op) {
  2866. case EOpMethodLoad:
  2867. {
  2868. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2869. const TType& bufferType = bufferObj->getType();
  2870. const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
  2871. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2872. // buffer then, but that's what it calls itself.
  2873. const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer ||
  2874. builtInType == EbvRWByteAddressBuffer);
  2875. if (isByteAddressBuffer)
  2876. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2877. intermediate.addConstantUnion(2, loc, true),
  2878. loc, TType(EbtInt));
  2879. // Index into the array to find the item being loaded.
  2880. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2881. node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2882. const TType derefType(argArray->getType(), 0);
  2883. node->setType(derefType);
  2884. }
  2885. break;
  2886. case EOpMethodLoad2:
  2887. case EOpMethodLoad3:
  2888. case EOpMethodLoad4:
  2889. {
  2890. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2891. TOperator constructOp = EOpNull;
  2892. int size = 0;
  2893. switch (op) {
  2894. case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
  2895. case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
  2896. case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
  2897. default: assert(0);
  2898. }
  2899. TIntermTyped* body = nullptr;
  2900. // First, we'll store the address in a variable to avoid multiple shifts
  2901. // (we must convert the byte address to an item address)
  2902. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2903. intermediate.addConstantUnion(2, loc, true),
  2904. loc, TType(EbtInt));
  2905. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2906. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2907. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2908. TIntermTyped* vec = nullptr;
  2909. // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
  2910. // address conversion.
  2911. for (int idx=0; idx<size; ++idx) {
  2912. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2913. // add index offset
  2914. if (idx != 0)
  2915. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
  2916. intermediate.addConstantUnion(idx, loc, true),
  2917. loc, TType(EbtInt));
  2918. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2919. : EOpIndexIndirect;
  2920. TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2921. TType derefType(argArray->getType(), 0);
  2922. derefType.getQualifier().makeTemporary();
  2923. indexVal->setType(derefType);
  2924. vec = intermediate.growAggregate(vec, indexVal);
  2925. }
  2926. vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
  2927. vec->getAsAggregate()->setOperator(constructOp);
  2928. body = intermediate.growAggregate(body, vec);
  2929. body->setType(vec->getType());
  2930. body->getAsAggregate()->setOperator(EOpSequence);
  2931. node = body;
  2932. }
  2933. break;
  2934. case EOpMethodStore:
  2935. case EOpMethodStore2:
  2936. case EOpMethodStore3:
  2937. case EOpMethodStore4:
  2938. {
  2939. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2940. TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped(); // value
  2941. // Index into the array to find the item being loaded.
  2942. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2943. // buffer then, but that's what it calls itself).
  2944. int size = 0;
  2945. switch (op) {
  2946. case EOpMethodStore: size = 1; break;
  2947. case EOpMethodStore2: size = 2; break;
  2948. case EOpMethodStore3: size = 3; break;
  2949. case EOpMethodStore4: size = 4; break;
  2950. default: assert(0);
  2951. }
  2952. TIntermAggregate* body = nullptr;
  2953. // First, we'll store the address in a variable to avoid multiple shifts
  2954. // (we must convert the byte address to an item address)
  2955. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2956. intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
  2957. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2958. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2959. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2960. for (int idx=0; idx<size; ++idx) {
  2961. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2962. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  2963. // add index offset
  2964. if (idx != 0)
  2965. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
  2966. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2967. : EOpIndexIndirect;
  2968. TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2969. const TType derefType(argArray->getType(), 0);
  2970. lValue->setType(derefType);
  2971. TIntermTyped* rValue;
  2972. if (size == 1) {
  2973. rValue = argValue;
  2974. } else {
  2975. rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
  2976. const TType indexType(argValue->getType(), 0);
  2977. rValue->setType(indexType);
  2978. }
  2979. TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  2980. body = intermediate.growAggregate(body, assign);
  2981. }
  2982. body->setOperator(EOpSequence);
  2983. node = body;
  2984. }
  2985. break;
  2986. case EOpMethodGetDimensions:
  2987. {
  2988. const int numArgs = (int)argAggregate->getSequence().size();
  2989. TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped(); // out num items
  2990. TIntermTyped* argStride = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr; // out stride
  2991. TIntermAggregate* body = nullptr;
  2992. // Length output:
  2993. if (argArray->getType().isSizedArray()) {
  2994. const int length = argArray->getType().getOuterArraySize();
  2995. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
  2996. intermediate.addConstantUnion(length, loc, true), loc);
  2997. body = intermediate.growAggregate(body, assign, loc);
  2998. } else {
  2999. TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
  3000. argNumItems->getType());
  3001. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
  3002. body = intermediate.growAggregate(body, assign, loc);
  3003. }
  3004. // Stride output:
  3005. if (argStride != nullptr) {
  3006. int size;
  3007. int stride;
  3008. intermediate.getMemberAlignment(argArray->getType(), size, stride, argArray->getType().getQualifier().layoutPacking,
  3009. argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
  3010. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
  3011. intermediate.addConstantUnion(stride, loc, true), loc);
  3012. body = intermediate.growAggregate(body, assign);
  3013. }
  3014. body->setOperator(EOpSequence);
  3015. node = body;
  3016. }
  3017. break;
  3018. case EOpInterlockedAdd:
  3019. case EOpInterlockedAnd:
  3020. case EOpInterlockedExchange:
  3021. case EOpInterlockedMax:
  3022. case EOpInterlockedMin:
  3023. case EOpInterlockedOr:
  3024. case EOpInterlockedXor:
  3025. case EOpInterlockedCompareExchange:
  3026. case EOpInterlockedCompareStore:
  3027. {
  3028. // We'll replace the first argument with the block dereference, and let
  3029. // downstream decomposition handle the rest.
  3030. TIntermSequence& sequence = argAggregate->getSequence();
  3031. TIntermTyped* argIndex = makeIntegerIndex(sequence[1]->getAsTyped()); // index
  3032. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
  3033. loc, TType(EbtInt));
  3034. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3035. TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  3036. const TType derefType(argArray->getType(), 0);
  3037. element->setType(derefType);
  3038. // Replace the numeric byte offset parameter with array reference.
  3039. sequence[1] = element;
  3040. sequence.erase(sequence.begin(), sequence.begin()+1);
  3041. }
  3042. break;
  3043. case EOpMethodIncrementCounter:
  3044. {
  3045. node = incDecCounter(1);
  3046. break;
  3047. }
  3048. case EOpMethodDecrementCounter:
  3049. {
  3050. TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
  3051. node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
  3052. preIncValue->getType());
  3053. break;
  3054. }
  3055. case EOpMethodAppend:
  3056. {
  3057. TIntermTyped* oldCounter = incDecCounter(1);
  3058. TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
  3059. TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
  3060. const TType derefType(argArray->getType(), 0);
  3061. lValue->setType(derefType);
  3062. node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  3063. break;
  3064. }
  3065. case EOpMethodConsume:
  3066. {
  3067. TIntermTyped* oldCounter = incDecCounter(-1);
  3068. TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
  3069. intermediate.addConstantUnion(-1, loc, true), loc,
  3070. oldCounter->getType());
  3071. node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
  3072. const TType derefType(argArray->getType(), 0);
  3073. node->setType(derefType);
  3074. break;
  3075. }
  3076. default:
  3077. break; // most pass through unchanged
  3078. }
  3079. }
  3080. // Create array of standard sample positions for given sample count.
  3081. // TODO: remove when a real method to query sample pos exists in SPIR-V.
  3082. TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
  3083. {
  3084. struct tSamplePos { float x, y; };
  3085. static const tSamplePos pos1[] = {
  3086. { 0.0/16.0, 0.0/16.0 },
  3087. };
  3088. // standard sample positions for 2, 4, 8, and 16 samples.
  3089. static const tSamplePos pos2[] = {
  3090. { 4.0/16.0, 4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
  3091. };
  3092. static const tSamplePos pos4[] = {
  3093. {-2.0/16.0, -6.0/16.0 }, { 6.0/16.0, -2.0/16.0 }, {-6.0/16.0, 2.0/16.0 }, { 2.0/16.0, 6.0/16.0 },
  3094. };
  3095. static const tSamplePos pos8[] = {
  3096. { 1.0/16.0, -3.0/16.0 }, {-1.0/16.0, 3.0/16.0 }, { 5.0/16.0, 1.0/16.0 }, {-3.0/16.0, -5.0/16.0 },
  3097. {-5.0/16.0, 5.0/16.0 }, {-7.0/16.0, -1.0/16.0 }, { 3.0/16.0, 7.0/16.0 }, { 7.0/16.0, -7.0/16.0 },
  3098. };
  3099. static const tSamplePos pos16[] = {
  3100. { 1.0/16.0, 1.0/16.0 }, {-1.0/16.0, -3.0/16.0 }, {-3.0/16.0, 2.0/16.0 }, { 4.0/16.0, -1.0/16.0 },
  3101. {-5.0/16.0, -2.0/16.0 }, { 2.0/16.0, 5.0/16.0 }, { 5.0/16.0, 3.0/16.0 }, { 3.0/16.0, -5.0/16.0 },
  3102. {-2.0/16.0, 6.0/16.0 }, { 0.0/16.0, -7.0/16.0 }, {-4.0/16.0, -6.0/16.0 }, {-6.0/16.0, 4.0/16.0 },
  3103. {-8.0/16.0, 0.0/16.0 }, { 7.0/16.0, -4.0/16.0 }, { 6.0/16.0, 7.0/16.0 }, {-7.0/16.0, -8.0/16.0 },
  3104. };
  3105. const tSamplePos* sampleLoc = nullptr;
  3106. int numSamples = count;
  3107. switch (count) {
  3108. case 2: sampleLoc = pos2; break;
  3109. case 4: sampleLoc = pos4; break;
  3110. case 8: sampleLoc = pos8; break;
  3111. case 16: sampleLoc = pos16; break;
  3112. default:
  3113. sampleLoc = pos1;
  3114. numSamples = 1;
  3115. }
  3116. TConstUnionArray* values = new TConstUnionArray(numSamples*2);
  3117. for (int pos=0; pos<count; ++pos) {
  3118. TConstUnion x, y;
  3119. x.setDConst(sampleLoc[pos].x);
  3120. y.setDConst(sampleLoc[pos].y);
  3121. (*values)[pos*2+0] = x;
  3122. (*values)[pos*2+1] = y;
  3123. }
  3124. TType retType(EbtFloat, EvqConst, 2);
  3125. if (numSamples != 1) {
  3126. TArraySizes* arraySizes = new TArraySizes;
  3127. arraySizes->addInnerSize(numSamples);
  3128. retType.transferArraySizes(arraySizes);
  3129. }
  3130. return new TIntermConstantUnion(*values, retType);
  3131. }
  3132. //
  3133. // Decompose DX9 and DX10 sample intrinsics & object methods into AST
  3134. //
  3135. void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3136. {
  3137. if (node == nullptr || !node->getAsOperator())
  3138. return;
  3139. // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
  3140. const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
  3141. result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
  3142. TIntermTyped* convertedResult = nullptr;
  3143. TType retType;
  3144. getTextureReturnType(sampler, retType);
  3145. if (retType.isStruct()) {
  3146. // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
  3147. TIntermAggregate* conversionAggregate = new TIntermAggregate;
  3148. convertedResult = conversionAggregate;
  3149. // Convert vector output to return structure. We will need a temp symbol to copy the results to.
  3150. TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
  3151. // We also need a temp symbol to hold the result of the texture. We don't want to re-fetch the
  3152. // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
  3153. TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
  3154. // Initial copy from texture to our sample result shadow.
  3155. TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
  3156. result, loc);
  3157. conversionAggregate->getSequence().push_back(shadowCopy);
  3158. unsigned vec4Pos = 0;
  3159. for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
  3160. const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
  3161. // Check for bad struct members. This should have been caught upstream. Complain, because
  3162. // wwe don't know what to do with it. This algorithm could be generalized to handle
  3163. // other things, e.g, sub-structures, but HLSL doesn't allow them.
  3164. if (!memberType.isVector() && !memberType.isScalar()) {
  3165. error(loc, "expected: scalar or vector type in texture structure", "", "");
  3166. return nullptr;
  3167. }
  3168. // Index into the struct variable to find the member to assign.
  3169. TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
  3170. intermediate.addSymbol(*structVar, loc),
  3171. intermediate.addConstantUnion(m, loc), loc);
  3172. structMember->setType(memberType);
  3173. // Assign each component of (possible) vector in struct member.
  3174. for (int component = 0; component < memberType.getVectorSize(); ++component) {
  3175. TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
  3176. intermediate.addSymbol(*sampleShadow, loc),
  3177. intermediate.addConstantUnion(vec4Pos++, loc), loc);
  3178. vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
  3179. TIntermTyped* memberAssign = nullptr;
  3180. if (memberType.isVector()) {
  3181. // Vector member: we need to create an access chain to the vector component.
  3182. TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
  3183. intermediate.addConstantUnion(component, loc), loc);
  3184. memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
  3185. } else {
  3186. // Scalar member: we can assign to it directly.
  3187. memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
  3188. }
  3189. conversionAggregate->getSequence().push_back(memberAssign);
  3190. }
  3191. }
  3192. // Add completed variable so the expression results in the whole struct value we just built.
  3193. conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
  3194. // Make it a sequence.
  3195. intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
  3196. } else {
  3197. // vector clamp the output if template vector type is smaller than sample result.
  3198. if (retType.getVectorSize() < node->getVectorSize()) {
  3199. // Too many components. Construct shorter vector from it.
  3200. const TOperator op = intermediate.mapTypeToConstructorOp(retType);
  3201. convertedResult = constructBuiltIn(retType, op, result, loc, false);
  3202. } else {
  3203. // Enough components. Use directly.
  3204. convertedResult = result;
  3205. }
  3206. }
  3207. convertedResult->setLoc(loc);
  3208. return convertedResult;
  3209. };
  3210. const TOperator op = node->getAsOperator()->getOp();
  3211. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3212. // Bail out if not a sampler method.
  3213. // Note though this is odd to do before checking the op, because the op
  3214. // could be something that takes the arguments, and the function in question
  3215. // takes the result of the op. So, this is not the final word.
  3216. if (arguments != nullptr) {
  3217. if (argAggregate == nullptr) {
  3218. if (arguments->getAsTyped()->getBasicType() != EbtSampler)
  3219. return;
  3220. } else {
  3221. if (argAggregate->getSequence().size() == 0 ||
  3222. argAggregate->getSequence()[0] == nullptr ||
  3223. argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
  3224. return;
  3225. }
  3226. }
  3227. switch (op) {
  3228. // **** DX9 intrinsics: ****
  3229. case EOpTexture:
  3230. {
  3231. // Texture with ddx & ddy is really gradient form in HLSL
  3232. if (argAggregate->getSequence().size() == 4)
  3233. node->getAsAggregate()->setOperator(EOpTextureGrad);
  3234. break;
  3235. }
  3236. case EOpTextureLod: //is almost EOpTextureBias (only args & operations are different)
  3237. {
  3238. TIntermTyped *argSamp = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3239. TIntermTyped *argCoord = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3240. assert(argCoord->getVectorSize() == 4);
  3241. TIntermTyped *w = intermediate.addConstantUnion(3, loc, true);
  3242. TIntermTyped *argLod = intermediate.addIndex(EOpIndexDirect, argCoord, w, loc);
  3243. TOperator constructOp = EOpNull;
  3244. const TSampler &sampler = argSamp->getType().getSampler();
  3245. int coordSize = 0;
  3246. switch (sampler.dim)
  3247. {
  3248. case Esd1D: constructOp = EOpConstructFloat; coordSize = 1; break; // 1D
  3249. case Esd2D: constructOp = EOpConstructVec2; coordSize = 2; break; // 2D
  3250. case Esd3D: constructOp = EOpConstructVec3; coordSize = 3; break; // 3D
  3251. case EsdCube: constructOp = EOpConstructVec3; coordSize = 3; break; // also 3D
  3252. default:
  3253. break;
  3254. }
  3255. TIntermAggregate *constructCoord = new TIntermAggregate(constructOp);
  3256. constructCoord->getSequence().push_back(argCoord);
  3257. constructCoord->setLoc(loc);
  3258. constructCoord->setType(TType(argCoord->getBasicType(), EvqTemporary, coordSize));
  3259. TIntermAggregate *tex = new TIntermAggregate(EOpTextureLod);
  3260. tex->getSequence().push_back(argSamp); // sampler
  3261. tex->getSequence().push_back(constructCoord); // coordinate
  3262. tex->getSequence().push_back(argLod); // lod
  3263. node = convertReturn(tex, sampler);
  3264. break;
  3265. }
  3266. case EOpTextureBias:
  3267. {
  3268. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3269. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3270. // HLSL puts bias in W component of coordinate. We extract it and add it to
  3271. // the argument list, instead
  3272. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  3273. TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  3274. TOperator constructOp = EOpNull;
  3275. const TSampler& sampler = arg0->getType().getSampler();
  3276. switch (sampler.dim) {
  3277. case Esd1D: constructOp = EOpConstructFloat; break; // 1D
  3278. case Esd2D: constructOp = EOpConstructVec2; break; // 2D
  3279. case Esd3D: constructOp = EOpConstructVec3; break; // 3D
  3280. case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
  3281. default: break;
  3282. }
  3283. TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
  3284. constructCoord->getSequence().push_back(arg1);
  3285. constructCoord->setLoc(loc);
  3286. // The input vector should never be less than 2, since there's always a bias.
  3287. // The max is for safety, and should be a no-op.
  3288. constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
  3289. TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
  3290. tex->getSequence().push_back(arg0); // sampler
  3291. tex->getSequence().push_back(constructCoord); // coordinate
  3292. tex->getSequence().push_back(bias); // bias
  3293. node = convertReturn(tex, sampler);
  3294. break;
  3295. }
  3296. // **** DX10 methods: ****
  3297. case EOpMethodSample: // fall through
  3298. case EOpMethodSampleBias: // ...
  3299. {
  3300. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3301. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3302. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3303. TIntermTyped* argBias = nullptr;
  3304. TIntermTyped* argOffset = nullptr;
  3305. const TSampler& sampler = argTex->getType().getSampler();
  3306. int nextArg = 3;
  3307. if (op == EOpMethodSampleBias) // SampleBias has a bias arg
  3308. argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3309. TOperator textureOp = EOpTexture;
  3310. if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
  3311. textureOp = EOpTextureOffset;
  3312. argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3313. }
  3314. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3315. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3316. txsample->getSequence().push_back(txcombine);
  3317. txsample->getSequence().push_back(argCoord);
  3318. if (argBias != nullptr)
  3319. txsample->getSequence().push_back(argBias);
  3320. if (argOffset != nullptr)
  3321. txsample->getSequence().push_back(argOffset);
  3322. node = convertReturn(txsample, sampler);
  3323. break;
  3324. }
  3325. case EOpMethodSampleGrad: // ...
  3326. {
  3327. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3328. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3329. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3330. TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
  3331. TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
  3332. TIntermTyped* argOffset = nullptr;
  3333. const TSampler& sampler = argTex->getType().getSampler();
  3334. TOperator textureOp = EOpTextureGrad;
  3335. if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
  3336. textureOp = EOpTextureGradOffset;
  3337. argOffset = argAggregate->getSequence()[5]->getAsTyped();
  3338. }
  3339. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3340. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3341. txsample->getSequence().push_back(txcombine);
  3342. txsample->getSequence().push_back(argCoord);
  3343. txsample->getSequence().push_back(argDDX);
  3344. txsample->getSequence().push_back(argDDY);
  3345. if (argOffset != nullptr)
  3346. txsample->getSequence().push_back(argOffset);
  3347. node = convertReturn(txsample, sampler);
  3348. break;
  3349. }
  3350. case EOpMethodGetDimensions:
  3351. {
  3352. // AST returns a vector of results, which we break apart component-wise into
  3353. // separate values to assign to the HLSL method's outputs, ala:
  3354. // tx . GetDimensions(width, height);
  3355. // float2 sizeQueryTemp = EOpTextureQuerySize
  3356. // width = sizeQueryTemp.X;
  3357. // height = sizeQueryTemp.Y;
  3358. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3359. const TType& texType = argTex->getType();
  3360. assert(texType.getBasicType() == EbtSampler);
  3361. const TSampler& sampler = texType.getSampler();
  3362. const TSamplerDim dim = sampler.dim;
  3363. const bool isImage = sampler.isImage();
  3364. const bool isMs = sampler.isMultiSample();
  3365. const int numArgs = (int)argAggregate->getSequence().size();
  3366. int numDims = 0;
  3367. switch (dim) {
  3368. case Esd1D: numDims = 1; break; // W
  3369. case Esd2D: numDims = 2; break; // W, H
  3370. case Esd3D: numDims = 3; break; // W, H, D
  3371. case EsdCube: numDims = 2; break; // W, H (cube)
  3372. case EsdBuffer: numDims = 1; break; // W (buffers)
  3373. case EsdRect: numDims = 2; break; // W, H (rect)
  3374. default:
  3375. assert(0 && "unhandled texture dimension");
  3376. }
  3377. // Arrayed adds another dimension for the number of array elements
  3378. if (sampler.isArrayed())
  3379. ++numDims;
  3380. // Establish whether the method itself is querying mip levels. This can be false even
  3381. // if the underlying query requires a MIP level, due to the available HLSL method overloads.
  3382. const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
  3383. // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
  3384. // True if:
  3385. // 1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
  3386. // or,
  3387. // 2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
  3388. const bool mipRequired =
  3389. ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
  3390. mipQuery; // 2...
  3391. // AST assumes integer return. Will be converted to float if required.
  3392. TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
  3393. sizeQuery->getSequence().push_back(argTex);
  3394. // If we're building an LOD query, add the LOD.
  3395. if (mipRequired) {
  3396. // If the base HLSL query had no MIP level given, use level 0.
  3397. TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
  3398. intermediate.addConstantUnion(0, loc, true);
  3399. sizeQuery->getSequence().push_back(queryLod);
  3400. }
  3401. sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
  3402. sizeQuery->setLoc(loc);
  3403. // Return value from size query
  3404. TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
  3405. tempArg->getWritableType().getQualifier().makeTemporary();
  3406. TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
  3407. intermediate.addSymbol(*tempArg, loc),
  3408. sizeQuery, loc);
  3409. // Compound statement for assigning outputs
  3410. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
  3411. // Index of first output parameter
  3412. const int outParamBase = mipQuery ? 2 : 1;
  3413. for (int compNum = 0; compNum < numDims; ++compNum) {
  3414. TIntermTyped* indexedOut = nullptr;
  3415. TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
  3416. if (numDims > 1) {
  3417. TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
  3418. indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
  3419. indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
  3420. indexedOut->setLoc(loc);
  3421. } else {
  3422. indexedOut = sizeQueryReturn;
  3423. }
  3424. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
  3425. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
  3426. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3427. }
  3428. // handle mip level parameter
  3429. if (mipQuery) {
  3430. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3431. TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
  3432. levelsQuery->getSequence().push_back(argTex);
  3433. levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3434. levelsQuery->setLoc(loc);
  3435. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
  3436. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3437. }
  3438. // 2DMS formats query # samples, which needs a different query op
  3439. if (sampler.isMultiSample()) {
  3440. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3441. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3442. samplesQuery->getSequence().push_back(argTex);
  3443. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3444. samplesQuery->setLoc(loc);
  3445. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
  3446. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3447. }
  3448. compoundStatement->setOperator(EOpSequence);
  3449. compoundStatement->setLoc(loc);
  3450. compoundStatement->setType(TType(EbtVoid));
  3451. node = compoundStatement;
  3452. break;
  3453. }
  3454. case EOpMethodSampleCmp: // fall through...
  3455. case EOpMethodSampleCmpLevelZero:
  3456. {
  3457. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3458. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3459. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3460. TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
  3461. TIntermTyped* argOffset = nullptr;
  3462. // Sampler argument should be a sampler.
  3463. if (argSamp->getType().getBasicType() != EbtSampler) {
  3464. error(loc, "expected: sampler type", "", "");
  3465. return;
  3466. }
  3467. // Sampler should be a SamplerComparisonState
  3468. if (! argSamp->getType().getSampler().isShadow()) {
  3469. error(loc, "expected: SamplerComparisonState", "", "");
  3470. return;
  3471. }
  3472. // optional offset value
  3473. if (argAggregate->getSequence().size() > 4)
  3474. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3475. const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
  3476. // AST wants comparison value as one of the texture coordinates
  3477. TOperator constructOp = EOpNull;
  3478. switch (coordDimWithCmpVal) {
  3479. // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
  3480. case 2: constructOp = EOpConstructVec2; break;
  3481. case 3: constructOp = EOpConstructVec3; break;
  3482. case 4: constructOp = EOpConstructVec4; break;
  3483. case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
  3484. default: assert(0); break;
  3485. }
  3486. TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
  3487. coordWithCmp->getSequence().push_back(argCoord);
  3488. if (coordDimWithCmpVal != 5) // cube array shadow is special.
  3489. coordWithCmp->getSequence().push_back(argCmpVal);
  3490. coordWithCmp->setLoc(loc);
  3491. coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
  3492. TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
  3493. if (argOffset != nullptr)
  3494. textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
  3495. // Create combined sampler & texture op
  3496. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3497. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3498. txsample->getSequence().push_back(txcombine);
  3499. txsample->getSequence().push_back(coordWithCmp);
  3500. if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
  3501. txsample->getSequence().push_back(argCmpVal);
  3502. // the LevelZero form uses 0 as an explicit LOD
  3503. if (op == EOpMethodSampleCmpLevelZero)
  3504. txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
  3505. // Add offset if present
  3506. if (argOffset != nullptr)
  3507. txsample->getSequence().push_back(argOffset);
  3508. txsample->setType(node->getType());
  3509. txsample->setLoc(loc);
  3510. node = txsample;
  3511. break;
  3512. }
  3513. case EOpMethodLoad:
  3514. {
  3515. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3516. TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
  3517. TIntermTyped* argOffset = nullptr;
  3518. TIntermTyped* lodComponent = nullptr;
  3519. TIntermTyped* coordSwizzle = nullptr;
  3520. const TSampler& sampler = argTex->getType().getSampler();
  3521. const bool isMS = sampler.isMultiSample();
  3522. const bool isBuffer = sampler.dim == EsdBuffer;
  3523. const bool isImage = sampler.isImage();
  3524. const TBasicType coordBaseType = argCoord->getType().getBasicType();
  3525. // Last component of coordinate is the mip level, for non-MS. we separate them here:
  3526. if (isMS || isBuffer || isImage) {
  3527. // MS, Buffer, and Image have no LOD
  3528. coordSwizzle = argCoord;
  3529. } else {
  3530. // Extract coordinate
  3531. int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
  3532. TSwizzleSelectors<TVectorSelector> coordFields;
  3533. for (int i = 0; i < swizzleSize; ++i)
  3534. coordFields.push_back(i);
  3535. TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
  3536. coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
  3537. coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
  3538. // Extract LOD
  3539. TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
  3540. lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
  3541. lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
  3542. }
  3543. const int numArgs = (int)argAggregate->getSequence().size();
  3544. const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
  3545. // Create texel fetch
  3546. const TOperator fetchOp = (isImage ? EOpImageLoad :
  3547. hasOffset ? EOpTextureFetchOffset :
  3548. EOpTextureFetch);
  3549. TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
  3550. // Build up the fetch
  3551. txfetch->getSequence().push_back(argTex);
  3552. txfetch->getSequence().push_back(coordSwizzle);
  3553. if (isMS) {
  3554. // add 2DMS sample index
  3555. TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
  3556. txfetch->getSequence().push_back(argSampleIdx);
  3557. } else if (isBuffer) {
  3558. // Nothing else to do for buffers.
  3559. } else if (isImage) {
  3560. // Nothing else to do for images.
  3561. } else {
  3562. // 2DMS and buffer have no LOD, but everything else does.
  3563. txfetch->getSequence().push_back(lodComponent);
  3564. }
  3565. // Obtain offset arg, if there is one.
  3566. if (hasOffset) {
  3567. const int offsetPos = (isMS ? 3 : 2);
  3568. argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
  3569. txfetch->getSequence().push_back(argOffset);
  3570. }
  3571. node = convertReturn(txfetch, sampler);
  3572. break;
  3573. }
  3574. case EOpMethodSampleLevel:
  3575. {
  3576. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3577. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3578. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3579. TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
  3580. TIntermTyped* argOffset = nullptr;
  3581. const TSampler& sampler = argTex->getType().getSampler();
  3582. const int numArgs = (int)argAggregate->getSequence().size();
  3583. if (numArgs == 5) // offset, if present
  3584. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3585. const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
  3586. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3587. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3588. txsample->getSequence().push_back(txcombine);
  3589. txsample->getSequence().push_back(argCoord);
  3590. txsample->getSequence().push_back(argLod);
  3591. if (argOffset != nullptr)
  3592. txsample->getSequence().push_back(argOffset);
  3593. node = convertReturn(txsample, sampler);
  3594. break;
  3595. }
  3596. case EOpMethodGather:
  3597. {
  3598. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3599. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3600. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3601. TIntermTyped* argOffset = nullptr;
  3602. // Offset is optional
  3603. if (argAggregate->getSequence().size() > 3)
  3604. argOffset = argAggregate->getSequence()[3]->getAsTyped();
  3605. const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
  3606. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3607. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3608. txgather->getSequence().push_back(txcombine);
  3609. txgather->getSequence().push_back(argCoord);
  3610. // Offset if not given is implicitly channel 0 (red)
  3611. if (argOffset != nullptr)
  3612. txgather->getSequence().push_back(argOffset);
  3613. txgather->setType(node->getType());
  3614. txgather->setLoc(loc);
  3615. node = txgather;
  3616. break;
  3617. }
  3618. case EOpMethodGatherRed: // fall through...
  3619. case EOpMethodGatherGreen: // ...
  3620. case EOpMethodGatherBlue: // ...
  3621. case EOpMethodGatherAlpha: // ...
  3622. case EOpMethodGatherCmpRed: // ...
  3623. case EOpMethodGatherCmpGreen: // ...
  3624. case EOpMethodGatherCmpBlue: // ...
  3625. case EOpMethodGatherCmpAlpha: // ...
  3626. {
  3627. int channel = 0; // the channel we are gathering
  3628. int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
  3629. switch (op) {
  3630. case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
  3631. case EOpMethodGatherRed: channel = 0; break;
  3632. case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
  3633. case EOpMethodGatherGreen: channel = 1; break;
  3634. case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
  3635. case EOpMethodGatherBlue: channel = 2; break;
  3636. case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
  3637. case EOpMethodGatherAlpha: channel = 3; break;
  3638. default: assert(0); break;
  3639. }
  3640. // For now, we have nothing to map the component-wise comparison forms
  3641. // to, because neither GLSL nor SPIR-V has such an opcode. Issue an
  3642. // unimplemented error instead. Most of the machinery is here if that
  3643. // should ever become available. However, red can be passed through
  3644. // to OpImageDrefGather. G/B/A cannot, because that opcode does not
  3645. // accept a component.
  3646. if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
  3647. error(loc, "unimplemented: component-level gather compare", "", "");
  3648. return;
  3649. }
  3650. int arg = 0;
  3651. TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
  3652. TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
  3653. TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
  3654. TIntermTyped* argOffset = nullptr;
  3655. TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
  3656. // TIntermTyped* argStatus = nullptr; // TODO: residency
  3657. TIntermTyped* argCmp = nullptr;
  3658. const TSamplerDim dim = argTex->getType().getSampler().dim;
  3659. const int argSize = (int)argAggregate->getSequence().size();
  3660. bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
  3661. bool hasOffset1 = false;
  3662. bool hasOffset4 = false;
  3663. // Sampler argument should be a sampler.
  3664. if (argSamp->getType().getBasicType() != EbtSampler) {
  3665. error(loc, "expected: sampler type", "", "");
  3666. return;
  3667. }
  3668. // Cmp forms require SamplerComparisonState
  3669. if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
  3670. error(loc, "expected: SamplerComparisonState", "", "");
  3671. return;
  3672. }
  3673. // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
  3674. if (dim == Esd2D) {
  3675. hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
  3676. hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
  3677. }
  3678. assert(!(hasOffset1 && hasOffset4));
  3679. TOperator textureOp = EOpTextureGather;
  3680. // Compare forms have compare value
  3681. if (cmpValues != 0)
  3682. argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3683. // Some forms have single offset
  3684. if (hasOffset1) {
  3685. textureOp = EOpTextureGatherOffset; // single offset form
  3686. argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3687. }
  3688. // Some forms have 4 gather offsets
  3689. if (hasOffset4) {
  3690. textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
  3691. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3692. argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
  3693. }
  3694. // Residency status
  3695. if (hasStatus) {
  3696. // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
  3697. error(loc, "unimplemented: residency status", "", "");
  3698. return;
  3699. }
  3700. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3701. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3702. TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
  3703. txgather->getSequence().push_back(txcombine);
  3704. txgather->getSequence().push_back(argCoord);
  3705. // AST wants an array of 4 offsets, where HLSL has separate args. Here
  3706. // we construct an array from the separate args.
  3707. if (hasOffset4) {
  3708. TType arrayType(EbtInt, EvqTemporary, 2);
  3709. TArraySizes* arraySizes = new TArraySizes;
  3710. arraySizes->addInnerSize(4);
  3711. arrayType.transferArraySizes(arraySizes);
  3712. TIntermAggregate* initList = new TIntermAggregate(EOpNull);
  3713. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3714. initList->getSequence().push_back(argOffsets[offsetNum]);
  3715. argOffset = addConstructor(loc, initList, arrayType);
  3716. }
  3717. // Add comparison value if we have one
  3718. if (argCmp != nullptr)
  3719. txgather->getSequence().push_back(argCmp);
  3720. // Add offset (either 1, or an array of 4) if we have one
  3721. if (argOffset != nullptr)
  3722. txgather->getSequence().push_back(argOffset);
  3723. // Add channel value if the sampler is not shadow
  3724. if (! argSamp->getType().getSampler().isShadow())
  3725. txgather->getSequence().push_back(argChannel);
  3726. txgather->setType(node->getType());
  3727. txgather->setLoc(loc);
  3728. node = txgather;
  3729. break;
  3730. }
  3731. case EOpMethodCalculateLevelOfDetail:
  3732. case EOpMethodCalculateLevelOfDetailUnclamped:
  3733. {
  3734. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3735. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3736. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3737. TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
  3738. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3739. txquerylod->getSequence().push_back(txcombine);
  3740. txquerylod->getSequence().push_back(argCoord);
  3741. TIntermTyped* lodComponent = intermediate.addConstantUnion(
  3742. op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
  3743. loc, true);
  3744. TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
  3745. lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
  3746. node = lodComponentIdx;
  3747. break;
  3748. }
  3749. case EOpMethodGetSamplePosition:
  3750. {
  3751. // TODO: this entire decomposition exists because there is not yet a way to query
  3752. // the sample position directly through SPIR-V. Instead, we return fixed sample
  3753. // positions for common cases. *** If the sample positions are set differently,
  3754. // this will be wrong. ***
  3755. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3756. TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
  3757. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3758. samplesQuery->getSequence().push_back(argTex);
  3759. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3760. samplesQuery->setLoc(loc);
  3761. TIntermAggregate* compoundStatement = nullptr;
  3762. TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
  3763. outSampleCount->getWritableType().getQualifier().makeTemporary();
  3764. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
  3765. samplesQuery, loc);
  3766. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3767. TIntermTyped* idxtest[4];
  3768. // Create tests against 2, 4, 8, and 16 sample values
  3769. int count = 0;
  3770. for (int val = 2; val <= 16; val *= 2)
  3771. idxtest[count++] =
  3772. intermediate.addBinaryNode(EOpEqual,
  3773. intermediate.addSymbol(*outSampleCount, loc),
  3774. intermediate.addConstantUnion(val, loc),
  3775. loc, TType(EbtBool));
  3776. const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3777. // Create index ops into position arrays given sample index.
  3778. // TODO: should it be clamped?
  3779. TIntermTyped* index[4];
  3780. count = 0;
  3781. for (int val = 2; val <= 16; val *= 2) {
  3782. index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
  3783. index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
  3784. }
  3785. // Create expression as:
  3786. // (sampleCount == 2) ? pos2[idx] :
  3787. // (sampleCount == 4) ? pos4[idx] :
  3788. // (sampleCount == 8) ? pos8[idx] :
  3789. // (sampleCount == 16) ? pos16[idx] : float2(0,0);
  3790. TIntermTyped* test =
  3791. intermediate.addSelection(idxtest[0], index[0],
  3792. intermediate.addSelection(idxtest[1], index[1],
  3793. intermediate.addSelection(idxtest[2], index[2],
  3794. intermediate.addSelection(idxtest[3], index[3],
  3795. getSamplePosArray(1), loc), loc), loc), loc);
  3796. compoundStatement = intermediate.growAggregate(compoundStatement, test);
  3797. compoundStatement->setOperator(EOpSequence);
  3798. compoundStatement->setLoc(loc);
  3799. compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
  3800. node = compoundStatement;
  3801. break;
  3802. }
  3803. case EOpSubpassLoad:
  3804. {
  3805. const TIntermTyped* argSubpass =
  3806. argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
  3807. arguments->getAsTyped();
  3808. const TSampler& sampler = argSubpass->getType().getSampler();
  3809. // subpass load: the multisample form is overloaded. Here, we convert that to
  3810. // the EOpSubpassLoadMS opcode.
  3811. if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
  3812. node->getAsOperator()->setOp(EOpSubpassLoadMS);
  3813. node = convertReturn(node, sampler);
  3814. break;
  3815. }
  3816. default:
  3817. break; // most pass through unchanged
  3818. }
  3819. }
  3820. //
  3821. // Decompose geometry shader methods
  3822. //
  3823. void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3824. {
  3825. if (node == nullptr || !node->getAsOperator())
  3826. return;
  3827. const TOperator op = node->getAsOperator()->getOp();
  3828. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3829. switch (op) {
  3830. case EOpMethodAppend:
  3831. if (argAggregate) {
  3832. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3833. if (language != EShLangGeometry) {
  3834. node = nullptr;
  3835. return;
  3836. }
  3837. TIntermAggregate* sequence = nullptr;
  3838. TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
  3839. emit->setLoc(loc);
  3840. emit->setType(TType(EbtVoid));
  3841. TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
  3842. // This will be patched in finalization during finalizeAppendMethods()
  3843. sequence = intermediate.growAggregate(sequence, data, loc);
  3844. sequence = intermediate.growAggregate(sequence, emit);
  3845. sequence->setOperator(EOpSequence);
  3846. sequence->setLoc(loc);
  3847. sequence->setType(TType(EbtVoid));
  3848. gsAppends.push_back({sequence, loc});
  3849. node = sequence;
  3850. }
  3851. break;
  3852. case EOpMethodRestartStrip:
  3853. {
  3854. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3855. if (language != EShLangGeometry) {
  3856. node = nullptr;
  3857. return;
  3858. }
  3859. TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
  3860. cut->setLoc(loc);
  3861. cut->setType(TType(EbtVoid));
  3862. node = cut;
  3863. }
  3864. break;
  3865. default:
  3866. break; // most pass through unchanged
  3867. }
  3868. }
  3869. //
  3870. // Optionally decompose intrinsics to AST opcodes.
  3871. //
  3872. void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3873. {
  3874. // Helper to find image data for image atomics:
  3875. // OpImageLoad(image[idx])
  3876. // We take the image load apart and add its params to the atomic op aggregate node
  3877. const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
  3878. TIntermAggregate* loadOp = load->getAsAggregate();
  3879. if (loadOp == nullptr) {
  3880. error(loc, "unknown image type in atomic operation", "", "");
  3881. node = nullptr;
  3882. return;
  3883. }
  3884. atomic->getSequence().push_back(loadOp->getSequence()[0]);
  3885. atomic->getSequence().push_back(loadOp->getSequence()[1]);
  3886. };
  3887. // Return true if this is an imageLoad, which we will change to an image atomic.
  3888. const auto isImageParam = [](TIntermTyped* image) -> bool {
  3889. TIntermAggregate* imageAggregate = image->getAsAggregate();
  3890. return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
  3891. };
  3892. const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
  3893. TSymbol* symbol = symbolTable.find(name);
  3894. if (nullptr == symbol) {
  3895. type.getQualifier().builtIn = builtin;
  3896. TVariable* variable = new TVariable(NewPoolTString(name), type);
  3897. symbolTable.insert(*variable);
  3898. symbol = symbolTable.find(name);
  3899. assert(symbol && "Inserted symbol could not be found!");
  3900. }
  3901. return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
  3902. };
  3903. // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
  3904. // opcodes for compatibility with existing software stacks.
  3905. static const bool decomposeHlslIntrinsics = true;
  3906. if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
  3907. return;
  3908. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3909. TIntermUnary* fnUnary = node->getAsUnaryNode();
  3910. const TOperator op = node->getAsOperator()->getOp();
  3911. switch (op) {
  3912. case EOpGenMul:
  3913. {
  3914. // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
  3915. // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
  3916. // we must reverse the operand order here. Hence, arg0 gets sequence[1], etc.
  3917. TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
  3918. TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
  3919. if (arg0->isVector() && arg1->isVector()) { // vec * vec
  3920. node->getAsAggregate()->setOperator(EOpDot);
  3921. } else {
  3922. node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
  3923. }
  3924. break;
  3925. }
  3926. case EOpRcp:
  3927. {
  3928. // rcp(a) -> 1 / a
  3929. TIntermTyped* arg0 = fnUnary->getOperand();
  3930. TBasicType type0 = arg0->getBasicType();
  3931. TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
  3932. node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
  3933. break;
  3934. }
  3935. case EOpAny: // fall through
  3936. case EOpAll:
  3937. {
  3938. TIntermTyped* typedArg = arguments->getAsTyped();
  3939. // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
  3940. // We'll convert here. Note that for efficiency, we could add a smarter
  3941. // decomposition for some type cases, e.g, maybe by decomposing a dot product.
  3942. if (typedArg->getType().getBasicType() != EbtBool) {
  3943. const TType boolType(EbtBool, EvqTemporary,
  3944. typedArg->getVectorSize(),
  3945. typedArg->getMatrixCols(),
  3946. typedArg->getMatrixRows(),
  3947. typedArg->isVector());
  3948. typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
  3949. node->getAsUnaryNode()->setOperand(typedArg);
  3950. }
  3951. break;
  3952. }
  3953. case EOpSaturate:
  3954. {
  3955. // saturate(a) -> clamp(a,0,1)
  3956. TIntermTyped* arg0 = fnUnary->getOperand();
  3957. TBasicType type0 = arg0->getBasicType();
  3958. TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
  3959. clamp->getSequence().push_back(arg0);
  3960. clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
  3961. clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
  3962. clamp->setLoc(loc);
  3963. clamp->setType(node->getType());
  3964. clamp->getWritableType().getQualifier().makeTemporary();
  3965. node = clamp;
  3966. break;
  3967. }
  3968. case EOpSinCos:
  3969. {
  3970. // sincos(a,b,c) -> b = sin(a), c = cos(a)
  3971. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  3972. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  3973. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
  3974. TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
  3975. TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
  3976. TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
  3977. TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
  3978. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
  3979. compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
  3980. compoundStatement->setOperator(EOpSequence);
  3981. compoundStatement->setLoc(loc);
  3982. compoundStatement->setType(TType(EbtVoid));
  3983. node = compoundStatement;
  3984. break;
  3985. }
  3986. case EOpClip:
  3987. {
  3988. // clip(a) -> if (any(a<0)) discard;
  3989. TIntermTyped* arg0 = fnUnary->getOperand();
  3990. TBasicType type0 = arg0->getBasicType();
  3991. TIntermTyped* compareNode = nullptr;
  3992. // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
  3993. if (!arg0->isScalar()) {
  3994. // component-wise compare: a < 0
  3995. TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
  3996. less->getSequence().push_back(arg0);
  3997. less->setLoc(loc);
  3998. // make vec or mat of bool matching dimensions of input
  3999. less->setType(TType(EbtBool, EvqTemporary,
  4000. arg0->getType().getVectorSize(),
  4001. arg0->getType().getMatrixCols(),
  4002. arg0->getType().getMatrixRows(),
  4003. arg0->getType().isVector()));
  4004. // calculate # of components for comparison const
  4005. const int constComponentCount =
  4006. std::max(arg0->getType().getVectorSize(), 1) *
  4007. std::max(arg0->getType().getMatrixCols(), 1) *
  4008. std::max(arg0->getType().getMatrixRows(), 1);
  4009. TConstUnion zero;
  4010. if (arg0->getType().isIntegerDomain())
  4011. zero.setDConst(0);
  4012. else
  4013. zero.setDConst(0.0);
  4014. TConstUnionArray zeros(constComponentCount, zero);
  4015. less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
  4016. compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
  4017. } else {
  4018. TIntermTyped* zero;
  4019. if (arg0->getType().isIntegerDomain())
  4020. zero = intermediate.addConstantUnion(0, loc, true);
  4021. else
  4022. zero = intermediate.addConstantUnion(0.0, type0, loc, true);
  4023. compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
  4024. }
  4025. TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
  4026. node = new TIntermSelection(compareNode, killNode, nullptr);
  4027. node->setLoc(loc);
  4028. break;
  4029. }
  4030. case EOpLog10:
  4031. {
  4032. // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
  4033. TIntermTyped* arg0 = fnUnary->getOperand();
  4034. TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
  4035. TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
  4036. node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
  4037. break;
  4038. }
  4039. case EOpDst:
  4040. {
  4041. // dest.x = 1;
  4042. // dest.y = src0.y * src1.y;
  4043. // dest.z = src0.z;
  4044. // dest.w = src1.w;
  4045. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4046. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4047. TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
  4048. TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
  4049. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  4050. TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
  4051. TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
  4052. TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
  4053. TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  4054. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4055. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4056. dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
  4057. dst->getSequence().push_back(src0z);
  4058. dst->getSequence().push_back(src1w);
  4059. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4060. dst->setLoc(loc);
  4061. node = dst;
  4062. break;
  4063. }
  4064. case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
  4065. case EOpInterlockedMin: // ...
  4066. case EOpInterlockedMax: // ...
  4067. case EOpInterlockedAnd: // ...
  4068. case EOpInterlockedOr: // ...
  4069. case EOpInterlockedXor: // ...
  4070. case EOpInterlockedExchange: // always has output arg
  4071. {
  4072. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4073. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // value
  4074. TIntermTyped* arg2 = nullptr;
  4075. if (argAggregate->getSequence().size() > 2)
  4076. arg2 = argAggregate->getSequence()[2]->getAsTyped();
  4077. const bool isImage = isImageParam(arg0);
  4078. const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
  4079. TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
  4080. atomic->setType(arg0->getType());
  4081. atomic->getWritableType().getQualifier().makeTemporary();
  4082. atomic->setLoc(loc);
  4083. if (isImage) {
  4084. // orig_value = imageAtomicOp(image, loc, data)
  4085. imageAtomicParams(atomic, arg0);
  4086. atomic->getSequence().push_back(arg1);
  4087. if (argAggregate->getSequence().size() > 2) {
  4088. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4089. } else {
  4090. node = atomic; // no assignment needed, as there was no out var.
  4091. }
  4092. } else {
  4093. // Normal memory variable:
  4094. // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
  4095. if (argAggregate->getSequence().size() > 2) {
  4096. // optional output param is present. return value goes to arg2.
  4097. atomic->getSequence().push_back(arg0);
  4098. atomic->getSequence().push_back(arg1);
  4099. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4100. } else {
  4101. // Set the matching operator. Since output is absent, this is all we need to do.
  4102. node->getAsAggregate()->setOperator(atomicOp);
  4103. node->setType(atomic->getType());
  4104. }
  4105. }
  4106. break;
  4107. }
  4108. case EOpInterlockedCompareExchange:
  4109. {
  4110. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4111. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
  4112. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
  4113. TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
  4114. const bool isImage = isImageParam(arg0);
  4115. TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
  4116. atomic->setLoc(loc);
  4117. atomic->setType(arg2->getType());
  4118. atomic->getWritableType().getQualifier().makeTemporary();
  4119. if (isImage) {
  4120. imageAtomicParams(atomic, arg0);
  4121. } else {
  4122. atomic->getSequence().push_back(arg0);
  4123. }
  4124. atomic->getSequence().push_back(arg1);
  4125. atomic->getSequence().push_back(arg2);
  4126. node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
  4127. break;
  4128. }
  4129. case EOpEvaluateAttributeSnapped:
  4130. {
  4131. // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
  4132. // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
  4133. // iU = (iU<<28)>>28
  4134. // fU = ((float)iU)/16
  4135. // Targets might handle this natively, in which case they can disable
  4136. // decompositions.
  4137. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
  4138. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
  4139. TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
  4140. TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
  4141. handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
  4142. i28);
  4143. TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
  4144. TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
  4145. intermediate.addConversion(EOpConstructFloat,
  4146. TType(EbtFloat, EvqTemporary, 2), iU),
  4147. recip16);
  4148. TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
  4149. interp->getSequence().push_back(arg0);
  4150. interp->getSequence().push_back(floatOffset);
  4151. interp->setLoc(loc);
  4152. interp->setType(arg0->getType());
  4153. interp->getWritableType().getQualifier().makeTemporary();
  4154. node = interp;
  4155. break;
  4156. }
  4157. case EOpLit:
  4158. {
  4159. TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
  4160. TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
  4161. TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
  4162. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4163. // Ambient
  4164. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4165. // Diffuse:
  4166. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4167. TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
  4168. diffuse->getSequence().push_back(n_dot_l);
  4169. diffuse->getSequence().push_back(zero);
  4170. diffuse->setLoc(loc);
  4171. diffuse->setType(TType(EbtFloat));
  4172. dst->getSequence().push_back(diffuse);
  4173. // Specular:
  4174. TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
  4175. min_ndot->getSequence().push_back(n_dot_l);
  4176. min_ndot->getSequence().push_back(n_dot_h);
  4177. min_ndot->setLoc(loc);
  4178. min_ndot->setType(TType(EbtFloat));
  4179. TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
  4180. TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
  4181. dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
  4182. // One:
  4183. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4184. dst->setLoc(loc);
  4185. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4186. node = dst;
  4187. break;
  4188. }
  4189. case EOpAsDouble:
  4190. {
  4191. // asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
  4192. // first construct a uint64.
  4193. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4194. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4195. if (arg0->getType().isVector()) { // TODO: ...
  4196. error(loc, "double2 conversion not implemented", "asdouble", "");
  4197. break;
  4198. }
  4199. TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
  4200. uint64->getSequence().push_back(arg0);
  4201. uint64->getSequence().push_back(arg1);
  4202. uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
  4203. uint64->setLoc(loc);
  4204. // bitcast uint2 to a double
  4205. TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
  4206. convert->getAsUnaryNode()->setOperand(uint64);
  4207. convert->setLoc(loc);
  4208. convert->setType(TType(EbtDouble, EvqTemporary));
  4209. node = convert;
  4210. break;
  4211. }
  4212. case EOpF16tof32:
  4213. {
  4214. // input uvecN with low 16 bits of each component holding a float16. convert to float32.
  4215. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4216. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  4217. const int vecSize = argValue->getType().getVectorSize();
  4218. TOperator constructOp = EOpNull;
  4219. switch (vecSize) {
  4220. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4221. case 2: constructOp = EOpConstructVec2; break;
  4222. case 3: constructOp = EOpConstructVec3; break;
  4223. case 4: constructOp = EOpConstructVec4; break;
  4224. default: assert(0); break;
  4225. }
  4226. // For scalar case, we don't need to construct another type.
  4227. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4228. if (result) {
  4229. result->setType(TType(EbtFloat, EvqTemporary, vecSize));
  4230. result->setLoc(loc);
  4231. }
  4232. for (int idx = 0; idx < vecSize; ++idx) {
  4233. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4234. TIntermTyped* component = argValue->getType().isVector() ?
  4235. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4236. if (component != argValue)
  4237. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4238. TIntermTyped* unpackOp = new TIntermUnary(EOpUnpackHalf2x16);
  4239. unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
  4240. unpackOp->getAsUnaryNode()->setOperand(component);
  4241. unpackOp->setLoc(loc);
  4242. TIntermTyped* lowOrder = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
  4243. if (result != nullptr) {
  4244. result->getSequence().push_back(lowOrder);
  4245. node = result;
  4246. } else {
  4247. node = lowOrder;
  4248. }
  4249. }
  4250. break;
  4251. }
  4252. case EOpF32tof16:
  4253. {
  4254. // input floatN converted to 16 bit float in low order bits of each component of uintN
  4255. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4256. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4257. const int vecSize = argValue->getType().getVectorSize();
  4258. TOperator constructOp = EOpNull;
  4259. switch (vecSize) {
  4260. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4261. case 2: constructOp = EOpConstructUVec2; break;
  4262. case 3: constructOp = EOpConstructUVec3; break;
  4263. case 4: constructOp = EOpConstructUVec4; break;
  4264. default: assert(0); break;
  4265. }
  4266. // For scalar case, we don't need to construct another type.
  4267. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4268. if (result) {
  4269. result->setType(TType(EbtUint, EvqTemporary, vecSize));
  4270. result->setLoc(loc);
  4271. }
  4272. for (int idx = 0; idx < vecSize; ++idx) {
  4273. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4274. TIntermTyped* component = argValue->getType().isVector() ?
  4275. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4276. if (component != argValue)
  4277. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4278. TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
  4279. vec2ComponentAndZero->getSequence().push_back(component);
  4280. vec2ComponentAndZero->getSequence().push_back(zero);
  4281. vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
  4282. vec2ComponentAndZero->setLoc(loc);
  4283. TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
  4284. packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
  4285. packOp->setLoc(loc);
  4286. packOp->setType(TType(EbtUint, EvqTemporary));
  4287. if (result != nullptr) {
  4288. result->getSequence().push_back(packOp);
  4289. node = result;
  4290. } else {
  4291. node = packOp;
  4292. }
  4293. }
  4294. break;
  4295. }
  4296. case EOpD3DCOLORtoUBYTE4:
  4297. {
  4298. // ivec4 ( x.zyxw * 255.001953 );
  4299. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4300. TSwizzleSelectors<TVectorSelector> selectors;
  4301. selectors.push_back(2);
  4302. selectors.push_back(1);
  4303. selectors.push_back(0);
  4304. selectors.push_back(3);
  4305. TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
  4306. TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
  4307. swizzled->setType(arg0->getType());
  4308. swizzled->getWritableType().getQualifier().makeTemporary();
  4309. TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
  4310. TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
  4311. rangeConverted->setType(arg0->getType());
  4312. rangeConverted->getWritableType().getQualifier().makeTemporary();
  4313. node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
  4314. node->setLoc(loc);
  4315. node->setType(TType(EbtInt, EvqTemporary, 4));
  4316. break;
  4317. }
  4318. case EOpIsFinite:
  4319. {
  4320. // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
  4321. // it to !isnan && !isinf
  4322. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4323. // We'll make a temporary in case the RHS is cmoplex
  4324. TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
  4325. tempArg->getWritableType().getQualifier().makeTemporary();
  4326. TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
  4327. intermediate.addSymbol(*tempArg, loc),
  4328. arg0, loc);
  4329. TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
  4330. const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
  4331. arg0->getMatrixRows());
  4332. TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
  4333. isnan->setType(boolType);
  4334. TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
  4335. notnan->setType(boolType);
  4336. TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
  4337. isinf->setType(boolType);
  4338. TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
  4339. notinf->setType(boolType);
  4340. TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
  4341. andNode->setType(boolType);
  4342. compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
  4343. compoundStatement->setOperator(EOpSequence);
  4344. compoundStatement->setLoc(loc);
  4345. compoundStatement->setType(boolType);
  4346. node = compoundStatement;
  4347. break;
  4348. }
  4349. case EOpWaveGetLaneCount:
  4350. {
  4351. // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
  4352. // so that it inhabits the symbol table, but has a user-invalid name
  4353. // in-case some source HLSL defined the symbol also).
  4354. TType type(EbtUint, EvqVaryingIn);
  4355. node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
  4356. break;
  4357. }
  4358. case EOpWaveGetLaneIndex:
  4359. {
  4360. // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
  4361. // symbol so that it inhabits the symbol table, but has a
  4362. // user-invalid name in-case some source HLSL defined the symbol
  4363. // also).
  4364. TType type(EbtUint, EvqVaryingIn);
  4365. node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
  4366. break;
  4367. }
  4368. case EOpWaveActiveCountBits:
  4369. {
  4370. // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
  4371. // uvec4 type.
  4372. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4373. // Get the uvec4 return from subgroupBallot().
  4374. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4375. EOpSubgroupBallot, true, arguments, uvec4Type);
  4376. // uint type.
  4377. TType uintType(EbtUint, EvqTemporary);
  4378. node = intermediate.addBuiltInFunctionCall(loc,
  4379. EOpSubgroupBallotBitCount, true, res, uintType);
  4380. break;
  4381. }
  4382. case EOpWavePrefixCountBits:
  4383. {
  4384. // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
  4385. // builtin
  4386. // uvec4 type.
  4387. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4388. // Get the uvec4 return from subgroupBallot().
  4389. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4390. EOpSubgroupBallot, true, arguments, uvec4Type);
  4391. // uint type.
  4392. TType uintType(EbtUint, EvqTemporary);
  4393. node = intermediate.addBuiltInFunctionCall(loc,
  4394. EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
  4395. break;
  4396. }
  4397. default:
  4398. break; // most pass through unchanged
  4399. }
  4400. }
  4401. //
  4402. // Handle seeing function call syntax in the grammar, which could be any of
  4403. // - .length() method
  4404. // - constructor
  4405. // - a call to a built-in function mapped to an operator
  4406. // - a call to a built-in function that will remain a function call (e.g., texturing)
  4407. // - user function
  4408. // - subroutine call (not implemented yet)
  4409. //
  4410. TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
  4411. {
  4412. TIntermTyped* result = nullptr;
  4413. TOperator op = function->getBuiltInOp();
  4414. if (op != EOpNull) {
  4415. //
  4416. // Then this should be a constructor.
  4417. // Don't go through the symbol table for constructors.
  4418. // Their parameters will be verified algorithmically.
  4419. //
  4420. TType type(EbtVoid); // use this to get the type back
  4421. if (! constructorError(loc, arguments, *function, op, type)) {
  4422. //
  4423. // It's a constructor, of type 'type'.
  4424. //
  4425. result = handleConstructor(loc, arguments, type);
  4426. if (result == nullptr) {
  4427. error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
  4428. return nullptr;
  4429. }
  4430. }
  4431. } else {
  4432. //
  4433. // Find it in the symbol table.
  4434. //
  4435. const TFunction* fnCandidate = nullptr;
  4436. bool builtIn = false;
  4437. int thisDepth = 0;
  4438. // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
  4439. // and clamp the opposite arg. Since that's complex, we farm it off to a separate method.
  4440. // It doesn't naturally fall out of processing an argument at a time in isolation.
  4441. if (function->getName() == "mul")
  4442. addGenMulArgumentConversion(loc, *function, arguments);
  4443. TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4444. // TODO: this needs improvement: there's no way at present to look up a signature in
  4445. // the symbol table for an arbitrary type. This is a temporary hack until that ability exists.
  4446. // It will have false positives, since it doesn't check arg counts or types.
  4447. if (arguments) {
  4448. // Check if first argument is struct buffer type. It may be an aggregate or a symbol, so we
  4449. // look for either case.
  4450. TIntermTyped* arg0 = nullptr;
  4451. if (aggregate && aggregate->getSequence().size() > 0 && aggregate->getSequence()[0])
  4452. arg0 = aggregate->getSequence()[0]->getAsTyped();
  4453. else if (arguments->getAsSymbolNode())
  4454. arg0 = arguments->getAsSymbolNode();
  4455. if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
  4456. static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
  4457. if (function->getName().length() > methodPrefixSize &&
  4458. isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
  4459. const TString mangle = function->getName() + "(";
  4460. TSymbol* symbol = symbolTable.find(mangle, &builtIn);
  4461. if (symbol)
  4462. fnCandidate = symbol->getAsFunction();
  4463. }
  4464. }
  4465. }
  4466. if (fnCandidate == nullptr)
  4467. fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
  4468. if (fnCandidate) {
  4469. // This is a declared function that might map to
  4470. // - a built-in operator,
  4471. // - a built-in function not mapped to an operator, or
  4472. // - a user function.
  4473. // turn an implicit member-function resolution into an explicit call
  4474. TString callerName;
  4475. if (thisDepth == 0)
  4476. callerName = fnCandidate->getMangledName();
  4477. else {
  4478. // get the explicit (full) name of the function
  4479. callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
  4480. callerName += fnCandidate->getMangledName();
  4481. // insert the implicit calling argument
  4482. pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
  4483. }
  4484. // Convert 'in' arguments, so that types match.
  4485. // However, skip those that need expansion, that is covered next.
  4486. if (arguments)
  4487. addInputArgumentConversions(*fnCandidate, arguments);
  4488. // Expand arguments. Some arguments must physically expand to a different set
  4489. // than what the shader declared and passes.
  4490. if (arguments && !builtIn)
  4491. expandArguments(loc, *fnCandidate, arguments);
  4492. // Expansion may have changed the form of arguments
  4493. aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4494. op = fnCandidate->getBuiltInOp();
  4495. if (builtIn && op != EOpNull) {
  4496. // A function call mapped to a built-in operation.
  4497. result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
  4498. fnCandidate->getType());
  4499. if (result == nullptr) {
  4500. error(arguments->getLoc(), " wrong operand type", "Internal Error",
  4501. "built in unary operator function. Type: %s",
  4502. static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
  4503. } else if (result->getAsOperator()) {
  4504. builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
  4505. }
  4506. } else {
  4507. // This is a function call not mapped to built-in operator.
  4508. // It could still be a built-in function, but only if PureOperatorBuiltins == false.
  4509. result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
  4510. TIntermAggregate* call = result->getAsAggregate();
  4511. call->setName(callerName);
  4512. // this is how we know whether the given function is a built-in function or a user-defined function
  4513. // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
  4514. // if builtIn == true, it's definitely a built-in function with EOpNull
  4515. if (! builtIn) {
  4516. call->setUserDefined();
  4517. intermediate.addToCallGraph(infoSink, currentCaller, callerName);
  4518. }
  4519. }
  4520. // for decompositions, since we want to operate on the function node, not the aggregate holding
  4521. // output conversions.
  4522. const TIntermTyped* fnNode = result;
  4523. decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
  4524. decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
  4525. decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
  4526. decomposeGeometryMethods(loc, result, arguments); // HLSL->AST geometry method decompositions
  4527. // Create the qualifier list, carried in the AST for the call.
  4528. // Because some arguments expand to multiple arguments, the qualifier list will
  4529. // be longer than the formal parameter list.
  4530. if (result == fnNode && result->getAsAggregate()) {
  4531. TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
  4532. for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
  4533. TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
  4534. if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
  4535. // add buffer and counter buffer argument qualifier
  4536. qualifierList.push_back(qual);
  4537. qualifierList.push_back(qual);
  4538. } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
  4539. true)) {
  4540. // add structure member expansion
  4541. for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
  4542. qualifierList.push_back(qual);
  4543. } else {
  4544. // Normal 1:1 case
  4545. qualifierList.push_back(qual);
  4546. }
  4547. }
  4548. }
  4549. // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
  4550. // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
  4551. // Also, build the qualifier list for user function calls, which are always called with an aggregate.
  4552. // We don't do this is if there has been a decomposition, which will have added its own conversions
  4553. // for output parameters.
  4554. if (result == fnNode && result->getAsAggregate())
  4555. result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
  4556. }
  4557. }
  4558. // generic error recovery
  4559. // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
  4560. // reduce cascades
  4561. if (result == nullptr)
  4562. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  4563. return result;
  4564. }
  4565. // An initial argument list is difficult: it can be null, or a single node,
  4566. // or an aggregate if more than one argument. Add one to the front, maintaining
  4567. // this lack of uniformity.
  4568. void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
  4569. {
  4570. if (arguments == nullptr)
  4571. arguments = front;
  4572. else if (arguments->getAsAggregate() != nullptr)
  4573. arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
  4574. else
  4575. arguments = intermediate.growAggregate(front, arguments);
  4576. }
  4577. //
  4578. // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat. This is a
  4579. // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
  4580. // can look at both arguments insert explicit shape changes if required.
  4581. //
  4582. void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
  4583. {
  4584. TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
  4585. if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
  4586. // It really ought to have two arguments.
  4587. error(loc, "expected: mul arguments", "", "");
  4588. return;
  4589. }
  4590. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4591. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4592. if (arg0->isVector() && arg1->isVector()) {
  4593. // For:
  4594. // vec * vec: it's handled during intrinsic selection, so while we could do it here,
  4595. // we can also ignore it, which is easier.
  4596. } else if (arg0->isVector() && arg1->isMatrix()) {
  4597. // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4598. if (arg0->getVectorSize() < arg1->getMatrixCols()) {
  4599. // vec is smaller, so truncate larger mat dimension
  4600. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4601. 0, arg0->getVectorSize(), arg1->getMatrixRows());
  4602. arg1 = addConstructor(loc, arg1, truncType);
  4603. } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
  4604. // vec is larger, so truncate vec to mat size
  4605. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4606. arg1->getMatrixCols());
  4607. arg0 = addConstructor(loc, arg0, truncType);
  4608. }
  4609. } else if (arg0->isMatrix() && arg1->isVector()) {
  4610. // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4611. if (arg1->getVectorSize() < arg0->getMatrixRows()) {
  4612. // vec is smaller, so truncate larger mat dimension
  4613. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4614. 0, arg0->getMatrixCols(), arg1->getVectorSize());
  4615. arg0 = addConstructor(loc, arg0, truncType);
  4616. } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
  4617. // vec is larger, so truncate vec to mat size
  4618. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4619. arg0->getMatrixRows());
  4620. arg1 = addConstructor(loc, arg1, truncType);
  4621. }
  4622. } else if (arg0->isMatrix() && arg1->isMatrix()) {
  4623. // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
  4624. // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
  4625. if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
  4626. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4627. 0, arg0->getMatrixCols(), arg1->getMatrixCols());
  4628. arg0 = addConstructor(loc, arg0, truncType);
  4629. } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
  4630. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4631. 0, arg0->getMatrixRows(), arg1->getMatrixRows());
  4632. arg1 = addConstructor(loc, arg1, truncType);
  4633. }
  4634. } else {
  4635. // It's something with scalars: we'll just leave it alone. Function selection will handle it
  4636. // downstream.
  4637. }
  4638. // Warn if we altered one of the arguments
  4639. if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
  4640. warn(loc, "mul() matrix size mismatch", "", "");
  4641. // Put arguments back. (They might be unchanged, in which case this is harmless).
  4642. argAggregate->getSequence()[0] = arg0;
  4643. argAggregate->getSequence()[1] = arg1;
  4644. call[0].type = &arg0->getWritableType();
  4645. call[1].type = &arg1->getWritableType();
  4646. }
  4647. //
  4648. // Add any needed implicit conversions for function-call arguments to input parameters.
  4649. //
  4650. void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
  4651. {
  4652. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4653. // Replace a single argument with a single argument.
  4654. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4655. if (function.getParamCount() == 1)
  4656. arguments = arg;
  4657. else {
  4658. if (aggregate == nullptr)
  4659. arguments = arg;
  4660. else
  4661. aggregate->getSequence()[paramNum] = arg;
  4662. }
  4663. };
  4664. // Process each argument's conversion
  4665. for (int param = 0; param < function.getParamCount(); ++param) {
  4666. if (! function[param].type->getQualifier().isParamInput())
  4667. continue;
  4668. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4669. // is the single argument itself or its children are the arguments. Only one argument
  4670. // means take 'arguments' itself as the one argument.
  4671. TIntermTyped* arg = function.getParamCount() == 1
  4672. ? arguments->getAsTyped()
  4673. : (aggregate ?
  4674. aggregate->getSequence()[param]->getAsTyped() :
  4675. arguments->getAsTyped());
  4676. if (*function[param].type != arg->getType()) {
  4677. // In-qualified arguments just need an extra node added above the argument to
  4678. // convert to the correct type.
  4679. TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
  4680. if (convArg != nullptr)
  4681. convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
  4682. if (convArg != nullptr)
  4683. setArg(param, convArg);
  4684. else
  4685. error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
  4686. } else {
  4687. if (wasFlattened(arg)) {
  4688. // If both formal and calling arg are to be flattened, leave that to argument
  4689. // expansion, not conversion.
  4690. if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4691. // Will make a two-level subtree.
  4692. // The deepest will copy member-by-member to build the structure to pass.
  4693. // The level above that will be a two-operand EOpComma sequence that follows the copy by the
  4694. // object itself.
  4695. TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
  4696. internalAggregate->getWritableType().getQualifier().makeTemporary();
  4697. TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
  4698. internalAggregate->getName(),
  4699. internalAggregate->getType());
  4700. internalSymbolNode->setLoc(arg->getLoc());
  4701. // This makes the deepest level, the member-wise copy
  4702. TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
  4703. internalSymbolNode, arg)->getAsAggregate();
  4704. // Now, pair that with the resulting aggregate.
  4705. assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
  4706. assignAgg->setOperator(EOpComma);
  4707. assignAgg->setType(internalAggregate->getType());
  4708. setArg(param, assignAgg);
  4709. }
  4710. }
  4711. }
  4712. }
  4713. }
  4714. //
  4715. // Add any needed implicit expansion of calling arguments from what the shader listed to what's
  4716. // internally needed for the AST (given the constraints downstream).
  4717. //
  4718. void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
  4719. {
  4720. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4721. int functionParamNumberOffset = 0;
  4722. // Replace a single argument with a single argument.
  4723. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4724. if (function.getParamCount() + functionParamNumberOffset == 1)
  4725. arguments = arg;
  4726. else {
  4727. if (aggregate == nullptr)
  4728. arguments = arg;
  4729. else
  4730. aggregate->getSequence()[paramNum] = arg;
  4731. }
  4732. };
  4733. // Replace a single argument with a list of arguments
  4734. const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
  4735. if (args.size() == 1)
  4736. setArg(paramNum, args.front());
  4737. else if (args.size() > 1) {
  4738. if (function.getParamCount() + functionParamNumberOffset == 1) {
  4739. arguments = intermediate.makeAggregate(args.front());
  4740. std::for_each(args.begin() + 1, args.end(),
  4741. [&](TIntermTyped* arg) {
  4742. arguments = intermediate.growAggregate(arguments, arg);
  4743. });
  4744. } else {
  4745. auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
  4746. aggregate->getSequence().insert(it, args.begin(), args.end());
  4747. }
  4748. functionParamNumberOffset += (int)(args.size() - 1);
  4749. }
  4750. };
  4751. // Process each argument's conversion
  4752. for (int param = 0; param < function.getParamCount(); ++param) {
  4753. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4754. // is the single argument itself or its children are the arguments. Only one argument
  4755. // means take 'arguments' itself as the one argument.
  4756. TIntermTyped* arg = function.getParamCount() == 1
  4757. ? arguments->getAsTyped()
  4758. : (aggregate ?
  4759. aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
  4760. arguments->getAsTyped());
  4761. if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4762. // Need to pass the structure members instead of the structure.
  4763. TVector<TIntermTyped*> memberArgs;
  4764. for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
  4765. memberArgs.push_back(flattenAccess(arg, memb));
  4766. setArgList(param + functionParamNumberOffset, memberArgs);
  4767. }
  4768. }
  4769. // TODO: if we need both hidden counter args (below) and struct expansion (above)
  4770. // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
  4771. // parameters and arguments.
  4772. // If any argument is a pass-by-reference struct buffer with an associated counter
  4773. // buffer, we have to add another hidden parameter for that counter.
  4774. if (aggregate)
  4775. addStructBuffArguments(loc, aggregate);
  4776. }
  4777. //
  4778. // Add any needed implicit output conversions for function-call arguments. This
  4779. // can require a new tree topology, complicated further by whether the function
  4780. // has a return value.
  4781. //
  4782. // Returns a node of a subtree that evaluates to the return value of the function.
  4783. //
  4784. TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
  4785. {
  4786. assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
  4787. const TSourceLoc& loc = intermNode.getLoc();
  4788. TIntermSequence argSequence; // temp sequence for unary node args
  4789. if (intermNode.getAsUnaryNode())
  4790. argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
  4791. TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
  4792. const auto needsConversion = [&](int argNum) {
  4793. return function[argNum].type->getQualifier().isParamOutput() &&
  4794. (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
  4795. shouldConvertLValue(arguments[argNum]) ||
  4796. wasFlattened(arguments[argNum]->getAsTyped()));
  4797. };
  4798. // Will there be any output conversions?
  4799. bool outputConversions = false;
  4800. for (int i = 0; i < function.getParamCount(); ++i) {
  4801. if (needsConversion(i)) {
  4802. outputConversions = true;
  4803. break;
  4804. }
  4805. }
  4806. if (! outputConversions)
  4807. return &intermNode;
  4808. // Setup for the new tree, if needed:
  4809. //
  4810. // Output conversions need a different tree topology.
  4811. // Out-qualified arguments need a temporary of the correct type, with the call
  4812. // followed by an assignment of the temporary to the original argument:
  4813. // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
  4814. // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
  4815. // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
  4816. TIntermTyped* conversionTree = nullptr;
  4817. TVariable* tempRet = nullptr;
  4818. if (intermNode.getBasicType() != EbtVoid) {
  4819. // do the "tempRet = function(...), " bit from above
  4820. tempRet = makeInternalVariable("tempReturn", intermNode.getType());
  4821. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4822. conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
  4823. } else
  4824. conversionTree = &intermNode;
  4825. conversionTree = intermediate.makeAggregate(conversionTree);
  4826. // Process each argument's conversion
  4827. for (int i = 0; i < function.getParamCount(); ++i) {
  4828. if (needsConversion(i)) {
  4829. // Out-qualified arguments needing conversion need to use the topology setup above.
  4830. // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
  4831. // Make a temporary for what the function expects the argument to look like.
  4832. TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
  4833. tempArg->getWritableType().getQualifier().makeTemporary();
  4834. TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
  4835. // This makes the deepest level, the member-wise copy
  4836. TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
  4837. tempArgNode);
  4838. tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
  4839. conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
  4840. // replace the argument with another node for the same tempArg variable
  4841. arguments[i] = intermediate.addSymbol(*tempArg, loc);
  4842. }
  4843. }
  4844. // Finalize the tree topology (see bigger comment above).
  4845. if (tempRet) {
  4846. // do the "..., tempRet" bit from above
  4847. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4848. conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
  4849. }
  4850. conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
  4851. return conversionTree;
  4852. }
  4853. //
  4854. // Add any needed "hidden" counter buffer arguments for function calls.
  4855. //
  4856. // Modifies the 'aggregate' argument if needed. Otherwise, is no-op.
  4857. //
  4858. void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
  4859. {
  4860. // See if there are any SB types with counters.
  4861. const bool hasStructBuffArg =
  4862. std::any_of(aggregate->getSequence().begin(),
  4863. aggregate->getSequence().end(),
  4864. [this](const TIntermNode* node) {
  4865. return (node && node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
  4866. });
  4867. // Nothing to do, if we didn't find one.
  4868. if (! hasStructBuffArg)
  4869. return;
  4870. TIntermSequence argsWithCounterBuffers;
  4871. for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
  4872. argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
  4873. if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
  4874. const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
  4875. if (blockSym != nullptr) {
  4876. TType counterType;
  4877. counterBufferType(loc, counterType);
  4878. const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
  4879. TVariable* variable = makeInternalVariable(counterBlockName, counterType);
  4880. // Mark this buffer's counter block as being in use
  4881. structBufferCounter[counterBlockName] = true;
  4882. TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
  4883. argsWithCounterBuffers.push_back(sym);
  4884. }
  4885. }
  4886. }
  4887. // Swap with the temp list we've built up.
  4888. aggregate->getSequence().swap(argsWithCounterBuffers);
  4889. }
  4890. //
  4891. // Do additional checking of built-in function calls that is not caught
  4892. // by normal semantic checks on argument type, extension tagging, etc.
  4893. //
  4894. // Assumes there has been a semantically correct match to a built-in function prototype.
  4895. //
  4896. void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
  4897. {
  4898. // Set up convenience accessors to the argument(s). There is almost always
  4899. // multiple arguments for the cases below, but when there might be one,
  4900. // check the unaryArg first.
  4901. const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
  4902. const TIntermTyped* unaryArg = nullptr;
  4903. const TIntermTyped* arg0 = nullptr;
  4904. if (callNode.getAsAggregate()) {
  4905. argp = &callNode.getAsAggregate()->getSequence();
  4906. if (argp->size() > 0)
  4907. arg0 = (*argp)[0]->getAsTyped();
  4908. } else {
  4909. assert(callNode.getAsUnaryNode());
  4910. unaryArg = callNode.getAsUnaryNode()->getOperand();
  4911. arg0 = unaryArg;
  4912. }
  4913. const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
  4914. switch (callNode.getOp()) {
  4915. case EOpTextureGather:
  4916. case EOpTextureGatherOffset:
  4917. case EOpTextureGatherOffsets:
  4918. {
  4919. // Figure out which variants are allowed by what extensions,
  4920. // and what arguments must be constant for which situations.
  4921. TString featureString = fnCandidate.getName() + "(...)";
  4922. const char* feature = featureString.c_str();
  4923. int compArg = -1; // track which argument, if any, is the constant component argument
  4924. switch (callNode.getOp()) {
  4925. case EOpTextureGather:
  4926. // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
  4927. // otherwise, need GL_ARB_texture_gather.
  4928. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
  4929. fnCandidate[0].type->getSampler().shadow) {
  4930. if (! fnCandidate[0].type->getSampler().shadow)
  4931. compArg = 2;
  4932. }
  4933. break;
  4934. case EOpTextureGatherOffset:
  4935. // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
  4936. if (! fnCandidate[0].type->getSampler().shadow)
  4937. compArg = 3;
  4938. break;
  4939. case EOpTextureGatherOffsets:
  4940. if (! fnCandidate[0].type->getSampler().shadow)
  4941. compArg = 3;
  4942. break;
  4943. default:
  4944. break;
  4945. }
  4946. if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
  4947. if (aggArgs[compArg]->getAsConstantUnion()) {
  4948. int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
  4949. if (value < 0 || value > 3)
  4950. error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
  4951. } else
  4952. error(loc, "must be a compile-time constant:", feature, "component argument");
  4953. }
  4954. break;
  4955. }
  4956. case EOpTextureOffset:
  4957. case EOpTextureFetchOffset:
  4958. case EOpTextureProjOffset:
  4959. case EOpTextureLodOffset:
  4960. case EOpTextureProjLodOffset:
  4961. case EOpTextureGradOffset:
  4962. case EOpTextureProjGradOffset:
  4963. {
  4964. // Handle texture-offset limits checking
  4965. // Pick which argument has to hold constant offsets
  4966. int arg = -1;
  4967. switch (callNode.getOp()) {
  4968. case EOpTextureOffset: arg = 2; break;
  4969. case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
  4970. case EOpTextureProjOffset: arg = 2; break;
  4971. case EOpTextureLodOffset: arg = 3; break;
  4972. case EOpTextureProjLodOffset: arg = 3; break;
  4973. case EOpTextureGradOffset: arg = 4; break;
  4974. case EOpTextureProjGradOffset: arg = 4; break;
  4975. default:
  4976. assert(0);
  4977. break;
  4978. }
  4979. if (arg > 0) {
  4980. if (aggArgs[arg]->getAsConstantUnion() == nullptr)
  4981. error(loc, "argument must be compile-time constant", "texel offset", "");
  4982. else {
  4983. const TType& type = aggArgs[arg]->getAsTyped()->getType();
  4984. for (int c = 0; c < type.getVectorSize(); ++c) {
  4985. int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
  4986. if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
  4987. error(loc, "value is out of range:", "texel offset",
  4988. "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
  4989. }
  4990. }
  4991. }
  4992. break;
  4993. }
  4994. case EOpTextureQuerySamples:
  4995. case EOpImageQuerySamples:
  4996. break;
  4997. case EOpImageAtomicAdd:
  4998. case EOpImageAtomicMin:
  4999. case EOpImageAtomicMax:
  5000. case EOpImageAtomicAnd:
  5001. case EOpImageAtomicOr:
  5002. case EOpImageAtomicXor:
  5003. case EOpImageAtomicExchange:
  5004. case EOpImageAtomicCompSwap:
  5005. break;
  5006. case EOpInterpolateAtCentroid:
  5007. case EOpInterpolateAtSample:
  5008. case EOpInterpolateAtOffset:
  5009. // Make sure the first argument is an interpolant, or an array element of an interpolant
  5010. if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
  5011. // It might still be an array element.
  5012. //
  5013. // We could check more, but the semantics of the first argument are already met; the
  5014. // only way to turn an array into a float/vec* is array dereference and swizzle.
  5015. //
  5016. // ES and desktop 4.3 and earlier: swizzles may not be used
  5017. // desktop 4.4 and later: swizzles may be used
  5018. const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
  5019. if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
  5020. error(loc, "first argument must be an interpolant, or interpolant-array element",
  5021. fnCandidate.getName().c_str(), "");
  5022. }
  5023. break;
  5024. default:
  5025. break;
  5026. }
  5027. }
  5028. //
  5029. // Handle seeing something in a grammar production that can be done by calling
  5030. // a constructor.
  5031. //
  5032. // The constructor still must be "handled" by handleFunctionCall(), which will
  5033. // then call handleConstructor().
  5034. //
  5035. TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
  5036. {
  5037. TOperator op = intermediate.mapTypeToConstructorOp(type);
  5038. if (op == EOpNull) {
  5039. error(loc, "cannot construct this type", type.getBasicString(), "");
  5040. return nullptr;
  5041. }
  5042. TString empty("");
  5043. return new TFunction(&empty, type, op);
  5044. }
  5045. //
  5046. // Handle seeing a "COLON semantic" at the end of a type declaration,
  5047. // by updating the type according to the semantic.
  5048. //
  5049. void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
  5050. const TString& upperCase)
  5051. {
  5052. // Parse and return semantic number. If limit is 0, it will be ignored. Otherwise, if the parsed
  5053. // semantic number is >= limit, errorMsg is issued and 0 is returned.
  5054. // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
  5055. // accept those in lambda functions.
  5056. const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
  5057. size_t pos = semantic.find_last_not_of("0123456789");
  5058. if (pos == std::string::npos)
  5059. return 0u;
  5060. unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
  5061. if (limit != 0 && semanticNum >= limit) {
  5062. error(loc, errorMsg, semantic.c_str(), "");
  5063. return 0u;
  5064. }
  5065. return semanticNum;
  5066. };
  5067. switch(builtIn) {
  5068. case EbvNone:
  5069. // Get location numbers from fragment outputs, instead of
  5070. // auto-assigning them.
  5071. if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
  5072. qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
  5073. nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
  5074. } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
  5075. builtIn = EbvClipDistance;
  5076. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
  5077. } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
  5078. builtIn = EbvCullDistance;
  5079. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
  5080. }
  5081. break;
  5082. case EbvPosition:
  5083. // adjust for stage in/out
  5084. if (language == EShLangFragment)
  5085. builtIn = EbvFragCoord;
  5086. break;
  5087. case EbvFragStencilRef:
  5088. error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
  5089. break;
  5090. case EbvTessLevelInner:
  5091. case EbvTessLevelOuter:
  5092. qualifier.patch = true;
  5093. break;
  5094. default:
  5095. break;
  5096. }
  5097. if (qualifier.builtIn == EbvNone)
  5098. qualifier.builtIn = builtIn;
  5099. qualifier.semanticName = intermediate.addSemanticName(upperCase);
  5100. }
  5101. //
  5102. // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
  5103. //
  5104. // 'location' has the "c[Subcomponent]" part.
  5105. // 'component' points to the "component" part, or nullptr if not present.
  5106. //
  5107. void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
  5108. const glslang::TString* component)
  5109. {
  5110. if (location.size() == 0 || location[0] != 'c') {
  5111. error(loc, "expected 'c'", "packoffset", "");
  5112. return;
  5113. }
  5114. if (location.size() == 1)
  5115. return;
  5116. if (! isdigit(location[1])) {
  5117. error(loc, "expected number after 'c'", "packoffset", "");
  5118. return;
  5119. }
  5120. qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
  5121. if (component != nullptr) {
  5122. int componentOffset = 0;
  5123. switch ((*component)[0]) {
  5124. case 'x': componentOffset = 0; break;
  5125. case 'y': componentOffset = 4; break;
  5126. case 'z': componentOffset = 8; break;
  5127. case 'w': componentOffset = 12; break;
  5128. default:
  5129. componentOffset = -1;
  5130. break;
  5131. }
  5132. if (componentOffset < 0 || component->size() > 1) {
  5133. error(loc, "expected {x, y, z, w} for component", "packoffset", "");
  5134. return;
  5135. }
  5136. qualifier.layoutOffset += componentOffset;
  5137. }
  5138. }
  5139. //
  5140. // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
  5141. //
  5142. // 'profile' points to the shader_profile part, or nullptr if not present.
  5143. // 'desc' is the type# part.
  5144. //
  5145. void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
  5146. const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
  5147. {
  5148. if (profile != nullptr)
  5149. warn(loc, "ignoring shader_profile", "register", "");
  5150. if (desc.size() < 1) {
  5151. error(loc, "expected register type", "register", "");
  5152. return;
  5153. }
  5154. int regNumber = 0;
  5155. if (desc.size() > 1) {
  5156. if (isdigit(desc[1]))
  5157. regNumber = atoi(desc.substr(1, desc.size()).c_str());
  5158. else {
  5159. error(loc, "expected register number after register type", "register", "");
  5160. return;
  5161. }
  5162. }
  5163. // more information about register types see
  5164. // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-register
  5165. const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
  5166. switch (std::tolower(desc[0])) {
  5167. case 'c':
  5168. // c register is the register slot in the global const buffer
  5169. // each slot is a vector of 4 32 bit components
  5170. qualifier.layoutOffset = regNumber * 4 * 4;
  5171. break;
  5172. // const buffer register slot
  5173. case 'b':
  5174. // textrues and structured buffers
  5175. case 't':
  5176. // samplers
  5177. case 's':
  5178. // uav resources
  5179. case 'u':
  5180. // if nothing else has set the binding, do so now
  5181. // (other mechanisms override this one)
  5182. if (!qualifier.hasBinding())
  5183. qualifier.layoutBinding = regNumber + subComponent;
  5184. // This handles per-register layout sets numbers. For the global mode which sets
  5185. // every symbol to the same value, see setLinkageLayoutSets().
  5186. if ((resourceInfo.size() % 3) == 0) {
  5187. // Apply per-symbol resource set and binding.
  5188. for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
  5189. if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
  5190. qualifier.layoutSet = atoi(it[1].c_str());
  5191. qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
  5192. break;
  5193. }
  5194. }
  5195. }
  5196. break;
  5197. default:
  5198. warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
  5199. break;
  5200. }
  5201. // space
  5202. unsigned int setNumber;
  5203. const auto crackSpace = [&]() -> bool {
  5204. const int spaceLen = 5;
  5205. if (spaceDesc->size() < spaceLen + 1)
  5206. return false;
  5207. if (spaceDesc->compare(0, spaceLen, "space") != 0)
  5208. return false;
  5209. if (! isdigit((*spaceDesc)[spaceLen]))
  5210. return false;
  5211. setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
  5212. return true;
  5213. };
  5214. // if nothing else has set the set, do so now
  5215. // (other mechanisms override this one)
  5216. if (spaceDesc && !qualifier.hasSet()) {
  5217. if (! crackSpace()) {
  5218. error(loc, "expected spaceN", "register", "");
  5219. return;
  5220. }
  5221. qualifier.layoutSet = setNumber;
  5222. }
  5223. }
  5224. // Convert to a scalar boolean, or if not allowed by HLSL semantics,
  5225. // report an error and return nullptr.
  5226. TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
  5227. bool mustBeScalar)
  5228. {
  5229. if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
  5230. error(loc, "requires a scalar", "conditional expression", "");
  5231. return nullptr;
  5232. }
  5233. return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
  5234. condition);
  5235. }
  5236. //
  5237. // Same error message for all places assignments don't work.
  5238. //
  5239. void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5240. {
  5241. error(loc, "", op, "cannot convert from '%s' to '%s'",
  5242. right.c_str(), left.c_str());
  5243. }
  5244. //
  5245. // Same error message for all places unary operations don't work.
  5246. //
  5247. void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
  5248. {
  5249. error(loc, " wrong operand type", op,
  5250. "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
  5251. op, operand.c_str());
  5252. }
  5253. //
  5254. // Same error message for all binary operations don't work.
  5255. //
  5256. void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5257. {
  5258. error(loc, " wrong operand types:", op,
  5259. "no operation '%s' exists that takes a left-hand operand of type '%s' and "
  5260. "a right operand of type '%s' (or there is no acceptable conversion)",
  5261. op, left.c_str(), right.c_str());
  5262. }
  5263. //
  5264. // A basic type of EbtVoid is a key that the name string was seen in the source, but
  5265. // it was not found as a variable in the symbol table. If so, give the error
  5266. // message and insert a dummy variable in the symbol table to prevent future errors.
  5267. //
  5268. void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
  5269. {
  5270. TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
  5271. if (! symbol)
  5272. return;
  5273. if (symbol->getType().getBasicType() == EbtVoid) {
  5274. error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
  5275. // Add to symbol table to prevent future error messages on the same name
  5276. if (symbol->getName().size() > 0) {
  5277. TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
  5278. symbolTable.insert(*fakeVariable);
  5279. // substitute a symbol node for this new variable
  5280. nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
  5281. }
  5282. }
  5283. }
  5284. //
  5285. // Both test, and if necessary spit out an error, to see if the node is really
  5286. // a constant.
  5287. //
  5288. void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
  5289. {
  5290. if (node->getQualifier().storage != EvqConst)
  5291. error(node->getLoc(), "constant expression required", token, "");
  5292. }
  5293. //
  5294. // Both test, and if necessary spit out an error, to see if the node is really
  5295. // an integer.
  5296. //
  5297. void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
  5298. {
  5299. if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
  5300. return;
  5301. error(node->getLoc(), "scalar integer expression required", token, "");
  5302. }
  5303. //
  5304. // Both test, and if necessary spit out an error, to see if we are currently
  5305. // globally scoped.
  5306. //
  5307. void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
  5308. {
  5309. if (! symbolTable.atGlobalLevel())
  5310. error(loc, "not allowed in nested scope", token, "");
  5311. }
  5312. bool HlslParseContext::builtInName(const TString& /*identifier*/)
  5313. {
  5314. return false;
  5315. }
  5316. //
  5317. // Make sure there is enough data and not too many arguments provided to the
  5318. // constructor to build something of the type of the constructor. Also returns
  5319. // the type of the constructor.
  5320. //
  5321. // Returns true if there was an error in construction.
  5322. //
  5323. bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
  5324. TOperator op, TType& type)
  5325. {
  5326. type.shallowCopy(function.getType());
  5327. bool constructingMatrix = false;
  5328. switch (op) {
  5329. case EOpConstructTextureSampler:
  5330. error(loc, "unhandled texture constructor", "constructor", "");
  5331. return true;
  5332. case EOpConstructMat2x2:
  5333. case EOpConstructMat2x3:
  5334. case EOpConstructMat2x4:
  5335. case EOpConstructMat3x2:
  5336. case EOpConstructMat3x3:
  5337. case EOpConstructMat3x4:
  5338. case EOpConstructMat4x2:
  5339. case EOpConstructMat4x3:
  5340. case EOpConstructMat4x4:
  5341. case EOpConstructDMat2x2:
  5342. case EOpConstructDMat2x3:
  5343. case EOpConstructDMat2x4:
  5344. case EOpConstructDMat3x2:
  5345. case EOpConstructDMat3x3:
  5346. case EOpConstructDMat3x4:
  5347. case EOpConstructDMat4x2:
  5348. case EOpConstructDMat4x3:
  5349. case EOpConstructDMat4x4:
  5350. case EOpConstructIMat2x2:
  5351. case EOpConstructIMat2x3:
  5352. case EOpConstructIMat2x4:
  5353. case EOpConstructIMat3x2:
  5354. case EOpConstructIMat3x3:
  5355. case EOpConstructIMat3x4:
  5356. case EOpConstructIMat4x2:
  5357. case EOpConstructIMat4x3:
  5358. case EOpConstructIMat4x4:
  5359. case EOpConstructUMat2x2:
  5360. case EOpConstructUMat2x3:
  5361. case EOpConstructUMat2x4:
  5362. case EOpConstructUMat3x2:
  5363. case EOpConstructUMat3x3:
  5364. case EOpConstructUMat3x4:
  5365. case EOpConstructUMat4x2:
  5366. case EOpConstructUMat4x3:
  5367. case EOpConstructUMat4x4:
  5368. case EOpConstructBMat2x2:
  5369. case EOpConstructBMat2x3:
  5370. case EOpConstructBMat2x4:
  5371. case EOpConstructBMat3x2:
  5372. case EOpConstructBMat3x3:
  5373. case EOpConstructBMat3x4:
  5374. case EOpConstructBMat4x2:
  5375. case EOpConstructBMat4x3:
  5376. case EOpConstructBMat4x4:
  5377. constructingMatrix = true;
  5378. break;
  5379. default:
  5380. break;
  5381. }
  5382. //
  5383. // Walk the arguments for first-pass checks and collection of information.
  5384. //
  5385. int size = 0;
  5386. bool constType = true;
  5387. bool full = false;
  5388. bool overFull = false;
  5389. bool matrixInMatrix = false;
  5390. bool arrayArg = false;
  5391. for (int arg = 0; arg < function.getParamCount(); ++arg) {
  5392. if (function[arg].type->isArray()) {
  5393. if (function[arg].type->isUnsizedArray()) {
  5394. // Can't construct from an unsized array.
  5395. error(loc, "array argument must be sized", "constructor", "");
  5396. return true;
  5397. }
  5398. arrayArg = true;
  5399. }
  5400. if (constructingMatrix && function[arg].type->isMatrix())
  5401. matrixInMatrix = true;
  5402. // 'full' will go to true when enough args have been seen. If we loop
  5403. // again, there is an extra argument.
  5404. if (full) {
  5405. // For vectors and matrices, it's okay to have too many components
  5406. // available, but not okay to have unused arguments.
  5407. overFull = true;
  5408. }
  5409. size += function[arg].type->computeNumComponents();
  5410. if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
  5411. full = true;
  5412. if (function[arg].type->getQualifier().storage != EvqConst)
  5413. constType = false;
  5414. }
  5415. if (constType)
  5416. type.getQualifier().storage = EvqConst;
  5417. if (type.isArray()) {
  5418. if (function.getParamCount() == 0) {
  5419. error(loc, "array constructor must have at least one argument", "constructor", "");
  5420. return true;
  5421. }
  5422. if (type.isUnsizedArray()) {
  5423. // auto adapt the constructor type to the number of arguments
  5424. type.changeOuterArraySize(function.getParamCount());
  5425. } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
  5426. error(loc, "array constructor needs one argument per array element", "constructor", "");
  5427. return true;
  5428. }
  5429. if (type.isArrayOfArrays()) {
  5430. // Types have to match, but we're still making the type.
  5431. // Finish making the type, and the comparison is done later
  5432. // when checking for conversion.
  5433. TArraySizes& arraySizes = *type.getArraySizes();
  5434. // At least the dimensionalities have to match.
  5435. if (! function[0].type->isArray() ||
  5436. arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
  5437. error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
  5438. return true;
  5439. }
  5440. if (arraySizes.isInnerUnsized()) {
  5441. // "Arrays of arrays ..., and the size for any dimension is optional"
  5442. // That means we need to adopt (from the first argument) the other array sizes into the type.
  5443. for (int d = 1; d < arraySizes.getNumDims(); ++d) {
  5444. if (arraySizes.getDimSize(d) == UnsizedArraySize) {
  5445. arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
  5446. }
  5447. }
  5448. }
  5449. }
  5450. }
  5451. // Some array -> array type casts are okay
  5452. if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
  5453. !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
  5454. type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
  5455. return false;
  5456. if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
  5457. error(loc, "constructing non-array constituent from array argument", "constructor", "");
  5458. return true;
  5459. }
  5460. if (matrixInMatrix && ! type.isArray()) {
  5461. return false;
  5462. }
  5463. if (overFull) {
  5464. error(loc, "too many arguments", "constructor", "");
  5465. return true;
  5466. }
  5467. if (op == EOpConstructStruct && ! type.isArray()) {
  5468. if (isScalarConstructor(node))
  5469. return false;
  5470. // Self-type construction: e.g, we can construct a struct from a single identically typed object.
  5471. if (function.getParamCount() == 1 && type == *function[0].type)
  5472. return false;
  5473. if ((int)type.getStruct()->size() != function.getParamCount()) {
  5474. error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
  5475. return true;
  5476. }
  5477. }
  5478. if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
  5479. (op == EOpConstructStruct && size < type.computeNumComponents())) {
  5480. error(loc, "not enough data provided for construction", "constructor", "");
  5481. return true;
  5482. }
  5483. return false;
  5484. }
  5485. // See if 'node', in the context of constructing aggregates, is a scalar argument
  5486. // to a constructor.
  5487. //
  5488. bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
  5489. {
  5490. // Obviously, it must be a scalar, but an aggregate node might not be fully
  5491. // completed yet: holding a sequence of initializers under an aggregate
  5492. // would not yet be typed, so don't check it's type. This corresponds to
  5493. // the aggregate operator also not being set yet. (An aggregate operation
  5494. // that legitimately yields a scalar will have a getOp() of that operator,
  5495. // not EOpNull.)
  5496. return node->getAsTyped() != nullptr &&
  5497. node->getAsTyped()->isScalar() &&
  5498. (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
  5499. }
  5500. // Checks to see if a void variable has been declared and raise an error message for such a case
  5501. //
  5502. // returns true in case of an error
  5503. //
  5504. bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
  5505. {
  5506. if (basicType == EbtVoid) {
  5507. error(loc, "illegal use of type 'void'", identifier.c_str(), "");
  5508. return true;
  5509. }
  5510. return false;
  5511. }
  5512. //
  5513. // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
  5514. //
  5515. void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
  5516. {
  5517. // move from parameter/unknown qualifiers to pipeline in/out qualifiers
  5518. switch (qualifier.storage) {
  5519. case EvqIn:
  5520. qualifier.storage = EvqVaryingIn;
  5521. break;
  5522. case EvqOut:
  5523. qualifier.storage = EvqVaryingOut;
  5524. break;
  5525. default:
  5526. break;
  5527. }
  5528. }
  5529. //
  5530. // Merge characteristics of the 'src' qualifier into the 'dst'.
  5531. // If there is duplication, issue error messages, unless 'force'
  5532. // is specified, which means to just override default settings.
  5533. //
  5534. // Also, when force is false, it will be assumed that 'src' follows
  5535. // 'dst', for the purpose of error checking order for versions
  5536. // that require specific orderings of qualifiers.
  5537. //
  5538. void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
  5539. {
  5540. // Storage qualification
  5541. if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
  5542. dst.storage = src.storage;
  5543. else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
  5544. (dst.storage == EvqOut && src.storage == EvqIn))
  5545. dst.storage = EvqInOut;
  5546. else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
  5547. (dst.storage == EvqConst && src.storage == EvqIn))
  5548. dst.storage = EvqConstReadOnly;
  5549. // Layout qualifiers
  5550. mergeObjectLayoutQualifiers(dst, src, false);
  5551. // individual qualifiers
  5552. bool repeated = false;
  5553. #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
  5554. MERGE_SINGLETON(invariant);
  5555. MERGE_SINGLETON(noContraction);
  5556. MERGE_SINGLETON(centroid);
  5557. MERGE_SINGLETON(smooth);
  5558. MERGE_SINGLETON(flat);
  5559. MERGE_SINGLETON(nopersp);
  5560. MERGE_SINGLETON(patch);
  5561. MERGE_SINGLETON(sample);
  5562. MERGE_SINGLETON(coherent);
  5563. MERGE_SINGLETON(volatil);
  5564. MERGE_SINGLETON(restrict);
  5565. MERGE_SINGLETON(readonly);
  5566. MERGE_SINGLETON(writeonly);
  5567. MERGE_SINGLETON(specConstant);
  5568. MERGE_SINGLETON(nonUniform);
  5569. }
  5570. // used to flatten the sampler type space into a single dimension
  5571. // correlates with the declaration of defaultSamplerPrecision[]
  5572. int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
  5573. {
  5574. int arrayIndex = sampler.arrayed ? 1 : 0;
  5575. int shadowIndex = sampler.shadow ? 1 : 0;
  5576. int externalIndex = sampler.external ? 1 : 0;
  5577. return EsdNumDims *
  5578. (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
  5579. }
  5580. //
  5581. // Do size checking for an array type's size.
  5582. //
  5583. void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
  5584. {
  5585. bool isConst = false;
  5586. sizePair.size = 1;
  5587. sizePair.node = nullptr;
  5588. TIntermConstantUnion* constant = expr->getAsConstantUnion();
  5589. if (constant) {
  5590. // handle true (non-specialization) constant
  5591. sizePair.size = constant->getConstArray()[0].getIConst();
  5592. isConst = true;
  5593. } else {
  5594. // see if it's a specialization constant instead
  5595. if (expr->getQualifier().isSpecConstant()) {
  5596. isConst = true;
  5597. sizePair.node = expr;
  5598. TIntermSymbol* symbol = expr->getAsSymbolNode();
  5599. if (symbol && symbol->getConstArray().size() > 0)
  5600. sizePair.size = symbol->getConstArray()[0].getIConst();
  5601. }
  5602. }
  5603. if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
  5604. error(loc, "array size must be a constant integer expression", "", "");
  5605. return;
  5606. }
  5607. if (sizePair.size <= 0) {
  5608. error(loc, "array size must be a positive integer", "", "");
  5609. return;
  5610. }
  5611. }
  5612. //
  5613. // Require array to be completely sized
  5614. //
  5615. void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
  5616. {
  5617. if (arraySizes.hasUnsized())
  5618. error(loc, "array size required", "", "");
  5619. }
  5620. void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
  5621. {
  5622. const TTypeList& structure = *type.getStruct();
  5623. for (int m = 0; m < (int)structure.size(); ++m) {
  5624. const TType& member = *structure[m].type;
  5625. if (member.isArray())
  5626. arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
  5627. }
  5628. }
  5629. //
  5630. // Do all the semantic checking for declaring or redeclaring an array, with and
  5631. // without a size, and make the right changes to the symbol table.
  5632. //
  5633. void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  5634. TSymbol*& symbol, bool track)
  5635. {
  5636. if (symbol == nullptr) {
  5637. bool currentScope;
  5638. symbol = symbolTable.find(identifier, nullptr, &currentScope);
  5639. if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
  5640. // bad shader (errors already reported) trying to redeclare a built-in name as an array
  5641. return;
  5642. }
  5643. if (symbol == nullptr || ! currentScope) {
  5644. //
  5645. // Successfully process a new definition.
  5646. // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
  5647. //
  5648. symbol = new TVariable(&identifier, type);
  5649. symbolTable.insert(*symbol);
  5650. if (track && symbolTable.atGlobalLevel())
  5651. trackLinkage(*symbol);
  5652. return;
  5653. }
  5654. if (symbol->getAsAnonMember()) {
  5655. error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
  5656. symbol = nullptr;
  5657. return;
  5658. }
  5659. }
  5660. //
  5661. // Process a redeclaration.
  5662. //
  5663. if (symbol == nullptr) {
  5664. error(loc, "array variable name expected", identifier.c_str(), "");
  5665. return;
  5666. }
  5667. // redeclareBuiltinVariable() should have already done the copyUp()
  5668. TType& existingType = symbol->getWritableType();
  5669. if (existingType.isSizedArray()) {
  5670. // be more lenient for input arrays to geometry shaders and tessellation control outputs,
  5671. // where the redeclaration is the same size
  5672. return;
  5673. }
  5674. existingType.updateArraySizes(type);
  5675. }
  5676. //
  5677. // Enforce non-initializer type/qualifier rules.
  5678. //
  5679. void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
  5680. TIntermTyped*& initializer)
  5681. {
  5682. //
  5683. // Make the qualifier make sense, given that there is an initializer.
  5684. //
  5685. if (initializer == nullptr) {
  5686. if (type.getQualifier().storage == EvqConst ||
  5687. type.getQualifier().storage == EvqConstReadOnly) {
  5688. initializer = intermediate.makeAggregate(loc);
  5689. warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
  5690. }
  5691. }
  5692. }
  5693. //
  5694. // See if the identifier is a built-in symbol that can be redeclared, and if so,
  5695. // copy the symbol table's read-only built-in variable to the current
  5696. // global level, where it can be modified based on the passed in type.
  5697. //
  5698. // Returns nullptr if no redeclaration took place; meaning a normal declaration still
  5699. // needs to occur for it, not necessarily an error.
  5700. //
  5701. // Returns a redeclared and type-modified variable if a redeclared occurred.
  5702. //
  5703. TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
  5704. const TQualifier& /*qualifier*/,
  5705. const TShaderQualifiers& /*publicType*/)
  5706. {
  5707. if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
  5708. return nullptr;
  5709. return nullptr;
  5710. }
  5711. //
  5712. // Generate index to the array element in a structure buffer (SSBO)
  5713. //
  5714. TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
  5715. {
  5716. // Bail out if not a struct buffer
  5717. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  5718. return nullptr;
  5719. // Runtime sized array is always the last element.
  5720. const TTypeList* bufferStruct = buffer->getType().getStruct();
  5721. TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
  5722. TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
  5723. argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
  5724. return argArray;
  5725. }
  5726. //
  5727. // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
  5728. // (template) type. E.g, StructuredBuffer<MyType> -> MyType. Else return nullptr.
  5729. //
  5730. TType* HlslParseContext::getStructBufferContentType(const TType& type) const
  5731. {
  5732. if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
  5733. return nullptr;
  5734. const int memberCount = (int)type.getStruct()->size();
  5735. assert(memberCount > 0);
  5736. TType* contentType = (*type.getStruct())[memberCount-1].type;
  5737. return contentType->isUnsizedArray() ? contentType : nullptr;
  5738. }
  5739. //
  5740. // If an existing struct buffer has a sharable type, then share it.
  5741. //
  5742. void HlslParseContext::shareStructBufferType(TType& type)
  5743. {
  5744. // PackOffset must be equivalent to share types on a per-member basis.
  5745. // Note: cannot use auto type due to recursion. Thus, this is a std::function.
  5746. const std::function<bool(TType& lhs, TType& rhs)>
  5747. compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
  5748. if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
  5749. return false;
  5750. if (lhs.isStruct() != rhs.isStruct())
  5751. return false;
  5752. if (lhs.isStruct() && rhs.isStruct()) {
  5753. if (lhs.getStruct()->size() != rhs.getStruct()->size())
  5754. return false;
  5755. for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
  5756. if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
  5757. return false;
  5758. }
  5759. return true;
  5760. };
  5761. // We need to compare certain qualifiers in addition to the type.
  5762. const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
  5763. if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
  5764. return false;
  5765. // If both are structures, recursively look for packOffset equality
  5766. // as well as type equality.
  5767. return compareQualifiers(lhs, rhs) && lhs == rhs;
  5768. };
  5769. // This is an exhaustive O(N) search, but real world shaders have
  5770. // only a small number of these.
  5771. for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
  5772. // If the deep structure matches, modulo qualifiers, use it
  5773. if (typeEqual(*structBufferTypes[idx], type)) {
  5774. type.shallowCopy(*structBufferTypes[idx]);
  5775. return;
  5776. }
  5777. }
  5778. // Otherwise, remember it:
  5779. TType* typeCopy = new TType;
  5780. typeCopy->shallowCopy(type);
  5781. structBufferTypes.push_back(typeCopy);
  5782. }
  5783. void HlslParseContext::paramFix(TType& type)
  5784. {
  5785. switch (type.getQualifier().storage) {
  5786. case EvqConst:
  5787. type.getQualifier().storage = EvqConstReadOnly;
  5788. break;
  5789. case EvqGlobal:
  5790. case EvqUniform:
  5791. case EvqTemporary:
  5792. type.getQualifier().storage = EvqIn;
  5793. break;
  5794. case EvqBuffer:
  5795. {
  5796. // SSBO parameter. These do not go through the declareBlock path since they are fn parameters.
  5797. correctUniform(type.getQualifier());
  5798. TQualifier bufferQualifier = globalBufferDefaults;
  5799. mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
  5800. bufferQualifier.storage = type.getQualifier().storage;
  5801. bufferQualifier.readonly = type.getQualifier().readonly;
  5802. bufferQualifier.coherent = type.getQualifier().coherent;
  5803. bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
  5804. type.getQualifier() = bufferQualifier;
  5805. break;
  5806. }
  5807. default:
  5808. break;
  5809. }
  5810. }
  5811. void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
  5812. {
  5813. if (type.containsSpecializationSize())
  5814. error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
  5815. }
  5816. //
  5817. // Layout qualifier stuff.
  5818. //
  5819. // Put the id's layout qualification into the public type, for qualifiers not having a number set.
  5820. // This is before we know any type information for error checking.
  5821. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
  5822. {
  5823. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5824. if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
  5825. qualifier.layoutMatrix = ElmRowMajor;
  5826. return;
  5827. }
  5828. if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
  5829. qualifier.layoutMatrix = ElmColumnMajor;
  5830. return;
  5831. }
  5832. if (id == "push_constant") {
  5833. requireVulkan(loc, "push_constant");
  5834. qualifier.layoutPushConstant = true;
  5835. return;
  5836. }
  5837. if (language == EShLangGeometry || language == EShLangTessEvaluation) {
  5838. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5839. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5840. warn(loc, "ignored", id.c_str(), "");
  5841. return;
  5842. }
  5843. if (language == EShLangGeometry) {
  5844. if (id == TQualifier::getGeometryString(ElgPoints)) {
  5845. // publicType.shaderQualifiers.geometry = ElgPoints;
  5846. warn(loc, "ignored", id.c_str(), "");
  5847. return;
  5848. }
  5849. if (id == TQualifier::getGeometryString(ElgLineStrip)) {
  5850. // publicType.shaderQualifiers.geometry = ElgLineStrip;
  5851. warn(loc, "ignored", id.c_str(), "");
  5852. return;
  5853. }
  5854. if (id == TQualifier::getGeometryString(ElgLines)) {
  5855. // publicType.shaderQualifiers.geometry = ElgLines;
  5856. warn(loc, "ignored", id.c_str(), "");
  5857. return;
  5858. }
  5859. if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
  5860. // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
  5861. warn(loc, "ignored", id.c_str(), "");
  5862. return;
  5863. }
  5864. if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
  5865. // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
  5866. warn(loc, "ignored", id.c_str(), "");
  5867. return;
  5868. }
  5869. if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
  5870. // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
  5871. warn(loc, "ignored", id.c_str(), "");
  5872. return;
  5873. }
  5874. } else {
  5875. assert(language == EShLangTessEvaluation);
  5876. // input primitive
  5877. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5878. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5879. warn(loc, "ignored", id.c_str(), "");
  5880. return;
  5881. }
  5882. if (id == TQualifier::getGeometryString(ElgQuads)) {
  5883. // publicType.shaderQualifiers.geometry = ElgQuads;
  5884. warn(loc, "ignored", id.c_str(), "");
  5885. return;
  5886. }
  5887. if (id == TQualifier::getGeometryString(ElgIsolines)) {
  5888. // publicType.shaderQualifiers.geometry = ElgIsolines;
  5889. warn(loc, "ignored", id.c_str(), "");
  5890. return;
  5891. }
  5892. // vertex spacing
  5893. if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
  5894. // publicType.shaderQualifiers.spacing = EvsEqual;
  5895. warn(loc, "ignored", id.c_str(), "");
  5896. return;
  5897. }
  5898. if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
  5899. // publicType.shaderQualifiers.spacing = EvsFractionalEven;
  5900. warn(loc, "ignored", id.c_str(), "");
  5901. return;
  5902. }
  5903. if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
  5904. // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
  5905. warn(loc, "ignored", id.c_str(), "");
  5906. return;
  5907. }
  5908. // triangle order
  5909. if (id == TQualifier::getVertexOrderString(EvoCw)) {
  5910. // publicType.shaderQualifiers.order = EvoCw;
  5911. warn(loc, "ignored", id.c_str(), "");
  5912. return;
  5913. }
  5914. if (id == TQualifier::getVertexOrderString(EvoCcw)) {
  5915. // publicType.shaderQualifiers.order = EvoCcw;
  5916. warn(loc, "ignored", id.c_str(), "");
  5917. return;
  5918. }
  5919. // point mode
  5920. if (id == "point_mode") {
  5921. // publicType.shaderQualifiers.pointMode = true;
  5922. warn(loc, "ignored", id.c_str(), "");
  5923. return;
  5924. }
  5925. }
  5926. }
  5927. if (language == EShLangFragment) {
  5928. if (id == "origin_upper_left") {
  5929. // publicType.shaderQualifiers.originUpperLeft = true;
  5930. warn(loc, "ignored", id.c_str(), "");
  5931. return;
  5932. }
  5933. if (id == "pixel_center_integer") {
  5934. // publicType.shaderQualifiers.pixelCenterInteger = true;
  5935. warn(loc, "ignored", id.c_str(), "");
  5936. return;
  5937. }
  5938. if (id == "early_fragment_tests") {
  5939. // publicType.shaderQualifiers.earlyFragmentTests = true;
  5940. warn(loc, "ignored", id.c_str(), "");
  5941. return;
  5942. }
  5943. for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
  5944. if (id == TQualifier::getLayoutDepthString(depth)) {
  5945. // publicType.shaderQualifiers.layoutDepth = depth;
  5946. warn(loc, "ignored", id.c_str(), "");
  5947. return;
  5948. }
  5949. }
  5950. if (id.compare(0, 13, "blend_support") == 0) {
  5951. bool found = false;
  5952. for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
  5953. if (id == TQualifier::getBlendEquationString(be)) {
  5954. requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
  5955. intermediate.addBlendEquation(be);
  5956. // publicType.shaderQualifiers.blendEquation = true;
  5957. warn(loc, "ignored", id.c_str(), "");
  5958. found = true;
  5959. break;
  5960. }
  5961. }
  5962. if (! found)
  5963. error(loc, "unknown blend equation", "blend_support", "");
  5964. return;
  5965. }
  5966. }
  5967. error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
  5968. }
  5969. // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
  5970. // This is before we know any type information for error checking.
  5971. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
  5972. const TIntermTyped* node)
  5973. {
  5974. const char* feature = "layout-id value";
  5975. // const char* nonLiteralFeature = "non-literal layout-id value";
  5976. integerCheck(node, feature);
  5977. const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
  5978. int value = 0;
  5979. if (constUnion) {
  5980. value = constUnion->getConstArray()[0].getIConst();
  5981. }
  5982. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5983. if (id == "offset") {
  5984. qualifier.layoutOffset = value;
  5985. return;
  5986. } else if (id == "align") {
  5987. // "The specified alignment must be a power of 2, or a compile-time error results."
  5988. if (! IsPow2(value))
  5989. error(loc, "must be a power of 2", "align", "");
  5990. else
  5991. qualifier.layoutAlign = value;
  5992. return;
  5993. } else if (id == "location") {
  5994. if ((unsigned int)value >= TQualifier::layoutLocationEnd)
  5995. error(loc, "location is too large", id.c_str(), "");
  5996. else
  5997. qualifier.layoutLocation = value;
  5998. return;
  5999. } else if (id == "set") {
  6000. if ((unsigned int)value >= TQualifier::layoutSetEnd)
  6001. error(loc, "set is too large", id.c_str(), "");
  6002. else
  6003. qualifier.layoutSet = value;
  6004. return;
  6005. } else if (id == "binding") {
  6006. if ((unsigned int)value >= TQualifier::layoutBindingEnd)
  6007. error(loc, "binding is too large", id.c_str(), "");
  6008. else
  6009. qualifier.layoutBinding = value;
  6010. return;
  6011. } else if (id == "component") {
  6012. if ((unsigned)value >= TQualifier::layoutComponentEnd)
  6013. error(loc, "component is too large", id.c_str(), "");
  6014. else
  6015. qualifier.layoutComponent = value;
  6016. return;
  6017. } else if (id.compare(0, 4, "xfb_") == 0) {
  6018. // "Any shader making any static use (after preprocessing) of any of these
  6019. // *xfb_* qualifiers will cause the shader to be in a transform feedback
  6020. // capturing mode and hence responsible for describing the transform feedback
  6021. // setup."
  6022. intermediate.setXfbMode();
  6023. if (id == "xfb_buffer") {
  6024. // "It is a compile-time error to specify an *xfb_buffer* that is greater than
  6025. // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
  6026. if (value >= resources.maxTransformFeedbackBuffers)
  6027. error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
  6028. resources.maxTransformFeedbackBuffers);
  6029. if (value >= (int)TQualifier::layoutXfbBufferEnd)
  6030. error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
  6031. else
  6032. qualifier.layoutXfbBuffer = value;
  6033. return;
  6034. } else if (id == "xfb_offset") {
  6035. if (value >= (int)TQualifier::layoutXfbOffsetEnd)
  6036. error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
  6037. else
  6038. qualifier.layoutXfbOffset = value;
  6039. return;
  6040. } else if (id == "xfb_stride") {
  6041. // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
  6042. // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
  6043. if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
  6044. error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
  6045. resources.maxTransformFeedbackInterleavedComponents);
  6046. else if (value >= (int)TQualifier::layoutXfbStrideEnd)
  6047. error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
  6048. if (value < (int)TQualifier::layoutXfbStrideEnd)
  6049. qualifier.layoutXfbStride = value;
  6050. return;
  6051. }
  6052. }
  6053. if (id == "input_attachment_index") {
  6054. requireVulkan(loc, "input_attachment_index");
  6055. if (value >= (int)TQualifier::layoutAttachmentEnd)
  6056. error(loc, "attachment index is too large", id.c_str(), "");
  6057. else
  6058. qualifier.layoutAttachment = value;
  6059. return;
  6060. }
  6061. if (id == "constant_id") {
  6062. setSpecConstantId(loc, qualifier, value);
  6063. return;
  6064. }
  6065. switch (language) {
  6066. case EShLangVertex:
  6067. break;
  6068. case EShLangTessControl:
  6069. if (id == "vertices") {
  6070. if (value == 0)
  6071. error(loc, "must be greater than 0", "vertices", "");
  6072. else
  6073. // publicType.shaderQualifiers.vertices = value;
  6074. warn(loc, "ignored", id.c_str(), "");
  6075. return;
  6076. }
  6077. break;
  6078. case EShLangTessEvaluation:
  6079. break;
  6080. case EShLangGeometry:
  6081. if (id == "invocations") {
  6082. if (value == 0)
  6083. error(loc, "must be at least 1", "invocations", "");
  6084. else
  6085. // publicType.shaderQualifiers.invocations = value;
  6086. warn(loc, "ignored", id.c_str(), "");
  6087. return;
  6088. }
  6089. if (id == "max_vertices") {
  6090. // publicType.shaderQualifiers.vertices = value;
  6091. warn(loc, "ignored", id.c_str(), "");
  6092. if (value > resources.maxGeometryOutputVertices)
  6093. error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
  6094. return;
  6095. }
  6096. if (id == "stream") {
  6097. qualifier.layoutStream = value;
  6098. return;
  6099. }
  6100. break;
  6101. case EShLangFragment:
  6102. if (id == "index") {
  6103. qualifier.layoutIndex = value;
  6104. return;
  6105. }
  6106. break;
  6107. case EShLangCompute:
  6108. if (id.compare(0, 11, "local_size_") == 0) {
  6109. if (id == "local_size_x") {
  6110. // publicType.shaderQualifiers.localSize[0] = value;
  6111. warn(loc, "ignored", id.c_str(), "");
  6112. return;
  6113. }
  6114. if (id == "local_size_y") {
  6115. // publicType.shaderQualifiers.localSize[1] = value;
  6116. warn(loc, "ignored", id.c_str(), "");
  6117. return;
  6118. }
  6119. if (id == "local_size_z") {
  6120. // publicType.shaderQualifiers.localSize[2] = value;
  6121. warn(loc, "ignored", id.c_str(), "");
  6122. return;
  6123. }
  6124. if (spvVersion.spv != 0) {
  6125. if (id == "local_size_x_id") {
  6126. // publicType.shaderQualifiers.localSizeSpecId[0] = value;
  6127. warn(loc, "ignored", id.c_str(), "");
  6128. return;
  6129. }
  6130. if (id == "local_size_y_id") {
  6131. // publicType.shaderQualifiers.localSizeSpecId[1] = value;
  6132. warn(loc, "ignored", id.c_str(), "");
  6133. return;
  6134. }
  6135. if (id == "local_size_z_id") {
  6136. // publicType.shaderQualifiers.localSizeSpecId[2] = value;
  6137. warn(loc, "ignored", id.c_str(), "");
  6138. return;
  6139. }
  6140. }
  6141. }
  6142. break;
  6143. default:
  6144. break;
  6145. }
  6146. error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
  6147. }
  6148. void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
  6149. {
  6150. if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
  6151. error(loc, "specialization-constant id is too large", "constant_id", "");
  6152. } else {
  6153. qualifier.layoutSpecConstantId = value;
  6154. qualifier.specConstant = true;
  6155. if (! intermediate.addUsedConstantId(value))
  6156. error(loc, "specialization-constant id already used", "constant_id", "");
  6157. }
  6158. return;
  6159. }
  6160. // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
  6161. //
  6162. // "More than one layout qualifier may appear in a single declaration.
  6163. // Additionally, the same layout-qualifier-name can occur multiple times
  6164. // within a layout qualifier or across multiple layout qualifiers in the
  6165. // same declaration. When the same layout-qualifier-name occurs
  6166. // multiple times, in a single declaration, the last occurrence overrides
  6167. // the former occurrence(s). Further, if such a layout-qualifier-name
  6168. // will effect subsequent declarations or other observable behavior, it
  6169. // is only the last occurrence that will have any effect, behaving as if
  6170. // the earlier occurrence(s) within the declaration are not present.
  6171. // This is also true for overriding layout-qualifier-names, where one
  6172. // overrides the other (e.g., row_major vs. column_major); only the last
  6173. // occurrence has any effect."
  6174. //
  6175. void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
  6176. {
  6177. if (src.hasMatrix())
  6178. dst.layoutMatrix = src.layoutMatrix;
  6179. if (src.hasPacking())
  6180. dst.layoutPacking = src.layoutPacking;
  6181. if (src.hasStream())
  6182. dst.layoutStream = src.layoutStream;
  6183. if (src.hasFormat())
  6184. dst.layoutFormat = src.layoutFormat;
  6185. if (src.hasXfbBuffer())
  6186. dst.layoutXfbBuffer = src.layoutXfbBuffer;
  6187. if (src.hasAlign())
  6188. dst.layoutAlign = src.layoutAlign;
  6189. if (! inheritOnly) {
  6190. if (src.hasLocation())
  6191. dst.layoutLocation = src.layoutLocation;
  6192. if (src.hasComponent())
  6193. dst.layoutComponent = src.layoutComponent;
  6194. if (src.hasIndex())
  6195. dst.layoutIndex = src.layoutIndex;
  6196. if (src.hasOffset())
  6197. dst.layoutOffset = src.layoutOffset;
  6198. if (src.hasSet())
  6199. dst.layoutSet = src.layoutSet;
  6200. if (src.layoutBinding != TQualifier::layoutBindingEnd)
  6201. dst.layoutBinding = src.layoutBinding;
  6202. if (src.hasXfbStride())
  6203. dst.layoutXfbStride = src.layoutXfbStride;
  6204. if (src.hasXfbOffset())
  6205. dst.layoutXfbOffset = src.layoutXfbOffset;
  6206. if (src.hasAttachment())
  6207. dst.layoutAttachment = src.layoutAttachment;
  6208. if (src.hasSpecConstantId())
  6209. dst.layoutSpecConstantId = src.layoutSpecConstantId;
  6210. if (src.layoutPushConstant)
  6211. dst.layoutPushConstant = true;
  6212. }
  6213. }
  6214. //
  6215. // Look up a function name in the symbol table, and make sure it is a function.
  6216. //
  6217. // First, look for an exact match. If there is none, use the generic selector
  6218. // TParseContextBase::selectFunction() to find one, parameterized by the
  6219. // convertible() and better() predicates defined below.
  6220. //
  6221. // Return the function symbol if found, otherwise nullptr.
  6222. //
  6223. const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
  6224. TIntermTyped*& args)
  6225. {
  6226. if (symbolTable.isFunctionNameVariable(call.getName())) {
  6227. error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
  6228. return nullptr;
  6229. }
  6230. // first, look for an exact match
  6231. bool dummyScope;
  6232. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
  6233. if (symbol)
  6234. return symbol->getAsFunction();
  6235. // no exact match, use the generic selector, parameterized by the GLSL rules
  6236. // create list of candidates to send
  6237. TVector<const TFunction*> candidateList;
  6238. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6239. // These built-in ops can accept any type, so we bypass the argument selection
  6240. if (candidateList.size() == 1 && builtIn &&
  6241. (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6242. candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
  6243. candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
  6244. candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
  6245. candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6246. candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
  6247. return candidateList[0];
  6248. }
  6249. bool allowOnlyUpConversions = true;
  6250. // can 'from' convert to 'to'?
  6251. const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
  6252. if (from == to)
  6253. return true;
  6254. // no aggregate conversions
  6255. if (from.isArray() || to.isArray() ||
  6256. from.isStruct() || to.isStruct())
  6257. return false;
  6258. switch (op) {
  6259. case EOpInterlockedAdd:
  6260. case EOpInterlockedAnd:
  6261. case EOpInterlockedCompareExchange:
  6262. case EOpInterlockedCompareStore:
  6263. case EOpInterlockedExchange:
  6264. case EOpInterlockedMax:
  6265. case EOpInterlockedMin:
  6266. case EOpInterlockedOr:
  6267. case EOpInterlockedXor:
  6268. // We do not promote the texture or image type for these ocodes. Normally that would not
  6269. // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
  6270. // stage it's merely e.g, a basic integer type.
  6271. //
  6272. // Instead, we want to promote other arguments, but stay within the same family. In other
  6273. // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
  6274. // but it is allowed to promote its other arguments.
  6275. if (arg == 0)
  6276. return false;
  6277. break;
  6278. case EOpMethodSample:
  6279. case EOpMethodSampleBias:
  6280. case EOpMethodSampleCmp:
  6281. case EOpMethodSampleCmpLevelZero:
  6282. case EOpMethodSampleGrad:
  6283. case EOpMethodSampleLevel:
  6284. case EOpMethodLoad:
  6285. case EOpMethodGetDimensions:
  6286. case EOpMethodGetSamplePosition:
  6287. case EOpMethodGather:
  6288. case EOpMethodCalculateLevelOfDetail:
  6289. case EOpMethodCalculateLevelOfDetailUnclamped:
  6290. case EOpMethodGatherRed:
  6291. case EOpMethodGatherGreen:
  6292. case EOpMethodGatherBlue:
  6293. case EOpMethodGatherAlpha:
  6294. case EOpMethodGatherCmp:
  6295. case EOpMethodGatherCmpRed:
  6296. case EOpMethodGatherCmpGreen:
  6297. case EOpMethodGatherCmpBlue:
  6298. case EOpMethodGatherCmpAlpha:
  6299. case EOpMethodAppend:
  6300. case EOpMethodRestartStrip:
  6301. // those are method calls, the object type can not be changed
  6302. // they are equal if the dim and type match (is dim sufficient?)
  6303. if (arg == 0)
  6304. return from.getSampler().type == to.getSampler().type &&
  6305. from.getSampler().arrayed == to.getSampler().arrayed &&
  6306. from.getSampler().shadow == to.getSampler().shadow &&
  6307. from.getSampler().ms == to.getSampler().ms &&
  6308. from.getSampler().dim == to.getSampler().dim;
  6309. break;
  6310. default:
  6311. break;
  6312. }
  6313. // basic types have to be convertible
  6314. if (allowOnlyUpConversions)
  6315. if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
  6316. return false;
  6317. // shapes have to be convertible
  6318. if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
  6319. (from.isScalarOrVec1() && to.isVector()) ||
  6320. (from.isScalarOrVec1() && to.isMatrix()) ||
  6321. (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
  6322. return true;
  6323. // TODO: what are the matrix rules? they go here
  6324. return false;
  6325. };
  6326. // Is 'to2' a better conversion than 'to1'?
  6327. // Ties should not be considered as better.
  6328. // Assumes 'convertible' already said true.
  6329. const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
  6330. // exact match is always better than mismatch
  6331. if (from == to2)
  6332. return from != to1;
  6333. if (from == to1)
  6334. return false;
  6335. // shape changes are always worse
  6336. if (from.isScalar() || from.isVector()) {
  6337. if (from.getVectorSize() == to2.getVectorSize() &&
  6338. from.getVectorSize() != to1.getVectorSize())
  6339. return true;
  6340. if (from.getVectorSize() == to1.getVectorSize() &&
  6341. from.getVectorSize() != to2.getVectorSize())
  6342. return false;
  6343. }
  6344. // Handle sampler betterness: An exact sampler match beats a non-exact match.
  6345. // (If we just looked at basic type, all EbtSamplers would look the same).
  6346. // If any type is not a sampler, just use the linearize function below.
  6347. if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
  6348. // We can ignore the vector size in the comparison.
  6349. TSampler to1Sampler = to1.getSampler();
  6350. TSampler to2Sampler = to2.getSampler();
  6351. to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
  6352. if (from.getSampler() == to2Sampler)
  6353. return from.getSampler() != to1Sampler;
  6354. if (from.getSampler() == to1Sampler)
  6355. return false;
  6356. }
  6357. // Might or might not be changing shape, which means basic type might
  6358. // or might not match, so within that, the question is how big a
  6359. // basic-type conversion is being done.
  6360. //
  6361. // Use a hierarchy of domains, translated to order of magnitude
  6362. // in a linearized view:
  6363. // - floating-point vs. integer
  6364. // - 32 vs. 64 bit (or width in general)
  6365. // - bool vs. non bool
  6366. // - signed vs. not signed
  6367. const auto linearize = [](const TBasicType& basicType) -> int {
  6368. switch (basicType) {
  6369. case EbtBool: return 1;
  6370. case EbtInt: return 10;
  6371. case EbtUint: return 11;
  6372. case EbtInt64: return 20;
  6373. case EbtUint64: return 21;
  6374. case EbtFloat: return 100;
  6375. case EbtDouble: return 110;
  6376. default: return 0;
  6377. }
  6378. };
  6379. return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
  6380. abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
  6381. };
  6382. // for ambiguity reporting
  6383. bool tie = false;
  6384. // send to the generic selector
  6385. const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6386. if (bestMatch == nullptr) {
  6387. // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
  6388. // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
  6389. // upconversions possible.
  6390. allowOnlyUpConversions = false;
  6391. bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6392. }
  6393. if (bestMatch == nullptr) {
  6394. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6395. return nullptr;
  6396. }
  6397. // For built-ins, we can convert across the arguments. This will happen in several steps:
  6398. // Step 1: If there's an exact match, use it.
  6399. // Step 2a: Otherwise, get the operator from the best match and promote arguments:
  6400. // Step 2b: reconstruct the TFunction based on the new arg types
  6401. // Step 3: Re-select after type promotion is applied, to find proper candidate.
  6402. if (builtIn) {
  6403. // Step 1: If there's an exact match, use it.
  6404. if (call.getMangledName() == bestMatch->getMangledName())
  6405. return bestMatch;
  6406. // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
  6407. // are that kind of operator.
  6408. if (args != nullptr) {
  6409. // The arg list can be a unary node, or an aggregate. We have to handle both.
  6410. // We will use the normal promote() facilities, which require an interm node.
  6411. TIntermOperator* promote = nullptr;
  6412. if (call.getParamCount() == 1) {
  6413. promote = new TIntermUnary(bestMatch->getBuiltInOp());
  6414. promote->getAsUnaryNode()->setOperand(args->getAsTyped());
  6415. } else {
  6416. promote = new TIntermAggregate(bestMatch->getBuiltInOp());
  6417. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6418. }
  6419. if (! intermediate.promote(promote))
  6420. return nullptr;
  6421. // Obtain the promoted arg list.
  6422. if (call.getParamCount() == 1) {
  6423. args = promote->getAsUnaryNode()->getOperand();
  6424. } else {
  6425. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6426. }
  6427. }
  6428. // Step 2b: reconstruct the TFunction based on the new arg types
  6429. TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
  6430. if (args->getAsAggregate()) {
  6431. // Handle aggregates: put all args into the new function call
  6432. for (int arg=0; arg<int(args->getAsAggregate()->getSequence().size()); ++arg) {
  6433. // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
  6434. TParameter param = { 0, new TType, nullptr };
  6435. param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
  6436. convertedCall.addParameter(param);
  6437. }
  6438. } else if (args->getAsUnaryNode()) {
  6439. // Handle unaries: put all args into the new function call
  6440. TParameter param = { 0, new TType, nullptr };
  6441. param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
  6442. convertedCall.addParameter(param);
  6443. } else if (args->getAsTyped()) {
  6444. // Handle bare e.g, floats, not in an aggregate.
  6445. TParameter param = { 0, new TType, nullptr };
  6446. param.type->shallowCopy(args->getAsTyped()->getType());
  6447. convertedCall.addParameter(param);
  6448. } else {
  6449. assert(0); // unknown argument list.
  6450. return nullptr;
  6451. }
  6452. // Step 3: Re-select after type promotion, to find proper candidate
  6453. // send to the generic selector
  6454. bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
  6455. // At this point, there should be no tie.
  6456. }
  6457. if (tie)
  6458. error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
  6459. // Append default parameter values if needed
  6460. if (!tie && bestMatch != nullptr) {
  6461. for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
  6462. handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
  6463. }
  6464. }
  6465. return bestMatch;
  6466. }
  6467. //
  6468. // Do everything necessary to handle a typedef declaration, for a single symbol.
  6469. //
  6470. // 'parseType' is the type part of the declaration (to the left)
  6471. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6472. //
  6473. void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
  6474. {
  6475. TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
  6476. if (! symbolTable.insert(*typeSymbol))
  6477. error(loc, "name already defined", "typedef", identifier.c_str());
  6478. }
  6479. // Do everything necessary to handle a struct declaration, including
  6480. // making IO aliases because HLSL allows mixed IO in a struct that specializes
  6481. // based on the usage (input, output, uniform, none).
  6482. void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
  6483. {
  6484. // If it was named, which means the type can be reused later, add
  6485. // it to the symbol table. (Unless it's a block, in which
  6486. // case the name is not a type.)
  6487. if (type.getBasicType() == EbtBlock || structName.size() == 0)
  6488. return;
  6489. TVariable* userTypeDef = new TVariable(&structName, type, true);
  6490. if (! symbolTable.insert(*userTypeDef)) {
  6491. error(loc, "redefinition", structName.c_str(), "struct");
  6492. return;
  6493. }
  6494. // See if we need IO aliases for the structure typeList
  6495. const auto condAlloc = [](bool pred, TTypeList*& list) {
  6496. if (pred && list == nullptr)
  6497. list = new TTypeList;
  6498. };
  6499. tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
  6500. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6501. condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
  6502. condAlloc( hasInput(member->type->getQualifier()), newLists.input);
  6503. condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
  6504. if (member->type->isStruct()) {
  6505. auto it = ioTypeMap.find(member->type->getStruct());
  6506. if (it != ioTypeMap.end()) {
  6507. condAlloc(it->second.uniform != nullptr, newLists.uniform);
  6508. condAlloc(it->second.input != nullptr, newLists.input);
  6509. condAlloc(it->second.output != nullptr, newLists.output);
  6510. }
  6511. }
  6512. }
  6513. if (newLists.uniform == nullptr &&
  6514. newLists.input == nullptr &&
  6515. newLists.output == nullptr) {
  6516. // Won't do any IO caching, clear up the type and get out now.
  6517. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
  6518. clearUniformInputOutput(member->type->getQualifier());
  6519. return;
  6520. }
  6521. // We have IO involved.
  6522. // Make a pure typeList for the symbol table, and cache side copies of IO versions.
  6523. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6524. const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
  6525. if (s != nullptr) {
  6526. ioMember.type = new TType;
  6527. ioMember.type->shallowCopy(*member->type);
  6528. ioMember.type->setStruct(s);
  6529. }
  6530. };
  6531. const auto newMember = [&](TTypeLoc& m) {
  6532. if (m.type == nullptr) {
  6533. m.type = new TType;
  6534. m.type->shallowCopy(*member->type);
  6535. }
  6536. };
  6537. TTypeLoc newUniformMember = { nullptr, member->loc };
  6538. TTypeLoc newInputMember = { nullptr, member->loc };
  6539. TTypeLoc newOutputMember = { nullptr, member->loc };
  6540. if (member->type->isStruct()) {
  6541. // swap in an IO child if there is one
  6542. auto it = ioTypeMap.find(member->type->getStruct());
  6543. if (it != ioTypeMap.end()) {
  6544. inheritStruct(it->second.uniform, newUniformMember);
  6545. inheritStruct(it->second.input, newInputMember);
  6546. inheritStruct(it->second.output, newOutputMember);
  6547. }
  6548. }
  6549. if (newLists.uniform) {
  6550. newMember(newUniformMember);
  6551. // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
  6552. if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
  6553. newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
  6554. correctUniform(newUniformMember.type->getQualifier());
  6555. newLists.uniform->push_back(newUniformMember);
  6556. }
  6557. if (newLists.input) {
  6558. newMember(newInputMember);
  6559. correctInput(newInputMember.type->getQualifier());
  6560. newLists.input->push_back(newInputMember);
  6561. }
  6562. if (newLists.output) {
  6563. newMember(newOutputMember);
  6564. correctOutput(newOutputMember.type->getQualifier());
  6565. newLists.output->push_back(newOutputMember);
  6566. }
  6567. // make original pure
  6568. clearUniformInputOutput(member->type->getQualifier());
  6569. }
  6570. ioTypeMap[type.getStruct()] = newLists;
  6571. }
  6572. // Lookup a user-type by name.
  6573. // If found, fill in the type and return the defining symbol.
  6574. // If not found, return nullptr.
  6575. TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
  6576. {
  6577. TSymbol* symbol = symbolTable.find(typeName);
  6578. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  6579. type.shallowCopy(symbol->getType());
  6580. return symbol;
  6581. } else
  6582. return nullptr;
  6583. }
  6584. //
  6585. // Do everything necessary to handle a variable (non-block) declaration.
  6586. // Either redeclaring a variable, or making a new one, updating the symbol
  6587. // table, and all error checking.
  6588. //
  6589. // Returns a subtree node that computes an initializer, if needed.
  6590. // Returns nullptr if there is no code to execute for initialization.
  6591. //
  6592. // 'parseType' is the type part of the declaration (to the left)
  6593. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6594. //
  6595. TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
  6596. TIntermTyped* initializer)
  6597. {
  6598. if (voidErrorCheck(loc, identifier, type.getBasicType()))
  6599. return nullptr;
  6600. // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
  6601. // This test is implicitly recursive, because initializers propagate constness
  6602. // up the aggregate node tree during creation. E.g, for:
  6603. // { { 1, 2 }, { 3, 4 } }
  6604. // the initializer list is marked EvqConst at the top node, and remains so here. However:
  6605. // { 1, { myvar, 2 }, 3 }
  6606. // is not a const intializer, and still becomes EvqGlobal here.
  6607. const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
  6608. if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
  6609. // Force to global
  6610. type.getQualifier().storage = EvqGlobal;
  6611. }
  6612. // make const and initialization consistent
  6613. fixConstInit(loc, identifier, type, initializer);
  6614. // Check for redeclaration of built-ins and/or attempting to declare a reserved name
  6615. TSymbol* symbol = nullptr;
  6616. inheritGlobalDefaults(type.getQualifier());
  6617. const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
  6618. // correct IO in the type
  6619. switch (type.getQualifier().storage) {
  6620. case EvqGlobal:
  6621. case EvqTemporary:
  6622. clearUniformInputOutput(type.getQualifier());
  6623. break;
  6624. case EvqUniform:
  6625. case EvqBuffer:
  6626. correctUniform(type.getQualifier());
  6627. if (type.isStruct()) {
  6628. auto it = ioTypeMap.find(type.getStruct());
  6629. if (it != ioTypeMap.end())
  6630. type.setStruct(it->second.uniform);
  6631. }
  6632. break;
  6633. default:
  6634. break;
  6635. }
  6636. // Declare the variable
  6637. if (type.isArray()) {
  6638. // array case
  6639. declareArray(loc, identifier, type, symbol, !flattenVar);
  6640. } else {
  6641. // non-array case
  6642. if (symbol == nullptr)
  6643. symbol = declareNonArray(loc, identifier, type, !flattenVar);
  6644. else if (type != symbol->getType())
  6645. error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
  6646. }
  6647. if (symbol == nullptr)
  6648. return nullptr;
  6649. if (flattenVar)
  6650. flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
  6651. if (initializer == nullptr)
  6652. return nullptr;
  6653. // Deal with initializer
  6654. TVariable* variable = symbol->getAsVariable();
  6655. if (variable == nullptr) {
  6656. error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
  6657. return nullptr;
  6658. }
  6659. return executeInitializer(loc, initializer, variable);
  6660. }
  6661. // Pick up global defaults from the provide global defaults into dst.
  6662. void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
  6663. {
  6664. if (dst.storage == EvqVaryingOut) {
  6665. if (! dst.hasStream() && language == EShLangGeometry)
  6666. dst.layoutStream = globalOutputDefaults.layoutStream;
  6667. if (! dst.hasXfbBuffer())
  6668. dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  6669. }
  6670. }
  6671. //
  6672. // Make an internal-only variable whose name is for debug purposes only
  6673. // and won't be searched for. Callers will only use the return value to use
  6674. // the variable, not the name to look it up. It is okay if the name
  6675. // is the same as other names; there won't be any conflict.
  6676. //
  6677. TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
  6678. {
  6679. TString* nameString = NewPoolTString(name);
  6680. TVariable* variable = new TVariable(nameString, type);
  6681. symbolTable.makeInternalVariable(*variable);
  6682. return variable;
  6683. }
  6684. // Make a symbol node holding a new internal temporary variable.
  6685. TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
  6686. const TType& type) const
  6687. {
  6688. TVariable* tmpVar = makeInternalVariable(name, type);
  6689. tmpVar->getWritableType().getQualifier().makeTemporary();
  6690. return intermediate.addSymbol(*tmpVar, loc);
  6691. }
  6692. //
  6693. // Declare a non-array variable, the main point being there is no redeclaration
  6694. // for resizing allowed.
  6695. //
  6696. // Return the successfully declared variable.
  6697. //
  6698. TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  6699. bool track)
  6700. {
  6701. // make a new variable
  6702. TVariable* variable = new TVariable(&identifier, type);
  6703. // add variable to symbol table
  6704. if (symbolTable.insert(*variable)) {
  6705. if (track && symbolTable.atGlobalLevel())
  6706. trackLinkage(*variable);
  6707. return variable;
  6708. }
  6709. error(loc, "redefinition", variable->getName().c_str(), "");
  6710. return nullptr;
  6711. }
  6712. //
  6713. // Handle all types of initializers from the grammar.
  6714. //
  6715. // Returning nullptr just means there is no code to execute to handle the
  6716. // initializer, which will, for example, be the case for constant initializers.
  6717. //
  6718. // Returns a subtree that accomplished the initialization.
  6719. //
  6720. TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
  6721. {
  6722. //
  6723. // Identifier must be of type constant, a global, or a temporary, and
  6724. // starting at version 120, desktop allows uniforms to have initializers.
  6725. //
  6726. TStorageQualifier qualifier = variable->getType().getQualifier().storage;
  6727. //
  6728. // If the initializer was from braces { ... }, we convert the whole subtree to a
  6729. // constructor-style subtree, allowing the rest of the code to operate
  6730. // identically for both kinds of initializers.
  6731. //
  6732. //
  6733. // Type can't be deduced from the initializer list, so a skeletal type to
  6734. // follow has to be passed in. Constness and specialization-constness
  6735. // should be deduced bottom up, not dictated by the skeletal type.
  6736. //
  6737. TType skeletalType;
  6738. skeletalType.shallowCopy(variable->getType());
  6739. skeletalType.getQualifier().makeTemporary();
  6740. if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
  6741. initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
  6742. if (initializer == nullptr) {
  6743. // error recovery; don't leave const without constant values
  6744. if (qualifier == EvqConst)
  6745. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6746. return nullptr;
  6747. }
  6748. // Fix outer arrayness if variable is unsized, getting size from the initializer
  6749. if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
  6750. variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
  6751. // Inner arrayness can also get set by an initializer
  6752. if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
  6753. initializer->getType().getArraySizes()->getNumDims() ==
  6754. variable->getType().getArraySizes()->getNumDims()) {
  6755. // adopt unsized sizes from the initializer's sizes
  6756. for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
  6757. if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
  6758. variable->getWritableType().getArraySizes()->setDimSize(d,
  6759. initializer->getType().getArraySizes()->getDimSize(d));
  6760. }
  6761. }
  6762. }
  6763. // Uniform and global consts require a constant initializer
  6764. if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
  6765. error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
  6766. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6767. return nullptr;
  6768. }
  6769. // Const variables require a constant initializer
  6770. if (qualifier == EvqConst) {
  6771. if (initializer->getType().getQualifier().storage != EvqConst) {
  6772. variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
  6773. qualifier = EvqConstReadOnly;
  6774. }
  6775. }
  6776. if (qualifier == EvqConst || qualifier == EvqUniform) {
  6777. // Compile-time tagging of the variable with its constant value...
  6778. initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
  6779. if (initializer != nullptr && variable->getType() != initializer->getType())
  6780. initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
  6781. if (initializer == nullptr || !initializer->getAsConstantUnion() ||
  6782. variable->getType() != initializer->getType()) {
  6783. error(loc, "non-matching or non-convertible constant type for const initializer",
  6784. variable->getType().getStorageQualifierString(), "");
  6785. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6786. return nullptr;
  6787. }
  6788. variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
  6789. } else {
  6790. // normal assigning of a value to a variable...
  6791. specializationCheck(loc, initializer->getType(), "initializer");
  6792. TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
  6793. TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
  6794. if (initNode == nullptr)
  6795. assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
  6796. return initNode;
  6797. }
  6798. return nullptr;
  6799. }
  6800. //
  6801. // Reprocess any initializer-list { ... } parts of the initializer.
  6802. // Need to hierarchically assign correct types and implicit
  6803. // conversions. Will do this mimicking the same process used for
  6804. // creating a constructor-style initializer, ensuring we get the
  6805. // same form.
  6806. //
  6807. // Returns a node representing an expression for the initializer list expressed
  6808. // as the correct type.
  6809. //
  6810. // Returns nullptr if there is an error.
  6811. //
  6812. TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
  6813. TIntermTyped* initializer, TIntermTyped* scalarInit)
  6814. {
  6815. // Will operate recursively. Once a subtree is found that is constructor style,
  6816. // everything below it is already good: Only the "top part" of the initializer
  6817. // can be an initializer list, where "top part" can extend for several (or all) levels.
  6818. // see if we have bottomed out in the tree within the initializer-list part
  6819. TIntermAggregate* initList = initializer->getAsAggregate();
  6820. if (initList == nullptr || initList->getOp() != EOpNull) {
  6821. // We don't have a list, but if it's a scalar and the 'type' is a
  6822. // composite, we need to lengthen below to make it useful.
  6823. // Otherwise, this is an already formed object to initialize with.
  6824. if (type.isScalar() || !initializer->getType().isScalar())
  6825. return initializer;
  6826. else
  6827. initList = intermediate.makeAggregate(initializer);
  6828. }
  6829. // Of the initializer-list set of nodes, need to process bottom up,
  6830. // so recurse deep, then process on the way up.
  6831. // Go down the tree here...
  6832. if (type.isArray()) {
  6833. // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
  6834. // Later on, initializer execution code will deal with array size logic.
  6835. TType arrayType;
  6836. arrayType.shallowCopy(type); // sharing struct stuff is fine
  6837. arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
  6838. // edit array sizes to fill in unsized dimensions
  6839. if (type.isUnsizedArray())
  6840. arrayType.changeOuterArraySize((int)initList->getSequence().size());
  6841. // set unsized array dimensions that can be derived from the initializer's first element
  6842. if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
  6843. TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
  6844. if (firstInit->getType().isArray() &&
  6845. arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
  6846. for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
  6847. if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
  6848. arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
  6849. }
  6850. }
  6851. }
  6852. // lengthen list to be long enough
  6853. lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
  6854. // recursively process each element
  6855. TType elementType(arrayType, 0); // dereferenced type
  6856. for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
  6857. initList->getSequence()[i] = convertInitializerList(loc, elementType,
  6858. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6859. if (initList->getSequence()[i] == nullptr)
  6860. return nullptr;
  6861. }
  6862. return addConstructor(loc, initList, arrayType);
  6863. } else if (type.isStruct()) {
  6864. // do we have implicit assignments to opaques?
  6865. for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
  6866. if ((*type.getStruct())[i].type->containsOpaque()) {
  6867. error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
  6868. return nullptr;
  6869. }
  6870. }
  6871. // lengthen list to be long enough
  6872. lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
  6873. if (type.getStruct()->size() != initList->getSequence().size()) {
  6874. error(loc, "wrong number of structure members", "initializer list", "");
  6875. return nullptr;
  6876. }
  6877. for (size_t i = 0; i < type.getStruct()->size(); ++i) {
  6878. initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
  6879. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6880. if (initList->getSequence()[i] == nullptr)
  6881. return nullptr;
  6882. }
  6883. } else if (type.isMatrix()) {
  6884. if (type.computeNumComponents() == (int)initList->getSequence().size()) {
  6885. // This means the matrix is initialized component-wise, rather than as
  6886. // a series of rows and columns. We can just use the list directly as
  6887. // a constructor; no further processing needed.
  6888. } else {
  6889. // lengthen list to be long enough
  6890. lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
  6891. if (type.getMatrixCols() != (int)initList->getSequence().size()) {
  6892. error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
  6893. return nullptr;
  6894. }
  6895. TType vectorType(type, 0); // dereferenced type
  6896. for (int i = 0; i < type.getMatrixCols(); ++i) {
  6897. initList->getSequence()[i] = convertInitializerList(loc, vectorType,
  6898. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6899. if (initList->getSequence()[i] == nullptr)
  6900. return nullptr;
  6901. }
  6902. }
  6903. } else if (type.isVector()) {
  6904. // lengthen list to be long enough
  6905. lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
  6906. // error check; we're at bottom, so work is finished below
  6907. if (type.getVectorSize() != (int)initList->getSequence().size()) {
  6908. error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
  6909. type.getCompleteString().c_str());
  6910. return nullptr;
  6911. }
  6912. } else if (type.isScalar()) {
  6913. // lengthen list to be long enough
  6914. lengthenList(loc, initList->getSequence(), 1, scalarInit);
  6915. if ((int)initList->getSequence().size() != 1) {
  6916. error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
  6917. return nullptr;
  6918. }
  6919. } else {
  6920. error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
  6921. return nullptr;
  6922. }
  6923. // Now that the subtree is processed, process this node as if the
  6924. // initializer list is a set of arguments to a constructor.
  6925. TIntermTyped* emulatedConstructorArguments;
  6926. if (initList->getSequence().size() == 1)
  6927. emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
  6928. else
  6929. emulatedConstructorArguments = initList;
  6930. return addConstructor(loc, emulatedConstructorArguments, type);
  6931. }
  6932. // Lengthen list to be long enough to cover any gap from the current list size
  6933. // to 'size'. If the list is longer, do nothing.
  6934. // The value to lengthen with is the default for short lists.
  6935. //
  6936. // By default, lists that are too short due to lack of initializers initialize to zero.
  6937. // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
  6938. // based on whether something is passed in as 'scalarInit'.
  6939. //
  6940. // 'scalarInit' must be safe to use each time this is called (no side effects replication).
  6941. //
  6942. void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
  6943. {
  6944. for (int c = (int)list.size(); c < size; ++c) {
  6945. if (scalarInit == nullptr)
  6946. list.push_back(intermediate.addConstantUnion(0, loc));
  6947. else
  6948. list.push_back(scalarInit);
  6949. }
  6950. }
  6951. //
  6952. // Test for the correctness of the parameters passed to various constructor functions
  6953. // and also convert them to the right data type, if allowed and required.
  6954. //
  6955. // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
  6956. //
  6957. TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6958. {
  6959. if (node == nullptr)
  6960. return nullptr;
  6961. // Construct identical type
  6962. if (type == node->getType())
  6963. return node;
  6964. // Handle the idiom "(struct type)<scalar value>"
  6965. if (type.isStruct() && isScalarConstructor(node)) {
  6966. // 'node' will almost always get used multiple times, so should not be used directly,
  6967. // it would create a DAG instead of a tree, which might be okay (would
  6968. // like to formalize that for constants and symbols), but if it has
  6969. // side effects, they would get executed multiple times, which is not okay.
  6970. if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
  6971. TIntermAggregate* seq = intermediate.makeAggregate(loc);
  6972. TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
  6973. seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
  6974. seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
  6975. seq->setOp(EOpComma);
  6976. seq->setType(type);
  6977. return seq;
  6978. } else
  6979. return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
  6980. }
  6981. return addConstructor(loc, node, type);
  6982. }
  6983. // Add a constructor, either from the grammar, or other programmatic reasons.
  6984. //
  6985. // 'node' is what to construct from.
  6986. // 'type' is what type to construct.
  6987. //
  6988. // Returns the constructed object.
  6989. // Return nullptr if it can't be done.
  6990. //
  6991. TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6992. {
  6993. TIntermAggregate* aggrNode = node->getAsAggregate();
  6994. TOperator op = intermediate.mapTypeToConstructorOp(type);
  6995. if (op == EOpConstructTextureSampler)
  6996. return intermediate.setAggregateOperator(aggrNode, op, type, loc);
  6997. TTypeList::const_iterator memberTypes;
  6998. if (op == EOpConstructStruct)
  6999. memberTypes = type.getStruct()->begin();
  7000. TType elementType;
  7001. if (type.isArray()) {
  7002. TType dereferenced(type, 0);
  7003. elementType.shallowCopy(dereferenced);
  7004. } else
  7005. elementType.shallowCopy(type);
  7006. bool singleArg;
  7007. if (aggrNode != nullptr) {
  7008. if (aggrNode->getOp() != EOpNull)
  7009. singleArg = true;
  7010. else
  7011. singleArg = false;
  7012. } else
  7013. singleArg = true;
  7014. TIntermTyped *newNode;
  7015. if (singleArg) {
  7016. // Handle array -> array conversion
  7017. // Constructing an array of one type from an array of another type is allowed,
  7018. // assuming there are enough components available (semantic-checked earlier).
  7019. if (type.isArray() && node->isArray())
  7020. newNode = convertArray(node, type);
  7021. // If structure constructor or array constructor is being called
  7022. // for only one parameter inside the aggregate, we need to call constructAggregate function once.
  7023. else if (type.isArray())
  7024. newNode = constructAggregate(node, elementType, 1, node->getLoc());
  7025. else if (op == EOpConstructStruct)
  7026. newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
  7027. else {
  7028. // shape conversion for matrix constructor from scalar. HLSL semantics are: scalar
  7029. // is replicated into every element of the matrix (not just the diagnonal), so
  7030. // that is handled specially here.
  7031. if (type.isMatrix() && node->getType().isScalarOrVec1())
  7032. node = intermediate.addShapeConversion(type, node);
  7033. newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
  7034. }
  7035. if (newNode && (type.isArray() || op == EOpConstructStruct))
  7036. newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
  7037. return newNode;
  7038. }
  7039. //
  7040. // Handle list of arguments.
  7041. //
  7042. TIntermSequence& sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
  7043. // if the structure constructor contains more than one parameter, then construct
  7044. // each parameter
  7045. int paramCount = 0; // keeps a track of the constructor parameter number being checked
  7046. // for each parameter to the constructor call, check to see if the right type is passed or convert them
  7047. // to the right type if possible (and allowed).
  7048. // for structure constructors, just check if the right type is passed, no conversion is allowed.
  7049. for (TIntermSequence::iterator p = sequenceVector.begin();
  7050. p != sequenceVector.end(); p++, paramCount++) {
  7051. if (type.isArray())
  7052. newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
  7053. else if (op == EOpConstructStruct)
  7054. newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
  7055. else
  7056. newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
  7057. if (newNode)
  7058. *p = newNode;
  7059. else
  7060. return nullptr;
  7061. }
  7062. TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
  7063. return constructor;
  7064. }
  7065. // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
  7066. // for the parameter to the constructor (passed to this function). Essentially, it converts
  7067. // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
  7068. // float, then float is converted to int.
  7069. //
  7070. // Returns nullptr for an error or the constructed node.
  7071. //
  7072. TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
  7073. const TSourceLoc& loc, bool subset)
  7074. {
  7075. TIntermTyped* newNode;
  7076. TOperator basicOp;
  7077. //
  7078. // First, convert types as needed.
  7079. //
  7080. switch (op) {
  7081. case EOpConstructF16Vec2:
  7082. case EOpConstructF16Vec3:
  7083. case EOpConstructF16Vec4:
  7084. case EOpConstructF16Mat2x2:
  7085. case EOpConstructF16Mat2x3:
  7086. case EOpConstructF16Mat2x4:
  7087. case EOpConstructF16Mat3x2:
  7088. case EOpConstructF16Mat3x3:
  7089. case EOpConstructF16Mat3x4:
  7090. case EOpConstructF16Mat4x2:
  7091. case EOpConstructF16Mat4x3:
  7092. case EOpConstructF16Mat4x4:
  7093. case EOpConstructFloat16:
  7094. basicOp = EOpConstructFloat16;
  7095. break;
  7096. case EOpConstructVec2:
  7097. case EOpConstructVec3:
  7098. case EOpConstructVec4:
  7099. case EOpConstructMat2x2:
  7100. case EOpConstructMat2x3:
  7101. case EOpConstructMat2x4:
  7102. case EOpConstructMat3x2:
  7103. case EOpConstructMat3x3:
  7104. case EOpConstructMat3x4:
  7105. case EOpConstructMat4x2:
  7106. case EOpConstructMat4x3:
  7107. case EOpConstructMat4x4:
  7108. case EOpConstructFloat:
  7109. basicOp = EOpConstructFloat;
  7110. break;
  7111. case EOpConstructDVec2:
  7112. case EOpConstructDVec3:
  7113. case EOpConstructDVec4:
  7114. case EOpConstructDMat2x2:
  7115. case EOpConstructDMat2x3:
  7116. case EOpConstructDMat2x4:
  7117. case EOpConstructDMat3x2:
  7118. case EOpConstructDMat3x3:
  7119. case EOpConstructDMat3x4:
  7120. case EOpConstructDMat4x2:
  7121. case EOpConstructDMat4x3:
  7122. case EOpConstructDMat4x4:
  7123. case EOpConstructDouble:
  7124. basicOp = EOpConstructDouble;
  7125. break;
  7126. case EOpConstructI16Vec2:
  7127. case EOpConstructI16Vec3:
  7128. case EOpConstructI16Vec4:
  7129. case EOpConstructInt16:
  7130. basicOp = EOpConstructInt16;
  7131. break;
  7132. case EOpConstructIVec2:
  7133. case EOpConstructIVec3:
  7134. case EOpConstructIVec4:
  7135. case EOpConstructIMat2x2:
  7136. case EOpConstructIMat2x3:
  7137. case EOpConstructIMat2x4:
  7138. case EOpConstructIMat3x2:
  7139. case EOpConstructIMat3x3:
  7140. case EOpConstructIMat3x4:
  7141. case EOpConstructIMat4x2:
  7142. case EOpConstructIMat4x3:
  7143. case EOpConstructIMat4x4:
  7144. case EOpConstructInt:
  7145. basicOp = EOpConstructInt;
  7146. break;
  7147. case EOpConstructU16Vec2:
  7148. case EOpConstructU16Vec3:
  7149. case EOpConstructU16Vec4:
  7150. case EOpConstructUint16:
  7151. basicOp = EOpConstructUint16;
  7152. break;
  7153. case EOpConstructUVec2:
  7154. case EOpConstructUVec3:
  7155. case EOpConstructUVec4:
  7156. case EOpConstructUMat2x2:
  7157. case EOpConstructUMat2x3:
  7158. case EOpConstructUMat2x4:
  7159. case EOpConstructUMat3x2:
  7160. case EOpConstructUMat3x3:
  7161. case EOpConstructUMat3x4:
  7162. case EOpConstructUMat4x2:
  7163. case EOpConstructUMat4x3:
  7164. case EOpConstructUMat4x4:
  7165. case EOpConstructUint:
  7166. basicOp = EOpConstructUint;
  7167. break;
  7168. case EOpConstructBVec2:
  7169. case EOpConstructBVec3:
  7170. case EOpConstructBVec4:
  7171. case EOpConstructBMat2x2:
  7172. case EOpConstructBMat2x3:
  7173. case EOpConstructBMat2x4:
  7174. case EOpConstructBMat3x2:
  7175. case EOpConstructBMat3x3:
  7176. case EOpConstructBMat3x4:
  7177. case EOpConstructBMat4x2:
  7178. case EOpConstructBMat4x3:
  7179. case EOpConstructBMat4x4:
  7180. case EOpConstructBool:
  7181. basicOp = EOpConstructBool;
  7182. break;
  7183. default:
  7184. error(loc, "unsupported construction", "", "");
  7185. return nullptr;
  7186. }
  7187. newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
  7188. if (newNode == nullptr) {
  7189. error(loc, "can't convert", "constructor", "");
  7190. return nullptr;
  7191. }
  7192. //
  7193. // Now, if there still isn't an operation to do the construction, and we need one, add one.
  7194. //
  7195. // Otherwise, skip out early.
  7196. if (subset || (newNode != node && newNode->getType() == type))
  7197. return newNode;
  7198. // setAggregateOperator will insert a new node for the constructor, as needed.
  7199. return intermediate.setAggregateOperator(newNode, op, type, loc);
  7200. }
  7201. // Convert the array in node to the requested type, which is also an array.
  7202. // Returns nullptr on failure, otherwise returns aggregate holding the list of
  7203. // elements needed to construct the array.
  7204. TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
  7205. {
  7206. assert(node->isArray() && type.isArray());
  7207. if (node->getType().computeNumComponents() < type.computeNumComponents())
  7208. return nullptr;
  7209. // TODO: write an argument replicator, for the case the argument should not be
  7210. // executed multiple times, yet multiple copies are needed.
  7211. TIntermTyped* constructee = node->getAsTyped();
  7212. // track where we are in consuming the argument
  7213. int constructeeElement = 0;
  7214. int constructeeComponent = 0;
  7215. // bump up to the next component to consume
  7216. const auto getNextComponent = [&]() {
  7217. TIntermTyped* component;
  7218. component = handleBracketDereference(node->getLoc(), constructee,
  7219. intermediate.addConstantUnion(constructeeElement, node->getLoc()));
  7220. if (component->isVector())
  7221. component = handleBracketDereference(node->getLoc(), component,
  7222. intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
  7223. // bump component pointer up
  7224. ++constructeeComponent;
  7225. if (constructeeComponent == constructee->getVectorSize()) {
  7226. constructeeComponent = 0;
  7227. ++constructeeElement;
  7228. }
  7229. return component;
  7230. };
  7231. // make one subnode per constructed array element
  7232. TIntermAggregate* constructor = nullptr;
  7233. TType derefType(type, 0);
  7234. TType speculativeComponentType(derefType, 0);
  7235. TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
  7236. TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
  7237. TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
  7238. for (int e = 0; e < type.getOuterArraySize(); ++e) {
  7239. // construct an element
  7240. TIntermTyped* elementArg;
  7241. if (type.getVectorSize() == constructee->getVectorSize()) {
  7242. // same element shape
  7243. elementArg = handleBracketDereference(node->getLoc(), constructee,
  7244. intermediate.addConstantUnion(e, node->getLoc()));
  7245. } else {
  7246. // mismatched element shapes
  7247. if (type.getVectorSize() == 1)
  7248. elementArg = getNextComponent();
  7249. else {
  7250. // make a vector
  7251. TIntermAggregate* elementConstructee = nullptr;
  7252. for (int c = 0; c < type.getVectorSize(); ++c)
  7253. elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
  7254. elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
  7255. }
  7256. }
  7257. // convert basic types
  7258. elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
  7259. if (elementArg == nullptr)
  7260. return nullptr;
  7261. // combine with top-level constructor
  7262. constructor = intermediate.growAggregate(constructor, elementArg);
  7263. }
  7264. return constructor;
  7265. }
  7266. // This function tests for the type of the parameters to the structure or array constructor. Raises
  7267. // an error message if the expected type does not match the parameter passed to the constructor.
  7268. //
  7269. // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
  7270. //
  7271. TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
  7272. const TSourceLoc& loc)
  7273. {
  7274. // Handle cases that map more 1:1 between constructor arguments and constructed.
  7275. TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
  7276. if (converted == nullptr || converted->getType() != type) {
  7277. error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
  7278. node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
  7279. return nullptr;
  7280. }
  7281. return converted;
  7282. }
  7283. //
  7284. // Do everything needed to add an interface block.
  7285. //
  7286. void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
  7287. {
  7288. assert(type.getWritableStruct() != nullptr);
  7289. // Clean up top-level decorations that don't belong.
  7290. switch (type.getQualifier().storage) {
  7291. case EvqUniform:
  7292. case EvqBuffer:
  7293. correctUniform(type.getQualifier());
  7294. break;
  7295. case EvqVaryingIn:
  7296. correctInput(type.getQualifier());
  7297. break;
  7298. case EvqVaryingOut:
  7299. correctOutput(type.getQualifier());
  7300. break;
  7301. default:
  7302. break;
  7303. }
  7304. TTypeList& typeList = *type.getWritableStruct();
  7305. // fix and check for member storage qualifiers and types that don't belong within a block
  7306. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7307. TType& memberType = *typeList[member].type;
  7308. TQualifier& memberQualifier = memberType.getQualifier();
  7309. const TSourceLoc& memberLoc = typeList[member].loc;
  7310. globalQualifierFix(memberLoc, memberQualifier);
  7311. memberQualifier.storage = type.getQualifier().storage;
  7312. if (memberType.isStruct()) {
  7313. // clean up and pick up the right set of decorations
  7314. auto it = ioTypeMap.find(memberType.getStruct());
  7315. switch (type.getQualifier().storage) {
  7316. case EvqUniform:
  7317. case EvqBuffer:
  7318. correctUniform(type.getQualifier());
  7319. if (it != ioTypeMap.end() && it->second.uniform)
  7320. memberType.setStruct(it->second.uniform);
  7321. break;
  7322. case EvqVaryingIn:
  7323. correctInput(type.getQualifier());
  7324. if (it != ioTypeMap.end() && it->second.input)
  7325. memberType.setStruct(it->second.input);
  7326. break;
  7327. case EvqVaryingOut:
  7328. correctOutput(type.getQualifier());
  7329. if (it != ioTypeMap.end() && it->second.output)
  7330. memberType.setStruct(it->second.output);
  7331. break;
  7332. default:
  7333. break;
  7334. }
  7335. }
  7336. }
  7337. // Make default block qualification, and adjust the member qualifications
  7338. TQualifier defaultQualification;
  7339. switch (type.getQualifier().storage) {
  7340. case EvqUniform: defaultQualification = globalUniformDefaults; break;
  7341. case EvqBuffer: defaultQualification = globalBufferDefaults; break;
  7342. case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
  7343. case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
  7344. default: defaultQualification.clear(); break;
  7345. }
  7346. // Special case for "push_constant uniform", which has a default of std430,
  7347. // contrary to normal uniform defaults, and can't have a default tracked for it.
  7348. if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
  7349. type.getQualifier().layoutPacking = ElpStd430;
  7350. // fix and check for member layout qualifiers
  7351. mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
  7352. bool memberWithLocation = false;
  7353. bool memberWithoutLocation = false;
  7354. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7355. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7356. const TSourceLoc& memberLoc = typeList[member].loc;
  7357. if (memberQualifier.hasStream()) {
  7358. if (defaultQualification.layoutStream != memberQualifier.layoutStream)
  7359. error(memberLoc, "member cannot contradict block", "stream", "");
  7360. }
  7361. // "This includes a block's inheritance of the
  7362. // current global default buffer, a block member's inheritance of the block's
  7363. // buffer, and the requirement that any *xfb_buffer* declared on a block
  7364. // member must match the buffer inherited from the block."
  7365. if (memberQualifier.hasXfbBuffer()) {
  7366. if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
  7367. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
  7368. }
  7369. if (memberQualifier.hasLocation()) {
  7370. switch (type.getQualifier().storage) {
  7371. case EvqVaryingIn:
  7372. case EvqVaryingOut:
  7373. memberWithLocation = true;
  7374. break;
  7375. default:
  7376. break;
  7377. }
  7378. } else
  7379. memberWithoutLocation = true;
  7380. TQualifier newMemberQualification = defaultQualification;
  7381. mergeQualifiers(newMemberQualification, memberQualifier);
  7382. memberQualifier = newMemberQualification;
  7383. }
  7384. // Process the members
  7385. fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
  7386. fixXfbOffsets(type.getQualifier(), typeList);
  7387. fixBlockUniformOffsets(type.getQualifier(), typeList);
  7388. // reverse merge, so that currentBlockQualifier now has all layout information
  7389. // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
  7390. mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
  7391. //
  7392. // Build and add the interface block as a new type named 'blockName'
  7393. //
  7394. // Use the instance name as the interface name if one exists, else the block name.
  7395. const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
  7396. TType blockType(&typeList, interfaceName, type.getQualifier());
  7397. if (type.isArray())
  7398. blockType.transferArraySizes(type.getArraySizes());
  7399. // Add the variable, as anonymous or named instanceName.
  7400. // Make an anonymous variable if no name was provided.
  7401. if (instanceName == nullptr)
  7402. instanceName = NewPoolTString("");
  7403. TVariable& variable = *new TVariable(instanceName, blockType);
  7404. if (! symbolTable.insert(variable)) {
  7405. if (*instanceName == "")
  7406. error(loc, "nameless block contains a member that already has a name at global scope",
  7407. "" /* blockName->c_str() */, "");
  7408. else
  7409. error(loc, "block instance name redefinition", variable.getName().c_str(), "");
  7410. return;
  7411. }
  7412. // Save it in the AST for linker use.
  7413. if (symbolTable.atGlobalLevel())
  7414. trackLinkage(variable);
  7415. }
  7416. //
  7417. // "For a block, this process applies to the entire block, or until the first member
  7418. // is reached that has a location layout qualifier. When a block member is declared with a location
  7419. // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
  7420. // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
  7421. // until the next member declared with a location qualifier. The values used for locations do not have to be
  7422. // declared in increasing order."
  7423. void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
  7424. {
  7425. // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
  7426. // have a location layout qualifier, or a compile-time error results."
  7427. if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
  7428. error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
  7429. else {
  7430. if (memberWithLocation) {
  7431. // remove any block-level location and make it per *every* member
  7432. int nextLocation = 0; // by the rule above, initial value is not relevant
  7433. if (qualifier.hasAnyLocation()) {
  7434. nextLocation = qualifier.layoutLocation;
  7435. qualifier.layoutLocation = TQualifier::layoutLocationEnd;
  7436. if (qualifier.hasComponent()) {
  7437. // "It is a compile-time error to apply the *component* qualifier to a ... block"
  7438. error(loc, "cannot apply to a block", "component", "");
  7439. }
  7440. if (qualifier.hasIndex()) {
  7441. error(loc, "cannot apply to a block", "index", "");
  7442. }
  7443. }
  7444. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7445. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7446. const TSourceLoc& memberLoc = typeList[member].loc;
  7447. if (! memberQualifier.hasLocation()) {
  7448. if (nextLocation >= (int)TQualifier::layoutLocationEnd)
  7449. error(memberLoc, "location is too large", "location", "");
  7450. memberQualifier.layoutLocation = nextLocation;
  7451. memberQualifier.layoutComponent = 0;
  7452. }
  7453. nextLocation = memberQualifier.layoutLocation +
  7454. intermediate.computeTypeLocationSize(*typeList[member].type, language);
  7455. }
  7456. }
  7457. }
  7458. }
  7459. void HlslParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
  7460. {
  7461. // "If a block is qualified with xfb_offset, all its
  7462. // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
  7463. // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
  7464. // offsets."
  7465. if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
  7466. return;
  7467. int nextOffset = qualifier.layoutXfbOffset;
  7468. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7469. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7470. bool contains64BitType = false;
  7471. bool contains32BitType = false;
  7472. bool contains16BitType = false;
  7473. int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
  7474. // see if we need to auto-assign an offset to this member
  7475. if (! memberQualifier.hasXfbOffset()) {
  7476. // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
  7477. if (contains64BitType)
  7478. RoundToPow2(nextOffset, 8);
  7479. else if (contains32BitType)
  7480. RoundToPow2(nextOffset, 4);
  7481. // "if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2"
  7482. else if (contains16BitType)
  7483. RoundToPow2(nextOffset, 2);
  7484. memberQualifier.layoutXfbOffset = nextOffset;
  7485. } else
  7486. nextOffset = memberQualifier.layoutXfbOffset;
  7487. nextOffset += memberSize;
  7488. }
  7489. // The above gave all block members an offset, so we can take it off the block now,
  7490. // which will avoid double counting the offset usage.
  7491. qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
  7492. }
  7493. // Calculate and save the offset of each block member, using the recursively
  7494. // defined block offset rules and the user-provided offset and align.
  7495. //
  7496. // Also, compute and save the total size of the block. For the block's size, arrayness
  7497. // is not taken into account, as each element is backed by a separate buffer.
  7498. //
  7499. void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
  7500. {
  7501. if (! qualifier.isUniformOrBuffer())
  7502. return;
  7503. if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
  7504. return;
  7505. int offset = 0;
  7506. int memberSize;
  7507. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7508. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7509. const TSourceLoc& memberLoc = typeList[member].loc;
  7510. // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
  7511. // modify just the children's view of matrix layout, if there is one for this member
  7512. TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
  7513. int dummyStride;
  7514. int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride,
  7515. qualifier.layoutPacking,
  7516. subMatrixLayout != ElmNone
  7517. ? subMatrixLayout == ElmRowMajor
  7518. : qualifier.layoutMatrix == ElmRowMajor);
  7519. if (memberQualifier.hasOffset()) {
  7520. // "The specified offset must be a multiple
  7521. // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
  7522. if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
  7523. error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
  7524. // "The offset qualifier forces the qualified member to start at or after the specified
  7525. // integral-constant expression, which will be its byte offset from the beginning of the buffer.
  7526. // "The actual offset of a member is computed as
  7527. // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
  7528. offset = std::max(offset, memberQualifier.layoutOffset);
  7529. }
  7530. // "The actual alignment of a member will be the greater of the specified align alignment and the standard
  7531. // (e.g., std140) base alignment for the member's type."
  7532. if (memberQualifier.hasAlign())
  7533. memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
  7534. // "If the resulting offset is not a multiple of the actual alignment,
  7535. // increase it to the first offset that is a multiple of
  7536. // the actual alignment."
  7537. RoundToPow2(offset, memberAlignment);
  7538. typeList[member].type->getQualifier().layoutOffset = offset;
  7539. offset += memberSize;
  7540. }
  7541. }
  7542. // For an identifier that is already declared, add more qualification to it.
  7543. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
  7544. {
  7545. TSymbol* symbol = symbolTable.find(identifier);
  7546. if (symbol == nullptr) {
  7547. error(loc, "identifier not previously declared", identifier.c_str(), "");
  7548. return;
  7549. }
  7550. if (symbol->getAsFunction()) {
  7551. error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
  7552. return;
  7553. }
  7554. if (qualifier.isAuxiliary() ||
  7555. qualifier.isMemory() ||
  7556. qualifier.isInterpolation() ||
  7557. qualifier.hasLayout() ||
  7558. qualifier.storage != EvqTemporary ||
  7559. qualifier.precision != EpqNone) {
  7560. error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
  7561. return;
  7562. }
  7563. // For read-only built-ins, add a new symbol for holding the modified qualifier.
  7564. // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
  7565. if (symbol->isReadOnly())
  7566. symbol = symbolTable.copyUp(symbol);
  7567. if (qualifier.invariant) {
  7568. if (intermediate.inIoAccessed(identifier))
  7569. error(loc, "cannot change qualification after use", "invariant", "");
  7570. symbol->getWritableType().getQualifier().invariant = true;
  7571. } else if (qualifier.noContraction) {
  7572. if (intermediate.inIoAccessed(identifier))
  7573. error(loc, "cannot change qualification after use", "precise", "");
  7574. symbol->getWritableType().getQualifier().noContraction = true;
  7575. } else if (qualifier.specConstant) {
  7576. symbol->getWritableType().getQualifier().makeSpecConstant();
  7577. if (qualifier.hasSpecConstantId())
  7578. symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
  7579. } else
  7580. warn(loc, "unknown requalification", "", "");
  7581. }
  7582. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
  7583. {
  7584. for (unsigned int i = 0; i < identifiers.size(); ++i)
  7585. addQualifierToExisting(loc, qualifier, *identifiers[i]);
  7586. }
  7587. //
  7588. // Update the intermediate for the given input geometry
  7589. //
  7590. bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7591. {
  7592. switch (geometry) {
  7593. case ElgPoints: // fall through
  7594. case ElgLines: // ...
  7595. case ElgTriangles: // ...
  7596. case ElgLinesAdjacency: // ...
  7597. case ElgTrianglesAdjacency: // ...
  7598. if (! intermediate.setInputPrimitive(geometry)) {
  7599. error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7600. return false;
  7601. }
  7602. break;
  7603. default:
  7604. error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
  7605. return false;
  7606. }
  7607. return true;
  7608. }
  7609. //
  7610. // Update the intermediate for the given output geometry
  7611. //
  7612. bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7613. {
  7614. // If this is not a geometry shader, ignore. It might be a mixed shader including several stages.
  7615. // Since that's an OK situation, return true for success.
  7616. if (language != EShLangGeometry)
  7617. return true;
  7618. switch (geometry) {
  7619. case ElgPoints:
  7620. case ElgLineStrip:
  7621. case ElgTriangleStrip:
  7622. if (! intermediate.setOutputPrimitive(geometry)) {
  7623. error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7624. return false;
  7625. }
  7626. break;
  7627. default:
  7628. error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
  7629. return false;
  7630. }
  7631. return true;
  7632. }
  7633. //
  7634. // Selection attributes
  7635. //
  7636. void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
  7637. const TAttributes& attributes)
  7638. {
  7639. if (selection == nullptr)
  7640. return;
  7641. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7642. switch (it->name) {
  7643. case EatFlatten:
  7644. selection->setFlatten();
  7645. break;
  7646. case EatBranch:
  7647. selection->setDontFlatten();
  7648. break;
  7649. default:
  7650. warn(loc, "attribute does not apply to a selection", "", "");
  7651. break;
  7652. }
  7653. }
  7654. }
  7655. //
  7656. // Switch attributes
  7657. //
  7658. void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
  7659. const TAttributes& attributes)
  7660. {
  7661. if (selection == nullptr)
  7662. return;
  7663. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7664. switch (it->name) {
  7665. case EatFlatten:
  7666. selection->setFlatten();
  7667. break;
  7668. case EatBranch:
  7669. selection->setDontFlatten();
  7670. break;
  7671. default:
  7672. warn(loc, "attribute does not apply to a switch", "", "");
  7673. break;
  7674. }
  7675. }
  7676. }
  7677. //
  7678. // Loop attributes
  7679. //
  7680. void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
  7681. const TAttributes& attributes)
  7682. {
  7683. if (loop == nullptr)
  7684. return;
  7685. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7686. switch (it->name) {
  7687. case EatUnroll:
  7688. loop->setUnroll();
  7689. break;
  7690. case EatLoop:
  7691. loop->setDontUnroll();
  7692. break;
  7693. default:
  7694. warn(loc, "attribute does not apply to a loop", "", "");
  7695. break;
  7696. }
  7697. }
  7698. }
  7699. //
  7700. // Updating default qualifier for the case of a declaration with just a qualifier,
  7701. // no type, block, or identifier.
  7702. //
  7703. void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
  7704. {
  7705. if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
  7706. assert(language == EShLangTessControl || language == EShLangGeometry);
  7707. // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
  7708. }
  7709. if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
  7710. if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
  7711. error(loc, "cannot change previously set layout value", "invocations", "");
  7712. }
  7713. if (publicType.shaderQualifiers.geometry != ElgNone) {
  7714. if (publicType.qualifier.storage == EvqVaryingIn) {
  7715. switch (publicType.shaderQualifiers.geometry) {
  7716. case ElgPoints:
  7717. case ElgLines:
  7718. case ElgLinesAdjacency:
  7719. case ElgTriangles:
  7720. case ElgTrianglesAdjacency:
  7721. case ElgQuads:
  7722. case ElgIsolines:
  7723. break;
  7724. default:
  7725. error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7726. "");
  7727. }
  7728. } else if (publicType.qualifier.storage == EvqVaryingOut) {
  7729. handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
  7730. } else
  7731. error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7732. GetStorageQualifierString(publicType.qualifier.storage));
  7733. }
  7734. if (publicType.shaderQualifiers.spacing != EvsNone)
  7735. intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
  7736. if (publicType.shaderQualifiers.order != EvoNone)
  7737. intermediate.setVertexOrder(publicType.shaderQualifiers.order);
  7738. if (publicType.shaderQualifiers.pointMode)
  7739. intermediate.setPointMode();
  7740. for (int i = 0; i < 3; ++i) {
  7741. if (publicType.shaderQualifiers.localSize[i] > 1) {
  7742. int max = 0;
  7743. switch (i) {
  7744. case 0: max = resources.maxComputeWorkGroupSizeX; break;
  7745. case 1: max = resources.maxComputeWorkGroupSizeY; break;
  7746. case 2: max = resources.maxComputeWorkGroupSizeZ; break;
  7747. default: break;
  7748. }
  7749. if (intermediate.getLocalSize(i) > (unsigned int)max)
  7750. error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
  7751. // Fix the existing constant gl_WorkGroupSize with this new information.
  7752. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7753. workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
  7754. }
  7755. if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
  7756. intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
  7757. // Set the workgroup built-in variable as a specialization constant
  7758. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7759. workGroupSize->getWritableType().getQualifier().specConstant = true;
  7760. }
  7761. }
  7762. if (publicType.shaderQualifiers.earlyFragmentTests)
  7763. intermediate.setEarlyFragmentTests();
  7764. const TQualifier& qualifier = publicType.qualifier;
  7765. switch (qualifier.storage) {
  7766. case EvqUniform:
  7767. if (qualifier.hasMatrix())
  7768. globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
  7769. if (qualifier.hasPacking())
  7770. globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
  7771. break;
  7772. case EvqBuffer:
  7773. if (qualifier.hasMatrix())
  7774. globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
  7775. if (qualifier.hasPacking())
  7776. globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
  7777. break;
  7778. case EvqVaryingIn:
  7779. break;
  7780. case EvqVaryingOut:
  7781. if (qualifier.hasStream())
  7782. globalOutputDefaults.layoutStream = qualifier.layoutStream;
  7783. if (qualifier.hasXfbBuffer())
  7784. globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
  7785. if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
  7786. if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
  7787. error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
  7788. qualifier.layoutXfbBuffer);
  7789. }
  7790. break;
  7791. default:
  7792. error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
  7793. return;
  7794. }
  7795. }
  7796. //
  7797. // Take the sequence of statements that has been built up since the last case/default,
  7798. // put it on the list of top-level nodes for the current (inner-most) switch statement,
  7799. // and follow that by the case/default we are on now. (See switch topology comment on
  7800. // TIntermSwitch.)
  7801. //
  7802. void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
  7803. {
  7804. TIntermSequence* switchSequence = switchSequenceStack.back();
  7805. if (statements) {
  7806. statements->setOperator(EOpSequence);
  7807. switchSequence->push_back(statements);
  7808. }
  7809. if (branchNode) {
  7810. // check all previous cases for the same label (or both are 'default')
  7811. for (unsigned int s = 0; s < switchSequence->size(); ++s) {
  7812. TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
  7813. if (prevBranch) {
  7814. TIntermTyped* prevExpression = prevBranch->getExpression();
  7815. TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
  7816. if (prevExpression == nullptr && newExpression == nullptr)
  7817. error(branchNode->getLoc(), "duplicate label", "default", "");
  7818. else if (prevExpression != nullptr &&
  7819. newExpression != nullptr &&
  7820. prevExpression->getAsConstantUnion() &&
  7821. newExpression->getAsConstantUnion() &&
  7822. prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
  7823. newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
  7824. error(branchNode->getLoc(), "duplicated value", "case", "");
  7825. }
  7826. }
  7827. switchSequence->push_back(branchNode);
  7828. }
  7829. }
  7830. //
  7831. // Turn the top-level node sequence built up of wrapupSwitchSubsequence
  7832. // into a switch node.
  7833. //
  7834. TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
  7835. TIntermAggregate* lastStatements, const TAttributes& attributes)
  7836. {
  7837. wrapupSwitchSubsequence(lastStatements, nullptr);
  7838. if (expression == nullptr ||
  7839. (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
  7840. expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
  7841. error(loc, "condition must be a scalar integer expression", "switch", "");
  7842. // If there is nothing to do, drop the switch but still execute the expression
  7843. TIntermSequence* switchSequence = switchSequenceStack.back();
  7844. if (switchSequence->size() == 0)
  7845. return expression;
  7846. if (lastStatements == nullptr) {
  7847. // emulate a break for error recovery
  7848. lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
  7849. lastStatements->setOperator(EOpSequence);
  7850. switchSequence->push_back(lastStatements);
  7851. }
  7852. TIntermAggregate* body = new TIntermAggregate(EOpSequence);
  7853. body->getSequence() = *switchSequenceStack.back();
  7854. body->setLoc(loc);
  7855. TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
  7856. switchNode->setLoc(loc);
  7857. handleSwitchAttributes(loc, switchNode, attributes);
  7858. return switchNode;
  7859. }
  7860. // Make a new symbol-table level that is made out of the members of a structure.
  7861. // This should be done as an anonymous struct (name is "") so that the symbol table
  7862. // finds the members with no explicit reference to a 'this' variable.
  7863. void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
  7864. {
  7865. // member variables
  7866. TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
  7867. symbolTable.pushThis(thisVariable);
  7868. // member functions
  7869. for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
  7870. // member should have a prefix matching currentTypePrefix.back()
  7871. // but, symbol lookup within the class scope will just use the
  7872. // unprefixed name. Hence, there are two: one fully prefixed and
  7873. // one with no prefix.
  7874. TFunction& member = *it->function->clone();
  7875. member.removePrefix(currentTypePrefix.back());
  7876. symbolTable.insert(member);
  7877. }
  7878. }
  7879. // Track levels of class/struct/namespace nesting with a prefix string using
  7880. // the type names separated by the scoping operator. E.g., two levels
  7881. // would look like:
  7882. //
  7883. // outer::inner
  7884. //
  7885. // The string is empty when at normal global level.
  7886. //
  7887. void HlslParseContext::pushNamespace(const TString& typeName)
  7888. {
  7889. // make new type prefix
  7890. TString newPrefix;
  7891. if (currentTypePrefix.size() > 0)
  7892. newPrefix = currentTypePrefix.back();
  7893. newPrefix.append(typeName);
  7894. newPrefix.append(scopeMangler);
  7895. currentTypePrefix.push_back(newPrefix);
  7896. }
  7897. // Opposite of pushNamespace(), see above
  7898. void HlslParseContext::popNamespace()
  7899. {
  7900. currentTypePrefix.pop_back();
  7901. }
  7902. // Use the class/struct nesting string to create a global name for
  7903. // a member of a class/struct.
  7904. void HlslParseContext::getFullNamespaceName(TString*& name) const
  7905. {
  7906. if (currentTypePrefix.size() == 0)
  7907. return;
  7908. TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
  7909. fullName->append(*name);
  7910. name = fullName;
  7911. }
  7912. // Helper function to add the namespace scope mangling syntax to a string.
  7913. void HlslParseContext::addScopeMangler(TString& name)
  7914. {
  7915. name.append(scopeMangler);
  7916. }
  7917. // Return true if this has uniform-interface like decorations.
  7918. bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
  7919. {
  7920. return qualifier.hasUniformLayout() ||
  7921. qualifier.layoutPushConstant;
  7922. }
  7923. // Potentially not the opposite of hasUniform(), as if some characteristic is
  7924. // ever used for more than one thing (e.g., uniform or input), hasUniform() should
  7925. // say it exists, but clearUniform() should leave it in place.
  7926. void HlslParseContext::clearUniform(TQualifier& qualifier)
  7927. {
  7928. qualifier.clearUniformLayout();
  7929. qualifier.layoutPushConstant = false;
  7930. }
  7931. // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
  7932. bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
  7933. {
  7934. switch (qualifier.builtIn) {
  7935. case EbvPosition:
  7936. case EbvPointSize:
  7937. return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
  7938. case EbvClipDistance:
  7939. case EbvCullDistance:
  7940. return language != EShLangVertex && language != EShLangCompute;
  7941. case EbvFragCoord:
  7942. case EbvFace:
  7943. case EbvHelperInvocation:
  7944. case EbvLayer:
  7945. case EbvPointCoord:
  7946. case EbvSampleId:
  7947. case EbvSampleMask:
  7948. case EbvSamplePosition:
  7949. case EbvViewportIndex:
  7950. return language == EShLangFragment;
  7951. case EbvGlobalInvocationId:
  7952. case EbvLocalInvocationIndex:
  7953. case EbvLocalInvocationId:
  7954. case EbvNumWorkGroups:
  7955. case EbvWorkGroupId:
  7956. case EbvWorkGroupSize:
  7957. return language == EShLangCompute;
  7958. case EbvInvocationId:
  7959. return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
  7960. case EbvPatchVertices:
  7961. return language == EShLangTessControl || language == EShLangTessEvaluation;
  7962. case EbvInstanceId:
  7963. case EbvInstanceIndex:
  7964. case EbvVertexId:
  7965. case EbvVertexIndex:
  7966. return language == EShLangVertex;
  7967. case EbvPrimitiveId:
  7968. return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
  7969. case EbvTessLevelInner:
  7970. case EbvTessLevelOuter:
  7971. return language == EShLangTessEvaluation;
  7972. case EbvTessCoord:
  7973. return language == EShLangTessEvaluation;
  7974. default:
  7975. return false;
  7976. }
  7977. }
  7978. // Return true if there are decorations to preserve for input-like storage.
  7979. bool HlslParseContext::hasInput(const TQualifier& qualifier) const
  7980. {
  7981. if (qualifier.hasAnyLocation())
  7982. return true;
  7983. if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
  7984. return true;
  7985. if (language == EShLangTessEvaluation && qualifier.patch)
  7986. return true;
  7987. if (isInputBuiltIn(qualifier))
  7988. return true;
  7989. return false;
  7990. }
  7991. // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
  7992. bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
  7993. {
  7994. switch (qualifier.builtIn) {
  7995. case EbvPosition:
  7996. case EbvPointSize:
  7997. case EbvClipVertex:
  7998. case EbvClipDistance:
  7999. case EbvCullDistance:
  8000. return language != EShLangFragment && language != EShLangCompute;
  8001. case EbvFragDepth:
  8002. case EbvFragDepthGreater:
  8003. case EbvFragDepthLesser:
  8004. case EbvSampleMask:
  8005. return language == EShLangFragment;
  8006. case EbvLayer:
  8007. case EbvViewportIndex:
  8008. return language == EShLangGeometry || language == EShLangVertex;
  8009. case EbvPrimitiveId:
  8010. return language == EShLangGeometry;
  8011. case EbvTessLevelInner:
  8012. case EbvTessLevelOuter:
  8013. return language == EShLangTessControl;
  8014. default:
  8015. return false;
  8016. }
  8017. }
  8018. // Return true if there are decorations to preserve for output-like storage.
  8019. bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
  8020. {
  8021. if (qualifier.hasAnyLocation())
  8022. return true;
  8023. if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
  8024. return true;
  8025. if (language == EShLangTessControl && qualifier.patch)
  8026. return true;
  8027. if (language == EShLangGeometry && qualifier.hasStream())
  8028. return true;
  8029. if (isOutputBuiltIn(qualifier))
  8030. return true;
  8031. return false;
  8032. }
  8033. // Make the IO decorations etc. be appropriate only for an input interface.
  8034. void HlslParseContext::correctInput(TQualifier& qualifier)
  8035. {
  8036. clearUniform(qualifier);
  8037. if (language == EShLangVertex)
  8038. qualifier.clearInterstage();
  8039. if (language != EShLangTessEvaluation)
  8040. qualifier.patch = false;
  8041. if (language != EShLangFragment) {
  8042. qualifier.clearInterpolation();
  8043. qualifier.sample = false;
  8044. }
  8045. qualifier.clearStreamLayout();
  8046. qualifier.clearXfbLayout();
  8047. if (! isInputBuiltIn(qualifier))
  8048. qualifier.builtIn = EbvNone;
  8049. }
  8050. // Make the IO decorations etc. be appropriate only for an output interface.
  8051. void HlslParseContext::correctOutput(TQualifier& qualifier)
  8052. {
  8053. clearUniform(qualifier);
  8054. if (language == EShLangFragment)
  8055. qualifier.clearInterstage();
  8056. if (language != EShLangGeometry)
  8057. qualifier.clearStreamLayout();
  8058. if (language == EShLangFragment)
  8059. qualifier.clearXfbLayout();
  8060. if (language != EShLangTessControl)
  8061. qualifier.patch = false;
  8062. switch (qualifier.builtIn) {
  8063. case EbvFragDepth:
  8064. intermediate.setDepthReplacing();
  8065. intermediate.setDepth(EldAny);
  8066. break;
  8067. case EbvFragDepthGreater:
  8068. intermediate.setDepthReplacing();
  8069. intermediate.setDepth(EldGreater);
  8070. qualifier.builtIn = EbvFragDepth;
  8071. break;
  8072. case EbvFragDepthLesser:
  8073. intermediate.setDepthReplacing();
  8074. intermediate.setDepth(EldLess);
  8075. qualifier.builtIn = EbvFragDepth;
  8076. break;
  8077. default:
  8078. break;
  8079. }
  8080. if (! isOutputBuiltIn(qualifier))
  8081. qualifier.builtIn = EbvNone;
  8082. }
  8083. // Make the IO decorations etc. be appropriate only for uniform type interfaces.
  8084. void HlslParseContext::correctUniform(TQualifier& qualifier)
  8085. {
  8086. if (qualifier.declaredBuiltIn == EbvNone)
  8087. qualifier.declaredBuiltIn = qualifier.builtIn;
  8088. qualifier.builtIn = EbvNone;
  8089. qualifier.clearInterstage();
  8090. qualifier.clearInterstageLayout();
  8091. }
  8092. // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
  8093. void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
  8094. {
  8095. clearUniform(qualifier);
  8096. correctUniform(qualifier);
  8097. }
  8098. // Set texture return type. Returns success (not all types are valid).
  8099. bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
  8100. {
  8101. // Seed the output with an invalid index. We will set it to a valid one if we can.
  8102. sampler.structReturnIndex = TSampler::noReturnStruct;
  8103. // Arrays aren't supported.
  8104. if (retType.isArray()) {
  8105. error(loc, "Arrays not supported in texture template types", "", "");
  8106. return false;
  8107. }
  8108. // If return type is a vector, remember the vector size in the sampler, and return.
  8109. if (retType.isVector() || retType.isScalar()) {
  8110. sampler.vectorSize = retType.getVectorSize();
  8111. return true;
  8112. }
  8113. // If it wasn't a vector, it must be a struct meeting certain requirements. The requirements
  8114. // are checked below: just check for struct-ness here.
  8115. if (!retType.isStruct()) {
  8116. error(loc, "Invalid texture template type", "", "");
  8117. return false;
  8118. }
  8119. // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
  8120. if (sampler.isSubpass()) {
  8121. error(loc, "Unimplemented: structure template type in subpass input", "", "");
  8122. return false;
  8123. }
  8124. TTypeList* members = retType.getWritableStruct();
  8125. // Check for too many or not enough structure members.
  8126. if (members->size() > 4 || members->size() == 0) {
  8127. error(loc, "Invalid member count in texture template structure", "", "");
  8128. return false;
  8129. }
  8130. // Error checking: We must have <= 4 total components, all of the same basic type.
  8131. unsigned totalComponents = 0;
  8132. for (unsigned m = 0; m < members->size(); ++m) {
  8133. // Check for bad member types
  8134. if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
  8135. error(loc, "Invalid texture template struct member type", "", "");
  8136. return false;
  8137. }
  8138. const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
  8139. totalComponents += memberVectorSize;
  8140. // too many total member components
  8141. if (totalComponents > 4) {
  8142. error(loc, "Too many components in texture template structure type", "", "");
  8143. return false;
  8144. }
  8145. // All members must be of a common basic type
  8146. if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
  8147. error(loc, "Texture template structure members must same basic type", "", "");
  8148. return false;
  8149. }
  8150. }
  8151. // If the structure in the return type already exists in the table, we'll use it. Otherwise, we'll make
  8152. // a new entry. This is a linear search, but it hardly ever happens, and the list cannot be very large.
  8153. for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
  8154. if (textureReturnStruct[idx] == members) {
  8155. sampler.structReturnIndex = idx;
  8156. return true;
  8157. }
  8158. }
  8159. // It wasn't found as an existing entry. See if we have room for a new one.
  8160. if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
  8161. error(loc, "Texture template struct return slots exceeded", "", "");
  8162. return false;
  8163. }
  8164. // Insert it in the vector that tracks struct return types.
  8165. sampler.structReturnIndex = unsigned(textureReturnStruct.size());
  8166. textureReturnStruct.push_back(members);
  8167. // Success!
  8168. return true;
  8169. }
  8170. // Return the sampler return type in retType.
  8171. void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
  8172. {
  8173. if (sampler.hasReturnStruct()) {
  8174. assert(textureReturnStruct.size() >= sampler.structReturnIndex);
  8175. // We land here if the texture return is a structure.
  8176. TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
  8177. const TType resultType(blockStruct, "");
  8178. retType.shallowCopy(resultType);
  8179. } else {
  8180. // We land here if the texture return is a vector or scalar.
  8181. const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
  8182. retType.shallowCopy(resultType);
  8183. }
  8184. }
  8185. // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
  8186. TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
  8187. {
  8188. const auto it = builtInTessLinkageSymbols.find(biType);
  8189. if (it == builtInTessLinkageSymbols.end()) // if it wasn't declared by the user, return nullptr
  8190. return nullptr;
  8191. return intermediate.addSymbol(*it->second->getAsVariable());
  8192. }
  8193. // Find the patch constant function (issues error, returns nullptr if not found)
  8194. const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
  8195. {
  8196. if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
  8197. error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
  8198. return nullptr;
  8199. }
  8200. const TString mangledName = patchConstantFunctionName + "(";
  8201. // create list of PCF candidates
  8202. TVector<const TFunction*> candidateList;
  8203. bool builtIn;
  8204. symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
  8205. // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
  8206. // allow any disambiguation of overloads.
  8207. if (candidateList.empty()) {
  8208. error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
  8209. return nullptr;
  8210. }
  8211. // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
  8212. // HLSL picks the last one in shader source order. Since that isn't yet implemented here, error
  8213. // out if there is more than one candidate.
  8214. if (candidateList.size() > 1) {
  8215. error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
  8216. return nullptr;
  8217. }
  8218. return candidateList[0];
  8219. }
  8220. // Finalization step: Add patch constant function invocation
  8221. void HlslParseContext::addPatchConstantInvocation()
  8222. {
  8223. TSourceLoc loc;
  8224. loc.init();
  8225. // If there's no patch constant function, or we're not a HS, do nothing.
  8226. if (patchConstantFunctionName.empty() || language != EShLangTessControl)
  8227. return;
  8228. // Look for built-in variables in a function's parameter list.
  8229. const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
  8230. for (int p=0; p<function.getParamCount(); ++p) {
  8231. TStorageQualifier storage = function[p].type->getQualifier().storage;
  8232. if (storage == EvqConstReadOnly) // treated identically to input
  8233. storage = EvqIn;
  8234. if (function[p].getDeclaredBuiltIn() != EbvNone)
  8235. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
  8236. else
  8237. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
  8238. }
  8239. };
  8240. // If we synthesize a built-in interface variable, we must add it to the linkage.
  8241. const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
  8242. if (name == nullptr) {
  8243. error(loc, "unable to locate patch function parameter name", "", "");
  8244. return;
  8245. } else {
  8246. TVariable& variable = *new TVariable(name, type);
  8247. if (! symbolTable.insert(variable)) {
  8248. error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
  8249. return;
  8250. }
  8251. globalQualifierFix(loc, variable.getWritableType().getQualifier());
  8252. if (symbolNode != nullptr)
  8253. *symbolNode = intermediate.addSymbol(variable);
  8254. trackLinkage(variable);
  8255. }
  8256. };
  8257. const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
  8258. const TType& type = *patchConstantFunction[param].type;
  8259. const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
  8260. return type.isSizedArray() && biType == EbvOutputPatch;
  8261. };
  8262. // We will perform these steps. Each is in a scoped block for separation: they could
  8263. // become separate functions to make addPatchConstantInvocation shorter.
  8264. //
  8265. // 1. Union the interfaces, and create built-ins for anything present in the PCF and
  8266. // declared as a built-in variable that isn't present in the entry point's signature.
  8267. //
  8268. // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
  8269. // or the ones we created. Matching is based on built-in type. We may use synthesized
  8270. // variables from (1) above.
  8271. //
  8272. // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
  8273. //
  8274. // 3. Create a return sequence: copy the return value (if any) from the PCF to a
  8275. // (non-sanitized) output variable. In case this may involve multiple copies, such as for
  8276. // an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
  8277. // indirections into a complex R-value coming from the call to the PCF.
  8278. //
  8279. // 4. Create a barrier.
  8280. //
  8281. // 5/5B. Call the PCF inside an if test for (invocation id == 0).
  8282. TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
  8283. if (patchConstantFunctionPtr == nullptr)
  8284. return;
  8285. TFunction& patchConstantFunction = *patchConstantFunctionPtr;
  8286. const int pcfParamCount = patchConstantFunction.getParamCount();
  8287. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  8288. TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
  8289. int outPatchParam = -1; // -1 means there isn't one.
  8290. // ================ Step 1A: Union Interfaces ================
  8291. // Our patch constant function.
  8292. {
  8293. std::set<tInterstageIoData> pcfBuiltIns; // patch constant function built-ins
  8294. std::set<tInterstageIoData> epfBuiltIns; // entry point function built-ins
  8295. assert(entryPointFunction);
  8296. assert(entryPointFunctionBody);
  8297. findBuiltIns(patchConstantFunction, pcfBuiltIns);
  8298. findBuiltIns(*entryPointFunction, epfBuiltIns);
  8299. // Find the set of built-ins in the PCF that are not present in the entry point.
  8300. std::set<tInterstageIoData> notInEntryPoint;
  8301. notInEntryPoint = pcfBuiltIns;
  8302. // std::set_difference not usable on unordered containers
  8303. for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
  8304. notInEntryPoint.erase(*bi);
  8305. // Now we'll add those to the entry and to the linkage.
  8306. for (int p=0; p<pcfParamCount; ++p) {
  8307. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8308. TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
  8309. // Track whether there is an output patch param
  8310. if (isOutputPatch(patchConstantFunction, p)) {
  8311. if (outPatchParam >= 0) {
  8312. // Presently we only support one per ctrl pt input.
  8313. error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
  8314. return;
  8315. }
  8316. outPatchParam = p;
  8317. }
  8318. if (biType != EbvNone) {
  8319. TType* paramType = patchConstantFunction[p].type->clone();
  8320. if (storage == EvqConstReadOnly) // treated identically to input
  8321. storage = EvqIn;
  8322. // Presently, the only non-built-in we support is InputPatch, which is treated as
  8323. // a pseudo-built-in.
  8324. if (biType == EbvInputPatch) {
  8325. builtInTessLinkageSymbols[biType] = inputPatch;
  8326. } else if (biType == EbvOutputPatch) {
  8327. // Nothing...
  8328. } else {
  8329. // Use the original declaration type for the linkage
  8330. paramType->getQualifier().builtIn = biType;
  8331. if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
  8332. addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
  8333. }
  8334. }
  8335. }
  8336. // If we didn't find it because the shader made one, add our own.
  8337. if (invocationIdSym == nullptr) {
  8338. TType invocationIdType(EbtUint, EvqIn, 1);
  8339. TString* invocationIdName = NewPoolTString("InvocationId");
  8340. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  8341. addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
  8342. }
  8343. assert(invocationIdSym);
  8344. }
  8345. TIntermTyped* pcfArguments = nullptr;
  8346. TVariable* perCtrlPtVar = nullptr;
  8347. // ================ Step 1B: Argument synthesis ================
  8348. // Create pcfArguments for synthesis of patchconstantfunction invocation
  8349. {
  8350. for (int p=0; p<pcfParamCount; ++p) {
  8351. TIntermTyped* inputArg = nullptr;
  8352. if (p == outPatchParam) {
  8353. if (perCtrlPtVar == nullptr) {
  8354. perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
  8355. *patchConstantFunction[outPatchParam].type);
  8356. perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
  8357. }
  8358. inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
  8359. } else {
  8360. // find which built-in it is
  8361. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8362. if (biType == EbvInputPatch && inputPatch == nullptr) {
  8363. error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
  8364. return;
  8365. }
  8366. inputArg = findTessLinkageSymbol(biType);
  8367. if (inputArg == nullptr) {
  8368. error(loc, "unable to find patch constant function built-in variable", "", "");
  8369. return;
  8370. }
  8371. }
  8372. if (pcfParamCount == 1)
  8373. pcfArguments = inputArg;
  8374. else
  8375. pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
  8376. }
  8377. }
  8378. // ================ Step 2: Synthesize call to PCF ================
  8379. TIntermAggregate* pcfCallSequence = nullptr;
  8380. TIntermTyped* pcfCall = nullptr;
  8381. {
  8382. // Create a function call to the patchconstantfunction
  8383. if (pcfArguments)
  8384. addInputArgumentConversions(patchConstantFunction, pcfArguments);
  8385. // Synthetic call.
  8386. pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
  8387. pcfCall->getAsAggregate()->setUserDefined();
  8388. pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
  8389. intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
  8390. patchConstantFunction.getMangledName());
  8391. if (pcfCall->getAsAggregate()) {
  8392. TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
  8393. for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
  8394. TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
  8395. qualifierList.push_back(qual);
  8396. }
  8397. pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
  8398. }
  8399. }
  8400. // ================ Step 2B: Per Control Point synthesis ================
  8401. // If there is per control point data, we must either emulate that with multiple
  8402. // invocations of the entry point to build up an array, or (TODO:) use a yet
  8403. // unavailable extension to look across the SIMD lanes. This is the former
  8404. // as a placeholder for the latter.
  8405. if (outPatchParam >= 0) {
  8406. // We must introduce a local temp variable of the type wanted by the PCF input.
  8407. const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
  8408. if (entryPointFunction->getType().getBasicType() == EbtVoid) {
  8409. error(loc, "entry point must return a value for use with patch constant function", "", "");
  8410. return;
  8411. }
  8412. // Create calls to wrapped main to fill in the array. We will substitute fixed values
  8413. // of invocation ID when calling the wrapped main.
  8414. // This is the type of the each member of the per ctrl point array.
  8415. const TType derefType(perCtrlPtVar->getType(), 0);
  8416. for (int cpt = 0; cpt < arraySize; ++cpt) {
  8417. // TODO: improve. substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
  8418. // for this function.
  8419. const TString origName = entryPointFunction->getName().substr(1);
  8420. TFunction callee(&origName, TType(EbtVoid));
  8421. TIntermTyped* callingArgs = nullptr;
  8422. for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
  8423. TParameter& param = (*entryPointFunction)[i];
  8424. TType& paramType = *param.type;
  8425. if (paramType.getQualifier().isParamOutput()) {
  8426. error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
  8427. return;
  8428. }
  8429. if (paramType.getQualifier().isParamInput()) {
  8430. TIntermTyped* arg = nullptr;
  8431. if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
  8432. // substitute invocation ID with the array element ID
  8433. arg = intermediate.addConstantUnion(cpt, loc);
  8434. } else {
  8435. TVariable* argVar = makeInternalVariable(*param.name, *param.type);
  8436. argVar->getWritableType().getQualifier().makeTemporary();
  8437. arg = intermediate.addSymbol(*argVar);
  8438. }
  8439. handleFunctionArgument(&callee, callingArgs, arg);
  8440. }
  8441. }
  8442. // Call and assign to per ctrl point variable
  8443. currentCaller = intermediate.getEntryPointMangledName().c_str();
  8444. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  8445. TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
  8446. TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
  8447. TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
  8448. element->setType(derefType);
  8449. element->setLoc(loc);
  8450. pcfCallSequence = intermediate.growAggregate(pcfCallSequence,
  8451. handleAssign(loc, EOpAssign, element, callReturn));
  8452. }
  8453. }
  8454. // ================ Step 3: Create return Sequence ================
  8455. // Return sequence: copy PCF result to a temporary, then to shader output variable.
  8456. if (pcfCall->getBasicType() != EbtVoid) {
  8457. const TType* retType = &patchConstantFunction.getType(); // return type from the PCF
  8458. TType outType; // output type that goes with the return type.
  8459. outType.shallowCopy(*retType);
  8460. // substitute the output type
  8461. const auto newLists = ioTypeMap.find(retType->getStruct());
  8462. if (newLists != ioTypeMap.end())
  8463. outType.setStruct(newLists->second.output);
  8464. // Substitute the top level type's built-in type
  8465. if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
  8466. outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
  8467. outType.getQualifier().patch = true; // make it a per-patch variable
  8468. TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
  8469. pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
  8470. if (pcfOutput->getType().containsBuiltIn())
  8471. split(*pcfOutput);
  8472. assignToInterface(*pcfOutput);
  8473. TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
  8474. // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
  8475. // repeated calls to the PCF:
  8476. TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
  8477. pcfCallResult->getWritableType().getQualifier().makeTemporary();
  8478. TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
  8479. TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
  8480. TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
  8481. intermediate.addSymbol(*pcfCallResult, loc));
  8482. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
  8483. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
  8484. } else {
  8485. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
  8486. }
  8487. // ================ Step 4: Barrier ================
  8488. TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
  8489. barrier->setLoc(loc);
  8490. barrier->setType(TType(EbtVoid));
  8491. epBodySeq.insert(epBodySeq.end(), barrier);
  8492. // ================ Step 5: Test on invocation ID ================
  8493. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  8494. TIntermTyped* cmp = intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
  8495. // ================ Step 5B: Create if statement on Invocation ID == 0 ================
  8496. intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
  8497. TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
  8498. invocationIdTest->setLoc(loc);
  8499. // add our test sequence before the return.
  8500. epBodySeq.insert(epBodySeq.end(), invocationIdTest);
  8501. }
  8502. // Finalization step: remove unused buffer blocks from linkage (we don't know until the
  8503. // shader is entirely compiled).
  8504. // Preserve order of remaining symbols.
  8505. void HlslParseContext::removeUnusedStructBufferCounters()
  8506. {
  8507. const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
  8508. [this](const TSymbol* sym) {
  8509. const auto sbcIt = structBufferCounter.find(sym->getName());
  8510. return sbcIt != structBufferCounter.end() && !sbcIt->second;
  8511. });
  8512. linkageSymbols.erase(endIt, linkageSymbols.end());
  8513. }
  8514. // Finalization step: patch texture shadow modes to match samplers they were combined with
  8515. void HlslParseContext::fixTextureShadowModes()
  8516. {
  8517. for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
  8518. TSampler& sampler = (*symbol)->getWritableType().getSampler();
  8519. if (sampler.isTexture()) {
  8520. const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
  8521. if (shadowMode != textureShadowVariant.end()) {
  8522. if (shadowMode->second->overloaded())
  8523. // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
  8524. intermediate.setNeedsLegalization();
  8525. sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
  8526. }
  8527. }
  8528. }
  8529. }
  8530. // Finalization step: patch append methods to use proper stream output, which isn't known until
  8531. // main is parsed, which could happen after the append method is parsed.
  8532. void HlslParseContext::finalizeAppendMethods()
  8533. {
  8534. TSourceLoc loc;
  8535. loc.init();
  8536. // Nothing to do: bypass test for valid stream output.
  8537. if (gsAppends.empty())
  8538. return;
  8539. if (gsStreamOutput == nullptr) {
  8540. error(loc, "unable to find output symbol for Append()", "", "");
  8541. return;
  8542. }
  8543. // Patch append sequences, now that we know the stream output symbol.
  8544. for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
  8545. append->node->getSequence()[0] =
  8546. handleAssign(append->loc, EOpAssign,
  8547. intermediate.addSymbol(*gsStreamOutput, append->loc),
  8548. append->node->getSequence()[0]->getAsTyped());
  8549. }
  8550. }
  8551. // post-processing
  8552. void HlslParseContext::finish()
  8553. {
  8554. // Error check: There was a dangling .mips operator. These are not nested constructs in the grammar, so
  8555. // cannot be detected there. This is not strictly needed in a non-validating parser; it's just helpful.
  8556. if (! mipsOperatorMipArg.empty()) {
  8557. error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
  8558. }
  8559. removeUnusedStructBufferCounters();
  8560. addPatchConstantInvocation();
  8561. fixTextureShadowModes();
  8562. finalizeAppendMethods();
  8563. // Communicate out (esp. for command line) that we formed AST that will make
  8564. // illegal AST SPIR-V and it needs transforms to legalize it.
  8565. if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
  8566. infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
  8567. TParseContextBase::finish();
  8568. }
  8569. } // end namespace glslang