hlslParseHelper.cpp 426 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169
  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 "../Include/Common.h"
  41. #include "../MachineIndependent/Scan.h"
  42. #include "../MachineIndependent/preprocessor/PpContext.h"
  43. #include "../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. parsingEntrypointParameters(false)
  68. {
  69. globalUniformDefaults.clear();
  70. globalUniformDefaults.layoutMatrix = ElmRowMajor;
  71. globalUniformDefaults.layoutPacking = ElpStd140;
  72. globalBufferDefaults.clear();
  73. globalBufferDefaults.layoutMatrix = ElmRowMajor;
  74. globalBufferDefaults.layoutPacking = ElpStd430;
  75. globalInputDefaults.clear();
  76. globalOutputDefaults.clear();
  77. clipSemanticNSizeIn.fill(0);
  78. cullSemanticNSizeIn.fill(0);
  79. clipSemanticNSizeOut.fill(0);
  80. cullSemanticNSizeOut.fill(0);
  81. // "Shaders in the transform
  82. // feedback capturing mode have an initial global default of
  83. // layout(xfb_buffer = 0) out;"
  84. if (language == EShLangVertex ||
  85. language == EShLangTessControl ||
  86. language == EShLangTessEvaluation ||
  87. language == EShLangGeometry)
  88. globalOutputDefaults.layoutXfbBuffer = 0;
  89. if (language == EShLangGeometry)
  90. globalOutputDefaults.layoutStream = 0;
  91. }
  92. HlslParseContext::~HlslParseContext()
  93. {
  94. }
  95. void HlslParseContext::initializeExtensionBehavior()
  96. {
  97. TParseContextBase::initializeExtensionBehavior();
  98. // HLSL allows #line by default.
  99. extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
  100. }
  101. void HlslParseContext::setLimits(const TBuiltInResource& r)
  102. {
  103. resources = r;
  104. intermediate.setLimits(resources);
  105. }
  106. //
  107. // Parse an array of strings using the parser in HlslRules.
  108. //
  109. // Returns true for successful acceptance of the shader, false if any errors.
  110. //
  111. bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
  112. {
  113. currentScanner = &input;
  114. ppContext.setInput(input, versionWillBeError);
  115. HlslScanContext scanContext(*this, ppContext);
  116. HlslGrammar grammar(scanContext, *this);
  117. if (!grammar.parse()) {
  118. // Print a message formated such that if you click on the message it will take you right to
  119. // the line through most UIs.
  120. const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
  121. infoSink.info << sourceLoc.getFilenameStr() << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
  122. << ", HLSL parsing failed.\n";
  123. ++numErrors;
  124. return false;
  125. }
  126. finish();
  127. return numErrors == 0;
  128. }
  129. //
  130. // Return true if this l-value node should be converted in some manner.
  131. // For instance: turning a load aggregate into a store in an l-value.
  132. //
  133. bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
  134. {
  135. if (node == nullptr || node->getAsTyped() == nullptr)
  136. return false;
  137. const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  138. const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
  139. // If it's a swizzled/indexed aggregate, look at the left node instead.
  140. if (lhsAsBinary != nullptr &&
  141. (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
  142. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  143. if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
  144. return true;
  145. return false;
  146. }
  147. void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
  148. TTypeList* newTypeList)
  149. {
  150. newTypeList = nullptr;
  151. correctUniform(memberType.getQualifier());
  152. if (memberType.isStruct()) {
  153. auto it = ioTypeMap.find(memberType.getStruct());
  154. if (it != ioTypeMap.end() && it->second.uniform)
  155. newTypeList = it->second.uniform;
  156. }
  157. TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
  158. }
  159. //
  160. // Return a TLayoutFormat corresponding to the given texture type.
  161. //
  162. TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
  163. {
  164. if (txType.isStruct()) {
  165. // TODO: implement.
  166. error(loc, "unimplemented: structure type in image or buffer", "", "");
  167. return ElfNone;
  168. }
  169. const int components = txType.getVectorSize();
  170. const TBasicType txBasicType = txType.getBasicType();
  171. const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
  172. if (intermediate.getNoStorageFormat())
  173. return ElfNone;
  174. return components == 1 ? v1 :
  175. components == 2 ? v2 : v4;
  176. };
  177. switch (txBasicType) {
  178. case EbtFloat: return selectFormat(ElfR32f, ElfRg32f, ElfRgba32f);
  179. case EbtInt: return selectFormat(ElfR32i, ElfRg32i, ElfRgba32i);
  180. case EbtUint: return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
  181. default:
  182. error(loc, "unknown basic type in image format", "", "");
  183. return ElfNone;
  184. }
  185. }
  186. //
  187. // Both test and if necessary, spit out an error, to see if the node is really
  188. // an l-value that can be operated on this way.
  189. //
  190. // Returns true if there was an error.
  191. //
  192. bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
  193. {
  194. if (shouldConvertLValue(node)) {
  195. // if we're writing to a texture, it must be an RW form.
  196. TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  197. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  198. if (!object->getType().getSampler().isImage()) {
  199. error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
  200. return true;
  201. }
  202. }
  203. // We tolerate samplers as l-values, even though they are nominally
  204. // illegal, because we expect a later optimization to eliminate them.
  205. if (node->getType().getBasicType() == EbtSampler) {
  206. intermediate.setNeedsLegalization();
  207. return false;
  208. }
  209. // Let the base class check errors
  210. return TParseContextBase::lValueErrorCheck(loc, op, node);
  211. }
  212. //
  213. // This function handles l-value conversions and verifications. It uses, but is not synonymous
  214. // with lValueErrorCheck. That function accepts an l-value directly, while this one must be
  215. // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
  216. // series of other image operations.
  217. //
  218. // Most things are passed through unmodified, except for error checking.
  219. //
  220. TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
  221. {
  222. if (node == nullptr)
  223. return nullptr;
  224. TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
  225. TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
  226. TIntermAggregate* sequence = nullptr;
  227. TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
  228. nodeAsBinary ? nodeAsBinary->getLeft() :
  229. nullptr;
  230. // Early bail out if there is no conversion to apply
  231. if (!shouldConvertLValue(lhs)) {
  232. if (lhs != nullptr)
  233. if (lValueErrorCheck(loc, op, lhs))
  234. return nullptr;
  235. return node;
  236. }
  237. // *** If we get here, we're going to apply some conversion to an l-value.
  238. // Helper to create a load.
  239. const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
  240. TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
  241. loadOp->setLoc(loc);
  242. loadOp->getSequence().push_back(object);
  243. loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
  244. loadOp->setType(derefType);
  245. sequence = intermediate.growAggregate(sequence,
  246. intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
  247. loc);
  248. };
  249. // Helper to create a store.
  250. const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
  251. TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
  252. storeOp->getSequence().push_back(object);
  253. storeOp->getSequence().push_back(coord);
  254. storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
  255. storeOp->setLoc(loc);
  256. storeOp->setType(TType(EbtVoid));
  257. sequence = intermediate.growAggregate(sequence, storeOp);
  258. };
  259. // Helper to create an assign.
  260. const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
  261. sequence = intermediate.growAggregate(sequence,
  262. intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
  263. loc);
  264. };
  265. // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
  266. const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
  267. // Add a trailing use of the temp, so the sequence returns the proper value.
  268. sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
  269. sequence->setOperator(EOpSequence);
  270. sequence->setLoc(loc);
  271. sequence->setType(derefType);
  272. return sequence;
  273. };
  274. // Helper to add unary op
  275. const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
  276. sequence = intermediate.growAggregate(sequence,
  277. intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
  278. rhsTmp->getType()),
  279. loc);
  280. };
  281. // Return true if swizzle or index writes all components of the given variable.
  282. const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
  283. if (swizzle == nullptr) // not a swizzle or index
  284. return true;
  285. // Track which components are being set.
  286. std::array<bool, 4> compIsSet;
  287. compIsSet.fill(false);
  288. const TIntermConstantUnion* asConst = swizzle->getRight()->getAsConstantUnion();
  289. const TIntermAggregate* asAggregate = swizzle->getRight()->getAsAggregate();
  290. // This could be either a direct index, or a swizzle.
  291. if (asConst) {
  292. compIsSet[asConst->getConstArray()[0].getIConst()] = true;
  293. } else if (asAggregate) {
  294. const TIntermSequence& seq = asAggregate->getSequence();
  295. for (int comp=0; comp<int(seq.size()); ++comp)
  296. compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
  297. } else {
  298. assert(0);
  299. }
  300. // Return true if all components are being set by the index or swizzle
  301. return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
  302. [](bool isSet) { return isSet; } );
  303. };
  304. // Create swizzle matching input swizzle
  305. const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
  306. if (swizzle)
  307. return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
  308. else
  309. return var;
  310. };
  311. TIntermBinary* lhsAsBinary = lhs->getAsBinaryNode();
  312. TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
  313. bool lhsIsSwizzle = false;
  314. // If it's a swizzled L-value, remember the swizzle, and use the LHS.
  315. if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
  316. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  317. lhsIsSwizzle = true;
  318. }
  319. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  320. TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
  321. const TSampler& texSampler = object->getType().getSampler();
  322. TType objDerefType;
  323. getTextureReturnType(texSampler, objDerefType);
  324. if (nodeAsBinary) {
  325. TIntermTyped* rhs = nodeAsBinary->getRight();
  326. const TOperator assignOp = nodeAsBinary->getOp();
  327. bool isModifyOp = false;
  328. switch (assignOp) {
  329. case EOpAddAssign:
  330. case EOpSubAssign:
  331. case EOpMulAssign:
  332. case EOpVectorTimesMatrixAssign:
  333. case EOpVectorTimesScalarAssign:
  334. case EOpMatrixTimesScalarAssign:
  335. case EOpMatrixTimesMatrixAssign:
  336. case EOpDivAssign:
  337. case EOpModAssign:
  338. case EOpAndAssign:
  339. case EOpInclusiveOrAssign:
  340. case EOpExclusiveOrAssign:
  341. case EOpLeftShiftAssign:
  342. case EOpRightShiftAssign:
  343. isModifyOp = true;
  344. // fall through...
  345. case EOpAssign:
  346. {
  347. // Since this is an lvalue, we'll convert an image load to a sequence like this
  348. // (to still provide the value):
  349. // OpSequence
  350. // OpImageStore(object, lhs, rhs)
  351. // rhs
  352. // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
  353. // so we'll convert instead to this:
  354. // OpSequence
  355. // rhsTmp = rhs
  356. // OpImageStore(object, coord, rhsTmp)
  357. // rhsTmp
  358. // If this is a read-modify-write op, like +=, we issue:
  359. // OpSequence
  360. // coordtmp = load's param1
  361. // rhsTmp = OpImageLoad(object, coordTmp)
  362. // rhsTmp op= rhs
  363. // OpImageStore(object, coordTmp, rhsTmp)
  364. // rhsTmp
  365. //
  366. // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
  367. // ...
  368. // rhsTmp.some_swizzle = ...
  369. // For partial writes, an error is generated.
  370. TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
  371. TIntermTyped* coordTmp = coord;
  372. if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
  373. rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  374. // Partial updates not yet supported
  375. if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
  376. error(loc, "unimplemented: partial image updates", "", "");
  377. }
  378. // Assign storeTemp = rhs
  379. if (isModifyOp) {
  380. // We have to make a temp var for the coordinate, to avoid evaluating it twice.
  381. coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  382. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  383. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  384. }
  385. // rhsTmp op= rhs.
  386. makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
  387. }
  388. makeStore(object, coordTmp, rhsTmp); // add a store
  389. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  390. }
  391. default:
  392. break;
  393. }
  394. }
  395. if (nodeAsUnary) {
  396. const TOperator assignOp = nodeAsUnary->getOp();
  397. switch (assignOp) {
  398. case EOpPreIncrement:
  399. case EOpPreDecrement:
  400. {
  401. // We turn this into:
  402. // OpSequence
  403. // coordtmp = load's param1
  404. // rhsTmp = OpImageLoad(object, coordTmp)
  405. // rhsTmp op
  406. // OpImageStore(object, coordTmp, rhsTmp)
  407. // rhsTmp
  408. TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  409. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  410. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  411. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  412. makeUnary(assignOp, rhsTmp); // op rhsTmp
  413. makeStore(object, coordTmp, rhsTmp); // OpImageStore(object, coordTmp, rhsTmp)
  414. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  415. }
  416. case EOpPostIncrement:
  417. case EOpPostDecrement:
  418. {
  419. // We turn this into:
  420. // OpSequence
  421. // coordtmp = load's param1
  422. // rhsTmp1 = OpImageLoad(object, coordTmp)
  423. // rhsTmp2 = rhsTmp1
  424. // rhsTmp2 op
  425. // OpImageStore(object, coordTmp, rhsTmp2)
  426. // rhsTmp1 (pre-op value)
  427. TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre", objDerefType);
  428. TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
  429. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  430. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  431. makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
  432. makeBinary(EOpAssign, rhsTmp2, rhsTmp1); // rhsTmp2 = rhsTmp1
  433. makeUnary(assignOp, rhsTmp2); // rhsTmp op
  434. makeStore(object, coordTmp, rhsTmp2); // OpImageStore(object, coordTmp, rhsTmp2)
  435. return finishSequence(rhsTmp1, objDerefType); // return rhsTmp from sequence
  436. }
  437. default:
  438. break;
  439. }
  440. }
  441. if (lhs)
  442. if (lValueErrorCheck(loc, op, lhs))
  443. return nullptr;
  444. return node;
  445. }
  446. void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
  447. {
  448. if (pragmaCallback)
  449. pragmaCallback(loc.line, tokens);
  450. if (tokens.size() == 0)
  451. return;
  452. // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
  453. TVector<TString> lowerTokens = tokens;
  454. for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
  455. std::transform(it->begin(), it->end(), it->begin(), ::tolower);
  456. // Handle pack_matrix
  457. if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
  458. // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
  459. // Row major becomes column major and vice versa.
  460. if (lowerTokens[2] == "row_major") {
  461. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
  462. } else if (lowerTokens[2] == "column_major") {
  463. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  464. } else {
  465. // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
  466. warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
  467. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  468. }
  469. return;
  470. }
  471. // Handle once
  472. if (lowerTokens[0] == "once") {
  473. warn(loc, "not implemented", "#pragma once", "");
  474. return;
  475. }
  476. }
  477. //
  478. // Look at a '.' matrix selector string and change it into components
  479. // for a matrix. There are two types:
  480. //
  481. // _21 second row, first column (one based)
  482. // _m21 third row, second column (zero based)
  483. //
  484. // Returns true if there is no error.
  485. //
  486. bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
  487. TSwizzleSelectors<TMatrixSelector>& components)
  488. {
  489. int startPos[MaxSwizzleSelectors];
  490. int numComps = 0;
  491. TString compString = fields;
  492. // Find where each component starts,
  493. // recording the first character position after the '_'.
  494. for (size_t c = 0; c < compString.size(); ++c) {
  495. if (compString[c] == '_') {
  496. if (numComps >= MaxSwizzleSelectors) {
  497. error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
  498. return false;
  499. }
  500. if (c > compString.size() - 3 ||
  501. ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
  502. error(loc, "matrix component swizzle missing", compString.c_str(), "");
  503. return false;
  504. }
  505. startPos[numComps++] = (int)c + 1;
  506. }
  507. }
  508. // Process each component
  509. for (int i = 0; i < numComps; ++i) {
  510. int pos = startPos[i];
  511. int bias = -1;
  512. if (compString[pos] == 'm' || compString[pos] == 'M') {
  513. bias = 0;
  514. ++pos;
  515. }
  516. TMatrixSelector comp;
  517. comp.coord1 = compString[pos+0] - '0' + bias;
  518. comp.coord2 = compString[pos+1] - '0' + bias;
  519. if (comp.coord1 < 0 || comp.coord1 >= cols) {
  520. error(loc, "matrix row component out of range", compString.c_str(), "");
  521. return false;
  522. }
  523. if (comp.coord2 < 0 || comp.coord2 >= rows) {
  524. error(loc, "matrix column component out of range", compString.c_str(), "");
  525. return false;
  526. }
  527. components.push_back(comp);
  528. }
  529. return true;
  530. }
  531. // If the 'comps' express a column of a matrix,
  532. // return the column. Column means the first coords all match.
  533. //
  534. // Otherwise, return -1.
  535. //
  536. int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
  537. {
  538. int col = -1;
  539. // right number of comps?
  540. if (selector.size() != rows)
  541. return -1;
  542. // all comps in the same column?
  543. // rows in order?
  544. col = selector[0].coord1;
  545. for (int i = 0; i < rows; ++i) {
  546. if (col != selector[i].coord1)
  547. return -1;
  548. if (i != selector[i].coord2)
  549. return -1;
  550. }
  551. return col;
  552. }
  553. //
  554. // Handle seeing a variable identifier in the grammar.
  555. //
  556. TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
  557. {
  558. int thisDepth;
  559. TSymbol* symbol = symbolTable.find(*string, thisDepth);
  560. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  561. error(loc, "expected symbol, not user-defined type", string->c_str(), "");
  562. return nullptr;
  563. }
  564. const TVariable* variable = nullptr;
  565. const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
  566. TIntermTyped* node = nullptr;
  567. if (anon) {
  568. // It was a member of an anonymous container, which could be a 'this' structure.
  569. // Create a subtree for its dereference.
  570. if (thisDepth > 0) {
  571. variable = getImplicitThis(thisDepth);
  572. if (variable == nullptr)
  573. error(loc, "cannot access member variables (static member function?)", "this", "");
  574. }
  575. if (variable == nullptr)
  576. variable = anon->getAnonContainer().getAsVariable();
  577. TIntermTyped* container = intermediate.addSymbol(*variable, loc);
  578. TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
  579. node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
  580. node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
  581. if (node->getType().hiddenMember())
  582. error(loc, "member of nameless block was not redeclared", string->c_str(), "");
  583. } else {
  584. // Not a member of an anonymous container.
  585. // The symbol table search was done in the lexical phase.
  586. // See if it was a variable.
  587. variable = symbol ? symbol->getAsVariable() : nullptr;
  588. if (variable) {
  589. if ((variable->getType().getBasicType() == EbtBlock ||
  590. variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
  591. error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
  592. variable = nullptr;
  593. }
  594. } else {
  595. if (symbol)
  596. error(loc, "variable name expected", string->c_str(), "");
  597. }
  598. // Recovery, if it wasn't found or was not a variable.
  599. if (variable == nullptr) {
  600. error(loc, "unknown variable", string->c_str(), "");
  601. variable = new TVariable(string, TType(EbtVoid));
  602. }
  603. if (variable->getType().getQualifier().isFrontEndConstant())
  604. node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
  605. else
  606. node = intermediate.addSymbol(*variable, loc);
  607. }
  608. if (variable->getType().getQualifier().isIo())
  609. intermediate.addIoAccessed(*string);
  610. return node;
  611. }
  612. //
  613. // Handle operator[] on any objects it applies to. Currently:
  614. // Textures
  615. // Buffers
  616. //
  617. TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  618. {
  619. // handle r-value operator[] on textures and images. l-values will be processed later.
  620. if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
  621. const TSampler& sampler = base->getType().getSampler();
  622. if (sampler.isImage() || sampler.isTexture()) {
  623. if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
  624. // The first operator[] to a .mips[] sequence is the mip level. We'll remember it.
  625. mipsOperatorMipArg.back().mipLevel = index;
  626. return base; // next [] index is to the same base.
  627. } else {
  628. TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
  629. TType sampReturnType;
  630. getTextureReturnType(sampler, sampReturnType);
  631. load->setType(sampReturnType);
  632. load->setLoc(loc);
  633. load->getSequence().push_back(base);
  634. load->getSequence().push_back(index);
  635. // Textures need a MIP. If we saw one go by, use it. Otherwise, use zero.
  636. if (sampler.isTexture()) {
  637. if (! mipsOperatorMipArg.empty()) {
  638. load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
  639. mipsOperatorMipArg.pop_back();
  640. } else {
  641. load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
  642. }
  643. }
  644. return load;
  645. }
  646. }
  647. }
  648. // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
  649. // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
  650. TIntermTyped* sbArray = indexStructBufferContent(loc, base);
  651. if (sbArray != nullptr) {
  652. // Now we'll apply the [] index to that array
  653. const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  654. TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
  655. const TType derefType(sbArray->getType(), 0);
  656. element->setType(derefType);
  657. return element;
  658. }
  659. return nullptr;
  660. }
  661. //
  662. // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
  663. TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
  664. {
  665. const TBasicType indexBasicType = index->getType().getBasicType();
  666. const int vecSize = index->getType().getVectorSize();
  667. // We can use int types directly as the index
  668. if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
  669. indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
  670. return index;
  671. // Cast index to unsigned integer if it isn't one.
  672. return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
  673. }
  674. //
  675. // Handle seeing a base[index] dereference in the grammar.
  676. //
  677. TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  678. {
  679. index = makeIntegerIndex(index);
  680. if (index == nullptr) {
  681. error(loc, " unknown index type ", "", "");
  682. return nullptr;
  683. }
  684. TIntermTyped* result = handleBracketOperator(loc, base, index);
  685. if (result != nullptr)
  686. return result; // it was handled as an operator[]
  687. bool flattened = false;
  688. int indexValue = 0;
  689. if (index->getQualifier().isFrontEndConstant())
  690. indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
  691. variableCheck(base);
  692. if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
  693. if (base->getAsSymbolNode())
  694. error(loc, " left of '[' is not of type array, matrix, or vector ",
  695. base->getAsSymbolNode()->getName().c_str(), "");
  696. else
  697. error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
  698. } else if (base->getType().getQualifier().isFrontEndConstant() &&
  699. index->getQualifier().isFrontEndConstant()) {
  700. // both base and index are front-end constants
  701. checkIndex(loc, base->getType(), indexValue);
  702. return intermediate.foldDereference(base, indexValue, loc);
  703. } else {
  704. // at least one of base and index is variable...
  705. if (index->getQualifier().isFrontEndConstant())
  706. checkIndex(loc, base->getType(), indexValue);
  707. if (base->getType().isScalarOrVec1())
  708. result = base;
  709. else if (base->getAsSymbolNode() && wasFlattened(base)) {
  710. if (index->getQualifier().storage != EvqConst)
  711. error(loc, "Invalid variable index to flattened array", base->getAsSymbolNode()->getName().c_str(), "");
  712. result = flattenAccess(base, indexValue);
  713. flattened = (result != base);
  714. } else {
  715. if (index->getQualifier().isFrontEndConstant()) {
  716. if (base->getType().isUnsizedArray())
  717. base->getWritableType().updateImplicitArraySize(indexValue + 1);
  718. else
  719. checkIndex(loc, base->getType(), indexValue);
  720. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  721. } else
  722. result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
  723. }
  724. }
  725. if (result == nullptr) {
  726. // Insert dummy error-recovery result
  727. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  728. } else {
  729. // If the array reference was flattened, it has the correct type. E.g, if it was
  730. // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
  731. // In that case, we preserve the qualifiers.
  732. if (!flattened) {
  733. // Insert valid dereferenced result
  734. TType newType(base->getType(), 0); // dereferenced type
  735. if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
  736. newType.getQualifier().storage = EvqConst;
  737. else
  738. newType.getQualifier().storage = EvqTemporary;
  739. result->setType(newType);
  740. }
  741. }
  742. return result;
  743. }
  744. // Handle seeing a binary node with a math operation.
  745. TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  746. TIntermTyped* left, TIntermTyped* right)
  747. {
  748. TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
  749. if (result == nullptr)
  750. binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
  751. return result;
  752. }
  753. // Handle seeing a unary node with a math operation.
  754. TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op,
  755. TIntermTyped* childNode)
  756. {
  757. TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
  758. if (result)
  759. return result;
  760. else
  761. unaryOpError(loc, str, childNode->getCompleteString());
  762. return childNode;
  763. }
  764. //
  765. // Return true if the name is a struct buffer method
  766. //
  767. bool HlslParseContext::isStructBufferMethod(const TString& name) const
  768. {
  769. return
  770. name == "GetDimensions" ||
  771. name == "Load" ||
  772. name == "Load2" ||
  773. name == "Load3" ||
  774. name == "Load4" ||
  775. name == "Store" ||
  776. name == "Store2" ||
  777. name == "Store3" ||
  778. name == "Store4" ||
  779. name == "InterlockedAdd" ||
  780. name == "InterlockedAnd" ||
  781. name == "InterlockedCompareExchange" ||
  782. name == "InterlockedCompareStore" ||
  783. name == "InterlockedExchange" ||
  784. name == "InterlockedMax" ||
  785. name == "InterlockedMin" ||
  786. name == "InterlockedOr" ||
  787. name == "InterlockedXor" ||
  788. name == "IncrementCounter" ||
  789. name == "DecrementCounter" ||
  790. name == "Append" ||
  791. name == "Consume";
  792. }
  793. //
  794. // Handle seeing a base.field dereference in the grammar, where 'field' is a
  795. // swizzle or member variable.
  796. //
  797. TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
  798. {
  799. variableCheck(base);
  800. if (base->isArray()) {
  801. error(loc, "cannot apply to an array:", ".", field.c_str());
  802. return base;
  803. }
  804. TIntermTyped* result = base;
  805. if (base->getType().getBasicType() == EbtSampler) {
  806. // Handle .mips[mipid][pos] operation on textures
  807. const TSampler& sampler = base->getType().getSampler();
  808. if (sampler.isTexture() && field == "mips") {
  809. // Push a null to signify that we expect a mip level under operator[] next.
  810. mipsOperatorMipArg.push_back(tMipsOperatorData(loc, nullptr));
  811. // Keep 'result' pointing to 'base', since we expect an operator[] to go by next.
  812. } else {
  813. if (field == "mips")
  814. error(loc, "unexpected texture type for .mips[][] operator:",
  815. base->getType().getCompleteString().c_str(), "");
  816. else
  817. error(loc, "unexpected operator on texture type:", field.c_str(),
  818. base->getType().getCompleteString().c_str());
  819. }
  820. } else if (base->isVector() || base->isScalar()) {
  821. TSwizzleSelectors<TVectorSelector> selectors;
  822. parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
  823. if (base->isScalar()) {
  824. if (selectors.size() == 1)
  825. return result;
  826. else {
  827. TType type(base->getBasicType(), EvqTemporary, selectors.size());
  828. return addConstructor(loc, base, type);
  829. }
  830. }
  831. if (base->getVectorSize() == 1) {
  832. TType scalarType(base->getBasicType(), EvqTemporary, 1);
  833. if (selectors.size() == 1)
  834. return addConstructor(loc, base, scalarType);
  835. else {
  836. TType vectorType(base->getBasicType(), EvqTemporary, selectors.size());
  837. return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
  838. }
  839. }
  840. if (base->getType().getQualifier().isFrontEndConstant())
  841. result = intermediate.foldSwizzle(base, selectors, loc);
  842. else {
  843. if (selectors.size() == 1) {
  844. TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
  845. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  846. result->setType(TType(base->getBasicType(), EvqTemporary));
  847. } else {
  848. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  849. result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
  850. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  851. selectors.size()));
  852. }
  853. }
  854. } else if (base->isMatrix()) {
  855. TSwizzleSelectors<TMatrixSelector> selectors;
  856. if (! parseMatrixSwizzleSelector(loc, field, base->getMatrixCols(), base->getMatrixRows(), selectors))
  857. return result;
  858. if (selectors.size() == 1) {
  859. // Representable by m[c][r]
  860. if (base->getType().getQualifier().isFrontEndConstant()) {
  861. result = intermediate.foldDereference(base, selectors[0].coord1, loc);
  862. result = intermediate.foldDereference(result, selectors[0].coord2, loc);
  863. } else {
  864. result = intermediate.addIndex(EOpIndexDirect, base,
  865. intermediate.addConstantUnion(selectors[0].coord1, loc),
  866. loc);
  867. TType dereferencedCol(base->getType(), 0);
  868. result->setType(dereferencedCol);
  869. result = intermediate.addIndex(EOpIndexDirect, result,
  870. intermediate.addConstantUnion(selectors[0].coord2, loc),
  871. loc);
  872. TType dereferenced(dereferencedCol, 0);
  873. result->setType(dereferenced);
  874. }
  875. } else {
  876. int column = getMatrixComponentsColumn(base->getMatrixRows(), selectors);
  877. if (column >= 0) {
  878. // Representable by m[c]
  879. if (base->getType().getQualifier().isFrontEndConstant())
  880. result = intermediate.foldDereference(base, column, loc);
  881. else {
  882. result = intermediate.addIndex(EOpIndexDirect, base, intermediate.addConstantUnion(column, loc),
  883. loc);
  884. TType dereferenced(base->getType(), 0);
  885. result->setType(dereferenced);
  886. }
  887. } else {
  888. // general case, not a column, not a single component
  889. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  890. result = intermediate.addIndex(EOpMatrixSwizzle, base, index, loc);
  891. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision,
  892. selectors.size()));
  893. }
  894. }
  895. } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
  896. const TTypeList* fields = base->getType().getStruct();
  897. bool fieldFound = false;
  898. int member;
  899. for (member = 0; member < (int)fields->size(); ++member) {
  900. if ((*fields)[member].type->getFieldName() == field) {
  901. fieldFound = true;
  902. break;
  903. }
  904. }
  905. if (fieldFound) {
  906. if (base->getAsSymbolNode() && wasFlattened(base)) {
  907. result = flattenAccess(base, member);
  908. } else {
  909. if (base->getType().getQualifier().storage == EvqConst)
  910. result = intermediate.foldDereference(base, member, loc);
  911. else {
  912. TIntermTyped* index = intermediate.addConstantUnion(member, loc);
  913. result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
  914. result->setType(*(*fields)[member].type);
  915. }
  916. }
  917. } else
  918. error(loc, "no such field in structure", field.c_str(), "");
  919. } else
  920. error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
  921. return result;
  922. }
  923. //
  924. // Return true if the field should be treated as a built-in method.
  925. // Return false otherwise.
  926. //
  927. bool HlslParseContext::isBuiltInMethod(const TSourceLoc&, TIntermTyped* base, const TString& field)
  928. {
  929. if (base == nullptr)
  930. return false;
  931. variableCheck(base);
  932. if (base->getType().getBasicType() == EbtSampler) {
  933. return true;
  934. } else if (isStructBufferType(base->getType()) && isStructBufferMethod(field)) {
  935. return true;
  936. } else if (field == "Append" ||
  937. field == "RestartStrip") {
  938. // We cannot check the type here: it may be sanitized if we're not compiling a geometry shader, but
  939. // the code is around in the shader source.
  940. return true;
  941. } else
  942. return false;
  943. }
  944. // Independently establish a built-in that is a member of a structure.
  945. // 'arraySizes' are what's desired for the independent built-in, whatever
  946. // the higher-level source/expression of them was.
  947. void HlslParseContext::splitBuiltIn(const TString& baseName, const TType& memberType, const TArraySizes* arraySizes,
  948. const TQualifier& outerQualifier)
  949. {
  950. // Because of arrays of structs, we might be asked more than once,
  951. // but the arraySizes passed in should have captured the whole thing
  952. // the first time.
  953. // However, clip/cull rely on multiple updates.
  954. if (!isClipOrCullDistance(memberType))
  955. if (splitBuiltIns.find(tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)) !=
  956. splitBuiltIns.end())
  957. return;
  958. TVariable* ioVar = makeInternalVariable(baseName + "." + memberType.getFieldName(), memberType);
  959. if (arraySizes != nullptr && !memberType.isArray())
  960. ioVar->getWritableType().copyArraySizes(*arraySizes);
  961. splitBuiltIns[tInterstageIoData(memberType.getQualifier().builtIn, outerQualifier.storage)] = ioVar;
  962. if (!isClipOrCullDistance(ioVar->getType()))
  963. trackLinkage(*ioVar);
  964. // Merge qualifier from the user structure
  965. mergeQualifiers(ioVar->getWritableType().getQualifier(), outerQualifier);
  966. // Fix the builtin type if needed (e.g, some types require fixed array sizes, no matter how the
  967. // shader declared them). This is done after mergeQualifiers(), in case fixBuiltInIoType looks
  968. // at the qualifier to determine e.g, in or out qualifications.
  969. fixBuiltInIoType(ioVar->getWritableType());
  970. // But, not location, we're losing that
  971. ioVar->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  972. }
  973. // Split a type into
  974. // 1. a struct of non-I/O members
  975. // 2. a collection of independent I/O variables
  976. void HlslParseContext::split(const TVariable& variable)
  977. {
  978. // Create a new variable:
  979. const TType& clonedType = *variable.getType().clone();
  980. const TType& splitType = split(clonedType, variable.getName(), clonedType.getQualifier());
  981. splitNonIoVars[variable.getUniqueId()] = makeInternalVariable(variable.getName(), splitType);
  982. }
  983. // Recursive implementation of split().
  984. // Returns reference to the modified type.
  985. const TType& HlslParseContext::split(const TType& type, const TString& name, const TQualifier& outerQualifier)
  986. {
  987. if (type.isStruct()) {
  988. TTypeList* userStructure = type.getWritableStruct();
  989. for (auto ioType = userStructure->begin(); ioType != userStructure->end(); ) {
  990. if (ioType->type->isBuiltIn()) {
  991. // move out the built-in
  992. splitBuiltIn(name, *ioType->type, type.getArraySizes(), outerQualifier);
  993. ioType = userStructure->erase(ioType);
  994. } else {
  995. split(*ioType->type, name + "." + ioType->type->getFieldName(), outerQualifier);
  996. ++ioType;
  997. }
  998. }
  999. }
  1000. return type;
  1001. }
  1002. // Is this an aggregate that should be flattened?
  1003. // Can be applied to intermediate levels of type in a hierarchy.
  1004. // Some things like flattening uniform arrays are only about the top level
  1005. // of the aggregate, triggered on 'topLevel'.
  1006. bool HlslParseContext::shouldFlatten(const TType& type, TStorageQualifier qualifier, bool topLevel) const
  1007. {
  1008. switch (qualifier) {
  1009. case EvqVaryingIn:
  1010. case EvqVaryingOut:
  1011. return type.isStruct() || type.isArray();
  1012. case EvqUniform:
  1013. return (type.isArray() && intermediate.getFlattenUniformArrays() && topLevel) ||
  1014. (type.isStruct() && type.containsOpaque());
  1015. default:
  1016. return false;
  1017. };
  1018. }
  1019. // Top level variable flattening: construct data
  1020. void HlslParseContext::flatten(const TVariable& variable, bool linkage, bool arrayed)
  1021. {
  1022. const TType& type = variable.getType();
  1023. // If it's a standalone built-in, there is nothing to flatten
  1024. if (type.isBuiltIn() && !type.isStruct())
  1025. return;
  1026. auto entry = flattenMap.insert(std::make_pair(variable.getUniqueId(),
  1027. TFlattenData(type.getQualifier().layoutBinding,
  1028. type.getQualifier().layoutLocation)));
  1029. // if flattening arrayed io struct, array each member of dereferenced type
  1030. if (arrayed) {
  1031. const TType dereferencedType(type, 0);
  1032. flatten(variable, dereferencedType, entry.first->second, variable.getName(), linkage,
  1033. type.getQualifier(), type.getArraySizes());
  1034. } else {
  1035. flatten(variable, type, entry.first->second, variable.getName(), linkage,
  1036. type.getQualifier(), nullptr);
  1037. }
  1038. }
  1039. // Recursively flatten the given variable at the provided type, building the flattenData as we go.
  1040. //
  1041. // This is mutually recursive with flattenStruct and flattenArray.
  1042. // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
  1043. // members, and later on, we want to turn a path through the tree structure into a final
  1044. // location in this linear sequence.
  1045. //
  1046. // If the tree was N-ary, that can be directly calculated. However, we are dealing with
  1047. // arbitrary numbers - perhaps a struct of 7 members containing an array of 3. Thus, we must
  1048. // build a data structure to allow the sequence of bracket and dot operators on arrays and
  1049. // structs to arrive at the proper member.
  1050. //
  1051. // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
  1052. // The leaves are the indexes into the flattened member array.
  1053. // Each level will have the next location for the Nth item stored sequentially, so for instance:
  1054. //
  1055. // struct { float2 a[2]; int b; float4 c[3] };
  1056. //
  1057. // This will produce the following flattened tree:
  1058. // Pos: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  1059. // (3, 7, 8, 5, 6, 0, 1, 2, 11, 12, 13, 3, 4, 5}
  1060. //
  1061. // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
  1062. // (0+2) = 8 --> (8+1) = 12 --> 12 = 4
  1063. //
  1064. // so the 4th flattened member in traversal order is ours.
  1065. //
  1066. int HlslParseContext::flatten(const TVariable& variable, const TType& type,
  1067. TFlattenData& flattenData, TString name, bool linkage,
  1068. const TQualifier& outerQualifier,
  1069. const TArraySizes* builtInArraySizes)
  1070. {
  1071. // If something is an arrayed struct, the array flattener will recursively call flatten()
  1072. // to then flatten the struct, so this is an "if else": we don't do both.
  1073. if (type.isArray())
  1074. return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
  1075. else if (type.isStruct())
  1076. return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
  1077. else {
  1078. assert(0); // should never happen
  1079. return -1;
  1080. }
  1081. }
  1082. // Add a single flattened member to the flattened data being tracked for the composite
  1083. // Returns true for the final flattening level.
  1084. int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
  1085. const TString& memberName, bool linkage,
  1086. const TQualifier& outerQualifier,
  1087. const TArraySizes* builtInArraySizes)
  1088. {
  1089. if (!shouldFlatten(type, outerQualifier.storage, false)) {
  1090. // This is as far as we flatten. Insert the variable.
  1091. TVariable* memberVariable = makeInternalVariable(memberName, type);
  1092. mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
  1093. if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
  1094. memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
  1095. if (memberVariable->getType().isBuiltIn()) {
  1096. // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
  1097. memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  1098. } else {
  1099. // inherited locations must be auto bumped, not replicated
  1100. if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
  1101. memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
  1102. flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
  1103. nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
  1104. }
  1105. }
  1106. // Only propagate arraysizes here for arrayed io
  1107. if (variable.getType().getQualifier().isArrayedIo(language) && builtInArraySizes != nullptr)
  1108. memberVariable->getWritableType().copyArraySizes(*builtInArraySizes);
  1109. flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
  1110. flattenData.members.push_back(memberVariable);
  1111. if (linkage)
  1112. trackLinkage(*memberVariable);
  1113. return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
  1114. } else {
  1115. // Further recursion required
  1116. return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
  1117. }
  1118. }
  1119. // Figure out the mapping between an aggregate's top members and an
  1120. // equivalent set of individual variables.
  1121. //
  1122. // Assumes shouldFlatten() or equivalent was called first.
  1123. int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
  1124. TFlattenData& flattenData, TString name, bool linkage,
  1125. const TQualifier& outerQualifier,
  1126. const TArraySizes* builtInArraySizes)
  1127. {
  1128. assert(type.isStruct());
  1129. auto members = *type.getStruct();
  1130. // Reserve space for this tree level.
  1131. int start = static_cast<int>(flattenData.offsets.size());
  1132. int pos = start;
  1133. flattenData.offsets.resize(int(pos + members.size()), -1);
  1134. for (int member = 0; member < (int)members.size(); ++member) {
  1135. TType& dereferencedType = *members[member].type;
  1136. if (dereferencedType.isBuiltIn())
  1137. splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
  1138. else {
  1139. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1140. name + "." + dereferencedType.getFieldName(),
  1141. linkage, outerQualifier,
  1142. builtInArraySizes == nullptr && dereferencedType.isArray()
  1143. ? dereferencedType.getArraySizes()
  1144. : builtInArraySizes);
  1145. flattenData.offsets[pos++] = mpos;
  1146. }
  1147. }
  1148. return start;
  1149. }
  1150. // Figure out mapping between an array's members and an
  1151. // equivalent set of individual variables.
  1152. //
  1153. // Assumes shouldFlatten() or equivalent was called first.
  1154. int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
  1155. TFlattenData& flattenData, TString name, bool linkage,
  1156. const TQualifier& outerQualifier)
  1157. {
  1158. assert(type.isSizedArray());
  1159. const int size = type.getOuterArraySize();
  1160. const TType dereferencedType(type, 0);
  1161. if (name.empty())
  1162. name = variable.getName();
  1163. // Reserve space for this tree level.
  1164. int start = static_cast<int>(flattenData.offsets.size());
  1165. int pos = start;
  1166. flattenData.offsets.resize(int(pos + size), -1);
  1167. for (int element=0; element < size; ++element) {
  1168. char elementNumBuf[20]; // sufficient for MAXINT
  1169. snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
  1170. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1171. name + elementNumBuf, linkage, outerQualifier,
  1172. type.getArraySizes());
  1173. flattenData.offsets[pos++] = mpos;
  1174. }
  1175. return start;
  1176. }
  1177. // Return true if we have flattened this node.
  1178. bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
  1179. {
  1180. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1181. wasFlattened(node->getAsSymbolNode()->getId());
  1182. }
  1183. // Return true if we have split this structure
  1184. bool HlslParseContext::wasSplit(const TIntermTyped* node) const
  1185. {
  1186. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1187. wasSplit(node->getAsSymbolNode()->getId());
  1188. }
  1189. // Turn an access into an aggregate that was flattened to instead be
  1190. // an access to the individual variable the member was flattened to.
  1191. // Assumes wasFlattened() or equivalent was called first.
  1192. TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
  1193. {
  1194. const TType dereferencedType(base->getType(), member); // dereferenced type
  1195. const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
  1196. TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
  1197. dereferencedType, symbolNode.getFlattenSubset());
  1198. return flattened ? flattened : base;
  1199. }
  1200. TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
  1201. const TType& dereferencedType, int subset)
  1202. {
  1203. const auto flattenData = flattenMap.find(uniqueId);
  1204. if (flattenData == flattenMap.end())
  1205. return nullptr;
  1206. // Calculate new cumulative offset from the packed tree
  1207. int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
  1208. TIntermSymbol* subsetSymbol;
  1209. if (!shouldFlatten(dereferencedType, outerStorage, false)) {
  1210. // Finished flattening: create symbol for variable
  1211. member = flattenData->second.offsets[newSubset];
  1212. const TVariable* memberVariable = flattenData->second.members[member];
  1213. subsetSymbol = intermediate.addSymbol(*memberVariable);
  1214. subsetSymbol->setFlattenSubset(-1);
  1215. } else {
  1216. // If this is not the final flattening, accumulate the position and return
  1217. // an object of the partially dereferenced type.
  1218. subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
  1219. subsetSymbol->setFlattenSubset(newSubset);
  1220. }
  1221. return subsetSymbol;
  1222. }
  1223. // For finding where the first leaf is in a subtree of a multi-level aggregate
  1224. // that is just getting a subset assigned. Follows the same logic as flattenAccess,
  1225. // but logically going down the "left-most" tree branch each step of the way.
  1226. //
  1227. // Returns the offset into the first leaf of the subset.
  1228. int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
  1229. {
  1230. const TIntermSymbol* sym = node.getAsSymbolNode();
  1231. if (sym == nullptr)
  1232. return 0;
  1233. if (!sym->isArray() && !sym->isStruct())
  1234. return 0;
  1235. int subset = sym->getFlattenSubset();
  1236. if (subset == -1)
  1237. return 0;
  1238. // Getting this far means a partial aggregate is identified by the flatten subset.
  1239. // Find the first leaf of the subset.
  1240. const auto flattenData = flattenMap.find(sym->getId());
  1241. if (flattenData == flattenMap.end())
  1242. return 0;
  1243. return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
  1244. do {
  1245. subset = flattenData->second.offsets[subset];
  1246. } while (true);
  1247. }
  1248. // Recursively do the desent
  1249. int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
  1250. {
  1251. if (!type.isArray() && !type.isStruct())
  1252. return offsets[subset];
  1253. TType derefType(type, 0);
  1254. return findSubtreeOffset(derefType, offsets[subset], offsets);
  1255. };
  1256. // Find and return the split IO TVariable for id, or nullptr if none.
  1257. TVariable* HlslParseContext::getSplitNonIoVar(int id) const
  1258. {
  1259. const auto splitNonIoVar = splitNonIoVars.find(id);
  1260. if (splitNonIoVar == splitNonIoVars.end())
  1261. return nullptr;
  1262. return splitNonIoVar->second;
  1263. }
  1264. // Pass through to base class after remembering built-in mappings.
  1265. void HlslParseContext::trackLinkage(TSymbol& symbol)
  1266. {
  1267. TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
  1268. if (biType != EbvNone)
  1269. builtInTessLinkageSymbols[biType] = symbol.clone();
  1270. TParseContextBase::trackLinkage(symbol);
  1271. }
  1272. // Returns true if the built-in is a clip or cull distance variable.
  1273. bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
  1274. {
  1275. return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
  1276. }
  1277. // Some types require fixed array sizes in SPIR-V, but can be scalars or
  1278. // arrays of sizes SPIR-V doesn't allow. For example, tessellation factors.
  1279. // This creates the right size. A conversion is performed when the internal
  1280. // type is copied to or from the external type. This corrects the externally
  1281. // facing input or output type to abide downstream semantics.
  1282. void HlslParseContext::fixBuiltInIoType(TType& type)
  1283. {
  1284. int requiredArraySize = 0;
  1285. int requiredVectorSize = 0;
  1286. switch (type.getQualifier().builtIn) {
  1287. case EbvTessLevelOuter: requiredArraySize = 4; break;
  1288. case EbvTessLevelInner: requiredArraySize = 2; break;
  1289. case EbvSampleMask:
  1290. {
  1291. // Promote scalar to array of size 1. Leave existing arrays alone.
  1292. if (!type.isArray())
  1293. requiredArraySize = 1;
  1294. break;
  1295. }
  1296. case EbvWorkGroupId: requiredVectorSize = 3; break;
  1297. case EbvGlobalInvocationId: requiredVectorSize = 3; break;
  1298. case EbvLocalInvocationId: requiredVectorSize = 3; break;
  1299. case EbvTessCoord: requiredVectorSize = 3; break;
  1300. default:
  1301. if (isClipOrCullDistance(type)) {
  1302. const int loc = type.getQualifier().layoutLocation;
  1303. if (type.getQualifier().builtIn == EbvClipDistance) {
  1304. if (type.getQualifier().storage == EvqVaryingIn)
  1305. clipSemanticNSizeIn[loc] = type.getVectorSize();
  1306. else
  1307. clipSemanticNSizeOut[loc] = type.getVectorSize();
  1308. } else {
  1309. if (type.getQualifier().storage == EvqVaryingIn)
  1310. cullSemanticNSizeIn[loc] = type.getVectorSize();
  1311. else
  1312. cullSemanticNSizeOut[loc] = type.getVectorSize();
  1313. }
  1314. }
  1315. return;
  1316. }
  1317. // Alter or set vector size as needed.
  1318. if (requiredVectorSize > 0) {
  1319. TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
  1320. newType.getQualifier() = type.getQualifier();
  1321. type.shallowCopy(newType);
  1322. }
  1323. // Alter or set array size as needed.
  1324. if (requiredArraySize > 0) {
  1325. if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
  1326. TArraySizes* arraySizes = new TArraySizes;
  1327. arraySizes->addInnerSize(requiredArraySize);
  1328. type.transferArraySizes(arraySizes);
  1329. }
  1330. }
  1331. }
  1332. // Variables that correspond to the user-interface in and out of a stage
  1333. // (not the built-in interface) are
  1334. // - assigned locations
  1335. // - registered as a linkage node (part of the stage's external interface).
  1336. // Assumes it is called in the order in which locations should be assigned.
  1337. void HlslParseContext::assignToInterface(TVariable& variable)
  1338. {
  1339. const auto assignLocation = [&](TVariable& variable) {
  1340. TType& type = variable.getWritableType();
  1341. if (!type.isStruct() || type.getStruct()->size() > 0) {
  1342. TQualifier& qualifier = type.getQualifier();
  1343. if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
  1344. if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
  1345. // Strip off the outer array dimension for those having an extra one.
  1346. int size;
  1347. if (type.isArray() && qualifier.isArrayedIo(language)) {
  1348. TType elementType(type, 0);
  1349. size = intermediate.computeTypeLocationSize(elementType, language);
  1350. } else
  1351. size = intermediate.computeTypeLocationSize(type, language);
  1352. if (qualifier.storage == EvqVaryingIn) {
  1353. variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
  1354. nextInLocation += size;
  1355. } else {
  1356. variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
  1357. nextOutLocation += size;
  1358. }
  1359. }
  1360. trackLinkage(variable);
  1361. }
  1362. }
  1363. };
  1364. if (wasFlattened(variable.getUniqueId())) {
  1365. auto& memberList = flattenMap[variable.getUniqueId()].members;
  1366. for (auto member = memberList.begin(); member != memberList.end(); ++member)
  1367. assignLocation(**member);
  1368. } else if (wasSplit(variable.getUniqueId())) {
  1369. TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
  1370. assignLocation(*splitIoVar);
  1371. } else {
  1372. assignLocation(variable);
  1373. }
  1374. }
  1375. //
  1376. // Handle seeing a function declarator in the grammar. This is the precursor
  1377. // to recognizing a function prototype or function definition.
  1378. //
  1379. void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
  1380. {
  1381. //
  1382. // Multiple declarations of the same function name are allowed.
  1383. //
  1384. // If this is a definition, the definition production code will check for redefinitions
  1385. // (we don't know at this point if it's a definition or not).
  1386. //
  1387. bool builtIn;
  1388. TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
  1389. const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
  1390. if (prototype) {
  1391. // All built-in functions are defined, even though they don't have a body.
  1392. // Count their prototype as a definition instead.
  1393. if (symbolTable.atBuiltInLevel())
  1394. function.setDefined();
  1395. else {
  1396. if (prevDec && ! builtIn)
  1397. symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
  1398. function.setPrototyped();
  1399. }
  1400. }
  1401. // This insert won't actually insert it if it's a duplicate signature, but it will still check for
  1402. // other forms of name collisions.
  1403. if (! symbolTable.insert(function))
  1404. error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
  1405. }
  1406. // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
  1407. // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
  1408. // Otherwise, it's a no-op
  1409. void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
  1410. TIntermAggregate*& paramNodes)
  1411. {
  1412. if (! hasStructBuffCounter(*param.type))
  1413. return;
  1414. const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
  1415. TType counterType;
  1416. counterBufferType(loc, counterType);
  1417. TVariable *variable = makeInternalVariable(counterBlockName, counterType);
  1418. if (! symbolTable.insert(*variable))
  1419. error(loc, "redefinition", variable->getName().c_str(), "");
  1420. paramNodes = intermediate.growAggregate(paramNodes,
  1421. intermediate.addSymbol(*variable, loc),
  1422. loc);
  1423. }
  1424. //
  1425. // Handle seeing the function prototype in front of a function definition in the grammar.
  1426. // The body is handled after this function returns.
  1427. //
  1428. // Returns an aggregate of parameter-symbol nodes.
  1429. //
  1430. TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
  1431. const TAttributes& attributes,
  1432. TIntermNode*& entryPointTree)
  1433. {
  1434. currentCaller = function.getMangledName();
  1435. TSymbol* symbol = symbolTable.find(function.getMangledName());
  1436. TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
  1437. if (prevDec == nullptr)
  1438. error(loc, "can't find function", function.getName().c_str(), "");
  1439. // Note: 'prevDec' could be 'function' if this is the first time we've seen function
  1440. // as it would have just been put in the symbol table. Otherwise, we're looking up
  1441. // an earlier occurrence.
  1442. if (prevDec && prevDec->isDefined()) {
  1443. // Then this function already has a body.
  1444. error(loc, "function already has a body", function.getName().c_str(), "");
  1445. }
  1446. if (prevDec && ! prevDec->isDefined()) {
  1447. prevDec->setDefined();
  1448. // Remember the return type for later checking for RETURN statements.
  1449. currentFunctionType = &(prevDec->getType());
  1450. } else
  1451. currentFunctionType = new TType(EbtVoid);
  1452. functionReturnsValue = false;
  1453. // Entry points need different I/O and other handling, transform it so the
  1454. // rest of this function doesn't care.
  1455. entryPointTree = transformEntryPoint(loc, function, attributes);
  1456. //
  1457. // New symbol table scope for body of function plus its arguments
  1458. //
  1459. pushScope();
  1460. //
  1461. // Insert parameters into the symbol table.
  1462. // If the parameter has no name, it's not an error, just don't insert it
  1463. // (could be used for unused args).
  1464. //
  1465. // Also, accumulate the list of parameters into the AST, so lower level code
  1466. // knows where to find parameters.
  1467. //
  1468. TIntermAggregate* paramNodes = new TIntermAggregate;
  1469. for (int i = 0; i < function.getParamCount(); i++) {
  1470. TParameter& param = function[i];
  1471. if (param.name != nullptr) {
  1472. TVariable *variable = new TVariable(param.name, *param.type);
  1473. if (i == 0 && function.hasImplicitThis()) {
  1474. // Anonymous 'this' members are already in a symbol-table level,
  1475. // and we need to know what function parameter to map them to.
  1476. symbolTable.makeInternalVariable(*variable);
  1477. pushImplicitThis(variable);
  1478. }
  1479. // Insert the parameters with name in the symbol table.
  1480. if (! symbolTable.insert(*variable))
  1481. error(loc, "redefinition", variable->getName().c_str(), "");
  1482. // Add parameters to the AST list.
  1483. if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
  1484. // Expand the AST parameter nodes (but not the name mangling or symbol table view)
  1485. // for structures that need to be flattened.
  1486. flatten(*variable, false);
  1487. const TTypeList* structure = variable->getType().getStruct();
  1488. for (int mem = 0; mem < (int)structure->size(); ++mem) {
  1489. paramNodes = intermediate.growAggregate(paramNodes,
  1490. flattenAccess(variable->getUniqueId(), mem,
  1491. variable->getType().getQualifier().storage,
  1492. *(*structure)[mem].type),
  1493. loc);
  1494. }
  1495. } else {
  1496. // Add the parameter to the AST
  1497. paramNodes = intermediate.growAggregate(paramNodes,
  1498. intermediate.addSymbol(*variable, loc),
  1499. loc);
  1500. }
  1501. // Add hidden AST parameter for struct buffer counters, if needed.
  1502. addStructBufferHiddenCounterParam(loc, param, paramNodes);
  1503. } else
  1504. paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
  1505. }
  1506. if (function.hasIllegalImplicitThis())
  1507. pushImplicitThis(nullptr);
  1508. intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
  1509. loopNestingLevel = 0;
  1510. controlFlowNestingLevel = 0;
  1511. postEntryPointReturn = false;
  1512. return paramNodes;
  1513. }
  1514. // Handle all [attrib] attribute for the shader entry point
  1515. void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
  1516. {
  1517. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1518. switch (it->name) {
  1519. case EatNumThreads:
  1520. {
  1521. const TIntermSequence& sequence = it->args->getSequence();
  1522. for (int lid = 0; lid < int(sequence.size()); ++lid)
  1523. intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
  1524. break;
  1525. }
  1526. case EatMaxVertexCount:
  1527. {
  1528. int maxVertexCount;
  1529. if (! it->getInt(maxVertexCount)) {
  1530. error(loc, "invalid maxvertexcount", "", "");
  1531. } else {
  1532. if (! intermediate.setVertices(maxVertexCount))
  1533. error(loc, "cannot change previously set maxvertexcount attribute", "", "");
  1534. }
  1535. break;
  1536. }
  1537. case EatPatchConstantFunc:
  1538. {
  1539. TString pcfName;
  1540. if (! it->getString(pcfName, 0, false)) {
  1541. error(loc, "invalid patch constant function", "", "");
  1542. } else {
  1543. patchConstantFunctionName = pcfName;
  1544. }
  1545. break;
  1546. }
  1547. case EatDomain:
  1548. {
  1549. // Handle [domain("...")]
  1550. TString domainStr;
  1551. if (! it->getString(domainStr)) {
  1552. error(loc, "invalid domain", "", "");
  1553. } else {
  1554. TLayoutGeometry domain = ElgNone;
  1555. if (domainStr == "tri") {
  1556. domain = ElgTriangles;
  1557. } else if (domainStr == "quad") {
  1558. domain = ElgQuads;
  1559. } else if (domainStr == "isoline") {
  1560. domain = ElgIsolines;
  1561. } else {
  1562. error(loc, "unsupported domain type", domainStr.c_str(), "");
  1563. }
  1564. if (language == EShLangTessEvaluation) {
  1565. if (! intermediate.setInputPrimitive(domain))
  1566. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1567. } else {
  1568. if (! intermediate.setOutputPrimitive(domain))
  1569. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1570. }
  1571. }
  1572. break;
  1573. }
  1574. case EatOutputTopology:
  1575. {
  1576. // Handle [outputtopology("...")]
  1577. TString topologyStr;
  1578. if (! it->getString(topologyStr)) {
  1579. error(loc, "invalid outputtopology", "", "");
  1580. } else {
  1581. TVertexOrder vertexOrder = EvoNone;
  1582. TLayoutGeometry primitive = ElgNone;
  1583. if (topologyStr == "point") {
  1584. intermediate.setPointMode();
  1585. } else if (topologyStr == "line") {
  1586. primitive = ElgIsolines;
  1587. } else if (topologyStr == "triangle_cw") {
  1588. vertexOrder = EvoCw;
  1589. primitive = ElgTriangles;
  1590. } else if (topologyStr == "triangle_ccw") {
  1591. vertexOrder = EvoCcw;
  1592. primitive = ElgTriangles;
  1593. } else {
  1594. error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
  1595. }
  1596. if (vertexOrder != EvoNone) {
  1597. if (! intermediate.setVertexOrder(vertexOrder)) {
  1598. error(loc, "cannot change previously set outputtopology",
  1599. TQualifier::getVertexOrderString(vertexOrder), "");
  1600. }
  1601. }
  1602. if (primitive != ElgNone)
  1603. intermediate.setOutputPrimitive(primitive);
  1604. }
  1605. break;
  1606. }
  1607. case EatPartitioning:
  1608. {
  1609. // Handle [partitioning("...")]
  1610. TString partitionStr;
  1611. if (! it->getString(partitionStr)) {
  1612. error(loc, "invalid partitioning", "", "");
  1613. } else {
  1614. TVertexSpacing partitioning = EvsNone;
  1615. if (partitionStr == "integer") {
  1616. partitioning = EvsEqual;
  1617. } else if (partitionStr == "fractional_even") {
  1618. partitioning = EvsFractionalEven;
  1619. } else if (partitionStr == "fractional_odd") {
  1620. partitioning = EvsFractionalOdd;
  1621. //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
  1622. } else {
  1623. error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
  1624. }
  1625. if (! intermediate.setVertexSpacing(partitioning))
  1626. error(loc, "cannot change previously set partitioning",
  1627. TQualifier::getVertexSpacingString(partitioning), "");
  1628. }
  1629. break;
  1630. }
  1631. case EatOutputControlPoints:
  1632. {
  1633. // Handle [outputcontrolpoints("...")]
  1634. int ctrlPoints;
  1635. if (! it->getInt(ctrlPoints)) {
  1636. error(loc, "invalid outputcontrolpoints", "", "");
  1637. } else {
  1638. if (! intermediate.setVertices(ctrlPoints)) {
  1639. error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
  1640. }
  1641. }
  1642. break;
  1643. }
  1644. case EatEarlyDepthStencil:
  1645. intermediate.setEarlyFragmentTests();
  1646. break;
  1647. case EatBuiltIn:
  1648. case EatLocation:
  1649. // tolerate these because of dual use of entrypoint and type attributes
  1650. break;
  1651. default:
  1652. warn(loc, "attribute does not apply to entry point", "", "");
  1653. break;
  1654. }
  1655. }
  1656. }
  1657. // Update the given type with any type-like attribute information in the
  1658. // attributes.
  1659. void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
  1660. bool allowEntry)
  1661. {
  1662. if (attributes.size() == 0)
  1663. return;
  1664. int value;
  1665. TString builtInString;
  1666. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1667. switch (it->name) {
  1668. case EatLocation:
  1669. // location
  1670. if (it->getInt(value))
  1671. type.getQualifier().layoutLocation = value;
  1672. else
  1673. error(loc, "needs a literal integer", "location", "");
  1674. break;
  1675. case EatBinding:
  1676. // binding
  1677. if (it->getInt(value)) {
  1678. type.getQualifier().layoutBinding = value;
  1679. type.getQualifier().layoutSet = 0;
  1680. } else
  1681. error(loc, "needs a literal integer", "binding", "");
  1682. // set
  1683. if (it->getInt(value, 1))
  1684. type.getQualifier().layoutSet = value;
  1685. break;
  1686. case EatGlobalBinding:
  1687. // global cbuffer binding
  1688. if (it->getInt(value))
  1689. globalUniformBinding = value;
  1690. else
  1691. error(loc, "needs a literal integer", "global binding", "");
  1692. // global cbuffer set
  1693. if (it->getInt(value, 1))
  1694. globalUniformSet = value;
  1695. break;
  1696. case EatInputAttachment:
  1697. // input attachment
  1698. if (it->getInt(value))
  1699. type.getQualifier().layoutAttachment = value;
  1700. else
  1701. error(loc, "needs a literal integer", "input attachment", "");
  1702. break;
  1703. case EatBuiltIn:
  1704. // PointSize built-in
  1705. if (it->getString(builtInString, 0, false)) {
  1706. if (builtInString == "PointSize")
  1707. type.getQualifier().builtIn = EbvPointSize;
  1708. }
  1709. break;
  1710. case EatPushConstant:
  1711. // push_constant
  1712. type.getQualifier().layoutPushConstant = true;
  1713. break;
  1714. case EatConstantId:
  1715. // specialization constant
  1716. if (type.getQualifier().storage != EvqConst) {
  1717. error(loc, "needs a const type", "constant_id", "");
  1718. break;
  1719. }
  1720. if (it->getInt(value)) {
  1721. TSourceLoc loc;
  1722. loc.init();
  1723. setSpecConstantId(loc, type.getQualifier(), value);
  1724. }
  1725. break;
  1726. // image formats
  1727. case EatFormatRgba32f: type.getQualifier().layoutFormat = ElfRgba32f; break;
  1728. case EatFormatRgba16f: type.getQualifier().layoutFormat = ElfRgba16f; break;
  1729. case EatFormatR32f: type.getQualifier().layoutFormat = ElfR32f; break;
  1730. case EatFormatRgba8: type.getQualifier().layoutFormat = ElfRgba8; break;
  1731. case EatFormatRgba8Snorm: type.getQualifier().layoutFormat = ElfRgba8Snorm; break;
  1732. case EatFormatRg32f: type.getQualifier().layoutFormat = ElfRg32f; break;
  1733. case EatFormatRg16f: type.getQualifier().layoutFormat = ElfRg16f; break;
  1734. case EatFormatR11fG11fB10f: type.getQualifier().layoutFormat = ElfR11fG11fB10f; break;
  1735. case EatFormatR16f: type.getQualifier().layoutFormat = ElfR16f; break;
  1736. case EatFormatRgba16: type.getQualifier().layoutFormat = ElfRgba16; break;
  1737. case EatFormatRgb10A2: type.getQualifier().layoutFormat = ElfRgb10A2; break;
  1738. case EatFormatRg16: type.getQualifier().layoutFormat = ElfRg16; break;
  1739. case EatFormatRg8: type.getQualifier().layoutFormat = ElfRg8; break;
  1740. case EatFormatR16: type.getQualifier().layoutFormat = ElfR16; break;
  1741. case EatFormatR8: type.getQualifier().layoutFormat = ElfR8; break;
  1742. case EatFormatRgba16Snorm: type.getQualifier().layoutFormat = ElfRgba16Snorm; break;
  1743. case EatFormatRg16Snorm: type.getQualifier().layoutFormat = ElfRg16Snorm; break;
  1744. case EatFormatRg8Snorm: type.getQualifier().layoutFormat = ElfRg8Snorm; break;
  1745. case EatFormatR16Snorm: type.getQualifier().layoutFormat = ElfR16Snorm; break;
  1746. case EatFormatR8Snorm: type.getQualifier().layoutFormat = ElfR8Snorm; break;
  1747. case EatFormatRgba32i: type.getQualifier().layoutFormat = ElfRgba32i; break;
  1748. case EatFormatRgba16i: type.getQualifier().layoutFormat = ElfRgba16i; break;
  1749. case EatFormatRgba8i: type.getQualifier().layoutFormat = ElfRgba8i; break;
  1750. case EatFormatR32i: type.getQualifier().layoutFormat = ElfR32i; break;
  1751. case EatFormatRg32i: type.getQualifier().layoutFormat = ElfRg32i; break;
  1752. case EatFormatRg16i: type.getQualifier().layoutFormat = ElfRg16i; break;
  1753. case EatFormatRg8i: type.getQualifier().layoutFormat = ElfRg8i; break;
  1754. case EatFormatR16i: type.getQualifier().layoutFormat = ElfR16i; break;
  1755. case EatFormatR8i: type.getQualifier().layoutFormat = ElfR8i; break;
  1756. case EatFormatRgba32ui: type.getQualifier().layoutFormat = ElfRgba32ui; break;
  1757. case EatFormatRgba16ui: type.getQualifier().layoutFormat = ElfRgba16ui; break;
  1758. case EatFormatRgba8ui: type.getQualifier().layoutFormat = ElfRgba8ui; break;
  1759. case EatFormatR32ui: type.getQualifier().layoutFormat = ElfR32ui; break;
  1760. case EatFormatRgb10a2ui: type.getQualifier().layoutFormat = ElfRgb10a2ui; break;
  1761. case EatFormatRg32ui: type.getQualifier().layoutFormat = ElfRg32ui; break;
  1762. case EatFormatRg16ui: type.getQualifier().layoutFormat = ElfRg16ui; break;
  1763. case EatFormatRg8ui: type.getQualifier().layoutFormat = ElfRg8ui; break;
  1764. case EatFormatR16ui: type.getQualifier().layoutFormat = ElfR16ui; break;
  1765. case EatFormatR8ui: type.getQualifier().layoutFormat = ElfR8ui; break;
  1766. case EatFormatUnknown: type.getQualifier().layoutFormat = ElfNone; break;
  1767. case EatNonWritable: type.getQualifier().readonly = true; break;
  1768. case EatNonReadable: type.getQualifier().writeonly = true; break;
  1769. default:
  1770. if (! allowEntry)
  1771. warn(loc, "attribute does not apply to a type", "", "");
  1772. break;
  1773. }
  1774. }
  1775. }
  1776. //
  1777. // Do all special handling for the entry point, including wrapping
  1778. // the shader's entry point with the official entry point that will call it.
  1779. //
  1780. // The following:
  1781. //
  1782. // retType shaderEntryPoint(args...) // shader declared entry point
  1783. // { body }
  1784. //
  1785. // Becomes
  1786. //
  1787. // out retType ret;
  1788. // in iargs<that are input>...;
  1789. // out oargs<that are output> ...;
  1790. //
  1791. // void shaderEntryPoint() // synthesized, but official, entry point
  1792. // {
  1793. // args<that are input> = iargs...;
  1794. // ret = @shaderEntryPoint(args...);
  1795. // oargs = args<that are output>...;
  1796. // }
  1797. // retType @shaderEntryPoint(args...)
  1798. // { body }
  1799. //
  1800. // The symbol table will still map the original entry point name to the
  1801. // the modified function and its new name:
  1802. //
  1803. // symbol table: shaderEntryPoint -> @shaderEntryPoint
  1804. //
  1805. // Returns nullptr if no entry-point tree was built, otherwise, returns
  1806. // a subtree that creates the entry point.
  1807. //
  1808. TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
  1809. const TAttributes& attributes)
  1810. {
  1811. // Return true if this is a tessellation patch constant function input to a domain shader.
  1812. const auto isDsPcfInput = [this](const TType& type) {
  1813. return language == EShLangTessEvaluation &&
  1814. type.contains([](const TType* t) {
  1815. return t->getQualifier().builtIn == EbvTessLevelOuter ||
  1816. t->getQualifier().builtIn == EbvTessLevelInner;
  1817. });
  1818. };
  1819. // if we aren't in the entry point, fix the IO as such and exit
  1820. if (! isEntrypointName(userFunction.getName())) {
  1821. remapNonEntryPointIO(userFunction);
  1822. return nullptr;
  1823. }
  1824. entryPointFunction = &userFunction; // needed in finish()
  1825. // Handle entry point attributes
  1826. handleEntryPointAttributes(loc, attributes);
  1827. // entry point logic...
  1828. // Move parameters and return value to shader in/out
  1829. TVariable* entryPointOutput; // gets created in remapEntryPointIO
  1830. TVector<TVariable*> inputs;
  1831. TVector<TVariable*> outputs;
  1832. remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
  1833. // Further this return/in/out transform by flattening, splitting, and assigning locations
  1834. const auto makeVariableInOut = [&](TVariable& variable) {
  1835. if (variable.getType().isStruct()) {
  1836. bool arrayed = variable.getType().getQualifier().isArrayedIo(language);
  1837. flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */, arrayed);
  1838. }
  1839. // TODO: flatten arrays too
  1840. // TODO: flatten everything in I/O
  1841. // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
  1842. // For clip and cull distance, multiple output variables potentially get merged
  1843. // into one in assignClipCullDistance. That code in assignClipCullDistance
  1844. // handles the interface logic, so we avoid it here in that case.
  1845. if (!isClipOrCullDistance(variable.getType()))
  1846. assignToInterface(variable);
  1847. };
  1848. if (entryPointOutput != nullptr)
  1849. makeVariableInOut(*entryPointOutput);
  1850. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1851. if (!isDsPcfInput((*it)->getType())) // wait until the end for PCF input (see comment below)
  1852. makeVariableInOut(*(*it));
  1853. for (auto it = outputs.begin(); it != outputs.end(); ++it)
  1854. makeVariableInOut(*(*it));
  1855. // In the domain shader, PCF input must be at the end of the linkage. That's because in the
  1856. // hull shader there is no ordering: the output comes from the separate PCF, which does not
  1857. // participate in the argument list. That is always put at the end of the HS linkage, so the
  1858. // input side of the DS must match. The argument may be in any position in the DS argument list
  1859. // however, so this ensures the linkage is built in the correct order regardless of argument order.
  1860. if (language == EShLangTessEvaluation) {
  1861. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1862. if (isDsPcfInput((*it)->getType()))
  1863. makeVariableInOut(*(*it));
  1864. }
  1865. // Add uniform parameters to the $Global uniform block.
  1866. TVector<TVariable*> opaque_uniforms;
  1867. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1868. TType& paramType = *userFunction[i].type;
  1869. TString& paramName = *userFunction[i].name;
  1870. if (paramType.getQualifier().storage == EvqUniform) {
  1871. if (!paramType.containsOpaque()) {
  1872. // Add it to the global uniform block.
  1873. growGlobalUniformBlock(loc, paramType, paramName);
  1874. } else {
  1875. // Declare it as a separate variable.
  1876. TVariable *var = makeInternalVariable(paramName.c_str(), paramType);
  1877. opaque_uniforms.push_back(var);
  1878. }
  1879. }
  1880. }
  1881. // Synthesize the call
  1882. pushScope(); // matches the one in handleFunctionBody()
  1883. // new signature
  1884. TType voidType(EbtVoid);
  1885. TFunction synthEntryPoint(&userFunction.getName(), voidType);
  1886. TIntermAggregate* synthParams = new TIntermAggregate();
  1887. intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
  1888. intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
  1889. intermediate.incrementEntryPointCount();
  1890. TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
  1891. // change original name
  1892. userFunction.addPrefix("@"); // change the name in the function, but not in the symbol table
  1893. // Copy inputs (shader-in -> calling arg), while building up the call node
  1894. TVector<TVariable*> argVars;
  1895. TIntermAggregate* synthBody = new TIntermAggregate();
  1896. auto inputIt = inputs.begin();
  1897. auto opaqueUniformIt = opaque_uniforms.begin();
  1898. TIntermTyped* callingArgs = nullptr;
  1899. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1900. TParameter& param = userFunction[i];
  1901. argVars.push_back(makeInternalVariable(*param.name, *param.type));
  1902. argVars.back()->getWritableType().getQualifier().makeTemporary();
  1903. // Track the input patch, which is the only non-builtin supported by hull shader PCF.
  1904. if (param.getDeclaredBuiltIn() == EbvInputPatch)
  1905. inputPatch = argVars.back();
  1906. TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
  1907. handleFunctionArgument(&callee, callingArgs, arg);
  1908. if (param.type->getQualifier().isParamInput()) {
  1909. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
  1910. intermediate.addSymbol(**inputIt)));
  1911. inputIt++;
  1912. }
  1913. if (param.type->getQualifier().storage == EvqUniform) {
  1914. if (!param.type->containsOpaque()) {
  1915. // Look it up in the $Global uniform block.
  1916. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
  1917. handleVariable(loc, param.name)));
  1918. } else {
  1919. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
  1920. intermediate.addSymbol(**opaqueUniformIt)));
  1921. ++opaqueUniformIt;
  1922. }
  1923. }
  1924. }
  1925. // Call
  1926. currentCaller = synthEntryPoint.getMangledName();
  1927. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  1928. currentCaller = userFunction.getMangledName();
  1929. // Return value
  1930. if (entryPointOutput) {
  1931. TIntermTyped* returnAssign;
  1932. // For hull shaders, the wrapped entry point return value is written to
  1933. // an array element as indexed by invocation ID, which we might have to make up.
  1934. // This is required to match SPIR-V semantics.
  1935. if (language == EShLangTessControl) {
  1936. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  1937. // If there is no user declared invocation ID, we must make one.
  1938. if (invocationIdSym == nullptr) {
  1939. TType invocationIdType(EbtUint, EvqIn, 1);
  1940. TString* invocationIdName = NewPoolTString("InvocationId");
  1941. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  1942. TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
  1943. globalQualifierFix(loc, variable->getWritableType().getQualifier());
  1944. trackLinkage(*variable);
  1945. invocationIdSym = intermediate.addSymbol(*variable);
  1946. }
  1947. TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
  1948. invocationIdSym, loc);
  1949. // Set the type of the array element being dereferenced
  1950. const TType derefElementType(entryPointOutput->getType(), 0);
  1951. element->setType(derefElementType);
  1952. returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
  1953. } else {
  1954. returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
  1955. }
  1956. intermediate.growAggregate(synthBody, returnAssign);
  1957. } else
  1958. intermediate.growAggregate(synthBody, callReturn);
  1959. // Output copies
  1960. auto outputIt = outputs.begin();
  1961. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1962. TParameter& param = userFunction[i];
  1963. // GS outputs are via emit, so we do not copy them here.
  1964. if (param.type->getQualifier().isParamOutput()) {
  1965. if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
  1966. // GS output stream does not assign outputs here: it's the Append() method
  1967. // which writes to the output, probably multiple times separated by Emit.
  1968. // We merely remember the output to use, here.
  1969. gsStreamOutput = *outputIt;
  1970. } else {
  1971. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
  1972. intermediate.addSymbol(**outputIt),
  1973. intermediate.addSymbol(*argVars[i])));
  1974. }
  1975. outputIt++;
  1976. }
  1977. }
  1978. // Put the pieces together to form a full function subtree
  1979. // for the synthesized entry point.
  1980. synthBody->setOperator(EOpSequence);
  1981. TIntermNode* synthFunctionDef = synthParams;
  1982. handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
  1983. entryPointFunctionBody = synthBody;
  1984. return synthFunctionDef;
  1985. }
  1986. void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
  1987. TIntermNode*& node)
  1988. {
  1989. node = intermediate.growAggregate(node, functionBody);
  1990. intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
  1991. node->getAsAggregate()->setName(function.getMangledName().c_str());
  1992. popScope();
  1993. if (function.hasImplicitThis())
  1994. popImplicitThis();
  1995. if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
  1996. error(loc, "function does not return a value:", "", function.getName().c_str());
  1997. }
  1998. // AST I/O is done through shader globals declared in the 'in' or 'out'
  1999. // storage class. An HLSL entry point has a return value, input parameters
  2000. // and output parameters. These need to get remapped to the AST I/O.
  2001. void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
  2002. TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
  2003. {
  2004. // We might have in input structure type with no decorations that caused it
  2005. // to look like an input type, yet it has (e.g.) interpolation types that
  2006. // must be modified that turn it into an input type.
  2007. // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
  2008. const auto synthesizeEditedInput = [this](TType& type) {
  2009. // True if a type needs to be 'flat'
  2010. const auto needsFlat = [](const TType& type) {
  2011. return type.containsBasicType(EbtInt) ||
  2012. type.containsBasicType(EbtUint) ||
  2013. type.containsBasicType(EbtInt64) ||
  2014. type.containsBasicType(EbtUint64) ||
  2015. type.containsBasicType(EbtBool) ||
  2016. type.containsBasicType(EbtDouble);
  2017. };
  2018. if (language == EShLangFragment && needsFlat(type)) {
  2019. if (type.isStruct()) {
  2020. TTypeList* finalList = nullptr;
  2021. auto it = ioTypeMap.find(type.getStruct());
  2022. if (it == ioTypeMap.end() || it->second.input == nullptr) {
  2023. // Getting here means we have no input struct, but we need one.
  2024. auto list = new TTypeList;
  2025. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  2026. TType* newType = new TType;
  2027. newType->shallowCopy(*member->type);
  2028. TTypeLoc typeLoc = { newType, member->loc };
  2029. list->push_back(typeLoc);
  2030. }
  2031. // install the new input type
  2032. if (it == ioTypeMap.end()) {
  2033. tIoKinds newLists = { list, nullptr, nullptr };
  2034. ioTypeMap[type.getStruct()] = newLists;
  2035. } else
  2036. it->second.input = list;
  2037. finalList = list;
  2038. } else
  2039. finalList = it->second.input;
  2040. // edit for 'flat'
  2041. for (auto member = finalList->begin(); member != finalList->end(); ++member) {
  2042. if (needsFlat(*member->type)) {
  2043. member->type->getQualifier().clearInterpolation();
  2044. member->type->getQualifier().flat = true;
  2045. }
  2046. }
  2047. } else {
  2048. type.getQualifier().clearInterpolation();
  2049. type.getQualifier().flat = true;
  2050. }
  2051. }
  2052. };
  2053. // Do the actual work to make a type be a shader input or output variable,
  2054. // and clear the original to be non-IO (for use as a normal function parameter/return).
  2055. const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
  2056. TVariable* ioVariable = makeInternalVariable(name, type);
  2057. clearUniformInputOutput(type.getQualifier());
  2058. if (type.isStruct()) {
  2059. auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
  2060. if (newLists != ioTypeMap.end()) {
  2061. if (storage == EvqVaryingIn && newLists->second.input)
  2062. ioVariable->getWritableType().setStruct(newLists->second.input);
  2063. else if (storage == EvqVaryingOut && newLists->second.output)
  2064. ioVariable->getWritableType().setStruct(newLists->second.output);
  2065. }
  2066. }
  2067. if (storage == EvqVaryingIn) {
  2068. correctInput(ioVariable->getWritableType().getQualifier());
  2069. if (language == EShLangTessEvaluation)
  2070. if (!ioVariable->getType().isArray())
  2071. ioVariable->getWritableType().getQualifier().patch = true;
  2072. } else {
  2073. correctOutput(ioVariable->getWritableType().getQualifier());
  2074. }
  2075. ioVariable->getWritableType().getQualifier().storage = storage;
  2076. fixBuiltInIoType(ioVariable->getWritableType());
  2077. return ioVariable;
  2078. };
  2079. // return value is actually a shader-scoped output (out)
  2080. if (function.getType().getBasicType() == EbtVoid) {
  2081. returnValue = nullptr;
  2082. } else {
  2083. if (language == EShLangTessControl) {
  2084. // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
  2085. // array in SPIR-V semantics. We'll write to it indexed by invocation ID.
  2086. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2087. TType outputType;
  2088. outputType.shallowCopy(function.getType());
  2089. // vertices has necessarily already been set when handling entry point attributes.
  2090. TArraySizes* arraySizes = new TArraySizes;
  2091. arraySizes->addInnerSize(intermediate.getVertices());
  2092. outputType.transferArraySizes(arraySizes);
  2093. clearUniformInputOutput(function.getWritableType().getQualifier());
  2094. returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
  2095. } else {
  2096. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2097. }
  2098. }
  2099. // parameters are actually shader-scoped inputs and outputs (in or out)
  2100. for (int i = 0; i < function.getParamCount(); i++) {
  2101. TType& paramType = *function[i].type;
  2102. if (paramType.getQualifier().isParamInput()) {
  2103. synthesizeEditedInput(paramType);
  2104. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
  2105. inputs.push_back(argAsGlobal);
  2106. }
  2107. if (paramType.getQualifier().isParamOutput()) {
  2108. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
  2109. outputs.push_back(argAsGlobal);
  2110. }
  2111. }
  2112. }
  2113. // An HLSL function that looks like an entry point, but is not,
  2114. // declares entry point IO built-ins, but these have to be undone.
  2115. void HlslParseContext::remapNonEntryPointIO(TFunction& function)
  2116. {
  2117. // return value
  2118. if (function.getType().getBasicType() != EbtVoid)
  2119. clearUniformInputOutput(function.getWritableType().getQualifier());
  2120. // parameters.
  2121. // References to structuredbuffer types are left unmodified
  2122. for (int i = 0; i < function.getParamCount(); i++)
  2123. if (!isReference(*function[i].type))
  2124. clearUniformInputOutput(function[i].type->getQualifier());
  2125. }
  2126. // Handle function returns, including type conversions to the function return type
  2127. // if necessary.
  2128. TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
  2129. {
  2130. functionReturnsValue = true;
  2131. if (currentFunctionType->getBasicType() == EbtVoid) {
  2132. error(loc, "void function cannot return a value", "return", "");
  2133. return intermediate.addBranch(EOpReturn, loc);
  2134. } else if (*currentFunctionType != value->getType()) {
  2135. value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
  2136. if (value && *currentFunctionType != value->getType())
  2137. value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
  2138. if (value == nullptr || *currentFunctionType != value->getType()) {
  2139. error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
  2140. return value;
  2141. }
  2142. }
  2143. return intermediate.addBranch(EOpReturn, value, loc);
  2144. }
  2145. void HlslParseContext::handleFunctionArgument(TFunction* function,
  2146. TIntermTyped*& arguments, TIntermTyped* newArg)
  2147. {
  2148. TParameter param = { 0, new TType, nullptr };
  2149. param.type->shallowCopy(newArg->getType());
  2150. function->addParameter(param);
  2151. if (arguments)
  2152. arguments = intermediate.growAggregate(arguments, newArg);
  2153. else
  2154. arguments = newArg;
  2155. }
  2156. // Position may require special handling: we can optionally invert Y.
  2157. // See: https://github.com/KhronosGroup/glslang/issues/1173
  2158. // https://github.com/KhronosGroup/glslang/issues/494
  2159. TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
  2160. TIntermTyped* left, TIntermTyped* right)
  2161. {
  2162. // If we are not asked for Y inversion, use a plain old assign.
  2163. if (!intermediate.getInvertY())
  2164. return intermediate.addAssign(op, left, right, loc);
  2165. // If we get here, we should invert Y.
  2166. TIntermAggregate* assignList = nullptr;
  2167. // If this is a complex rvalue, we don't want to dereference it many times. Create a temporary.
  2168. TVariable* rhsTempVar = nullptr;
  2169. rhsTempVar = makeInternalVariable("@position", right->getType());
  2170. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2171. {
  2172. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2173. assignList = intermediate.growAggregate(assignList,
  2174. intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
  2175. }
  2176. // pos.y = -pos.y
  2177. {
  2178. const int Y = 1;
  2179. TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
  2180. TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
  2181. TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
  2182. TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
  2183. TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
  2184. const TType derefType(right->getType(), 0);
  2185. lhsElement->setType(derefType);
  2186. rhsElement->setType(derefType);
  2187. TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
  2188. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
  2189. }
  2190. // Assign the rhs temp (now with Y inversion) to the final output
  2191. {
  2192. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2193. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
  2194. }
  2195. assert(assignList != nullptr);
  2196. assignList->setOperator(EOpSequence);
  2197. return assignList;
  2198. }
  2199. // Clip and cull distance require special handling due to a semantic mismatch. In HLSL,
  2200. // these can be float scalar, float vector, or arrays of float scalar or float vector.
  2201. // In SPIR-V, they are arrays of scalar floats in all cases. We must copy individual components
  2202. // (e.g, both x and y components of a float2) out into the destination float array.
  2203. //
  2204. // The values are assigned to sequential members of the output array. The inner dimension
  2205. // is vector components. The outer dimension is array elements.
  2206. TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
  2207. TIntermTyped* left, TIntermTyped* right)
  2208. {
  2209. switch (language) {
  2210. case EShLangFragment:
  2211. case EShLangVertex:
  2212. case EShLangGeometry:
  2213. break;
  2214. default:
  2215. error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
  2216. return nullptr;
  2217. }
  2218. TVariable** clipCullVar = nullptr;
  2219. // Figure out if we are assigning to, or from, clip or cull distance.
  2220. const bool isOutput = isClipOrCullDistance(left->getType());
  2221. // This is the rvalue or lvalue holding the clip or cull distance.
  2222. TIntermTyped* clipCullNode = isOutput ? left : right;
  2223. // This is the value going into or out of the clip or cull distance.
  2224. TIntermTyped* internalNode = isOutput ? right : left;
  2225. const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
  2226. decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
  2227. // Refer to either the clip or the cull distance, depending on semantic.
  2228. switch (builtInType) {
  2229. case EbvClipDistance:
  2230. clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
  2231. semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
  2232. break;
  2233. case EbvCullDistance:
  2234. clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
  2235. semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
  2236. break;
  2237. // called invalidly: we expected a clip or a cull distance.
  2238. // static compile time problem: should not happen.
  2239. default: assert(0); return nullptr;
  2240. }
  2241. // This is the offset in the destination array of a given semantic's data
  2242. std::array<int, maxClipCullRegs> semanticOffset;
  2243. // Calculate offset of variable of semantic N in destination array
  2244. int arrayLoc = 0;
  2245. int vecItems = 0;
  2246. for (int x = 0; x < maxClipCullRegs; ++x) {
  2247. // See if we overflowed the vec4 packing
  2248. if ((vecItems + (*semanticNSize)[x]) > 4) {
  2249. arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
  2250. vecItems = 0;
  2251. }
  2252. semanticOffset[x] = arrayLoc;
  2253. vecItems += (*semanticNSize)[x];
  2254. arrayLoc += (*semanticNSize)[x];
  2255. }
  2256. // It can have up to 2 array dimensions (in the case of geometry shader inputs)
  2257. const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
  2258. const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
  2259. // vector sizes:
  2260. const int internalVectorSize = internalNode->getType().getVectorSize();
  2261. // array sizes, or 1 if it's not an array:
  2262. const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
  2263. const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
  2264. // The created type may be an array of arrays, e.g, for geometry shader inputs.
  2265. const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
  2266. // If we haven't created the output already, create it now.
  2267. if (*clipCullVar == nullptr) {
  2268. // ClipDistance and CullDistance are handled specially in the entry point input/output copy
  2269. // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
  2270. // into a float array, or vice versa. Here, we make the array the right size and type,
  2271. // which depends on the incoming data, which has several potential dimensions:
  2272. // * Semantic ID
  2273. // * vector size
  2274. // * array size
  2275. // Of those, semantic ID and array size cannot appear simultaneously.
  2276. //
  2277. // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
  2278. // array dimensions. The shader's declaration may have one or two array dimensions. One is always
  2279. // the geometry's dimension.
  2280. const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
  2281. const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
  2282. const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
  2283. TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
  2284. clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
  2285. // Create required array dimension
  2286. TArraySizes* arraySizes = new TArraySizes;
  2287. if (isImplicitlyArrayed)
  2288. arraySizes->addInnerSize(requiredOuterArraySize);
  2289. arraySizes->addInnerSize(requiredInnerArraySize);
  2290. clipCullType.transferArraySizes(arraySizes);
  2291. // Obtain symbol name: we'll use that for the symbol we introduce.
  2292. TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
  2293. assert(sym != nullptr);
  2294. // We are moving the semantic ID from the layout location, so it is no longer needed or
  2295. // desired there.
  2296. clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  2297. // Create variable and track its linkage
  2298. *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
  2299. trackLinkage(**clipCullVar);
  2300. }
  2301. // Create symbol for the clip or cull variable.
  2302. TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
  2303. // vector sizes:
  2304. const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
  2305. // array sizes, or 1 if it's not an array:
  2306. const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
  2307. const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
  2308. const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
  2309. // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
  2310. // fixBuiltInIoType() should have handled that upstream.
  2311. assert(clipCullSym->getType().isArray());
  2312. assert(clipCullSym->getType().getVectorSize() == 1);
  2313. assert(clipCullSym->getType().getBasicType() == EbtFloat);
  2314. // We may be creating multiple sub-assignments. This is an aggregate to hold them.
  2315. // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
  2316. TIntermAggregate* assignList = nullptr;
  2317. // Holds individual component assignments as we make them.
  2318. TIntermTyped* clipCullAssign = nullptr;
  2319. // If the types are homomorphic, use a simple assign. No need to mess about with
  2320. // individual components.
  2321. if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
  2322. clipCullInnerArraySize == internalInnerArraySize &&
  2323. clipCullOuterArraySize == internalOuterArraySize &&
  2324. clipCullVectorSize == internalVectorSize) {
  2325. if (isOutput)
  2326. clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
  2327. else
  2328. clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
  2329. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2330. assignList->setOperator(EOpSequence);
  2331. return assignList;
  2332. }
  2333. // We are going to copy each component of the internal (per array element if indicated) to sequential
  2334. // array elements of the clipCullSym. This tracks the lhs element we're writing to as we go along.
  2335. // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
  2336. int clipCullInnerArrayPos = semanticOffset[semanticId];
  2337. int clipCullOuterArrayPos = 0;
  2338. // Lambda to add an index to a node, set the type of the result, and return the new node.
  2339. const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
  2340. const TType derefType(node->getType(), 0);
  2341. node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
  2342. node->setType(derefType);
  2343. return node;
  2344. };
  2345. // Loop through every component of every element of the internal, and copy to or from the matching external.
  2346. for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
  2347. for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
  2348. for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
  2349. // clip/cull array member to read from / write to:
  2350. TIntermTyped* clipCullMember = clipCullSym;
  2351. // If implicitly arrayed, there is an outer array dimension involved
  2352. if (isImplicitlyArrayed)
  2353. clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
  2354. // Index into proper array position for clip cull member
  2355. clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
  2356. // if needed, start over with next outer array slice.
  2357. if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
  2358. clipCullInnerArrayPos = semanticOffset[semanticId];
  2359. ++clipCullOuterArrayPos;
  2360. }
  2361. // internal member to read from / write to:
  2362. TIntermTyped* internalMember = internalNode;
  2363. // If internal node has outer array dimension, index appropriately.
  2364. if (internalArrayDims > 1)
  2365. internalMember = addIndex(internalMember, internalOuterArrayPos);
  2366. // If internal node has inner array dimension, index appropriately.
  2367. if (internalArrayDims > 0)
  2368. internalMember = addIndex(internalMember, internalInnerArrayPos);
  2369. // If internal node is a vector, extract the component of interest.
  2370. if (internalNode->getType().isVector())
  2371. internalMember = addIndex(internalMember, internalComponent);
  2372. // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
  2373. if (isOutput)
  2374. clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
  2375. else
  2376. clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
  2377. // Track assignment in the sequence.
  2378. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2379. }
  2380. }
  2381. }
  2382. assert(assignList != nullptr);
  2383. assignList->setOperator(EOpSequence);
  2384. return assignList;
  2385. }
  2386. // Some simple source assignments need to be flattened to a sequence
  2387. // of AST assignments. Catch these and flatten, otherwise, pass through
  2388. // to intermediate.addAssign().
  2389. //
  2390. // Also, assignment to matrix swizzles requires multiple component assignments,
  2391. // intercept those as well.
  2392. TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2393. TIntermTyped* right)
  2394. {
  2395. if (left == nullptr || right == nullptr)
  2396. return nullptr;
  2397. // writing to opaques will require fixing transforms
  2398. if (left->getType().containsOpaque())
  2399. intermediate.setNeedsLegalization();
  2400. if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
  2401. return handleAssignToMatrixSwizzle(loc, op, left, right);
  2402. // Return true if the given node is an index operation into a split variable.
  2403. const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
  2404. const TIntermBinary* binaryNode = node->getAsBinaryNode();
  2405. if (binaryNode == nullptr)
  2406. return false;
  2407. return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) &&
  2408. wasSplit(binaryNode->getLeft());
  2409. };
  2410. // Return symbol if node is symbol or index ref
  2411. const auto getSymbol = [](const TIntermTyped* node) -> const TIntermSymbol* {
  2412. const TIntermSymbol* symbolNode = node->getAsSymbolNode();
  2413. if (symbolNode != nullptr)
  2414. return symbolNode;
  2415. const TIntermBinary* binaryNode = node->getAsBinaryNode();
  2416. if (binaryNode != nullptr && (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect))
  2417. return binaryNode->getLeft()->getAsSymbolNode();
  2418. return nullptr;
  2419. };
  2420. // Return true if this stage assigns clip position with potentially inverted Y
  2421. const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
  2422. return node->getType().getQualifier().builtIn == EbvPosition &&
  2423. (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
  2424. };
  2425. const TIntermSymbol* leftSymbol = getSymbol(left);
  2426. const TIntermSymbol* rightSymbol = getSymbol(right);
  2427. const bool isSplitLeft = wasSplit(left) || indexesSplit(left);
  2428. const bool isSplitRight = wasSplit(right) || indexesSplit(right);
  2429. const bool isFlattenLeft = wasFlattened(leftSymbol);
  2430. const bool isFlattenRight = wasFlattened(rightSymbol);
  2431. // OK to do a single assign if neither side is split or flattened. Otherwise,
  2432. // fall through to a member-wise copy.
  2433. if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
  2434. // Clip and cull distance requires more processing. See comment above assignClipCullDistance.
  2435. if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
  2436. const bool isOutput = isClipOrCullDistance(left->getType());
  2437. const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
  2438. return assignClipCullDistance(loc, op, semanticId, left, right);
  2439. } else if (assignsClipPos(left)) {
  2440. // Position can require special handling: see comment above assignPosition
  2441. return assignPosition(loc, op, left, right);
  2442. } else if (left->getQualifier().builtIn == EbvSampleMask) {
  2443. // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
  2444. // in the shader. Copy the scalar RHS into the LHS array element zero, if that happens.
  2445. if (left->isArray() && !right->isArray()) {
  2446. const TType derefType(left->getType(), 0);
  2447. left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
  2448. left->setType(derefType);
  2449. // Fall through to add assign.
  2450. }
  2451. }
  2452. return intermediate.addAssign(op, left, right, loc);
  2453. }
  2454. TIntermAggregate* assignList = nullptr;
  2455. const TVector<TVariable*>* leftVariables = nullptr;
  2456. const TVector<TVariable*>* rightVariables = nullptr;
  2457. // A temporary to store the right node's value, so we don't keep indirecting into it
  2458. // if it's not a simple symbol.
  2459. TVariable* rhsTempVar = nullptr;
  2460. // If the RHS is a simple symbol node, we'll copy it for each member.
  2461. TIntermSymbol* cloneSymNode = nullptr;
  2462. int memberCount = 0;
  2463. // Track how many items there are to copy.
  2464. if (left->getType().isStruct())
  2465. memberCount = (int)left->getType().getStruct()->size();
  2466. if (left->getType().isArray())
  2467. memberCount = left->getType().getCumulativeArraySize();
  2468. if (isFlattenLeft)
  2469. leftVariables = &flattenMap.find(leftSymbol->getId())->second.members;
  2470. if (isFlattenRight) {
  2471. rightVariables = &flattenMap.find(rightSymbol->getId())->second.members;
  2472. } else {
  2473. // The RHS is not flattened. There are several cases:
  2474. // 1. 1 item to copy: Use the RHS directly.
  2475. // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
  2476. // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
  2477. if (memberCount <= 1) {
  2478. // case 1: we'll use the symbol directly below. Nothing to do.
  2479. } else {
  2480. if (right->getAsSymbolNode() != nullptr) {
  2481. // case 2: we'll copy the symbol per iteration below.
  2482. cloneSymNode = right->getAsSymbolNode();
  2483. } else {
  2484. // case 3: assign to a temp, and indirect into that.
  2485. rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
  2486. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2487. TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
  2488. // Add this to the aggregate being built.
  2489. assignList = intermediate.growAggregate(assignList,
  2490. intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
  2491. }
  2492. }
  2493. }
  2494. // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
  2495. // variables, which is awkward when copying between split and unsplit structures. This variable tracks
  2496. // array indirections so they can be percolated from outer structs to inner variables.
  2497. std::vector <int> arrayElement;
  2498. TStorageQualifier leftStorage = left->getType().getQualifier().storage;
  2499. TStorageQualifier rightStorage = right->getType().getQualifier().storage;
  2500. int leftOffsetStart = findSubtreeOffset(*left);
  2501. int rightOffsetStart = findSubtreeOffset(*right);
  2502. int leftOffset = leftOffsetStart;
  2503. int rightOffset = rightOffsetStart;
  2504. const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
  2505. bool flattened)
  2506. -> TIntermTyped * {
  2507. const bool split = isLeft ? isSplitLeft : isSplitRight;
  2508. TIntermTyped* subTree;
  2509. const TType derefType(type, member);
  2510. const TVariable* builtInVar = nullptr;
  2511. if ((flattened || split) && derefType.isBuiltIn()) {
  2512. auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
  2513. derefType.getQualifier().builtIn,
  2514. isLeft ? leftStorage : rightStorage));
  2515. if (splitPair != splitBuiltIns.end())
  2516. builtInVar = splitPair->second;
  2517. }
  2518. if (builtInVar != nullptr) {
  2519. // copy from interstage IO built-in if needed
  2520. subTree = intermediate.addSymbol(*builtInVar);
  2521. if (subTree->getType().isArray()) {
  2522. // Arrayness of builtIn symbols isn't handled by the normal recursion:
  2523. // it's been extracted and moved to the built-in.
  2524. if (!arrayElement.empty()) {
  2525. const TType splitDerefType(subTree->getType(), arrayElement.back());
  2526. subTree = intermediate.addIndex(EOpIndexDirect, subTree,
  2527. intermediate.addConstantUnion(arrayElement.back(), loc), loc);
  2528. subTree->setType(splitDerefType);
  2529. } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
  2530. // This might also be a stage with arrayed outputs, in which case there's an index
  2531. // operation we should transfer to the output builtin.
  2532. const TType splitDerefType(subTree->getType(), 0);
  2533. subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
  2534. splitNode->getAsBinaryNode()->getRight(), loc);
  2535. subTree->setType(splitDerefType);
  2536. }
  2537. }
  2538. } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
  2539. if (isLeft) {
  2540. // offset will cycle through variables for arrayed io
  2541. if (leftOffset >= static_cast<int>(leftVariables->size()))
  2542. leftOffset = leftOffsetStart;
  2543. subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
  2544. } else {
  2545. // offset will cycle through variables for arrayed io
  2546. if (rightOffset >= static_cast<int>(rightVariables->size()))
  2547. rightOffset = rightOffsetStart;
  2548. subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
  2549. }
  2550. // arrayed io
  2551. if (subTree->getType().isArray()) {
  2552. if (!arrayElement.empty()) {
  2553. const TType derefType(subTree->getType(), arrayElement.front());
  2554. subTree = intermediate.addIndex(EOpIndexDirect, subTree,
  2555. intermediate.addConstantUnion(arrayElement.front(), loc), loc);
  2556. subTree->setType(derefType);
  2557. } else {
  2558. // There's an index operation we should transfer to the output builtin.
  2559. assert(splitNode->getAsOperator() != nullptr &&
  2560. splitNode->getAsOperator()->getOp() == EOpIndexIndirect);
  2561. const TType splitDerefType(subTree->getType(), 0);
  2562. subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
  2563. splitNode->getAsBinaryNode()->getRight(), loc);
  2564. subTree->setType(splitDerefType);
  2565. }
  2566. }
  2567. } else {
  2568. // Index operator if it's an aggregate, else EOpNull
  2569. const TOperator accessOp = type.isArray() ? EOpIndexDirect
  2570. : type.isStruct() ? EOpIndexDirectStruct
  2571. : EOpNull;
  2572. if (accessOp == EOpNull) {
  2573. subTree = splitNode;
  2574. } else {
  2575. subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
  2576. loc);
  2577. const TType splitDerefType(splitNode->getType(), splitMember);
  2578. subTree->setType(splitDerefType);
  2579. }
  2580. }
  2581. return subTree;
  2582. };
  2583. // Use the proper RHS node: a new symbol from a TVariable, copy
  2584. // of an TIntermSymbol node, or sometimes the right node directly.
  2585. right = rhsTempVar != nullptr ? intermediate.addSymbol(*rhsTempVar, loc) :
  2586. cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
  2587. right;
  2588. // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
  2589. // whole thing. So, we'll resort to an explicit type via std::function.
  2590. const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2591. bool topLevel)>
  2592. traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2593. bool topLevel) -> void {
  2594. // If we get here, we are assigning to or from a whole array or struct that must be
  2595. // flattened, so have to do member-by-member assignment:
  2596. bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
  2597. bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
  2598. if ((left->getType().isArray() || right->getType().isArray()) &&
  2599. (shouldFlattenSubsetLeft || isSplitLeft ||
  2600. shouldFlattenSubsetRight || isSplitRight)) {
  2601. const int elementsL = left->getType().isArray() ? left->getType().getOuterArraySize() : 1;
  2602. const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
  2603. // The arrays might not be the same size,
  2604. // e.g., if the size has been forced for EbvTessLevelInner/Outer.
  2605. const int elementsToCopy = std::min(elementsL, elementsR);
  2606. // array case
  2607. for (int element = 0; element < elementsToCopy; ++element) {
  2608. arrayElement.push_back(element);
  2609. // Add a new AST symbol node if we have a temp variable holding a complex RHS.
  2610. TIntermTyped* subLeft = getMember(true, left->getType(), element, left, element,
  2611. shouldFlattenSubsetLeft);
  2612. TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
  2613. shouldFlattenSubsetRight);
  2614. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), element, splitLeft,
  2615. element, shouldFlattenSubsetLeft)
  2616. : subLeft;
  2617. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
  2618. element, shouldFlattenSubsetRight)
  2619. : subRight;
  2620. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2621. arrayElement.pop_back();
  2622. }
  2623. } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft || isSplitLeft ||
  2624. shouldFlattenSubsetRight || isSplitRight)) {
  2625. // struct case
  2626. const auto& membersL = *left->getType().getStruct();
  2627. const auto& membersR = *right->getType().getStruct();
  2628. // These track the members in the split structures corresponding to the same in the unsplit structures,
  2629. // which we traverse in parallel.
  2630. int memberL = 0;
  2631. int memberR = 0;
  2632. // Handle empty structure assignment
  2633. if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
  2634. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2635. for (int member = 0; member < int(membersL.size()); ++member) {
  2636. const TType& typeL = *membersL[member].type;
  2637. const TType& typeR = *membersR[member].type;
  2638. TIntermTyped* subLeft = getMember(true, left->getType(), member, left, member,
  2639. shouldFlattenSubsetLeft);
  2640. TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
  2641. shouldFlattenSubsetRight);
  2642. // If there is no splitting, use the same values to avoid inefficiency.
  2643. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), member, splitLeft,
  2644. memberL, shouldFlattenSubsetLeft)
  2645. : subLeft;
  2646. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
  2647. memberR, shouldFlattenSubsetRight)
  2648. : subRight;
  2649. if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
  2650. // Clip and cull distance built-in assignment is complex in its own right, and is handled in
  2651. // a separate function dedicated to that task. See comment above assignClipCullDistance;
  2652. const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
  2653. // Since all clip/cull semantics boil down to the same built-in type, we need to get the
  2654. // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
  2655. const TType derefType((isOutput ? left : right)->getType(), member);
  2656. const int semanticId = derefType.getQualifier().layoutLocation;
  2657. TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
  2658. subSplitLeft, subSplitRight);
  2659. assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
  2660. } else if (assignsClipPos(subSplitLeft)) {
  2661. // Position can require special handling: see comment above assignPosition
  2662. TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
  2663. assignList = intermediate.growAggregate(assignList, positionAssign, loc);
  2664. } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
  2665. !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
  2666. // If this is the final flattening (no nested types below to flatten)
  2667. // we'll copy the member, else recurse into the type hierarchy.
  2668. // However, if splitting the struct, that means we can copy a whole
  2669. // subtree here IFF it does not itself contain any interstage built-in
  2670. // IO variables, so we only have to recurse into it if there's something
  2671. // for splitting to do. That can save a lot of AST verbosity for
  2672. // a bunch of memberwise copies.
  2673. assignList = intermediate.growAggregate(assignList,
  2674. intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
  2675. loc);
  2676. } else {
  2677. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2678. }
  2679. memberL += (typeL.isBuiltIn() ? 0 : 1);
  2680. memberR += (typeR.isBuiltIn() ? 0 : 1);
  2681. }
  2682. } else {
  2683. // Member copy
  2684. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2685. }
  2686. };
  2687. TIntermTyped* splitLeft = left;
  2688. TIntermTyped* splitRight = right;
  2689. // If either left or right was a split structure, we must read or write it, but still have to
  2690. // parallel-recurse through the unsplit structure to identify the built-in IO vars.
  2691. // The left can be either a symbol, or an index into a symbol (e.g, array reference)
  2692. if (isSplitLeft) {
  2693. if (indexesSplit(left)) {
  2694. // Index case: Refer to the indexed symbol, if the left is an index operator.
  2695. const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2696. TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2697. splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
  2698. left->getAsBinaryNode()->getRight(), loc);
  2699. const TType derefType(splitLeftNonIo->getType(), 0);
  2700. splitLeft->setType(derefType);
  2701. } else {
  2702. // Symbol case: otherwise, if not indexed, we have the symbol directly.
  2703. const TIntermSymbol* symNode = left->getAsSymbolNode();
  2704. splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2705. }
  2706. }
  2707. if (isSplitRight)
  2708. splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
  2709. // This makes the whole assignment, recursing through subtypes as needed.
  2710. traverse(left, right, splitLeft, splitRight, true);
  2711. assert(assignList != nullptr);
  2712. assignList->setOperator(EOpSequence);
  2713. return assignList;
  2714. }
  2715. // An assignment to matrix swizzle must be decomposed into individual assignments.
  2716. // These must be selected component-wise from the RHS and stored component-wise
  2717. // into the LHS.
  2718. TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2719. TIntermTyped* right)
  2720. {
  2721. assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
  2722. if (op != EOpAssign)
  2723. error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
  2724. // isolate the matrix and swizzle nodes
  2725. TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
  2726. const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
  2727. // if the RHS isn't already a simple vector, let's store into one
  2728. TIntermSymbol* vector = right->getAsSymbolNode();
  2729. TIntermTyped* vectorAssign = nullptr;
  2730. if (vector == nullptr) {
  2731. // create a new intermediate vector variable to assign to
  2732. TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
  2733. vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
  2734. // assign the right to the new vector
  2735. vectorAssign = handleAssign(loc, op, vector, right);
  2736. }
  2737. // Assign the vector components to the matrix components.
  2738. // Store this as a sequence, so a single aggregate node represents this
  2739. // entire operation.
  2740. TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
  2741. TType columnType(matrix->getType(), 0);
  2742. TType componentType(columnType, 0);
  2743. TType indexType(EbtInt);
  2744. for (int i = 0; i < (int)swizzle.size(); i += 2) {
  2745. // the right component, single index into the RHS vector
  2746. TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
  2747. intermediate.addConstantUnion(i/2, loc), loc);
  2748. // the left component, double index into the LHS matrix
  2749. TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
  2750. intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
  2751. indexType, loc),
  2752. loc);
  2753. leftComp->setType(columnType);
  2754. leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
  2755. intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
  2756. indexType, loc),
  2757. loc);
  2758. leftComp->setType(componentType);
  2759. // Add the assignment to the aggregate
  2760. result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
  2761. }
  2762. result->setOp(EOpSequence);
  2763. return result;
  2764. }
  2765. //
  2766. // HLSL atomic operations have slightly different arguments than
  2767. // GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
  2768. // This provides the post-decomposition equivalent opcode.
  2769. //
  2770. TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
  2771. {
  2772. switch (op) {
  2773. case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
  2774. case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
  2775. case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
  2776. case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
  2777. case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
  2778. case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
  2779. case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
  2780. case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
  2781. case EOpInterlockedCompareStore: // TODO: ...
  2782. default:
  2783. error(loc, "unknown atomic operation", "unknown op", "");
  2784. return EOpNull;
  2785. }
  2786. }
  2787. //
  2788. // Create a combined sampler/texture from separate sampler and texture.
  2789. //
  2790. TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
  2791. TIntermTyped* argSampler)
  2792. {
  2793. TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
  2794. txcombine->getSequence().push_back(argTex);
  2795. txcombine->getSequence().push_back(argSampler);
  2796. TSampler samplerType = argTex->getType().getSampler();
  2797. samplerType.combined = true;
  2798. // TODO:
  2799. // This block exists until the spec no longer requires shadow modes on texture objects.
  2800. // It can be deleted after that, along with the shadowTextureVariant member.
  2801. {
  2802. const bool shadowMode = argSampler->getType().getSampler().shadow;
  2803. TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
  2804. if (texSymbol == nullptr)
  2805. texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2806. if (texSymbol == nullptr) {
  2807. error(loc, "unable to find texture symbol", "", "");
  2808. return nullptr;
  2809. }
  2810. // This forces the texture's shadow state to be the sampler's
  2811. // shadow state. This depends on downstream optimization to
  2812. // DCE one variant in [shadow, nonshadow] if both are present,
  2813. // or the SPIR-V module would be invalid.
  2814. int newId = texSymbol->getId();
  2815. // Check to see if this texture has been given a shadow mode already.
  2816. // If so, look up the one we already have.
  2817. const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
  2818. if (textureShadowEntry != textureShadowVariant.end())
  2819. newId = textureShadowEntry->second->get(shadowMode);
  2820. else
  2821. textureShadowVariant[texSymbol->getId()] = NewPoolObject(tShadowTextureSymbols(), 1);
  2822. // Sometimes we have to create another symbol (if this texture has been seen before,
  2823. // and we haven't created the form for this shadow mode).
  2824. if (newId == -1) {
  2825. TType texType;
  2826. texType.shallowCopy(argTex->getType());
  2827. texType.getSampler().shadow = shadowMode; // set appropriate shadow mode.
  2828. globalQualifierFix(loc, texType.getQualifier());
  2829. TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
  2830. trackLinkage(*newTexture);
  2831. newId = newTexture->getUniqueId();
  2832. }
  2833. assert(newId != -1);
  2834. if (textureShadowVariant.find(newId) == textureShadowVariant.end())
  2835. textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
  2836. textureShadowVariant[newId]->set(shadowMode, newId);
  2837. // Remember this shadow mode in the texture and the merged type.
  2838. argTex->getWritableType().getSampler().shadow = shadowMode;
  2839. samplerType.shadow = shadowMode;
  2840. texSymbol->switchId(newId);
  2841. }
  2842. txcombine->setType(TType(samplerType, EvqTemporary));
  2843. txcombine->setLoc(loc);
  2844. return txcombine;
  2845. }
  2846. // Return true if this a buffer type that has an associated counter buffer.
  2847. bool HlslParseContext::hasStructBuffCounter(const TType& type) const
  2848. {
  2849. switch (type.getQualifier().declaredBuiltIn) {
  2850. case EbvAppendConsume: // fall through...
  2851. case EbvRWStructuredBuffer: // ...
  2852. return true;
  2853. default:
  2854. return false; // the other structuredbuffer types do not have a counter.
  2855. }
  2856. }
  2857. void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
  2858. {
  2859. // Counter type
  2860. TType* counterType = new TType(EbtUint, EvqBuffer);
  2861. counterType->setFieldName(intermediate.implicitCounterName);
  2862. TTypeList* blockStruct = new TTypeList;
  2863. TTypeLoc member = { counterType, loc };
  2864. blockStruct->push_back(member);
  2865. TType blockType(blockStruct, "", counterType->getQualifier());
  2866. blockType.getQualifier().storage = EvqBuffer;
  2867. type.shallowCopy(blockType);
  2868. shareStructBufferType(type);
  2869. }
  2870. // declare counter for a structured buffer type
  2871. void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
  2872. {
  2873. // Bail out if not a struct buffer
  2874. if (! isStructBufferType(bufferType))
  2875. return;
  2876. if (! hasStructBuffCounter(bufferType))
  2877. return;
  2878. TType blockType;
  2879. counterBufferType(loc, blockType);
  2880. TString* blockName = NewPoolTString(intermediate.addCounterBufferName(name).c_str());
  2881. // Counter buffer is not yet in use
  2882. structBufferCounter[*blockName] = false;
  2883. shareStructBufferType(blockType);
  2884. declareBlock(loc, blockType, blockName);
  2885. }
  2886. // return the counter that goes with a given structuredbuffer
  2887. TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
  2888. {
  2889. // Bail out if not a struct buffer
  2890. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  2891. return nullptr;
  2892. const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
  2893. // Mark the counter as being used
  2894. structBufferCounter[counterBlockName] = true;
  2895. TIntermTyped* counterVar = handleVariable(loc, &counterBlockName); // find the block structure
  2896. TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
  2897. TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
  2898. counterMember->setType(TType(EbtUint));
  2899. return counterMember;
  2900. }
  2901. //
  2902. // Decompose structure buffer methods into AST
  2903. //
  2904. void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  2905. {
  2906. if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
  2907. return;
  2908. const TOperator op = node->getAsOperator()->getOp();
  2909. TIntermAggregate* argAggregate = arguments->getAsAggregate();
  2910. // Buffer is the object upon which method is called, so always arg 0
  2911. TIntermTyped* bufferObj = nullptr;
  2912. // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
  2913. if (argAggregate) {
  2914. if (argAggregate->getSequence().empty())
  2915. return;
  2916. if (argAggregate->getSequence()[0])
  2917. bufferObj = argAggregate->getSequence()[0]->getAsTyped();
  2918. } else {
  2919. bufferObj = arguments->getAsSymbolNode();
  2920. }
  2921. if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
  2922. return;
  2923. // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
  2924. // This lambda adds something to it and returns the old value.
  2925. const auto incDecCounter = [&](int incval) -> TIntermTyped* {
  2926. TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
  2927. TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
  2928. if (counter == nullptr)
  2929. return nullptr;
  2930. TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
  2931. counterIncrement->setType(TType(EbtUint, EvqTemporary));
  2932. counterIncrement->setLoc(loc);
  2933. counterIncrement->getSequence().push_back(counter);
  2934. counterIncrement->getSequence().push_back(incrementValue);
  2935. return counterIncrement;
  2936. };
  2937. // Index to obtain the runtime sized array out of the buffer.
  2938. TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
  2939. if (argArray == nullptr)
  2940. return; // It might not be a struct buffer method.
  2941. switch (op) {
  2942. case EOpMethodLoad:
  2943. {
  2944. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2945. const TType& bufferType = bufferObj->getType();
  2946. const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
  2947. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2948. // buffer then, but that's what it calls itself.
  2949. const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer ||
  2950. builtInType == EbvRWByteAddressBuffer);
  2951. if (isByteAddressBuffer)
  2952. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2953. intermediate.addConstantUnion(2, loc, true),
  2954. loc, TType(EbtInt));
  2955. // Index into the array to find the item being loaded.
  2956. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2957. node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2958. const TType derefType(argArray->getType(), 0);
  2959. node->setType(derefType);
  2960. }
  2961. break;
  2962. case EOpMethodLoad2:
  2963. case EOpMethodLoad3:
  2964. case EOpMethodLoad4:
  2965. {
  2966. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2967. TOperator constructOp = EOpNull;
  2968. int size = 0;
  2969. switch (op) {
  2970. case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
  2971. case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
  2972. case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
  2973. default: assert(0);
  2974. }
  2975. TIntermTyped* body = nullptr;
  2976. // First, we'll store the address in a variable to avoid multiple shifts
  2977. // (we must convert the byte address to an item address)
  2978. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2979. intermediate.addConstantUnion(2, loc, true),
  2980. loc, TType(EbtInt));
  2981. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2982. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2983. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2984. TIntermTyped* vec = nullptr;
  2985. // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
  2986. // address conversion.
  2987. for (int idx=0; idx<size; ++idx) {
  2988. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2989. // add index offset
  2990. if (idx != 0)
  2991. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
  2992. intermediate.addConstantUnion(idx, loc, true),
  2993. loc, TType(EbtInt));
  2994. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2995. : EOpIndexIndirect;
  2996. TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2997. TType derefType(argArray->getType(), 0);
  2998. derefType.getQualifier().makeTemporary();
  2999. indexVal->setType(derefType);
  3000. vec = intermediate.growAggregate(vec, indexVal);
  3001. }
  3002. vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
  3003. vec->getAsAggregate()->setOperator(constructOp);
  3004. body = intermediate.growAggregate(body, vec);
  3005. body->setType(vec->getType());
  3006. body->getAsAggregate()->setOperator(EOpSequence);
  3007. node = body;
  3008. }
  3009. break;
  3010. case EOpMethodStore:
  3011. case EOpMethodStore2:
  3012. case EOpMethodStore3:
  3013. case EOpMethodStore4:
  3014. {
  3015. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  3016. TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped(); // value
  3017. // Index into the array to find the item being loaded.
  3018. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  3019. // buffer then, but that's what it calls itself).
  3020. int size = 0;
  3021. switch (op) {
  3022. case EOpMethodStore: size = 1; break;
  3023. case EOpMethodStore2: size = 2; break;
  3024. case EOpMethodStore3: size = 3; break;
  3025. case EOpMethodStore4: size = 4; break;
  3026. default: assert(0);
  3027. }
  3028. TIntermAggregate* body = nullptr;
  3029. // First, we'll store the address in a variable to avoid multiple shifts
  3030. // (we must convert the byte address to an item address)
  3031. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  3032. intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
  3033. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  3034. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  3035. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  3036. for (int idx=0; idx<size; ++idx) {
  3037. TIntermTyped* offsetIdx = byteAddrIdxVar;
  3038. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  3039. // add index offset
  3040. if (idx != 0)
  3041. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
  3042. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  3043. : EOpIndexIndirect;
  3044. TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  3045. const TType derefType(argArray->getType(), 0);
  3046. lValue->setType(derefType);
  3047. TIntermTyped* rValue;
  3048. if (size == 1) {
  3049. rValue = argValue;
  3050. } else {
  3051. rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
  3052. const TType indexType(argValue->getType(), 0);
  3053. rValue->setType(indexType);
  3054. }
  3055. TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  3056. body = intermediate.growAggregate(body, assign);
  3057. }
  3058. body->setOperator(EOpSequence);
  3059. node = body;
  3060. }
  3061. break;
  3062. case EOpMethodGetDimensions:
  3063. {
  3064. const int numArgs = (int)argAggregate->getSequence().size();
  3065. TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped(); // out num items
  3066. TIntermTyped* argStride = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr; // out stride
  3067. TIntermAggregate* body = nullptr;
  3068. // Length output:
  3069. if (argArray->getType().isSizedArray()) {
  3070. const int length = argArray->getType().getOuterArraySize();
  3071. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
  3072. intermediate.addConstantUnion(length, loc, true), loc);
  3073. body = intermediate.growAggregate(body, assign, loc);
  3074. } else {
  3075. TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
  3076. argNumItems->getType());
  3077. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
  3078. body = intermediate.growAggregate(body, assign, loc);
  3079. }
  3080. // Stride output:
  3081. if (argStride != nullptr) {
  3082. int size;
  3083. int stride;
  3084. intermediate.getMemberAlignment(argArray->getType(), size, stride, argArray->getType().getQualifier().layoutPacking,
  3085. argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
  3086. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
  3087. intermediate.addConstantUnion(stride, loc, true), loc);
  3088. body = intermediate.growAggregate(body, assign);
  3089. }
  3090. body->setOperator(EOpSequence);
  3091. node = body;
  3092. }
  3093. break;
  3094. case EOpInterlockedAdd:
  3095. case EOpInterlockedAnd:
  3096. case EOpInterlockedExchange:
  3097. case EOpInterlockedMax:
  3098. case EOpInterlockedMin:
  3099. case EOpInterlockedOr:
  3100. case EOpInterlockedXor:
  3101. case EOpInterlockedCompareExchange:
  3102. case EOpInterlockedCompareStore:
  3103. {
  3104. // We'll replace the first argument with the block dereference, and let
  3105. // downstream decomposition handle the rest.
  3106. TIntermSequence& sequence = argAggregate->getSequence();
  3107. TIntermTyped* argIndex = makeIntegerIndex(sequence[1]->getAsTyped()); // index
  3108. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
  3109. loc, TType(EbtInt));
  3110. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3111. TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  3112. const TType derefType(argArray->getType(), 0);
  3113. element->setType(derefType);
  3114. // Replace the numeric byte offset parameter with array reference.
  3115. sequence[1] = element;
  3116. sequence.erase(sequence.begin(), sequence.begin()+1);
  3117. }
  3118. break;
  3119. case EOpMethodIncrementCounter:
  3120. {
  3121. node = incDecCounter(1);
  3122. break;
  3123. }
  3124. case EOpMethodDecrementCounter:
  3125. {
  3126. TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
  3127. node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
  3128. preIncValue->getType());
  3129. break;
  3130. }
  3131. case EOpMethodAppend:
  3132. {
  3133. TIntermTyped* oldCounter = incDecCounter(1);
  3134. TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
  3135. TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
  3136. const TType derefType(argArray->getType(), 0);
  3137. lValue->setType(derefType);
  3138. node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  3139. break;
  3140. }
  3141. case EOpMethodConsume:
  3142. {
  3143. TIntermTyped* oldCounter = incDecCounter(-1);
  3144. TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
  3145. intermediate.addConstantUnion(-1, loc, true), loc,
  3146. oldCounter->getType());
  3147. node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
  3148. const TType derefType(argArray->getType(), 0);
  3149. node->setType(derefType);
  3150. break;
  3151. }
  3152. default:
  3153. break; // most pass through unchanged
  3154. }
  3155. }
  3156. // Create array of standard sample positions for given sample count.
  3157. // TODO: remove when a real method to query sample pos exists in SPIR-V.
  3158. TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
  3159. {
  3160. struct tSamplePos { float x, y; };
  3161. static const tSamplePos pos1[] = {
  3162. { 0.0/16.0, 0.0/16.0 },
  3163. };
  3164. // standard sample positions for 2, 4, 8, and 16 samples.
  3165. static const tSamplePos pos2[] = {
  3166. { 4.0/16.0, 4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
  3167. };
  3168. static const tSamplePos pos4[] = {
  3169. {-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 },
  3170. };
  3171. static const tSamplePos pos8[] = {
  3172. { 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 },
  3173. {-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 },
  3174. };
  3175. static const tSamplePos pos16[] = {
  3176. { 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 },
  3177. {-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 },
  3178. {-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 },
  3179. {-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 },
  3180. };
  3181. const tSamplePos* sampleLoc = nullptr;
  3182. int numSamples = count;
  3183. switch (count) {
  3184. case 2: sampleLoc = pos2; break;
  3185. case 4: sampleLoc = pos4; break;
  3186. case 8: sampleLoc = pos8; break;
  3187. case 16: sampleLoc = pos16; break;
  3188. default:
  3189. sampleLoc = pos1;
  3190. numSamples = 1;
  3191. }
  3192. TConstUnionArray* values = new TConstUnionArray(numSamples*2);
  3193. for (int pos=0; pos<count; ++pos) {
  3194. TConstUnion x, y;
  3195. x.setDConst(sampleLoc[pos].x);
  3196. y.setDConst(sampleLoc[pos].y);
  3197. (*values)[pos*2+0] = x;
  3198. (*values)[pos*2+1] = y;
  3199. }
  3200. TType retType(EbtFloat, EvqConst, 2);
  3201. if (numSamples != 1) {
  3202. TArraySizes* arraySizes = new TArraySizes;
  3203. arraySizes->addInnerSize(numSamples);
  3204. retType.transferArraySizes(arraySizes);
  3205. }
  3206. return new TIntermConstantUnion(*values, retType);
  3207. }
  3208. //
  3209. // Decompose DX9 and DX10 sample intrinsics & object methods into AST
  3210. //
  3211. void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3212. {
  3213. if (node == nullptr || !node->getAsOperator())
  3214. return;
  3215. // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
  3216. const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
  3217. result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
  3218. TIntermTyped* convertedResult = nullptr;
  3219. TType retType;
  3220. getTextureReturnType(sampler, retType);
  3221. if (retType.isStruct()) {
  3222. // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
  3223. TIntermAggregate* conversionAggregate = new TIntermAggregate;
  3224. convertedResult = conversionAggregate;
  3225. // Convert vector output to return structure. We will need a temp symbol to copy the results to.
  3226. TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
  3227. // We also need a temp symbol to hold the result of the texture. We don't want to re-fetch the
  3228. // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
  3229. TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
  3230. // Initial copy from texture to our sample result shadow.
  3231. TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
  3232. result, loc);
  3233. conversionAggregate->getSequence().push_back(shadowCopy);
  3234. unsigned vec4Pos = 0;
  3235. for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
  3236. const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
  3237. // Check for bad struct members. This should have been caught upstream. Complain, because
  3238. // wwe don't know what to do with it. This algorithm could be generalized to handle
  3239. // other things, e.g, sub-structures, but HLSL doesn't allow them.
  3240. if (!memberType.isVector() && !memberType.isScalar()) {
  3241. error(loc, "expected: scalar or vector type in texture structure", "", "");
  3242. return nullptr;
  3243. }
  3244. // Index into the struct variable to find the member to assign.
  3245. TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
  3246. intermediate.addSymbol(*structVar, loc),
  3247. intermediate.addConstantUnion(m, loc), loc);
  3248. structMember->setType(memberType);
  3249. // Assign each component of (possible) vector in struct member.
  3250. for (int component = 0; component < memberType.getVectorSize(); ++component) {
  3251. TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
  3252. intermediate.addSymbol(*sampleShadow, loc),
  3253. intermediate.addConstantUnion(vec4Pos++, loc), loc);
  3254. vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
  3255. TIntermTyped* memberAssign = nullptr;
  3256. if (memberType.isVector()) {
  3257. // Vector member: we need to create an access chain to the vector component.
  3258. TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
  3259. intermediate.addConstantUnion(component, loc), loc);
  3260. memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
  3261. } else {
  3262. // Scalar member: we can assign to it directly.
  3263. memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
  3264. }
  3265. conversionAggregate->getSequence().push_back(memberAssign);
  3266. }
  3267. }
  3268. // Add completed variable so the expression results in the whole struct value we just built.
  3269. conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
  3270. // Make it a sequence.
  3271. intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
  3272. } else {
  3273. // vector clamp the output if template vector type is smaller than sample result.
  3274. if (retType.getVectorSize() < node->getVectorSize()) {
  3275. // Too many components. Construct shorter vector from it.
  3276. const TOperator op = intermediate.mapTypeToConstructorOp(retType);
  3277. convertedResult = constructBuiltIn(retType, op, result, loc, false);
  3278. } else {
  3279. // Enough components. Use directly.
  3280. convertedResult = result;
  3281. }
  3282. }
  3283. convertedResult->setLoc(loc);
  3284. return convertedResult;
  3285. };
  3286. const TOperator op = node->getAsOperator()->getOp();
  3287. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3288. // Bail out if not a sampler method.
  3289. // Note though this is odd to do before checking the op, because the op
  3290. // could be something that takes the arguments, and the function in question
  3291. // takes the result of the op. So, this is not the final word.
  3292. if (arguments != nullptr) {
  3293. if (argAggregate == nullptr) {
  3294. if (arguments->getAsTyped()->getBasicType() != EbtSampler)
  3295. return;
  3296. } else {
  3297. if (argAggregate->getSequence().size() == 0 ||
  3298. argAggregate->getSequence()[0] == nullptr ||
  3299. argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
  3300. return;
  3301. }
  3302. }
  3303. switch (op) {
  3304. // **** DX9 intrinsics: ****
  3305. case EOpTexture:
  3306. {
  3307. // Texture with ddx & ddy is really gradient form in HLSL
  3308. if (argAggregate->getSequence().size() == 4)
  3309. node->getAsAggregate()->setOperator(EOpTextureGrad);
  3310. break;
  3311. }
  3312. case EOpTextureLod: //is almost EOpTextureBias (only args & operations are different)
  3313. {
  3314. TIntermTyped *argSamp = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3315. TIntermTyped *argCoord = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3316. assert(argCoord->getVectorSize() == 4);
  3317. TIntermTyped *w = intermediate.addConstantUnion(3, loc, true);
  3318. TIntermTyped *argLod = intermediate.addIndex(EOpIndexDirect, argCoord, w, loc);
  3319. TOperator constructOp = EOpNull;
  3320. const TSampler &sampler = argSamp->getType().getSampler();
  3321. int coordSize = 0;
  3322. switch (sampler.dim)
  3323. {
  3324. case Esd1D: constructOp = EOpConstructFloat; coordSize = 1; break; // 1D
  3325. case Esd2D: constructOp = EOpConstructVec2; coordSize = 2; break; // 2D
  3326. case Esd3D: constructOp = EOpConstructVec3; coordSize = 3; break; // 3D
  3327. case EsdCube: constructOp = EOpConstructVec3; coordSize = 3; break; // also 3D
  3328. default:
  3329. error(loc, "unhandled DX9 texture LoD dimension", "", "");
  3330. break;
  3331. }
  3332. TIntermAggregate *constructCoord = new TIntermAggregate(constructOp);
  3333. constructCoord->getSequence().push_back(argCoord);
  3334. constructCoord->setLoc(loc);
  3335. constructCoord->setType(TType(argCoord->getBasicType(), EvqTemporary, coordSize));
  3336. TIntermAggregate *tex = new TIntermAggregate(EOpTextureLod);
  3337. tex->getSequence().push_back(argSamp); // sampler
  3338. tex->getSequence().push_back(constructCoord); // coordinate
  3339. tex->getSequence().push_back(argLod); // lod
  3340. node = convertReturn(tex, sampler);
  3341. break;
  3342. }
  3343. case EOpTextureBias:
  3344. {
  3345. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3346. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3347. // HLSL puts bias in W component of coordinate. We extract it and add it to
  3348. // the argument list, instead
  3349. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  3350. TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  3351. TOperator constructOp = EOpNull;
  3352. const TSampler& sampler = arg0->getType().getSampler();
  3353. switch (sampler.dim) {
  3354. case Esd1D: constructOp = EOpConstructFloat; break; // 1D
  3355. case Esd2D: constructOp = EOpConstructVec2; break; // 2D
  3356. case Esd3D: constructOp = EOpConstructVec3; break; // 3D
  3357. case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
  3358. default:
  3359. error(loc, "unhandled DX9 texture bias dimension", "", "");
  3360. break;
  3361. }
  3362. TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
  3363. constructCoord->getSequence().push_back(arg1);
  3364. constructCoord->setLoc(loc);
  3365. // The input vector should never be less than 2, since there's always a bias.
  3366. // The max is for safety, and should be a no-op.
  3367. constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
  3368. TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
  3369. tex->getSequence().push_back(arg0); // sampler
  3370. tex->getSequence().push_back(constructCoord); // coordinate
  3371. tex->getSequence().push_back(bias); // bias
  3372. node = convertReturn(tex, sampler);
  3373. break;
  3374. }
  3375. // **** DX10 methods: ****
  3376. case EOpMethodSample: // fall through
  3377. case EOpMethodSampleBias: // ...
  3378. {
  3379. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3380. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3381. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3382. TIntermTyped* argBias = nullptr;
  3383. TIntermTyped* argOffset = nullptr;
  3384. const TSampler& sampler = argTex->getType().getSampler();
  3385. int nextArg = 3;
  3386. if (op == EOpMethodSampleBias) // SampleBias has a bias arg
  3387. argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3388. TOperator textureOp = EOpTexture;
  3389. if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
  3390. textureOp = EOpTextureOffset;
  3391. argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3392. }
  3393. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3394. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3395. txsample->getSequence().push_back(txcombine);
  3396. txsample->getSequence().push_back(argCoord);
  3397. if (argBias != nullptr)
  3398. txsample->getSequence().push_back(argBias);
  3399. if (argOffset != nullptr)
  3400. txsample->getSequence().push_back(argOffset);
  3401. node = convertReturn(txsample, sampler);
  3402. break;
  3403. }
  3404. case EOpMethodSampleGrad: // ...
  3405. {
  3406. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3407. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3408. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3409. TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
  3410. TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
  3411. TIntermTyped* argOffset = nullptr;
  3412. const TSampler& sampler = argTex->getType().getSampler();
  3413. TOperator textureOp = EOpTextureGrad;
  3414. if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
  3415. textureOp = EOpTextureGradOffset;
  3416. argOffset = argAggregate->getSequence()[5]->getAsTyped();
  3417. }
  3418. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3419. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3420. txsample->getSequence().push_back(txcombine);
  3421. txsample->getSequence().push_back(argCoord);
  3422. txsample->getSequence().push_back(argDDX);
  3423. txsample->getSequence().push_back(argDDY);
  3424. if (argOffset != nullptr)
  3425. txsample->getSequence().push_back(argOffset);
  3426. node = convertReturn(txsample, sampler);
  3427. break;
  3428. }
  3429. case EOpMethodGetDimensions:
  3430. {
  3431. // AST returns a vector of results, which we break apart component-wise into
  3432. // separate values to assign to the HLSL method's outputs, ala:
  3433. // tx . GetDimensions(width, height);
  3434. // float2 sizeQueryTemp = EOpTextureQuerySize
  3435. // width = sizeQueryTemp.X;
  3436. // height = sizeQueryTemp.Y;
  3437. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3438. const TType& texType = argTex->getType();
  3439. assert(texType.getBasicType() == EbtSampler);
  3440. const TSampler& sampler = texType.getSampler();
  3441. const TSamplerDim dim = sampler.dim;
  3442. const bool isImage = sampler.isImage();
  3443. const bool isMs = sampler.isMultiSample();
  3444. const int numArgs = (int)argAggregate->getSequence().size();
  3445. int numDims = 0;
  3446. switch (dim) {
  3447. case Esd1D: numDims = 1; break; // W
  3448. case Esd2D: numDims = 2; break; // W, H
  3449. case Esd3D: numDims = 3; break; // W, H, D
  3450. case EsdCube: numDims = 2; break; // W, H (cube)
  3451. case EsdBuffer: numDims = 1; break; // W (buffers)
  3452. case EsdRect: numDims = 2; break; // W, H (rect)
  3453. default:
  3454. error(loc, "unhandled DX10 MethodGet dimension", "", "");
  3455. break;
  3456. }
  3457. // Arrayed adds another dimension for the number of array elements
  3458. if (sampler.isArrayed())
  3459. ++numDims;
  3460. // Establish whether the method itself is querying mip levels. This can be false even
  3461. // if the underlying query requires a MIP level, due to the available HLSL method overloads.
  3462. const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
  3463. // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
  3464. // True if:
  3465. // 1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
  3466. // or,
  3467. // 2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
  3468. const bool mipRequired =
  3469. ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
  3470. mipQuery; // 2...
  3471. // AST assumes integer return. Will be converted to float if required.
  3472. TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
  3473. sizeQuery->getSequence().push_back(argTex);
  3474. // If we're building an LOD query, add the LOD.
  3475. if (mipRequired) {
  3476. // If the base HLSL query had no MIP level given, use level 0.
  3477. TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
  3478. intermediate.addConstantUnion(0, loc, true);
  3479. sizeQuery->getSequence().push_back(queryLod);
  3480. }
  3481. sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
  3482. sizeQuery->setLoc(loc);
  3483. // Return value from size query
  3484. TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
  3485. tempArg->getWritableType().getQualifier().makeTemporary();
  3486. TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
  3487. intermediate.addSymbol(*tempArg, loc),
  3488. sizeQuery, loc);
  3489. // Compound statement for assigning outputs
  3490. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
  3491. // Index of first output parameter
  3492. const int outParamBase = mipQuery ? 2 : 1;
  3493. for (int compNum = 0; compNum < numDims; ++compNum) {
  3494. TIntermTyped* indexedOut = nullptr;
  3495. TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
  3496. if (numDims > 1) {
  3497. TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
  3498. indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
  3499. indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
  3500. indexedOut->setLoc(loc);
  3501. } else {
  3502. indexedOut = sizeQueryReturn;
  3503. }
  3504. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
  3505. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
  3506. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3507. }
  3508. // handle mip level parameter
  3509. if (mipQuery) {
  3510. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3511. TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
  3512. levelsQuery->getSequence().push_back(argTex);
  3513. levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3514. levelsQuery->setLoc(loc);
  3515. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
  3516. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3517. }
  3518. // 2DMS formats query # samples, which needs a different query op
  3519. if (sampler.isMultiSample()) {
  3520. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3521. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3522. samplesQuery->getSequence().push_back(argTex);
  3523. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3524. samplesQuery->setLoc(loc);
  3525. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
  3526. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3527. }
  3528. compoundStatement->setOperator(EOpSequence);
  3529. compoundStatement->setLoc(loc);
  3530. compoundStatement->setType(TType(EbtVoid));
  3531. node = compoundStatement;
  3532. break;
  3533. }
  3534. case EOpMethodSampleCmp: // fall through...
  3535. case EOpMethodSampleCmpLevelZero:
  3536. {
  3537. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3538. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3539. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3540. TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
  3541. TIntermTyped* argOffset = nullptr;
  3542. // Sampler argument should be a sampler.
  3543. if (argSamp->getType().getBasicType() != EbtSampler) {
  3544. error(loc, "expected: sampler type", "", "");
  3545. return;
  3546. }
  3547. // Sampler should be a SamplerComparisonState
  3548. if (! argSamp->getType().getSampler().isShadow()) {
  3549. error(loc, "expected: SamplerComparisonState", "", "");
  3550. return;
  3551. }
  3552. // optional offset value
  3553. if (argAggregate->getSequence().size() > 4)
  3554. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3555. const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
  3556. // AST wants comparison value as one of the texture coordinates
  3557. TOperator constructOp = EOpNull;
  3558. switch (coordDimWithCmpVal) {
  3559. // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
  3560. case 2: constructOp = EOpConstructVec2; break;
  3561. case 3: constructOp = EOpConstructVec3; break;
  3562. case 4: constructOp = EOpConstructVec4; break;
  3563. case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
  3564. default:
  3565. error(loc, "unhandled DX10 MethodSample dimension", "", "");
  3566. break;
  3567. }
  3568. TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
  3569. coordWithCmp->getSequence().push_back(argCoord);
  3570. if (coordDimWithCmpVal != 5) // cube array shadow is special.
  3571. coordWithCmp->getSequence().push_back(argCmpVal);
  3572. coordWithCmp->setLoc(loc);
  3573. coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
  3574. TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
  3575. if (argOffset != nullptr)
  3576. textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
  3577. // Create combined sampler & texture op
  3578. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3579. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3580. txsample->getSequence().push_back(txcombine);
  3581. txsample->getSequence().push_back(coordWithCmp);
  3582. if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
  3583. txsample->getSequence().push_back(argCmpVal);
  3584. // the LevelZero form uses 0 as an explicit LOD
  3585. if (op == EOpMethodSampleCmpLevelZero)
  3586. txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
  3587. // Add offset if present
  3588. if (argOffset != nullptr)
  3589. txsample->getSequence().push_back(argOffset);
  3590. txsample->setType(node->getType());
  3591. txsample->setLoc(loc);
  3592. node = txsample;
  3593. break;
  3594. }
  3595. case EOpMethodLoad:
  3596. {
  3597. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3598. TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
  3599. TIntermTyped* argOffset = nullptr;
  3600. TIntermTyped* lodComponent = nullptr;
  3601. TIntermTyped* coordSwizzle = nullptr;
  3602. const TSampler& sampler = argTex->getType().getSampler();
  3603. const bool isMS = sampler.isMultiSample();
  3604. const bool isBuffer = sampler.dim == EsdBuffer;
  3605. const bool isImage = sampler.isImage();
  3606. const TBasicType coordBaseType = argCoord->getType().getBasicType();
  3607. // Last component of coordinate is the mip level, for non-MS. we separate them here:
  3608. if (isMS || isBuffer || isImage) {
  3609. // MS, Buffer, and Image have no LOD
  3610. coordSwizzle = argCoord;
  3611. } else {
  3612. // Extract coordinate
  3613. int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
  3614. TSwizzleSelectors<TVectorSelector> coordFields;
  3615. for (int i = 0; i < swizzleSize; ++i)
  3616. coordFields.push_back(i);
  3617. TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
  3618. coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
  3619. coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
  3620. // Extract LOD
  3621. TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
  3622. lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
  3623. lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
  3624. }
  3625. const int numArgs = (int)argAggregate->getSequence().size();
  3626. const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
  3627. // Create texel fetch
  3628. const TOperator fetchOp = (isImage ? EOpImageLoad :
  3629. hasOffset ? EOpTextureFetchOffset :
  3630. EOpTextureFetch);
  3631. TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
  3632. // Build up the fetch
  3633. txfetch->getSequence().push_back(argTex);
  3634. txfetch->getSequence().push_back(coordSwizzle);
  3635. if (isMS) {
  3636. // add 2DMS sample index
  3637. TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
  3638. txfetch->getSequence().push_back(argSampleIdx);
  3639. } else if (isBuffer) {
  3640. // Nothing else to do for buffers.
  3641. } else if (isImage) {
  3642. // Nothing else to do for images.
  3643. } else {
  3644. // 2DMS and buffer have no LOD, but everything else does.
  3645. txfetch->getSequence().push_back(lodComponent);
  3646. }
  3647. // Obtain offset arg, if there is one.
  3648. if (hasOffset) {
  3649. const int offsetPos = (isMS ? 3 : 2);
  3650. argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
  3651. txfetch->getSequence().push_back(argOffset);
  3652. }
  3653. node = convertReturn(txfetch, sampler);
  3654. break;
  3655. }
  3656. case EOpMethodSampleLevel:
  3657. {
  3658. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3659. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3660. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3661. TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
  3662. TIntermTyped* argOffset = nullptr;
  3663. const TSampler& sampler = argTex->getType().getSampler();
  3664. const int numArgs = (int)argAggregate->getSequence().size();
  3665. if (numArgs == 5) // offset, if present
  3666. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3667. const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
  3668. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3669. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3670. txsample->getSequence().push_back(txcombine);
  3671. txsample->getSequence().push_back(argCoord);
  3672. txsample->getSequence().push_back(argLod);
  3673. if (argOffset != nullptr)
  3674. txsample->getSequence().push_back(argOffset);
  3675. node = convertReturn(txsample, sampler);
  3676. break;
  3677. }
  3678. case EOpMethodGather:
  3679. {
  3680. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3681. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3682. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3683. TIntermTyped* argOffset = nullptr;
  3684. // Offset is optional
  3685. if (argAggregate->getSequence().size() > 3)
  3686. argOffset = argAggregate->getSequence()[3]->getAsTyped();
  3687. const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
  3688. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3689. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3690. txgather->getSequence().push_back(txcombine);
  3691. txgather->getSequence().push_back(argCoord);
  3692. // Offset if not given is implicitly channel 0 (red)
  3693. if (argOffset != nullptr)
  3694. txgather->getSequence().push_back(argOffset);
  3695. txgather->setType(node->getType());
  3696. txgather->setLoc(loc);
  3697. node = txgather;
  3698. break;
  3699. }
  3700. case EOpMethodGatherRed: // fall through...
  3701. case EOpMethodGatherGreen: // ...
  3702. case EOpMethodGatherBlue: // ...
  3703. case EOpMethodGatherAlpha: // ...
  3704. case EOpMethodGatherCmpRed: // ...
  3705. case EOpMethodGatherCmpGreen: // ...
  3706. case EOpMethodGatherCmpBlue: // ...
  3707. case EOpMethodGatherCmpAlpha: // ...
  3708. {
  3709. int channel = 0; // the channel we are gathering
  3710. int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
  3711. switch (op) {
  3712. case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
  3713. case EOpMethodGatherRed: channel = 0; break;
  3714. case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
  3715. case EOpMethodGatherGreen: channel = 1; break;
  3716. case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
  3717. case EOpMethodGatherBlue: channel = 2; break;
  3718. case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
  3719. case EOpMethodGatherAlpha: channel = 3; break;
  3720. default: assert(0); break;
  3721. }
  3722. // For now, we have nothing to map the component-wise comparison forms
  3723. // to, because neither GLSL nor SPIR-V has such an opcode. Issue an
  3724. // unimplemented error instead. Most of the machinery is here if that
  3725. // should ever become available. However, red can be passed through
  3726. // to OpImageDrefGather. G/B/A cannot, because that opcode does not
  3727. // accept a component.
  3728. if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
  3729. error(loc, "unimplemented: component-level gather compare", "", "");
  3730. return;
  3731. }
  3732. int arg = 0;
  3733. TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
  3734. TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
  3735. TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
  3736. TIntermTyped* argOffset = nullptr;
  3737. TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
  3738. // TIntermTyped* argStatus = nullptr; // TODO: residency
  3739. TIntermTyped* argCmp = nullptr;
  3740. const TSamplerDim dim = argTex->getType().getSampler().dim;
  3741. const int argSize = (int)argAggregate->getSequence().size();
  3742. bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
  3743. bool hasOffset1 = false;
  3744. bool hasOffset4 = false;
  3745. // Sampler argument should be a sampler.
  3746. if (argSamp->getType().getBasicType() != EbtSampler) {
  3747. error(loc, "expected: sampler type", "", "");
  3748. return;
  3749. }
  3750. // Cmp forms require SamplerComparisonState
  3751. if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
  3752. error(loc, "expected: SamplerComparisonState", "", "");
  3753. return;
  3754. }
  3755. // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
  3756. if (dim == Esd2D) {
  3757. hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
  3758. hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
  3759. }
  3760. assert(!(hasOffset1 && hasOffset4));
  3761. TOperator textureOp = EOpTextureGather;
  3762. // Compare forms have compare value
  3763. if (cmpValues != 0)
  3764. argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3765. // Some forms have single offset
  3766. if (hasOffset1) {
  3767. textureOp = EOpTextureGatherOffset; // single offset form
  3768. argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3769. }
  3770. // Some forms have 4 gather offsets
  3771. if (hasOffset4) {
  3772. textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
  3773. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3774. argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
  3775. }
  3776. // Residency status
  3777. if (hasStatus) {
  3778. // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
  3779. error(loc, "unimplemented: residency status", "", "");
  3780. return;
  3781. }
  3782. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3783. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3784. TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
  3785. txgather->getSequence().push_back(txcombine);
  3786. txgather->getSequence().push_back(argCoord);
  3787. // AST wants an array of 4 offsets, where HLSL has separate args. Here
  3788. // we construct an array from the separate args.
  3789. if (hasOffset4) {
  3790. TType arrayType(EbtInt, EvqTemporary, 2);
  3791. TArraySizes* arraySizes = new TArraySizes;
  3792. arraySizes->addInnerSize(4);
  3793. arrayType.transferArraySizes(arraySizes);
  3794. TIntermAggregate* initList = new TIntermAggregate(EOpNull);
  3795. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3796. initList->getSequence().push_back(argOffsets[offsetNum]);
  3797. argOffset = addConstructor(loc, initList, arrayType);
  3798. }
  3799. // Add comparison value if we have one
  3800. if (argCmp != nullptr)
  3801. txgather->getSequence().push_back(argCmp);
  3802. // Add offset (either 1, or an array of 4) if we have one
  3803. if (argOffset != nullptr)
  3804. txgather->getSequence().push_back(argOffset);
  3805. // Add channel value if the sampler is not shadow
  3806. if (! argSamp->getType().getSampler().isShadow())
  3807. txgather->getSequence().push_back(argChannel);
  3808. txgather->setType(node->getType());
  3809. txgather->setLoc(loc);
  3810. node = txgather;
  3811. break;
  3812. }
  3813. case EOpMethodCalculateLevelOfDetail:
  3814. case EOpMethodCalculateLevelOfDetailUnclamped:
  3815. {
  3816. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3817. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3818. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3819. TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
  3820. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3821. txquerylod->getSequence().push_back(txcombine);
  3822. txquerylod->getSequence().push_back(argCoord);
  3823. TIntermTyped* lodComponent = intermediate.addConstantUnion(
  3824. op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
  3825. loc, true);
  3826. TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
  3827. lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
  3828. node = lodComponentIdx;
  3829. break;
  3830. }
  3831. case EOpMethodGetSamplePosition:
  3832. {
  3833. // TODO: this entire decomposition exists because there is not yet a way to query
  3834. // the sample position directly through SPIR-V. Instead, we return fixed sample
  3835. // positions for common cases. *** If the sample positions are set differently,
  3836. // this will be wrong. ***
  3837. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3838. TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
  3839. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3840. samplesQuery->getSequence().push_back(argTex);
  3841. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3842. samplesQuery->setLoc(loc);
  3843. TIntermAggregate* compoundStatement = nullptr;
  3844. TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
  3845. outSampleCount->getWritableType().getQualifier().makeTemporary();
  3846. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
  3847. samplesQuery, loc);
  3848. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3849. TIntermTyped* idxtest[4];
  3850. // Create tests against 2, 4, 8, and 16 sample values
  3851. int count = 0;
  3852. for (int val = 2; val <= 16; val *= 2)
  3853. idxtest[count++] =
  3854. intermediate.addBinaryNode(EOpEqual,
  3855. intermediate.addSymbol(*outSampleCount, loc),
  3856. intermediate.addConstantUnion(val, loc),
  3857. loc, TType(EbtBool));
  3858. const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3859. // Create index ops into position arrays given sample index.
  3860. // TODO: should it be clamped?
  3861. TIntermTyped* index[4];
  3862. count = 0;
  3863. for (int val = 2; val <= 16; val *= 2) {
  3864. index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
  3865. index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
  3866. }
  3867. // Create expression as:
  3868. // (sampleCount == 2) ? pos2[idx] :
  3869. // (sampleCount == 4) ? pos4[idx] :
  3870. // (sampleCount == 8) ? pos8[idx] :
  3871. // (sampleCount == 16) ? pos16[idx] : float2(0,0);
  3872. TIntermTyped* test =
  3873. intermediate.addSelection(idxtest[0], index[0],
  3874. intermediate.addSelection(idxtest[1], index[1],
  3875. intermediate.addSelection(idxtest[2], index[2],
  3876. intermediate.addSelection(idxtest[3], index[3],
  3877. getSamplePosArray(1), loc), loc), loc), loc);
  3878. compoundStatement = intermediate.growAggregate(compoundStatement, test);
  3879. compoundStatement->setOperator(EOpSequence);
  3880. compoundStatement->setLoc(loc);
  3881. compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
  3882. node = compoundStatement;
  3883. break;
  3884. }
  3885. case EOpSubpassLoad:
  3886. {
  3887. const TIntermTyped* argSubpass =
  3888. argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
  3889. arguments->getAsTyped();
  3890. const TSampler& sampler = argSubpass->getType().getSampler();
  3891. // subpass load: the multisample form is overloaded. Here, we convert that to
  3892. // the EOpSubpassLoadMS opcode.
  3893. if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
  3894. node->getAsOperator()->setOp(EOpSubpassLoadMS);
  3895. node = convertReturn(node, sampler);
  3896. break;
  3897. }
  3898. default:
  3899. break; // most pass through unchanged
  3900. }
  3901. }
  3902. //
  3903. // Decompose geometry shader methods
  3904. //
  3905. void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3906. {
  3907. if (node == nullptr || !node->getAsOperator())
  3908. return;
  3909. const TOperator op = node->getAsOperator()->getOp();
  3910. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3911. switch (op) {
  3912. case EOpMethodAppend:
  3913. if (argAggregate) {
  3914. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3915. if (language != EShLangGeometry) {
  3916. node = nullptr;
  3917. return;
  3918. }
  3919. TIntermAggregate* sequence = nullptr;
  3920. TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
  3921. emit->setLoc(loc);
  3922. emit->setType(TType(EbtVoid));
  3923. TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
  3924. // This will be patched in finalization during finalizeAppendMethods()
  3925. sequence = intermediate.growAggregate(sequence, data, loc);
  3926. sequence = intermediate.growAggregate(sequence, emit);
  3927. sequence->setOperator(EOpSequence);
  3928. sequence->setLoc(loc);
  3929. sequence->setType(TType(EbtVoid));
  3930. gsAppends.push_back({sequence, loc});
  3931. node = sequence;
  3932. }
  3933. break;
  3934. case EOpMethodRestartStrip:
  3935. {
  3936. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3937. if (language != EShLangGeometry) {
  3938. node = nullptr;
  3939. return;
  3940. }
  3941. TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
  3942. cut->setLoc(loc);
  3943. cut->setType(TType(EbtVoid));
  3944. node = cut;
  3945. }
  3946. break;
  3947. default:
  3948. break; // most pass through unchanged
  3949. }
  3950. }
  3951. //
  3952. // Optionally decompose intrinsics to AST opcodes.
  3953. //
  3954. void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3955. {
  3956. // Helper to find image data for image atomics:
  3957. // OpImageLoad(image[idx])
  3958. // We take the image load apart and add its params to the atomic op aggregate node
  3959. const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
  3960. TIntermAggregate* loadOp = load->getAsAggregate();
  3961. if (loadOp == nullptr) {
  3962. error(loc, "unknown image type in atomic operation", "", "");
  3963. node = nullptr;
  3964. return;
  3965. }
  3966. atomic->getSequence().push_back(loadOp->getSequence()[0]);
  3967. atomic->getSequence().push_back(loadOp->getSequence()[1]);
  3968. };
  3969. // Return true if this is an imageLoad, which we will change to an image atomic.
  3970. const auto isImageParam = [](TIntermTyped* image) -> bool {
  3971. TIntermAggregate* imageAggregate = image->getAsAggregate();
  3972. return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
  3973. };
  3974. const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
  3975. TSymbol* symbol = symbolTable.find(name);
  3976. if (nullptr == symbol) {
  3977. type.getQualifier().builtIn = builtin;
  3978. TVariable* variable = new TVariable(NewPoolTString(name), type);
  3979. symbolTable.insert(*variable);
  3980. symbol = symbolTable.find(name);
  3981. assert(symbol && "Inserted symbol could not be found!");
  3982. }
  3983. return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
  3984. };
  3985. // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
  3986. // opcodes for compatibility with existing software stacks.
  3987. static const bool decomposeHlslIntrinsics = true;
  3988. if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
  3989. return;
  3990. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3991. TIntermUnary* fnUnary = node->getAsUnaryNode();
  3992. const TOperator op = node->getAsOperator()->getOp();
  3993. switch (op) {
  3994. case EOpGenMul:
  3995. {
  3996. // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
  3997. // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
  3998. // we must reverse the operand order here. Hence, arg0 gets sequence[1], etc.
  3999. TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
  4000. TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
  4001. if (arg0->isVector() && arg1->isVector()) { // vec * vec
  4002. node->getAsAggregate()->setOperator(EOpDot);
  4003. } else {
  4004. node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
  4005. }
  4006. break;
  4007. }
  4008. case EOpRcp:
  4009. {
  4010. // rcp(a) -> 1 / a
  4011. TIntermTyped* arg0 = fnUnary->getOperand();
  4012. TBasicType type0 = arg0->getBasicType();
  4013. TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
  4014. node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
  4015. break;
  4016. }
  4017. case EOpAny: // fall through
  4018. case EOpAll:
  4019. {
  4020. TIntermTyped* typedArg = arguments->getAsTyped();
  4021. // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
  4022. // We'll convert here. Note that for efficiency, we could add a smarter
  4023. // decomposition for some type cases, e.g, maybe by decomposing a dot product.
  4024. if (typedArg->getType().getBasicType() != EbtBool) {
  4025. const TType boolType(EbtBool, EvqTemporary,
  4026. typedArg->getVectorSize(),
  4027. typedArg->getMatrixCols(),
  4028. typedArg->getMatrixRows(),
  4029. typedArg->isVector());
  4030. typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
  4031. node->getAsUnaryNode()->setOperand(typedArg);
  4032. }
  4033. break;
  4034. }
  4035. case EOpSaturate:
  4036. {
  4037. // saturate(a) -> clamp(a,0,1)
  4038. TIntermTyped* arg0 = fnUnary->getOperand();
  4039. TBasicType type0 = arg0->getBasicType();
  4040. TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
  4041. clamp->getSequence().push_back(arg0);
  4042. clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
  4043. clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
  4044. clamp->setLoc(loc);
  4045. clamp->setType(node->getType());
  4046. clamp->getWritableType().getQualifier().makeTemporary();
  4047. node = clamp;
  4048. break;
  4049. }
  4050. case EOpSinCos:
  4051. {
  4052. // sincos(a,b,c) -> b = sin(a), c = cos(a)
  4053. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4054. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4055. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
  4056. TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
  4057. TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
  4058. TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
  4059. TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
  4060. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
  4061. compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
  4062. compoundStatement->setOperator(EOpSequence);
  4063. compoundStatement->setLoc(loc);
  4064. compoundStatement->setType(TType(EbtVoid));
  4065. node = compoundStatement;
  4066. break;
  4067. }
  4068. case EOpClip:
  4069. {
  4070. // clip(a) -> if (any(a<0)) discard;
  4071. TIntermTyped* arg0 = fnUnary->getOperand();
  4072. TBasicType type0 = arg0->getBasicType();
  4073. TIntermTyped* compareNode = nullptr;
  4074. // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
  4075. if (!arg0->isScalar()) {
  4076. // component-wise compare: a < 0
  4077. TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
  4078. less->getSequence().push_back(arg0);
  4079. less->setLoc(loc);
  4080. // make vec or mat of bool matching dimensions of input
  4081. less->setType(TType(EbtBool, EvqTemporary,
  4082. arg0->getType().getVectorSize(),
  4083. arg0->getType().getMatrixCols(),
  4084. arg0->getType().getMatrixRows(),
  4085. arg0->getType().isVector()));
  4086. // calculate # of components for comparison const
  4087. const int constComponentCount =
  4088. std::max(arg0->getType().getVectorSize(), 1) *
  4089. std::max(arg0->getType().getMatrixCols(), 1) *
  4090. std::max(arg0->getType().getMatrixRows(), 1);
  4091. TConstUnion zero;
  4092. if (arg0->getType().isIntegerDomain())
  4093. zero.setDConst(0);
  4094. else
  4095. zero.setDConst(0.0);
  4096. TConstUnionArray zeros(constComponentCount, zero);
  4097. less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
  4098. compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
  4099. } else {
  4100. TIntermTyped* zero;
  4101. if (arg0->getType().isIntegerDomain())
  4102. zero = intermediate.addConstantUnion(0, loc, true);
  4103. else
  4104. zero = intermediate.addConstantUnion(0.0, type0, loc, true);
  4105. compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
  4106. }
  4107. TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
  4108. node = new TIntermSelection(compareNode, killNode, nullptr);
  4109. node->setLoc(loc);
  4110. break;
  4111. }
  4112. case EOpLog10:
  4113. {
  4114. // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
  4115. TIntermTyped* arg0 = fnUnary->getOperand();
  4116. TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
  4117. TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
  4118. node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
  4119. break;
  4120. }
  4121. case EOpDst:
  4122. {
  4123. // dest.x = 1;
  4124. // dest.y = src0.y * src1.y;
  4125. // dest.z = src0.z;
  4126. // dest.w = src1.w;
  4127. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4128. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4129. TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
  4130. TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
  4131. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  4132. TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
  4133. TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
  4134. TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
  4135. TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  4136. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4137. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4138. dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
  4139. dst->getSequence().push_back(src0z);
  4140. dst->getSequence().push_back(src1w);
  4141. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4142. dst->setLoc(loc);
  4143. node = dst;
  4144. break;
  4145. }
  4146. case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
  4147. case EOpInterlockedMin: // ...
  4148. case EOpInterlockedMax: // ...
  4149. case EOpInterlockedAnd: // ...
  4150. case EOpInterlockedOr: // ...
  4151. case EOpInterlockedXor: // ...
  4152. case EOpInterlockedExchange: // always has output arg
  4153. {
  4154. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4155. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // value
  4156. TIntermTyped* arg2 = nullptr;
  4157. if (argAggregate->getSequence().size() > 2)
  4158. arg2 = argAggregate->getSequence()[2]->getAsTyped();
  4159. const bool isImage = isImageParam(arg0);
  4160. const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
  4161. TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
  4162. atomic->setType(arg0->getType());
  4163. atomic->getWritableType().getQualifier().makeTemporary();
  4164. atomic->setLoc(loc);
  4165. if (isImage) {
  4166. // orig_value = imageAtomicOp(image, loc, data)
  4167. imageAtomicParams(atomic, arg0);
  4168. atomic->getSequence().push_back(arg1);
  4169. if (argAggregate->getSequence().size() > 2) {
  4170. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4171. } else {
  4172. node = atomic; // no assignment needed, as there was no out var.
  4173. }
  4174. } else {
  4175. // Normal memory variable:
  4176. // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
  4177. if (argAggregate->getSequence().size() > 2) {
  4178. // optional output param is present. return value goes to arg2.
  4179. atomic->getSequence().push_back(arg0);
  4180. atomic->getSequence().push_back(arg1);
  4181. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4182. } else {
  4183. // Set the matching operator. Since output is absent, this is all we need to do.
  4184. node->getAsAggregate()->setOperator(atomicOp);
  4185. node->setType(atomic->getType());
  4186. }
  4187. }
  4188. break;
  4189. }
  4190. case EOpInterlockedCompareExchange:
  4191. {
  4192. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4193. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
  4194. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
  4195. TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
  4196. const bool isImage = isImageParam(arg0);
  4197. TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
  4198. atomic->setLoc(loc);
  4199. atomic->setType(arg2->getType());
  4200. atomic->getWritableType().getQualifier().makeTemporary();
  4201. if (isImage) {
  4202. imageAtomicParams(atomic, arg0);
  4203. } else {
  4204. atomic->getSequence().push_back(arg0);
  4205. }
  4206. atomic->getSequence().push_back(arg1);
  4207. atomic->getSequence().push_back(arg2);
  4208. node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
  4209. break;
  4210. }
  4211. case EOpEvaluateAttributeSnapped:
  4212. {
  4213. // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
  4214. // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
  4215. // iU = (iU<<28)>>28
  4216. // fU = ((float)iU)/16
  4217. // Targets might handle this natively, in which case they can disable
  4218. // decompositions.
  4219. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
  4220. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
  4221. TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
  4222. TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
  4223. handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
  4224. i28);
  4225. TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
  4226. TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
  4227. intermediate.addConversion(EOpConstructFloat,
  4228. TType(EbtFloat, EvqTemporary, 2), iU),
  4229. recip16);
  4230. TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
  4231. interp->getSequence().push_back(arg0);
  4232. interp->getSequence().push_back(floatOffset);
  4233. interp->setLoc(loc);
  4234. interp->setType(arg0->getType());
  4235. interp->getWritableType().getQualifier().makeTemporary();
  4236. node = interp;
  4237. break;
  4238. }
  4239. case EOpLit:
  4240. {
  4241. TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
  4242. TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
  4243. TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
  4244. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4245. // Ambient
  4246. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4247. // Diffuse:
  4248. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4249. TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
  4250. diffuse->getSequence().push_back(n_dot_l);
  4251. diffuse->getSequence().push_back(zero);
  4252. diffuse->setLoc(loc);
  4253. diffuse->setType(TType(EbtFloat));
  4254. dst->getSequence().push_back(diffuse);
  4255. // Specular:
  4256. TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
  4257. min_ndot->getSequence().push_back(n_dot_l);
  4258. min_ndot->getSequence().push_back(n_dot_h);
  4259. min_ndot->setLoc(loc);
  4260. min_ndot->setType(TType(EbtFloat));
  4261. TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
  4262. TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
  4263. dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
  4264. // One:
  4265. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4266. dst->setLoc(loc);
  4267. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4268. node = dst;
  4269. break;
  4270. }
  4271. case EOpAsDouble:
  4272. {
  4273. // asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
  4274. // first construct a uint64.
  4275. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4276. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4277. if (arg0->getType().isVector()) { // TODO: ...
  4278. error(loc, "double2 conversion not implemented", "asdouble", "");
  4279. break;
  4280. }
  4281. TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
  4282. uint64->getSequence().push_back(arg0);
  4283. uint64->getSequence().push_back(arg1);
  4284. uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
  4285. uint64->setLoc(loc);
  4286. // bitcast uint2 to a double
  4287. TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
  4288. convert->getAsUnaryNode()->setOperand(uint64);
  4289. convert->setLoc(loc);
  4290. convert->setType(TType(EbtDouble, EvqTemporary));
  4291. node = convert;
  4292. break;
  4293. }
  4294. case EOpF16tof32:
  4295. {
  4296. // input uvecN with low 16 bits of each component holding a float16. convert to float32.
  4297. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4298. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  4299. const int vecSize = argValue->getType().getVectorSize();
  4300. TOperator constructOp = EOpNull;
  4301. switch (vecSize) {
  4302. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4303. case 2: constructOp = EOpConstructVec2; break;
  4304. case 3: constructOp = EOpConstructVec3; break;
  4305. case 4: constructOp = EOpConstructVec4; break;
  4306. default: assert(0); break;
  4307. }
  4308. // For scalar case, we don't need to construct another type.
  4309. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4310. if (result) {
  4311. result->setType(TType(EbtFloat, EvqTemporary, vecSize));
  4312. result->setLoc(loc);
  4313. }
  4314. for (int idx = 0; idx < vecSize; ++idx) {
  4315. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4316. TIntermTyped* component = argValue->getType().isVector() ?
  4317. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4318. if (component != argValue)
  4319. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4320. TIntermTyped* unpackOp = new TIntermUnary(EOpUnpackHalf2x16);
  4321. unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
  4322. unpackOp->getAsUnaryNode()->setOperand(component);
  4323. unpackOp->setLoc(loc);
  4324. TIntermTyped* lowOrder = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
  4325. if (result != nullptr) {
  4326. result->getSequence().push_back(lowOrder);
  4327. node = result;
  4328. } else {
  4329. node = lowOrder;
  4330. }
  4331. }
  4332. break;
  4333. }
  4334. case EOpF32tof16:
  4335. {
  4336. // input floatN converted to 16 bit float in low order bits of each component of uintN
  4337. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4338. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4339. const int vecSize = argValue->getType().getVectorSize();
  4340. TOperator constructOp = EOpNull;
  4341. switch (vecSize) {
  4342. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4343. case 2: constructOp = EOpConstructUVec2; break;
  4344. case 3: constructOp = EOpConstructUVec3; break;
  4345. case 4: constructOp = EOpConstructUVec4; break;
  4346. default: assert(0); break;
  4347. }
  4348. // For scalar case, we don't need to construct another type.
  4349. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4350. if (result) {
  4351. result->setType(TType(EbtUint, EvqTemporary, vecSize));
  4352. result->setLoc(loc);
  4353. }
  4354. for (int idx = 0; idx < vecSize; ++idx) {
  4355. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4356. TIntermTyped* component = argValue->getType().isVector() ?
  4357. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4358. if (component != argValue)
  4359. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4360. TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
  4361. vec2ComponentAndZero->getSequence().push_back(component);
  4362. vec2ComponentAndZero->getSequence().push_back(zero);
  4363. vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
  4364. vec2ComponentAndZero->setLoc(loc);
  4365. TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
  4366. packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
  4367. packOp->setLoc(loc);
  4368. packOp->setType(TType(EbtUint, EvqTemporary));
  4369. if (result != nullptr) {
  4370. result->getSequence().push_back(packOp);
  4371. node = result;
  4372. } else {
  4373. node = packOp;
  4374. }
  4375. }
  4376. break;
  4377. }
  4378. case EOpD3DCOLORtoUBYTE4:
  4379. {
  4380. // ivec4 ( x.zyxw * 255.001953 );
  4381. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4382. TSwizzleSelectors<TVectorSelector> selectors;
  4383. selectors.push_back(2);
  4384. selectors.push_back(1);
  4385. selectors.push_back(0);
  4386. selectors.push_back(3);
  4387. TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
  4388. TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
  4389. swizzled->setType(arg0->getType());
  4390. swizzled->getWritableType().getQualifier().makeTemporary();
  4391. TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
  4392. TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
  4393. rangeConverted->setType(arg0->getType());
  4394. rangeConverted->getWritableType().getQualifier().makeTemporary();
  4395. node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
  4396. node->setLoc(loc);
  4397. node->setType(TType(EbtInt, EvqTemporary, 4));
  4398. break;
  4399. }
  4400. case EOpIsFinite:
  4401. {
  4402. // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
  4403. // it to !isnan && !isinf
  4404. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4405. // We'll make a temporary in case the RHS is cmoplex
  4406. TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
  4407. tempArg->getWritableType().getQualifier().makeTemporary();
  4408. TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
  4409. intermediate.addSymbol(*tempArg, loc),
  4410. arg0, loc);
  4411. TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
  4412. const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
  4413. arg0->getMatrixRows());
  4414. TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
  4415. isnan->setType(boolType);
  4416. TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
  4417. notnan->setType(boolType);
  4418. TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
  4419. isinf->setType(boolType);
  4420. TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
  4421. notinf->setType(boolType);
  4422. TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
  4423. andNode->setType(boolType);
  4424. compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
  4425. compoundStatement->setOperator(EOpSequence);
  4426. compoundStatement->setLoc(loc);
  4427. compoundStatement->setType(boolType);
  4428. node = compoundStatement;
  4429. break;
  4430. }
  4431. case EOpWaveGetLaneCount:
  4432. {
  4433. // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
  4434. // so that it inhabits the symbol table, but has a user-invalid name
  4435. // in-case some source HLSL defined the symbol also).
  4436. TType type(EbtUint, EvqVaryingIn);
  4437. node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
  4438. break;
  4439. }
  4440. case EOpWaveGetLaneIndex:
  4441. {
  4442. // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
  4443. // symbol so that it inhabits the symbol table, but has a
  4444. // user-invalid name in-case some source HLSL defined the symbol
  4445. // also).
  4446. TType type(EbtUint, EvqVaryingIn);
  4447. node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
  4448. break;
  4449. }
  4450. case EOpWaveActiveCountBits:
  4451. {
  4452. // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
  4453. // uvec4 type.
  4454. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4455. // Get the uvec4 return from subgroupBallot().
  4456. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4457. EOpSubgroupBallot, true, arguments, uvec4Type);
  4458. // uint type.
  4459. TType uintType(EbtUint, EvqTemporary);
  4460. node = intermediate.addBuiltInFunctionCall(loc,
  4461. EOpSubgroupBallotBitCount, true, res, uintType);
  4462. break;
  4463. }
  4464. case EOpWavePrefixCountBits:
  4465. {
  4466. // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
  4467. // builtin
  4468. // uvec4 type.
  4469. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4470. // Get the uvec4 return from subgroupBallot().
  4471. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4472. EOpSubgroupBallot, true, arguments, uvec4Type);
  4473. // uint type.
  4474. TType uintType(EbtUint, EvqTemporary);
  4475. node = intermediate.addBuiltInFunctionCall(loc,
  4476. EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
  4477. break;
  4478. }
  4479. default:
  4480. break; // most pass through unchanged
  4481. }
  4482. }
  4483. //
  4484. // Handle seeing function call syntax in the grammar, which could be any of
  4485. // - .length() method
  4486. // - constructor
  4487. // - a call to a built-in function mapped to an operator
  4488. // - a call to a built-in function that will remain a function call (e.g., texturing)
  4489. // - user function
  4490. // - subroutine call (not implemented yet)
  4491. //
  4492. TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
  4493. {
  4494. TIntermTyped* result = nullptr;
  4495. TOperator op = function->getBuiltInOp();
  4496. if (op != EOpNull) {
  4497. //
  4498. // Then this should be a constructor.
  4499. // Don't go through the symbol table for constructors.
  4500. // Their parameters will be verified algorithmically.
  4501. //
  4502. TType type(EbtVoid); // use this to get the type back
  4503. if (! constructorError(loc, arguments, *function, op, type)) {
  4504. //
  4505. // It's a constructor, of type 'type'.
  4506. //
  4507. result = handleConstructor(loc, arguments, type);
  4508. if (result == nullptr) {
  4509. error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
  4510. return nullptr;
  4511. }
  4512. }
  4513. } else {
  4514. //
  4515. // Find it in the symbol table.
  4516. //
  4517. const TFunction* fnCandidate = nullptr;
  4518. bool builtIn = false;
  4519. int thisDepth = 0;
  4520. // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
  4521. // and clamp the opposite arg. Since that's complex, we farm it off to a separate method.
  4522. // It doesn't naturally fall out of processing an argument at a time in isolation.
  4523. if (function->getName() == "mul")
  4524. addGenMulArgumentConversion(loc, *function, arguments);
  4525. TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4526. // TODO: this needs improvement: there's no way at present to look up a signature in
  4527. // the symbol table for an arbitrary type. This is a temporary hack until that ability exists.
  4528. // It will have false positives, since it doesn't check arg counts or types.
  4529. if (arguments) {
  4530. // Check if first argument is struct buffer type. It may be an aggregate or a symbol, so we
  4531. // look for either case.
  4532. TIntermTyped* arg0 = nullptr;
  4533. if (aggregate && aggregate->getSequence().size() > 0 && aggregate->getSequence()[0])
  4534. arg0 = aggregate->getSequence()[0]->getAsTyped();
  4535. else if (arguments->getAsSymbolNode())
  4536. arg0 = arguments->getAsSymbolNode();
  4537. if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
  4538. static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
  4539. if (function->getName().length() > methodPrefixSize &&
  4540. isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
  4541. const TString mangle = function->getName() + "(";
  4542. TSymbol* symbol = symbolTable.find(mangle, &builtIn);
  4543. if (symbol)
  4544. fnCandidate = symbol->getAsFunction();
  4545. }
  4546. }
  4547. }
  4548. if (fnCandidate == nullptr)
  4549. fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
  4550. if (fnCandidate) {
  4551. // This is a declared function that might map to
  4552. // - a built-in operator,
  4553. // - a built-in function not mapped to an operator, or
  4554. // - a user function.
  4555. // turn an implicit member-function resolution into an explicit call
  4556. TString callerName;
  4557. if (thisDepth == 0)
  4558. callerName = fnCandidate->getMangledName();
  4559. else {
  4560. // get the explicit (full) name of the function
  4561. callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
  4562. callerName += fnCandidate->getMangledName();
  4563. // insert the implicit calling argument
  4564. pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
  4565. }
  4566. // Convert 'in' arguments, so that types match.
  4567. // However, skip those that need expansion, that is covered next.
  4568. if (arguments)
  4569. addInputArgumentConversions(*fnCandidate, arguments);
  4570. // Expand arguments. Some arguments must physically expand to a different set
  4571. // than what the shader declared and passes.
  4572. if (arguments && !builtIn)
  4573. expandArguments(loc, *fnCandidate, arguments);
  4574. // Expansion may have changed the form of arguments
  4575. aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4576. op = fnCandidate->getBuiltInOp();
  4577. if (builtIn && op != EOpNull) {
  4578. // SM 4.0 and above guarantees roundEven semantics for round()
  4579. if (!hlslDX9Compatible() && op == EOpRound)
  4580. op = EOpRoundEven;
  4581. // A function call mapped to a built-in operation.
  4582. result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
  4583. fnCandidate->getType());
  4584. if (result == nullptr) {
  4585. error(arguments->getLoc(), " wrong operand type", "Internal Error",
  4586. "built in unary operator function. Type: %s",
  4587. static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
  4588. } else if (result->getAsOperator()) {
  4589. builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
  4590. }
  4591. } else {
  4592. // This is a function call not mapped to built-in operator.
  4593. // It could still be a built-in function, but only if PureOperatorBuiltins == false.
  4594. result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
  4595. TIntermAggregate* call = result->getAsAggregate();
  4596. call->setName(callerName);
  4597. // this is how we know whether the given function is a built-in function or a user-defined function
  4598. // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
  4599. // if builtIn == true, it's definitely a built-in function with EOpNull
  4600. if (! builtIn) {
  4601. call->setUserDefined();
  4602. intermediate.addToCallGraph(infoSink, currentCaller, callerName);
  4603. }
  4604. }
  4605. // for decompositions, since we want to operate on the function node, not the aggregate holding
  4606. // output conversions.
  4607. const TIntermTyped* fnNode = result;
  4608. decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
  4609. decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
  4610. decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
  4611. decomposeGeometryMethods(loc, result, arguments); // HLSL->AST geometry method decompositions
  4612. // Create the qualifier list, carried in the AST for the call.
  4613. // Because some arguments expand to multiple arguments, the qualifier list will
  4614. // be longer than the formal parameter list.
  4615. if (result == fnNode && result->getAsAggregate()) {
  4616. TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
  4617. for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
  4618. TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
  4619. if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
  4620. // add buffer and counter buffer argument qualifier
  4621. qualifierList.push_back(qual);
  4622. qualifierList.push_back(qual);
  4623. } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
  4624. true)) {
  4625. // add structure member expansion
  4626. for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
  4627. qualifierList.push_back(qual);
  4628. } else {
  4629. // Normal 1:1 case
  4630. qualifierList.push_back(qual);
  4631. }
  4632. }
  4633. }
  4634. // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
  4635. // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
  4636. // Also, build the qualifier list for user function calls, which are always called with an aggregate.
  4637. // We don't do this is if there has been a decomposition, which will have added its own conversions
  4638. // for output parameters.
  4639. if (result == fnNode && result->getAsAggregate())
  4640. result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
  4641. }
  4642. }
  4643. // generic error recovery
  4644. // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
  4645. // reduce cascades
  4646. if (result == nullptr)
  4647. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  4648. return result;
  4649. }
  4650. // An initial argument list is difficult: it can be null, or a single node,
  4651. // or an aggregate if more than one argument. Add one to the front, maintaining
  4652. // this lack of uniformity.
  4653. void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
  4654. {
  4655. if (arguments == nullptr)
  4656. arguments = front;
  4657. else if (arguments->getAsAggregate() != nullptr)
  4658. arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
  4659. else
  4660. arguments = intermediate.growAggregate(front, arguments);
  4661. }
  4662. //
  4663. // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat. This is a
  4664. // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
  4665. // can look at both arguments insert explicit shape changes if required.
  4666. //
  4667. void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
  4668. {
  4669. TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
  4670. if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
  4671. // It really ought to have two arguments.
  4672. error(loc, "expected: mul arguments", "", "");
  4673. return;
  4674. }
  4675. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4676. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4677. if (arg0->isVector() && arg1->isVector()) {
  4678. // For:
  4679. // vec * vec: it's handled during intrinsic selection, so while we could do it here,
  4680. // we can also ignore it, which is easier.
  4681. } else if (arg0->isVector() && arg1->isMatrix()) {
  4682. // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4683. if (arg0->getVectorSize() < arg1->getMatrixCols()) {
  4684. // vec is smaller, so truncate larger mat dimension
  4685. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4686. 0, arg0->getVectorSize(), arg1->getMatrixRows());
  4687. arg1 = addConstructor(loc, arg1, truncType);
  4688. } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
  4689. // vec is larger, so truncate vec to mat size
  4690. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4691. arg1->getMatrixCols());
  4692. arg0 = addConstructor(loc, arg0, truncType);
  4693. }
  4694. } else if (arg0->isMatrix() && arg1->isVector()) {
  4695. // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4696. if (arg1->getVectorSize() < arg0->getMatrixRows()) {
  4697. // vec is smaller, so truncate larger mat dimension
  4698. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4699. 0, arg0->getMatrixCols(), arg1->getVectorSize());
  4700. arg0 = addConstructor(loc, arg0, truncType);
  4701. } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
  4702. // vec is larger, so truncate vec to mat size
  4703. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4704. arg0->getMatrixRows());
  4705. arg1 = addConstructor(loc, arg1, truncType);
  4706. }
  4707. } else if (arg0->isMatrix() && arg1->isMatrix()) {
  4708. // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
  4709. // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
  4710. if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
  4711. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4712. 0, arg0->getMatrixCols(), arg1->getMatrixCols());
  4713. arg0 = addConstructor(loc, arg0, truncType);
  4714. } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
  4715. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4716. 0, arg0->getMatrixRows(), arg1->getMatrixRows());
  4717. arg1 = addConstructor(loc, arg1, truncType);
  4718. }
  4719. } else {
  4720. // It's something with scalars: we'll just leave it alone. Function selection will handle it
  4721. // downstream.
  4722. }
  4723. // Warn if we altered one of the arguments
  4724. if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
  4725. warn(loc, "mul() matrix size mismatch", "", "");
  4726. // Put arguments back. (They might be unchanged, in which case this is harmless).
  4727. argAggregate->getSequence()[0] = arg0;
  4728. argAggregate->getSequence()[1] = arg1;
  4729. call[0].type = &arg0->getWritableType();
  4730. call[1].type = &arg1->getWritableType();
  4731. }
  4732. //
  4733. // Add any needed implicit conversions for function-call arguments to input parameters.
  4734. //
  4735. void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
  4736. {
  4737. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4738. // Replace a single argument with a single argument.
  4739. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4740. if (function.getParamCount() == 1)
  4741. arguments = arg;
  4742. else {
  4743. if (aggregate == nullptr)
  4744. arguments = arg;
  4745. else
  4746. aggregate->getSequence()[paramNum] = arg;
  4747. }
  4748. };
  4749. // Process each argument's conversion
  4750. for (int param = 0; param < function.getParamCount(); ++param) {
  4751. if (! function[param].type->getQualifier().isParamInput())
  4752. continue;
  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]->getAsTyped() :
  4760. arguments->getAsTyped());
  4761. if (*function[param].type != arg->getType()) {
  4762. // In-qualified arguments just need an extra node added above the argument to
  4763. // convert to the correct type.
  4764. TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
  4765. if (convArg != nullptr)
  4766. convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
  4767. if (convArg != nullptr)
  4768. setArg(param, convArg);
  4769. else
  4770. error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
  4771. } else {
  4772. if (wasFlattened(arg)) {
  4773. // If both formal and calling arg are to be flattened, leave that to argument
  4774. // expansion, not conversion.
  4775. if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4776. // Will make a two-level subtree.
  4777. // The deepest will copy member-by-member to build the structure to pass.
  4778. // The level above that will be a two-operand EOpComma sequence that follows the copy by the
  4779. // object itself.
  4780. TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
  4781. internalAggregate->getWritableType().getQualifier().makeTemporary();
  4782. TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
  4783. internalAggregate->getName(),
  4784. internalAggregate->getType());
  4785. internalSymbolNode->setLoc(arg->getLoc());
  4786. // This makes the deepest level, the member-wise copy
  4787. TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
  4788. internalSymbolNode, arg)->getAsAggregate();
  4789. // Now, pair that with the resulting aggregate.
  4790. assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
  4791. assignAgg->setOperator(EOpComma);
  4792. assignAgg->setType(internalAggregate->getType());
  4793. setArg(param, assignAgg);
  4794. }
  4795. }
  4796. }
  4797. }
  4798. }
  4799. //
  4800. // Add any needed implicit expansion of calling arguments from what the shader listed to what's
  4801. // internally needed for the AST (given the constraints downstream).
  4802. //
  4803. void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
  4804. {
  4805. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4806. int functionParamNumberOffset = 0;
  4807. // Replace a single argument with a single argument.
  4808. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4809. if (function.getParamCount() + functionParamNumberOffset == 1)
  4810. arguments = arg;
  4811. else {
  4812. if (aggregate == nullptr)
  4813. arguments = arg;
  4814. else
  4815. aggregate->getSequence()[paramNum] = arg;
  4816. }
  4817. };
  4818. // Replace a single argument with a list of arguments
  4819. const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
  4820. if (args.size() == 1)
  4821. setArg(paramNum, args.front());
  4822. else if (args.size() > 1) {
  4823. if (function.getParamCount() + functionParamNumberOffset == 1) {
  4824. arguments = intermediate.makeAggregate(args.front());
  4825. std::for_each(args.begin() + 1, args.end(),
  4826. [&](TIntermTyped* arg) {
  4827. arguments = intermediate.growAggregate(arguments, arg);
  4828. });
  4829. } else {
  4830. auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
  4831. aggregate->getSequence().insert(it, args.begin(), args.end());
  4832. }
  4833. functionParamNumberOffset += (int)(args.size() - 1);
  4834. }
  4835. };
  4836. // Process each argument's conversion
  4837. for (int param = 0; param < function.getParamCount(); ++param) {
  4838. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4839. // is the single argument itself or its children are the arguments. Only one argument
  4840. // means take 'arguments' itself as the one argument.
  4841. TIntermTyped* arg = function.getParamCount() == 1
  4842. ? arguments->getAsTyped()
  4843. : (aggregate ?
  4844. aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
  4845. arguments->getAsTyped());
  4846. if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4847. // Need to pass the structure members instead of the structure.
  4848. TVector<TIntermTyped*> memberArgs;
  4849. for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
  4850. memberArgs.push_back(flattenAccess(arg, memb));
  4851. setArgList(param + functionParamNumberOffset, memberArgs);
  4852. }
  4853. }
  4854. // TODO: if we need both hidden counter args (below) and struct expansion (above)
  4855. // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
  4856. // parameters and arguments.
  4857. // If any argument is a pass-by-reference struct buffer with an associated counter
  4858. // buffer, we have to add another hidden parameter for that counter.
  4859. if (aggregate)
  4860. addStructBuffArguments(loc, aggregate);
  4861. }
  4862. //
  4863. // Add any needed implicit output conversions for function-call arguments. This
  4864. // can require a new tree topology, complicated further by whether the function
  4865. // has a return value.
  4866. //
  4867. // Returns a node of a subtree that evaluates to the return value of the function.
  4868. //
  4869. TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
  4870. {
  4871. assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
  4872. const TSourceLoc& loc = intermNode.getLoc();
  4873. TIntermSequence argSequence; // temp sequence for unary node args
  4874. if (intermNode.getAsUnaryNode())
  4875. argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
  4876. TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
  4877. const auto needsConversion = [&](int argNum) {
  4878. return function[argNum].type->getQualifier().isParamOutput() &&
  4879. (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
  4880. shouldConvertLValue(arguments[argNum]) ||
  4881. wasFlattened(arguments[argNum]->getAsTyped()));
  4882. };
  4883. // Will there be any output conversions?
  4884. bool outputConversions = false;
  4885. for (int i = 0; i < function.getParamCount(); ++i) {
  4886. if (needsConversion(i)) {
  4887. outputConversions = true;
  4888. break;
  4889. }
  4890. }
  4891. if (! outputConversions)
  4892. return &intermNode;
  4893. // Setup for the new tree, if needed:
  4894. //
  4895. // Output conversions need a different tree topology.
  4896. // Out-qualified arguments need a temporary of the correct type, with the call
  4897. // followed by an assignment of the temporary to the original argument:
  4898. // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
  4899. // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
  4900. // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
  4901. TIntermTyped* conversionTree = nullptr;
  4902. TVariable* tempRet = nullptr;
  4903. if (intermNode.getBasicType() != EbtVoid) {
  4904. // do the "tempRet = function(...), " bit from above
  4905. tempRet = makeInternalVariable("tempReturn", intermNode.getType());
  4906. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4907. conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
  4908. } else
  4909. conversionTree = &intermNode;
  4910. conversionTree = intermediate.makeAggregate(conversionTree);
  4911. // Process each argument's conversion
  4912. for (int i = 0; i < function.getParamCount(); ++i) {
  4913. if (needsConversion(i)) {
  4914. // Out-qualified arguments needing conversion need to use the topology setup above.
  4915. // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
  4916. // Make a temporary for what the function expects the argument to look like.
  4917. TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
  4918. tempArg->getWritableType().getQualifier().makeTemporary();
  4919. TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
  4920. // This makes the deepest level, the member-wise copy
  4921. TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
  4922. tempArgNode);
  4923. tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
  4924. conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
  4925. // replace the argument with another node for the same tempArg variable
  4926. arguments[i] = intermediate.addSymbol(*tempArg, loc);
  4927. }
  4928. }
  4929. // Finalize the tree topology (see bigger comment above).
  4930. if (tempRet) {
  4931. // do the "..., tempRet" bit from above
  4932. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4933. conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
  4934. }
  4935. conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
  4936. return conversionTree;
  4937. }
  4938. //
  4939. // Add any needed "hidden" counter buffer arguments for function calls.
  4940. //
  4941. // Modifies the 'aggregate' argument if needed. Otherwise, is no-op.
  4942. //
  4943. void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
  4944. {
  4945. // See if there are any SB types with counters.
  4946. const bool hasStructBuffArg =
  4947. std::any_of(aggregate->getSequence().begin(),
  4948. aggregate->getSequence().end(),
  4949. [this](const TIntermNode* node) {
  4950. return (node && node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
  4951. });
  4952. // Nothing to do, if we didn't find one.
  4953. if (! hasStructBuffArg)
  4954. return;
  4955. TIntermSequence argsWithCounterBuffers;
  4956. for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
  4957. argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
  4958. if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
  4959. const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
  4960. if (blockSym != nullptr) {
  4961. TType counterType;
  4962. counterBufferType(loc, counterType);
  4963. const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
  4964. TVariable* variable = makeInternalVariable(counterBlockName, counterType);
  4965. // Mark this buffer's counter block as being in use
  4966. structBufferCounter[counterBlockName] = true;
  4967. TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
  4968. argsWithCounterBuffers.push_back(sym);
  4969. }
  4970. }
  4971. }
  4972. // Swap with the temp list we've built up.
  4973. aggregate->getSequence().swap(argsWithCounterBuffers);
  4974. }
  4975. //
  4976. // Do additional checking of built-in function calls that is not caught
  4977. // by normal semantic checks on argument type, extension tagging, etc.
  4978. //
  4979. // Assumes there has been a semantically correct match to a built-in function prototype.
  4980. //
  4981. void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
  4982. {
  4983. // Set up convenience accessors to the argument(s). There is almost always
  4984. // multiple arguments for the cases below, but when there might be one,
  4985. // check the unaryArg first.
  4986. const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
  4987. const TIntermTyped* unaryArg = nullptr;
  4988. const TIntermTyped* arg0 = nullptr;
  4989. if (callNode.getAsAggregate()) {
  4990. argp = &callNode.getAsAggregate()->getSequence();
  4991. if (argp->size() > 0)
  4992. arg0 = (*argp)[0]->getAsTyped();
  4993. } else {
  4994. assert(callNode.getAsUnaryNode());
  4995. unaryArg = callNode.getAsUnaryNode()->getOperand();
  4996. arg0 = unaryArg;
  4997. }
  4998. const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
  4999. switch (callNode.getOp()) {
  5000. case EOpTextureGather:
  5001. case EOpTextureGatherOffset:
  5002. case EOpTextureGatherOffsets:
  5003. {
  5004. // Figure out which variants are allowed by what extensions,
  5005. // and what arguments must be constant for which situations.
  5006. TString featureString = fnCandidate.getName() + "(...)";
  5007. const char* feature = featureString.c_str();
  5008. int compArg = -1; // track which argument, if any, is the constant component argument
  5009. switch (callNode.getOp()) {
  5010. case EOpTextureGather:
  5011. // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
  5012. // otherwise, need GL_ARB_texture_gather.
  5013. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
  5014. fnCandidate[0].type->getSampler().shadow) {
  5015. if (! fnCandidate[0].type->getSampler().shadow)
  5016. compArg = 2;
  5017. }
  5018. break;
  5019. case EOpTextureGatherOffset:
  5020. // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
  5021. if (! fnCandidate[0].type->getSampler().shadow)
  5022. compArg = 3;
  5023. break;
  5024. case EOpTextureGatherOffsets:
  5025. if (! fnCandidate[0].type->getSampler().shadow)
  5026. compArg = 3;
  5027. break;
  5028. default:
  5029. break;
  5030. }
  5031. if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
  5032. if (aggArgs[compArg]->getAsConstantUnion()) {
  5033. int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
  5034. if (value < 0 || value > 3)
  5035. error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
  5036. } else
  5037. error(loc, "must be a compile-time constant:", feature, "component argument");
  5038. }
  5039. break;
  5040. }
  5041. case EOpTextureOffset:
  5042. case EOpTextureFetchOffset:
  5043. case EOpTextureProjOffset:
  5044. case EOpTextureLodOffset:
  5045. case EOpTextureProjLodOffset:
  5046. case EOpTextureGradOffset:
  5047. case EOpTextureProjGradOffset:
  5048. {
  5049. // Handle texture-offset limits checking
  5050. // Pick which argument has to hold constant offsets
  5051. int arg = -1;
  5052. switch (callNode.getOp()) {
  5053. case EOpTextureOffset: arg = 2; break;
  5054. case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
  5055. case EOpTextureProjOffset: arg = 2; break;
  5056. case EOpTextureLodOffset: arg = 3; break;
  5057. case EOpTextureProjLodOffset: arg = 3; break;
  5058. case EOpTextureGradOffset: arg = 4; break;
  5059. case EOpTextureProjGradOffset: arg = 4; break;
  5060. default:
  5061. assert(0);
  5062. break;
  5063. }
  5064. if (arg > 0) {
  5065. if (aggArgs[arg]->getAsConstantUnion() == nullptr)
  5066. error(loc, "argument must be compile-time constant", "texel offset", "");
  5067. else {
  5068. const TType& type = aggArgs[arg]->getAsTyped()->getType();
  5069. for (int c = 0; c < type.getVectorSize(); ++c) {
  5070. int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
  5071. if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
  5072. error(loc, "value is out of range:", "texel offset",
  5073. "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
  5074. }
  5075. }
  5076. }
  5077. break;
  5078. }
  5079. case EOpTextureQuerySamples:
  5080. case EOpImageQuerySamples:
  5081. break;
  5082. case EOpImageAtomicAdd:
  5083. case EOpImageAtomicMin:
  5084. case EOpImageAtomicMax:
  5085. case EOpImageAtomicAnd:
  5086. case EOpImageAtomicOr:
  5087. case EOpImageAtomicXor:
  5088. case EOpImageAtomicExchange:
  5089. case EOpImageAtomicCompSwap:
  5090. break;
  5091. case EOpInterpolateAtCentroid:
  5092. case EOpInterpolateAtSample:
  5093. case EOpInterpolateAtOffset:
  5094. // Make sure the first argument is an interpolant, or an array element of an interpolant
  5095. if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
  5096. // It might still be an array element.
  5097. //
  5098. // We could check more, but the semantics of the first argument are already met; the
  5099. // only way to turn an array into a float/vec* is array dereference and swizzle.
  5100. //
  5101. // ES and desktop 4.3 and earlier: swizzles may not be used
  5102. // desktop 4.4 and later: swizzles may be used
  5103. const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
  5104. if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
  5105. error(loc, "first argument must be an interpolant, or interpolant-array element",
  5106. fnCandidate.getName().c_str(), "");
  5107. }
  5108. break;
  5109. default:
  5110. break;
  5111. }
  5112. }
  5113. //
  5114. // Handle seeing something in a grammar production that can be done by calling
  5115. // a constructor.
  5116. //
  5117. // The constructor still must be "handled" by handleFunctionCall(), which will
  5118. // then call handleConstructor().
  5119. //
  5120. TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
  5121. {
  5122. TOperator op = intermediate.mapTypeToConstructorOp(type);
  5123. if (op == EOpNull) {
  5124. error(loc, "cannot construct this type", type.getBasicString(), "");
  5125. return nullptr;
  5126. }
  5127. TString empty("");
  5128. return new TFunction(&empty, type, op);
  5129. }
  5130. //
  5131. // Handle seeing a "COLON semantic" at the end of a type declaration,
  5132. // by updating the type according to the semantic.
  5133. //
  5134. void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
  5135. const TString& upperCase)
  5136. {
  5137. // Parse and return semantic number. If limit is 0, it will be ignored. Otherwise, if the parsed
  5138. // semantic number is >= limit, errorMsg is issued and 0 is returned.
  5139. // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
  5140. // accept those in lambda functions.
  5141. const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
  5142. size_t pos = semantic.find_last_not_of("0123456789");
  5143. if (pos == std::string::npos)
  5144. return 0u;
  5145. unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
  5146. if (limit != 0 && semanticNum >= limit) {
  5147. error(loc, errorMsg, semantic.c_str(), "");
  5148. return 0u;
  5149. }
  5150. return semanticNum;
  5151. };
  5152. if (builtIn == EbvNone && hlslDX9Compatible()) {
  5153. if (language == EShLangVertex) {
  5154. if (qualifier.isParamOutput()) {
  5155. if (upperCase == "POSITION") {
  5156. builtIn = EbvPosition;
  5157. }
  5158. if (upperCase == "PSIZE") {
  5159. builtIn = EbvPointSize;
  5160. }
  5161. }
  5162. } else if (language == EShLangFragment) {
  5163. if (qualifier.isParamInput() && upperCase == "VPOS") {
  5164. builtIn = EbvFragCoord;
  5165. }
  5166. if (qualifier.isParamOutput()) {
  5167. if (upperCase.compare(0, 5, "COLOR") == 0) {
  5168. qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
  5169. nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
  5170. }
  5171. if (upperCase == "DEPTH") {
  5172. builtIn = EbvFragDepth;
  5173. }
  5174. }
  5175. }
  5176. }
  5177. switch(builtIn) {
  5178. case EbvNone:
  5179. // Get location numbers from fragment outputs, instead of
  5180. // auto-assigning them.
  5181. if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
  5182. qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
  5183. nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
  5184. } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
  5185. builtIn = EbvClipDistance;
  5186. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
  5187. } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
  5188. builtIn = EbvCullDistance;
  5189. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
  5190. }
  5191. break;
  5192. case EbvPosition:
  5193. // adjust for stage in/out
  5194. if (language == EShLangFragment)
  5195. builtIn = EbvFragCoord;
  5196. break;
  5197. case EbvFragStencilRef:
  5198. error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
  5199. break;
  5200. case EbvTessLevelInner:
  5201. case EbvTessLevelOuter:
  5202. qualifier.patch = true;
  5203. break;
  5204. default:
  5205. break;
  5206. }
  5207. if (qualifier.builtIn == EbvNone)
  5208. qualifier.builtIn = builtIn;
  5209. qualifier.semanticName = intermediate.addSemanticName(upperCase);
  5210. }
  5211. //
  5212. // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
  5213. //
  5214. // 'location' has the "c[Subcomponent]" part.
  5215. // 'component' points to the "component" part, or nullptr if not present.
  5216. //
  5217. void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
  5218. const glslang::TString* component)
  5219. {
  5220. if (location.size() == 0 || location[0] != 'c') {
  5221. error(loc, "expected 'c'", "packoffset", "");
  5222. return;
  5223. }
  5224. if (location.size() == 1)
  5225. return;
  5226. if (! isdigit(location[1])) {
  5227. error(loc, "expected number after 'c'", "packoffset", "");
  5228. return;
  5229. }
  5230. qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
  5231. if (component != nullptr) {
  5232. int componentOffset = 0;
  5233. switch ((*component)[0]) {
  5234. case 'x': componentOffset = 0; break;
  5235. case 'y': componentOffset = 4; break;
  5236. case 'z': componentOffset = 8; break;
  5237. case 'w': componentOffset = 12; break;
  5238. default:
  5239. componentOffset = -1;
  5240. break;
  5241. }
  5242. if (componentOffset < 0 || component->size() > 1) {
  5243. error(loc, "expected {x, y, z, w} for component", "packoffset", "");
  5244. return;
  5245. }
  5246. qualifier.layoutOffset += componentOffset;
  5247. }
  5248. }
  5249. //
  5250. // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
  5251. //
  5252. // 'profile' points to the shader_profile part, or nullptr if not present.
  5253. // 'desc' is the type# part.
  5254. //
  5255. void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
  5256. const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
  5257. {
  5258. if (profile != nullptr)
  5259. warn(loc, "ignoring shader_profile", "register", "");
  5260. if (desc.size() < 1) {
  5261. error(loc, "expected register type", "register", "");
  5262. return;
  5263. }
  5264. int regNumber = 0;
  5265. if (desc.size() > 1) {
  5266. if (isdigit(desc[1]))
  5267. regNumber = atoi(desc.substr(1, desc.size()).c_str());
  5268. else {
  5269. error(loc, "expected register number after register type", "register", "");
  5270. return;
  5271. }
  5272. }
  5273. // more information about register types see
  5274. // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-register
  5275. const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
  5276. switch (std::tolower(desc[0])) {
  5277. case 'c':
  5278. // c register is the register slot in the global const buffer
  5279. // each slot is a vector of 4 32 bit components
  5280. qualifier.layoutOffset = regNumber * 4 * 4;
  5281. break;
  5282. // const buffer register slot
  5283. case 'b':
  5284. // textrues and structured buffers
  5285. case 't':
  5286. // samplers
  5287. case 's':
  5288. // uav resources
  5289. case 'u':
  5290. // if nothing else has set the binding, do so now
  5291. // (other mechanisms override this one)
  5292. if (!qualifier.hasBinding())
  5293. qualifier.layoutBinding = regNumber + subComponent;
  5294. // This handles per-register layout sets numbers. For the global mode which sets
  5295. // every symbol to the same value, see setLinkageLayoutSets().
  5296. if ((resourceInfo.size() % 3) == 0) {
  5297. // Apply per-symbol resource set and binding.
  5298. for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
  5299. if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
  5300. qualifier.layoutSet = atoi(it[1].c_str());
  5301. qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
  5302. break;
  5303. }
  5304. }
  5305. }
  5306. break;
  5307. default:
  5308. warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
  5309. break;
  5310. }
  5311. // space
  5312. unsigned int setNumber;
  5313. const auto crackSpace = [&]() -> bool {
  5314. const int spaceLen = 5;
  5315. if (spaceDesc->size() < spaceLen + 1)
  5316. return false;
  5317. if (spaceDesc->compare(0, spaceLen, "space") != 0)
  5318. return false;
  5319. if (! isdigit((*spaceDesc)[spaceLen]))
  5320. return false;
  5321. setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
  5322. return true;
  5323. };
  5324. // if nothing else has set the set, do so now
  5325. // (other mechanisms override this one)
  5326. if (spaceDesc && !qualifier.hasSet()) {
  5327. if (! crackSpace()) {
  5328. error(loc, "expected spaceN", "register", "");
  5329. return;
  5330. }
  5331. qualifier.layoutSet = setNumber;
  5332. }
  5333. }
  5334. // Convert to a scalar boolean, or if not allowed by HLSL semantics,
  5335. // report an error and return nullptr.
  5336. TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
  5337. bool mustBeScalar)
  5338. {
  5339. if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
  5340. error(loc, "requires a scalar", "conditional expression", "");
  5341. return nullptr;
  5342. }
  5343. return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
  5344. condition);
  5345. }
  5346. //
  5347. // Same error message for all places assignments don't work.
  5348. //
  5349. void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5350. {
  5351. error(loc, "", op, "cannot convert from '%s' to '%s'",
  5352. right.c_str(), left.c_str());
  5353. }
  5354. //
  5355. // Same error message for all places unary operations don't work.
  5356. //
  5357. void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
  5358. {
  5359. error(loc, " wrong operand type", op,
  5360. "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
  5361. op, operand.c_str());
  5362. }
  5363. //
  5364. // Same error message for all binary operations don't work.
  5365. //
  5366. void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5367. {
  5368. error(loc, " wrong operand types:", op,
  5369. "no operation '%s' exists that takes a left-hand operand of type '%s' and "
  5370. "a right operand of type '%s' (or there is no acceptable conversion)",
  5371. op, left.c_str(), right.c_str());
  5372. }
  5373. //
  5374. // A basic type of EbtVoid is a key that the name string was seen in the source, but
  5375. // it was not found as a variable in the symbol table. If so, give the error
  5376. // message and insert a dummy variable in the symbol table to prevent future errors.
  5377. //
  5378. void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
  5379. {
  5380. TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
  5381. if (! symbol)
  5382. return;
  5383. if (symbol->getType().getBasicType() == EbtVoid) {
  5384. error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
  5385. // Add to symbol table to prevent future error messages on the same name
  5386. if (symbol->getName().size() > 0) {
  5387. TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
  5388. symbolTable.insert(*fakeVariable);
  5389. // substitute a symbol node for this new variable
  5390. nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
  5391. }
  5392. }
  5393. }
  5394. //
  5395. // Both test, and if necessary spit out an error, to see if the node is really
  5396. // a constant.
  5397. //
  5398. void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
  5399. {
  5400. if (node->getQualifier().storage != EvqConst)
  5401. error(node->getLoc(), "constant expression required", token, "");
  5402. }
  5403. //
  5404. // Both test, and if necessary spit out an error, to see if the node is really
  5405. // an integer.
  5406. //
  5407. void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
  5408. {
  5409. if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
  5410. return;
  5411. error(node->getLoc(), "scalar integer expression required", token, "");
  5412. }
  5413. //
  5414. // Both test, and if necessary spit out an error, to see if we are currently
  5415. // globally scoped.
  5416. //
  5417. void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
  5418. {
  5419. if (! symbolTable.atGlobalLevel())
  5420. error(loc, "not allowed in nested scope", token, "");
  5421. }
  5422. bool HlslParseContext::builtInName(const TString& /*identifier*/)
  5423. {
  5424. return false;
  5425. }
  5426. //
  5427. // Make sure there is enough data and not too many arguments provided to the
  5428. // constructor to build something of the type of the constructor. Also returns
  5429. // the type of the constructor.
  5430. //
  5431. // Returns true if there was an error in construction.
  5432. //
  5433. bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
  5434. TOperator op, TType& type)
  5435. {
  5436. type.shallowCopy(function.getType());
  5437. bool constructingMatrix = false;
  5438. switch (op) {
  5439. case EOpConstructTextureSampler:
  5440. error(loc, "unhandled texture constructor", "constructor", "");
  5441. return true;
  5442. case EOpConstructMat2x2:
  5443. case EOpConstructMat2x3:
  5444. case EOpConstructMat2x4:
  5445. case EOpConstructMat3x2:
  5446. case EOpConstructMat3x3:
  5447. case EOpConstructMat3x4:
  5448. case EOpConstructMat4x2:
  5449. case EOpConstructMat4x3:
  5450. case EOpConstructMat4x4:
  5451. case EOpConstructDMat2x2:
  5452. case EOpConstructDMat2x3:
  5453. case EOpConstructDMat2x4:
  5454. case EOpConstructDMat3x2:
  5455. case EOpConstructDMat3x3:
  5456. case EOpConstructDMat3x4:
  5457. case EOpConstructDMat4x2:
  5458. case EOpConstructDMat4x3:
  5459. case EOpConstructDMat4x4:
  5460. case EOpConstructIMat2x2:
  5461. case EOpConstructIMat2x3:
  5462. case EOpConstructIMat2x4:
  5463. case EOpConstructIMat3x2:
  5464. case EOpConstructIMat3x3:
  5465. case EOpConstructIMat3x4:
  5466. case EOpConstructIMat4x2:
  5467. case EOpConstructIMat4x3:
  5468. case EOpConstructIMat4x4:
  5469. case EOpConstructUMat2x2:
  5470. case EOpConstructUMat2x3:
  5471. case EOpConstructUMat2x4:
  5472. case EOpConstructUMat3x2:
  5473. case EOpConstructUMat3x3:
  5474. case EOpConstructUMat3x4:
  5475. case EOpConstructUMat4x2:
  5476. case EOpConstructUMat4x3:
  5477. case EOpConstructUMat4x4:
  5478. case EOpConstructBMat2x2:
  5479. case EOpConstructBMat2x3:
  5480. case EOpConstructBMat2x4:
  5481. case EOpConstructBMat3x2:
  5482. case EOpConstructBMat3x3:
  5483. case EOpConstructBMat3x4:
  5484. case EOpConstructBMat4x2:
  5485. case EOpConstructBMat4x3:
  5486. case EOpConstructBMat4x4:
  5487. constructingMatrix = true;
  5488. break;
  5489. default:
  5490. break;
  5491. }
  5492. //
  5493. // Walk the arguments for first-pass checks and collection of information.
  5494. //
  5495. int size = 0;
  5496. bool constType = true;
  5497. bool full = false;
  5498. bool overFull = false;
  5499. bool matrixInMatrix = false;
  5500. bool arrayArg = false;
  5501. for (int arg = 0; arg < function.getParamCount(); ++arg) {
  5502. if (function[arg].type->isArray()) {
  5503. if (function[arg].type->isUnsizedArray()) {
  5504. // Can't construct from an unsized array.
  5505. error(loc, "array argument must be sized", "constructor", "");
  5506. return true;
  5507. }
  5508. arrayArg = true;
  5509. }
  5510. if (constructingMatrix && function[arg].type->isMatrix())
  5511. matrixInMatrix = true;
  5512. // 'full' will go to true when enough args have been seen. If we loop
  5513. // again, there is an extra argument.
  5514. if (full) {
  5515. // For vectors and matrices, it's okay to have too many components
  5516. // available, but not okay to have unused arguments.
  5517. overFull = true;
  5518. }
  5519. size += function[arg].type->computeNumComponents();
  5520. if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
  5521. full = true;
  5522. if (function[arg].type->getQualifier().storage != EvqConst)
  5523. constType = false;
  5524. }
  5525. if (constType)
  5526. type.getQualifier().storage = EvqConst;
  5527. if (type.isArray()) {
  5528. if (function.getParamCount() == 0) {
  5529. error(loc, "array constructor must have at least one argument", "constructor", "");
  5530. return true;
  5531. }
  5532. if (type.isUnsizedArray()) {
  5533. // auto adapt the constructor type to the number of arguments
  5534. type.changeOuterArraySize(function.getParamCount());
  5535. } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
  5536. error(loc, "array constructor needs one argument per array element", "constructor", "");
  5537. return true;
  5538. }
  5539. if (type.isArrayOfArrays()) {
  5540. // Types have to match, but we're still making the type.
  5541. // Finish making the type, and the comparison is done later
  5542. // when checking for conversion.
  5543. TArraySizes& arraySizes = *type.getArraySizes();
  5544. // At least the dimensionalities have to match.
  5545. if (! function[0].type->isArray() ||
  5546. arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
  5547. error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
  5548. return true;
  5549. }
  5550. if (arraySizes.isInnerUnsized()) {
  5551. // "Arrays of arrays ..., and the size for any dimension is optional"
  5552. // That means we need to adopt (from the first argument) the other array sizes into the type.
  5553. for (int d = 1; d < arraySizes.getNumDims(); ++d) {
  5554. if (arraySizes.getDimSize(d) == UnsizedArraySize) {
  5555. arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
  5556. }
  5557. }
  5558. }
  5559. }
  5560. }
  5561. // Some array -> array type casts are okay
  5562. if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
  5563. !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
  5564. type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
  5565. return false;
  5566. if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
  5567. error(loc, "constructing non-array constituent from array argument", "constructor", "");
  5568. return true;
  5569. }
  5570. if (matrixInMatrix && ! type.isArray()) {
  5571. return false;
  5572. }
  5573. if (overFull) {
  5574. error(loc, "too many arguments", "constructor", "");
  5575. return true;
  5576. }
  5577. if (op == EOpConstructStruct && ! type.isArray()) {
  5578. if (isScalarConstructor(node))
  5579. return false;
  5580. // Self-type construction: e.g, we can construct a struct from a single identically typed object.
  5581. if (function.getParamCount() == 1 && type == *function[0].type)
  5582. return false;
  5583. if ((int)type.getStruct()->size() != function.getParamCount()) {
  5584. error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
  5585. return true;
  5586. }
  5587. }
  5588. if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
  5589. (op == EOpConstructStruct && size < type.computeNumComponents())) {
  5590. error(loc, "not enough data provided for construction", "constructor", "");
  5591. return true;
  5592. }
  5593. return false;
  5594. }
  5595. // See if 'node', in the context of constructing aggregates, is a scalar argument
  5596. // to a constructor.
  5597. //
  5598. bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
  5599. {
  5600. // Obviously, it must be a scalar, but an aggregate node might not be fully
  5601. // completed yet: holding a sequence of initializers under an aggregate
  5602. // would not yet be typed, so don't check it's type. This corresponds to
  5603. // the aggregate operator also not being set yet. (An aggregate operation
  5604. // that legitimately yields a scalar will have a getOp() of that operator,
  5605. // not EOpNull.)
  5606. return node->getAsTyped() != nullptr &&
  5607. node->getAsTyped()->isScalar() &&
  5608. (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
  5609. }
  5610. // Checks to see if a void variable has been declared and raise an error message for such a case
  5611. //
  5612. // returns true in case of an error
  5613. //
  5614. bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
  5615. {
  5616. if (basicType == EbtVoid) {
  5617. error(loc, "illegal use of type 'void'", identifier.c_str(), "");
  5618. return true;
  5619. }
  5620. return false;
  5621. }
  5622. //
  5623. // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
  5624. //
  5625. void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
  5626. {
  5627. // move from parameter/unknown qualifiers to pipeline in/out qualifiers
  5628. switch (qualifier.storage) {
  5629. case EvqIn:
  5630. qualifier.storage = EvqVaryingIn;
  5631. break;
  5632. case EvqOut:
  5633. qualifier.storage = EvqVaryingOut;
  5634. break;
  5635. default:
  5636. break;
  5637. }
  5638. }
  5639. //
  5640. // Merge characteristics of the 'src' qualifier into the 'dst'.
  5641. // If there is duplication, issue error messages, unless 'force'
  5642. // is specified, which means to just override default settings.
  5643. //
  5644. // Also, when force is false, it will be assumed that 'src' follows
  5645. // 'dst', for the purpose of error checking order for versions
  5646. // that require specific orderings of qualifiers.
  5647. //
  5648. void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
  5649. {
  5650. // Storage qualification
  5651. if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
  5652. dst.storage = src.storage;
  5653. else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
  5654. (dst.storage == EvqOut && src.storage == EvqIn))
  5655. dst.storage = EvqInOut;
  5656. else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
  5657. (dst.storage == EvqConst && src.storage == EvqIn))
  5658. dst.storage = EvqConstReadOnly;
  5659. // Layout qualifiers
  5660. mergeObjectLayoutQualifiers(dst, src, false);
  5661. // individual qualifiers
  5662. bool repeated = false;
  5663. #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
  5664. MERGE_SINGLETON(invariant);
  5665. MERGE_SINGLETON(noContraction);
  5666. MERGE_SINGLETON(centroid);
  5667. MERGE_SINGLETON(smooth);
  5668. MERGE_SINGLETON(flat);
  5669. MERGE_SINGLETON(nopersp);
  5670. MERGE_SINGLETON(patch);
  5671. MERGE_SINGLETON(sample);
  5672. MERGE_SINGLETON(coherent);
  5673. MERGE_SINGLETON(volatil);
  5674. MERGE_SINGLETON(restrict);
  5675. MERGE_SINGLETON(readonly);
  5676. MERGE_SINGLETON(writeonly);
  5677. MERGE_SINGLETON(specConstant);
  5678. MERGE_SINGLETON(nonUniform);
  5679. }
  5680. // used to flatten the sampler type space into a single dimension
  5681. // correlates with the declaration of defaultSamplerPrecision[]
  5682. int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
  5683. {
  5684. int arrayIndex = sampler.arrayed ? 1 : 0;
  5685. int shadowIndex = sampler.shadow ? 1 : 0;
  5686. int externalIndex = sampler.external ? 1 : 0;
  5687. return EsdNumDims *
  5688. (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
  5689. }
  5690. //
  5691. // Do size checking for an array type's size.
  5692. //
  5693. void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
  5694. {
  5695. bool isConst = false;
  5696. sizePair.size = 1;
  5697. sizePair.node = nullptr;
  5698. TIntermConstantUnion* constant = expr->getAsConstantUnion();
  5699. if (constant) {
  5700. // handle true (non-specialization) constant
  5701. sizePair.size = constant->getConstArray()[0].getIConst();
  5702. isConst = true;
  5703. } else {
  5704. // see if it's a specialization constant instead
  5705. if (expr->getQualifier().isSpecConstant()) {
  5706. isConst = true;
  5707. sizePair.node = expr;
  5708. TIntermSymbol* symbol = expr->getAsSymbolNode();
  5709. if (symbol && symbol->getConstArray().size() > 0)
  5710. sizePair.size = symbol->getConstArray()[0].getIConst();
  5711. }
  5712. }
  5713. if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
  5714. error(loc, "array size must be a constant integer expression", "", "");
  5715. return;
  5716. }
  5717. if (sizePair.size <= 0) {
  5718. error(loc, "array size must be a positive integer", "", "");
  5719. return;
  5720. }
  5721. }
  5722. //
  5723. // Require array to be completely sized
  5724. //
  5725. void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
  5726. {
  5727. if (arraySizes.hasUnsized())
  5728. error(loc, "array size required", "", "");
  5729. }
  5730. void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
  5731. {
  5732. const TTypeList& structure = *type.getStruct();
  5733. for (int m = 0; m < (int)structure.size(); ++m) {
  5734. const TType& member = *structure[m].type;
  5735. if (member.isArray())
  5736. arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
  5737. }
  5738. }
  5739. //
  5740. // Do all the semantic checking for declaring or redeclaring an array, with and
  5741. // without a size, and make the right changes to the symbol table.
  5742. //
  5743. void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  5744. TSymbol*& symbol, bool track)
  5745. {
  5746. if (symbol == nullptr) {
  5747. bool currentScope;
  5748. symbol = symbolTable.find(identifier, nullptr, &currentScope);
  5749. if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
  5750. // bad shader (errors already reported) trying to redeclare a built-in name as an array
  5751. return;
  5752. }
  5753. if (symbol == nullptr || ! currentScope) {
  5754. //
  5755. // Successfully process a new definition.
  5756. // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
  5757. //
  5758. symbol = new TVariable(&identifier, type);
  5759. symbolTable.insert(*symbol);
  5760. if (track && symbolTable.atGlobalLevel())
  5761. trackLinkage(*symbol);
  5762. return;
  5763. }
  5764. if (symbol->getAsAnonMember()) {
  5765. error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
  5766. symbol = nullptr;
  5767. return;
  5768. }
  5769. }
  5770. //
  5771. // Process a redeclaration.
  5772. //
  5773. if (symbol == nullptr) {
  5774. error(loc, "array variable name expected", identifier.c_str(), "");
  5775. return;
  5776. }
  5777. // redeclareBuiltinVariable() should have already done the copyUp()
  5778. TType& existingType = symbol->getWritableType();
  5779. if (existingType.isSizedArray()) {
  5780. // be more lenient for input arrays to geometry shaders and tessellation control outputs,
  5781. // where the redeclaration is the same size
  5782. return;
  5783. }
  5784. existingType.updateArraySizes(type);
  5785. }
  5786. //
  5787. // Enforce non-initializer type/qualifier rules.
  5788. //
  5789. void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
  5790. TIntermTyped*& initializer)
  5791. {
  5792. //
  5793. // Make the qualifier make sense, given that there is an initializer.
  5794. //
  5795. if (initializer == nullptr) {
  5796. if (type.getQualifier().storage == EvqConst ||
  5797. type.getQualifier().storage == EvqConstReadOnly) {
  5798. initializer = intermediate.makeAggregate(loc);
  5799. warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
  5800. }
  5801. }
  5802. }
  5803. //
  5804. // See if the identifier is a built-in symbol that can be redeclared, and if so,
  5805. // copy the symbol table's read-only built-in variable to the current
  5806. // global level, where it can be modified based on the passed in type.
  5807. //
  5808. // Returns nullptr if no redeclaration took place; meaning a normal declaration still
  5809. // needs to occur for it, not necessarily an error.
  5810. //
  5811. // Returns a redeclared and type-modified variable if a redeclared occurred.
  5812. //
  5813. TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
  5814. const TQualifier& /*qualifier*/,
  5815. const TShaderQualifiers& /*publicType*/)
  5816. {
  5817. if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
  5818. return nullptr;
  5819. return nullptr;
  5820. }
  5821. //
  5822. // Generate index to the array element in a structure buffer (SSBO)
  5823. //
  5824. TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
  5825. {
  5826. // Bail out if not a struct buffer
  5827. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  5828. return nullptr;
  5829. // Runtime sized array is always the last element.
  5830. const TTypeList* bufferStruct = buffer->getType().getStruct();
  5831. TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
  5832. TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
  5833. argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
  5834. return argArray;
  5835. }
  5836. //
  5837. // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
  5838. // (template) type. E.g, StructuredBuffer<MyType> -> MyType. Else return nullptr.
  5839. //
  5840. TType* HlslParseContext::getStructBufferContentType(const TType& type) const
  5841. {
  5842. if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
  5843. return nullptr;
  5844. const int memberCount = (int)type.getStruct()->size();
  5845. assert(memberCount > 0);
  5846. TType* contentType = (*type.getStruct())[memberCount-1].type;
  5847. return contentType->isUnsizedArray() ? contentType : nullptr;
  5848. }
  5849. //
  5850. // If an existing struct buffer has a sharable type, then share it.
  5851. //
  5852. void HlslParseContext::shareStructBufferType(TType& type)
  5853. {
  5854. // PackOffset must be equivalent to share types on a per-member basis.
  5855. // Note: cannot use auto type due to recursion. Thus, this is a std::function.
  5856. const std::function<bool(TType& lhs, TType& rhs)>
  5857. compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
  5858. if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
  5859. return false;
  5860. if (lhs.isStruct() != rhs.isStruct())
  5861. return false;
  5862. if (lhs.isStruct() && rhs.isStruct()) {
  5863. if (lhs.getStruct()->size() != rhs.getStruct()->size())
  5864. return false;
  5865. for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
  5866. if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
  5867. return false;
  5868. }
  5869. return true;
  5870. };
  5871. // We need to compare certain qualifiers in addition to the type.
  5872. const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
  5873. if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
  5874. return false;
  5875. // If both are structures, recursively look for packOffset equality
  5876. // as well as type equality.
  5877. return compareQualifiers(lhs, rhs) && lhs == rhs;
  5878. };
  5879. // This is an exhaustive O(N) search, but real world shaders have
  5880. // only a small number of these.
  5881. for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
  5882. // If the deep structure matches, modulo qualifiers, use it
  5883. if (typeEqual(*structBufferTypes[idx], type)) {
  5884. type.shallowCopy(*structBufferTypes[idx]);
  5885. return;
  5886. }
  5887. }
  5888. // Otherwise, remember it:
  5889. TType* typeCopy = new TType;
  5890. typeCopy->shallowCopy(type);
  5891. structBufferTypes.push_back(typeCopy);
  5892. }
  5893. void HlslParseContext::paramFix(TType& type)
  5894. {
  5895. switch (type.getQualifier().storage) {
  5896. case EvqConst:
  5897. type.getQualifier().storage = EvqConstReadOnly;
  5898. break;
  5899. case EvqGlobal:
  5900. case EvqTemporary:
  5901. type.getQualifier().storage = EvqIn;
  5902. break;
  5903. case EvqBuffer:
  5904. {
  5905. // SSBO parameter. These do not go through the declareBlock path since they are fn parameters.
  5906. correctUniform(type.getQualifier());
  5907. TQualifier bufferQualifier = globalBufferDefaults;
  5908. mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
  5909. bufferQualifier.storage = type.getQualifier().storage;
  5910. bufferQualifier.readonly = type.getQualifier().readonly;
  5911. bufferQualifier.coherent = type.getQualifier().coherent;
  5912. bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
  5913. type.getQualifier() = bufferQualifier;
  5914. break;
  5915. }
  5916. default:
  5917. break;
  5918. }
  5919. }
  5920. void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
  5921. {
  5922. if (type.containsSpecializationSize())
  5923. error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
  5924. }
  5925. //
  5926. // Layout qualifier stuff.
  5927. //
  5928. // Put the id's layout qualification into the public type, for qualifiers not having a number set.
  5929. // This is before we know any type information for error checking.
  5930. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
  5931. {
  5932. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5933. if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
  5934. qualifier.layoutMatrix = ElmRowMajor;
  5935. return;
  5936. }
  5937. if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
  5938. qualifier.layoutMatrix = ElmColumnMajor;
  5939. return;
  5940. }
  5941. if (id == "push_constant") {
  5942. requireVulkan(loc, "push_constant");
  5943. qualifier.layoutPushConstant = true;
  5944. return;
  5945. }
  5946. if (language == EShLangGeometry || language == EShLangTessEvaluation) {
  5947. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5948. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5949. warn(loc, "ignored", id.c_str(), "");
  5950. return;
  5951. }
  5952. if (language == EShLangGeometry) {
  5953. if (id == TQualifier::getGeometryString(ElgPoints)) {
  5954. // publicType.shaderQualifiers.geometry = ElgPoints;
  5955. warn(loc, "ignored", id.c_str(), "");
  5956. return;
  5957. }
  5958. if (id == TQualifier::getGeometryString(ElgLineStrip)) {
  5959. // publicType.shaderQualifiers.geometry = ElgLineStrip;
  5960. warn(loc, "ignored", id.c_str(), "");
  5961. return;
  5962. }
  5963. if (id == TQualifier::getGeometryString(ElgLines)) {
  5964. // publicType.shaderQualifiers.geometry = ElgLines;
  5965. warn(loc, "ignored", id.c_str(), "");
  5966. return;
  5967. }
  5968. if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
  5969. // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
  5970. warn(loc, "ignored", id.c_str(), "");
  5971. return;
  5972. }
  5973. if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
  5974. // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
  5975. warn(loc, "ignored", id.c_str(), "");
  5976. return;
  5977. }
  5978. if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
  5979. // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
  5980. warn(loc, "ignored", id.c_str(), "");
  5981. return;
  5982. }
  5983. } else {
  5984. assert(language == EShLangTessEvaluation);
  5985. // input primitive
  5986. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5987. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5988. warn(loc, "ignored", id.c_str(), "");
  5989. return;
  5990. }
  5991. if (id == TQualifier::getGeometryString(ElgQuads)) {
  5992. // publicType.shaderQualifiers.geometry = ElgQuads;
  5993. warn(loc, "ignored", id.c_str(), "");
  5994. return;
  5995. }
  5996. if (id == TQualifier::getGeometryString(ElgIsolines)) {
  5997. // publicType.shaderQualifiers.geometry = ElgIsolines;
  5998. warn(loc, "ignored", id.c_str(), "");
  5999. return;
  6000. }
  6001. // vertex spacing
  6002. if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
  6003. // publicType.shaderQualifiers.spacing = EvsEqual;
  6004. warn(loc, "ignored", id.c_str(), "");
  6005. return;
  6006. }
  6007. if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
  6008. // publicType.shaderQualifiers.spacing = EvsFractionalEven;
  6009. warn(loc, "ignored", id.c_str(), "");
  6010. return;
  6011. }
  6012. if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
  6013. // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
  6014. warn(loc, "ignored", id.c_str(), "");
  6015. return;
  6016. }
  6017. // triangle order
  6018. if (id == TQualifier::getVertexOrderString(EvoCw)) {
  6019. // publicType.shaderQualifiers.order = EvoCw;
  6020. warn(loc, "ignored", id.c_str(), "");
  6021. return;
  6022. }
  6023. if (id == TQualifier::getVertexOrderString(EvoCcw)) {
  6024. // publicType.shaderQualifiers.order = EvoCcw;
  6025. warn(loc, "ignored", id.c_str(), "");
  6026. return;
  6027. }
  6028. // point mode
  6029. if (id == "point_mode") {
  6030. // publicType.shaderQualifiers.pointMode = true;
  6031. warn(loc, "ignored", id.c_str(), "");
  6032. return;
  6033. }
  6034. }
  6035. }
  6036. if (language == EShLangFragment) {
  6037. if (id == "origin_upper_left") {
  6038. // publicType.shaderQualifiers.originUpperLeft = true;
  6039. warn(loc, "ignored", id.c_str(), "");
  6040. return;
  6041. }
  6042. if (id == "pixel_center_integer") {
  6043. // publicType.shaderQualifiers.pixelCenterInteger = true;
  6044. warn(loc, "ignored", id.c_str(), "");
  6045. return;
  6046. }
  6047. if (id == "early_fragment_tests") {
  6048. // publicType.shaderQualifiers.earlyFragmentTests = true;
  6049. warn(loc, "ignored", id.c_str(), "");
  6050. return;
  6051. }
  6052. for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
  6053. if (id == TQualifier::getLayoutDepthString(depth)) {
  6054. // publicType.shaderQualifiers.layoutDepth = depth;
  6055. warn(loc, "ignored", id.c_str(), "");
  6056. return;
  6057. }
  6058. }
  6059. if (id.compare(0, 13, "blend_support") == 0) {
  6060. bool found = false;
  6061. for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
  6062. if (id == TQualifier::getBlendEquationString(be)) {
  6063. requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
  6064. intermediate.addBlendEquation(be);
  6065. // publicType.shaderQualifiers.blendEquation = true;
  6066. warn(loc, "ignored", id.c_str(), "");
  6067. found = true;
  6068. break;
  6069. }
  6070. }
  6071. if (! found)
  6072. error(loc, "unknown blend equation", "blend_support", "");
  6073. return;
  6074. }
  6075. }
  6076. error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
  6077. }
  6078. // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
  6079. // This is before we know any type information for error checking.
  6080. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
  6081. const TIntermTyped* node)
  6082. {
  6083. const char* feature = "layout-id value";
  6084. // const char* nonLiteralFeature = "non-literal layout-id value";
  6085. integerCheck(node, feature);
  6086. const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
  6087. int value = 0;
  6088. if (constUnion) {
  6089. value = constUnion->getConstArray()[0].getIConst();
  6090. }
  6091. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  6092. if (id == "offset") {
  6093. qualifier.layoutOffset = value;
  6094. return;
  6095. } else if (id == "align") {
  6096. // "The specified alignment must be a power of 2, or a compile-time error results."
  6097. if (! IsPow2(value))
  6098. error(loc, "must be a power of 2", "align", "");
  6099. else
  6100. qualifier.layoutAlign = value;
  6101. return;
  6102. } else if (id == "location") {
  6103. if ((unsigned int)value >= TQualifier::layoutLocationEnd)
  6104. error(loc, "location is too large", id.c_str(), "");
  6105. else
  6106. qualifier.layoutLocation = value;
  6107. return;
  6108. } else if (id == "set") {
  6109. if ((unsigned int)value >= TQualifier::layoutSetEnd)
  6110. error(loc, "set is too large", id.c_str(), "");
  6111. else
  6112. qualifier.layoutSet = value;
  6113. return;
  6114. } else if (id == "binding") {
  6115. if ((unsigned int)value >= TQualifier::layoutBindingEnd)
  6116. error(loc, "binding is too large", id.c_str(), "");
  6117. else
  6118. qualifier.layoutBinding = value;
  6119. return;
  6120. } else if (id == "component") {
  6121. if ((unsigned)value >= TQualifier::layoutComponentEnd)
  6122. error(loc, "component is too large", id.c_str(), "");
  6123. else
  6124. qualifier.layoutComponent = value;
  6125. return;
  6126. } else if (id.compare(0, 4, "xfb_") == 0) {
  6127. // "Any shader making any static use (after preprocessing) of any of these
  6128. // *xfb_* qualifiers will cause the shader to be in a transform feedback
  6129. // capturing mode and hence responsible for describing the transform feedback
  6130. // setup."
  6131. intermediate.setXfbMode();
  6132. if (id == "xfb_buffer") {
  6133. // "It is a compile-time error to specify an *xfb_buffer* that is greater than
  6134. // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
  6135. if (value >= resources.maxTransformFeedbackBuffers)
  6136. error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
  6137. resources.maxTransformFeedbackBuffers);
  6138. if (value >= (int)TQualifier::layoutXfbBufferEnd)
  6139. error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
  6140. else
  6141. qualifier.layoutXfbBuffer = value;
  6142. return;
  6143. } else if (id == "xfb_offset") {
  6144. if (value >= (int)TQualifier::layoutXfbOffsetEnd)
  6145. error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
  6146. else
  6147. qualifier.layoutXfbOffset = value;
  6148. return;
  6149. } else if (id == "xfb_stride") {
  6150. // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
  6151. // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
  6152. if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
  6153. error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
  6154. resources.maxTransformFeedbackInterleavedComponents);
  6155. else if (value >= (int)TQualifier::layoutXfbStrideEnd)
  6156. error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
  6157. if (value < (int)TQualifier::layoutXfbStrideEnd)
  6158. qualifier.layoutXfbStride = value;
  6159. return;
  6160. }
  6161. }
  6162. if (id == "input_attachment_index") {
  6163. requireVulkan(loc, "input_attachment_index");
  6164. if (value >= (int)TQualifier::layoutAttachmentEnd)
  6165. error(loc, "attachment index is too large", id.c_str(), "");
  6166. else
  6167. qualifier.layoutAttachment = value;
  6168. return;
  6169. }
  6170. if (id == "constant_id") {
  6171. setSpecConstantId(loc, qualifier, value);
  6172. return;
  6173. }
  6174. switch (language) {
  6175. case EShLangVertex:
  6176. break;
  6177. case EShLangTessControl:
  6178. if (id == "vertices") {
  6179. if (value == 0)
  6180. error(loc, "must be greater than 0", "vertices", "");
  6181. else
  6182. // publicType.shaderQualifiers.vertices = value;
  6183. warn(loc, "ignored", id.c_str(), "");
  6184. return;
  6185. }
  6186. break;
  6187. case EShLangTessEvaluation:
  6188. break;
  6189. case EShLangGeometry:
  6190. if (id == "invocations") {
  6191. if (value == 0)
  6192. error(loc, "must be at least 1", "invocations", "");
  6193. else
  6194. // publicType.shaderQualifiers.invocations = value;
  6195. warn(loc, "ignored", id.c_str(), "");
  6196. return;
  6197. }
  6198. if (id == "max_vertices") {
  6199. // publicType.shaderQualifiers.vertices = value;
  6200. warn(loc, "ignored", id.c_str(), "");
  6201. if (value > resources.maxGeometryOutputVertices)
  6202. error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
  6203. return;
  6204. }
  6205. if (id == "stream") {
  6206. qualifier.layoutStream = value;
  6207. return;
  6208. }
  6209. break;
  6210. case EShLangFragment:
  6211. if (id == "index") {
  6212. qualifier.layoutIndex = value;
  6213. return;
  6214. }
  6215. break;
  6216. case EShLangCompute:
  6217. if (id.compare(0, 11, "local_size_") == 0) {
  6218. if (id == "local_size_x") {
  6219. // publicType.shaderQualifiers.localSize[0] = value;
  6220. warn(loc, "ignored", id.c_str(), "");
  6221. return;
  6222. }
  6223. if (id == "local_size_y") {
  6224. // publicType.shaderQualifiers.localSize[1] = value;
  6225. warn(loc, "ignored", id.c_str(), "");
  6226. return;
  6227. }
  6228. if (id == "local_size_z") {
  6229. // publicType.shaderQualifiers.localSize[2] = value;
  6230. warn(loc, "ignored", id.c_str(), "");
  6231. return;
  6232. }
  6233. if (spvVersion.spv != 0) {
  6234. if (id == "local_size_x_id") {
  6235. // publicType.shaderQualifiers.localSizeSpecId[0] = value;
  6236. warn(loc, "ignored", id.c_str(), "");
  6237. return;
  6238. }
  6239. if (id == "local_size_y_id") {
  6240. // publicType.shaderQualifiers.localSizeSpecId[1] = value;
  6241. warn(loc, "ignored", id.c_str(), "");
  6242. return;
  6243. }
  6244. if (id == "local_size_z_id") {
  6245. // publicType.shaderQualifiers.localSizeSpecId[2] = value;
  6246. warn(loc, "ignored", id.c_str(), "");
  6247. return;
  6248. }
  6249. }
  6250. }
  6251. break;
  6252. default:
  6253. break;
  6254. }
  6255. error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
  6256. }
  6257. void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
  6258. {
  6259. if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
  6260. error(loc, "specialization-constant id is too large", "constant_id", "");
  6261. } else {
  6262. qualifier.layoutSpecConstantId = value;
  6263. qualifier.specConstant = true;
  6264. if (! intermediate.addUsedConstantId(value))
  6265. error(loc, "specialization-constant id already used", "constant_id", "");
  6266. }
  6267. return;
  6268. }
  6269. // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
  6270. //
  6271. // "More than one layout qualifier may appear in a single declaration.
  6272. // Additionally, the same layout-qualifier-name can occur multiple times
  6273. // within a layout qualifier or across multiple layout qualifiers in the
  6274. // same declaration. When the same layout-qualifier-name occurs
  6275. // multiple times, in a single declaration, the last occurrence overrides
  6276. // the former occurrence(s). Further, if such a layout-qualifier-name
  6277. // will effect subsequent declarations or other observable behavior, it
  6278. // is only the last occurrence that will have any effect, behaving as if
  6279. // the earlier occurrence(s) within the declaration are not present.
  6280. // This is also true for overriding layout-qualifier-names, where one
  6281. // overrides the other (e.g., row_major vs. column_major); only the last
  6282. // occurrence has any effect."
  6283. //
  6284. void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
  6285. {
  6286. if (src.hasMatrix())
  6287. dst.layoutMatrix = src.layoutMatrix;
  6288. if (src.hasPacking())
  6289. dst.layoutPacking = src.layoutPacking;
  6290. if (src.hasStream())
  6291. dst.layoutStream = src.layoutStream;
  6292. if (src.hasFormat())
  6293. dst.layoutFormat = src.layoutFormat;
  6294. if (src.hasXfbBuffer())
  6295. dst.layoutXfbBuffer = src.layoutXfbBuffer;
  6296. if (src.hasAlign())
  6297. dst.layoutAlign = src.layoutAlign;
  6298. if (! inheritOnly) {
  6299. if (src.hasLocation())
  6300. dst.layoutLocation = src.layoutLocation;
  6301. if (src.hasComponent())
  6302. dst.layoutComponent = src.layoutComponent;
  6303. if (src.hasIndex())
  6304. dst.layoutIndex = src.layoutIndex;
  6305. if (src.hasOffset())
  6306. dst.layoutOffset = src.layoutOffset;
  6307. if (src.hasSet())
  6308. dst.layoutSet = src.layoutSet;
  6309. if (src.layoutBinding != TQualifier::layoutBindingEnd)
  6310. dst.layoutBinding = src.layoutBinding;
  6311. if (src.hasXfbStride())
  6312. dst.layoutXfbStride = src.layoutXfbStride;
  6313. if (src.hasXfbOffset())
  6314. dst.layoutXfbOffset = src.layoutXfbOffset;
  6315. if (src.hasAttachment())
  6316. dst.layoutAttachment = src.layoutAttachment;
  6317. if (src.hasSpecConstantId())
  6318. dst.layoutSpecConstantId = src.layoutSpecConstantId;
  6319. if (src.layoutPushConstant)
  6320. dst.layoutPushConstant = true;
  6321. }
  6322. }
  6323. //
  6324. // Look up a function name in the symbol table, and make sure it is a function.
  6325. //
  6326. // First, look for an exact match. If there is none, use the generic selector
  6327. // TParseContextBase::selectFunction() to find one, parameterized by the
  6328. // convertible() and better() predicates defined below.
  6329. //
  6330. // Return the function symbol if found, otherwise nullptr.
  6331. //
  6332. const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
  6333. TIntermTyped*& args)
  6334. {
  6335. if (symbolTable.isFunctionNameVariable(call.getName())) {
  6336. error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
  6337. return nullptr;
  6338. }
  6339. // first, look for an exact match
  6340. bool dummyScope;
  6341. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
  6342. if (symbol)
  6343. return symbol->getAsFunction();
  6344. // no exact match, use the generic selector, parameterized by the GLSL rules
  6345. // create list of candidates to send
  6346. TVector<const TFunction*> candidateList;
  6347. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6348. // These built-in ops can accept any type, so we bypass the argument selection
  6349. if (candidateList.size() == 1 && builtIn &&
  6350. (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6351. candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
  6352. candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
  6353. candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
  6354. candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6355. candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
  6356. return candidateList[0];
  6357. }
  6358. bool allowOnlyUpConversions = true;
  6359. // can 'from' convert to 'to'?
  6360. const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
  6361. if (from == to)
  6362. return true;
  6363. // no aggregate conversions
  6364. if (from.isArray() || to.isArray() ||
  6365. from.isStruct() || to.isStruct())
  6366. return false;
  6367. switch (op) {
  6368. case EOpInterlockedAdd:
  6369. case EOpInterlockedAnd:
  6370. case EOpInterlockedCompareExchange:
  6371. case EOpInterlockedCompareStore:
  6372. case EOpInterlockedExchange:
  6373. case EOpInterlockedMax:
  6374. case EOpInterlockedMin:
  6375. case EOpInterlockedOr:
  6376. case EOpInterlockedXor:
  6377. // We do not promote the texture or image type for these ocodes. Normally that would not
  6378. // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
  6379. // stage it's merely e.g, a basic integer type.
  6380. //
  6381. // Instead, we want to promote other arguments, but stay within the same family. In other
  6382. // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
  6383. // but it is allowed to promote its other arguments.
  6384. if (arg == 0)
  6385. return false;
  6386. break;
  6387. case EOpMethodSample:
  6388. case EOpMethodSampleBias:
  6389. case EOpMethodSampleCmp:
  6390. case EOpMethodSampleCmpLevelZero:
  6391. case EOpMethodSampleGrad:
  6392. case EOpMethodSampleLevel:
  6393. case EOpMethodLoad:
  6394. case EOpMethodGetDimensions:
  6395. case EOpMethodGetSamplePosition:
  6396. case EOpMethodGather:
  6397. case EOpMethodCalculateLevelOfDetail:
  6398. case EOpMethodCalculateLevelOfDetailUnclamped:
  6399. case EOpMethodGatherRed:
  6400. case EOpMethodGatherGreen:
  6401. case EOpMethodGatherBlue:
  6402. case EOpMethodGatherAlpha:
  6403. case EOpMethodGatherCmp:
  6404. case EOpMethodGatherCmpRed:
  6405. case EOpMethodGatherCmpGreen:
  6406. case EOpMethodGatherCmpBlue:
  6407. case EOpMethodGatherCmpAlpha:
  6408. case EOpMethodAppend:
  6409. case EOpMethodRestartStrip:
  6410. // those are method calls, the object type can not be changed
  6411. // they are equal if the dim and type match (is dim sufficient?)
  6412. if (arg == 0)
  6413. return from.getSampler().type == to.getSampler().type &&
  6414. from.getSampler().arrayed == to.getSampler().arrayed &&
  6415. from.getSampler().shadow == to.getSampler().shadow &&
  6416. from.getSampler().ms == to.getSampler().ms &&
  6417. from.getSampler().dim == to.getSampler().dim;
  6418. break;
  6419. default:
  6420. break;
  6421. }
  6422. // basic types have to be convertible
  6423. if (allowOnlyUpConversions)
  6424. if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
  6425. return false;
  6426. // shapes have to be convertible
  6427. if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
  6428. (from.isScalarOrVec1() && to.isVector()) ||
  6429. (from.isScalarOrVec1() && to.isMatrix()) ||
  6430. (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
  6431. return true;
  6432. // TODO: what are the matrix rules? they go here
  6433. return false;
  6434. };
  6435. // Is 'to2' a better conversion than 'to1'?
  6436. // Ties should not be considered as better.
  6437. // Assumes 'convertible' already said true.
  6438. const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
  6439. // exact match is always better than mismatch
  6440. if (from == to2)
  6441. return from != to1;
  6442. if (from == to1)
  6443. return false;
  6444. // shape changes are always worse
  6445. if (from.isScalar() || from.isVector()) {
  6446. if (from.getVectorSize() == to2.getVectorSize() &&
  6447. from.getVectorSize() != to1.getVectorSize())
  6448. return true;
  6449. if (from.getVectorSize() == to1.getVectorSize() &&
  6450. from.getVectorSize() != to2.getVectorSize())
  6451. return false;
  6452. }
  6453. // Handle sampler betterness: An exact sampler match beats a non-exact match.
  6454. // (If we just looked at basic type, all EbtSamplers would look the same).
  6455. // If any type is not a sampler, just use the linearize function below.
  6456. if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
  6457. // We can ignore the vector size in the comparison.
  6458. TSampler to1Sampler = to1.getSampler();
  6459. TSampler to2Sampler = to2.getSampler();
  6460. to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
  6461. if (from.getSampler() == to2Sampler)
  6462. return from.getSampler() != to1Sampler;
  6463. if (from.getSampler() == to1Sampler)
  6464. return false;
  6465. }
  6466. // Might or might not be changing shape, which means basic type might
  6467. // or might not match, so within that, the question is how big a
  6468. // basic-type conversion is being done.
  6469. //
  6470. // Use a hierarchy of domains, translated to order of magnitude
  6471. // in a linearized view:
  6472. // - floating-point vs. integer
  6473. // - 32 vs. 64 bit (or width in general)
  6474. // - bool vs. non bool
  6475. // - signed vs. not signed
  6476. const auto linearize = [](const TBasicType& basicType) -> int {
  6477. switch (basicType) {
  6478. case EbtBool: return 1;
  6479. case EbtInt: return 10;
  6480. case EbtUint: return 11;
  6481. case EbtInt64: return 20;
  6482. case EbtUint64: return 21;
  6483. case EbtFloat: return 100;
  6484. case EbtDouble: return 110;
  6485. default: return 0;
  6486. }
  6487. };
  6488. return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
  6489. abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
  6490. };
  6491. // for ambiguity reporting
  6492. bool tie = false;
  6493. // send to the generic selector
  6494. const TFunction* bestMatch = nullptr;
  6495. // printf has var args and is in the symbol table as "printf()",
  6496. // mangled to "printf("
  6497. if (call.getName() == "printf") {
  6498. TSymbol* symbol = symbolTable.find("printf(", &builtIn);
  6499. if (symbol)
  6500. return symbol->getAsFunction();
  6501. }
  6502. bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6503. if (bestMatch == nullptr) {
  6504. // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
  6505. // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
  6506. // upconversions possible.
  6507. allowOnlyUpConversions = false;
  6508. bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6509. }
  6510. if (bestMatch == nullptr) {
  6511. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6512. return nullptr;
  6513. }
  6514. // For built-ins, we can convert across the arguments. This will happen in several steps:
  6515. // Step 1: If there's an exact match, use it.
  6516. // Step 2a: Otherwise, get the operator from the best match and promote arguments:
  6517. // Step 2b: reconstruct the TFunction based on the new arg types
  6518. // Step 3: Re-select after type promotion is applied, to find proper candidate.
  6519. if (builtIn) {
  6520. // Step 1: If there's an exact match, use it.
  6521. if (call.getMangledName() == bestMatch->getMangledName())
  6522. return bestMatch;
  6523. // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
  6524. // are that kind of operator.
  6525. if (args != nullptr) {
  6526. // The arg list can be a unary node, or an aggregate. We have to handle both.
  6527. // We will use the normal promote() facilities, which require an interm node.
  6528. TIntermOperator* promote = nullptr;
  6529. if (call.getParamCount() == 1) {
  6530. promote = new TIntermUnary(bestMatch->getBuiltInOp());
  6531. promote->getAsUnaryNode()->setOperand(args->getAsTyped());
  6532. } else {
  6533. promote = new TIntermAggregate(bestMatch->getBuiltInOp());
  6534. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6535. }
  6536. if (! intermediate.promote(promote))
  6537. return nullptr;
  6538. // Obtain the promoted arg list.
  6539. if (call.getParamCount() == 1) {
  6540. args = promote->getAsUnaryNode()->getOperand();
  6541. } else {
  6542. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6543. }
  6544. }
  6545. // Step 2b: reconstruct the TFunction based on the new arg types
  6546. TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
  6547. if (args->getAsAggregate()) {
  6548. // Handle aggregates: put all args into the new function call
  6549. for (int arg = 0; arg < int(args->getAsAggregate()->getSequence().size()); ++arg) {
  6550. // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
  6551. TParameter param = { 0, new TType, nullptr };
  6552. param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
  6553. convertedCall.addParameter(param);
  6554. }
  6555. } else if (args->getAsUnaryNode()) {
  6556. // Handle unaries: put all args into the new function call
  6557. TParameter param = { 0, new TType, nullptr };
  6558. param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
  6559. convertedCall.addParameter(param);
  6560. } else if (args->getAsTyped()) {
  6561. // Handle bare e.g, floats, not in an aggregate.
  6562. TParameter param = { 0, new TType, nullptr };
  6563. param.type->shallowCopy(args->getAsTyped()->getType());
  6564. convertedCall.addParameter(param);
  6565. } else {
  6566. assert(0); // unknown argument list.
  6567. return nullptr;
  6568. }
  6569. // Step 3: Re-select after type promotion, to find proper candidate
  6570. // send to the generic selector
  6571. bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
  6572. // At this point, there should be no tie.
  6573. }
  6574. if (tie)
  6575. error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
  6576. // Append default parameter values if needed
  6577. if (!tie && bestMatch != nullptr) {
  6578. for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
  6579. handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
  6580. }
  6581. }
  6582. return bestMatch;
  6583. }
  6584. //
  6585. // Do everything necessary to handle a typedef declaration, for a single symbol.
  6586. //
  6587. // 'parseType' is the type part of the declaration (to the left)
  6588. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6589. //
  6590. void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
  6591. {
  6592. TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
  6593. if (! symbolTable.insert(*typeSymbol))
  6594. error(loc, "name already defined", "typedef", identifier.c_str());
  6595. }
  6596. // Do everything necessary to handle a struct declaration, including
  6597. // making IO aliases because HLSL allows mixed IO in a struct that specializes
  6598. // based on the usage (input, output, uniform, none).
  6599. void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
  6600. {
  6601. // If it was named, which means the type can be reused later, add
  6602. // it to the symbol table. (Unless it's a block, in which
  6603. // case the name is not a type.)
  6604. if (type.getBasicType() == EbtBlock || structName.size() == 0)
  6605. return;
  6606. TVariable* userTypeDef = new TVariable(&structName, type, true);
  6607. if (! symbolTable.insert(*userTypeDef)) {
  6608. error(loc, "redefinition", structName.c_str(), "struct");
  6609. return;
  6610. }
  6611. // See if we need IO aliases for the structure typeList
  6612. const auto condAlloc = [](bool pred, TTypeList*& list) {
  6613. if (pred && list == nullptr)
  6614. list = new TTypeList;
  6615. };
  6616. tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
  6617. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6618. condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
  6619. condAlloc( hasInput(member->type->getQualifier()), newLists.input);
  6620. condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
  6621. if (member->type->isStruct()) {
  6622. auto it = ioTypeMap.find(member->type->getStruct());
  6623. if (it != ioTypeMap.end()) {
  6624. condAlloc(it->second.uniform != nullptr, newLists.uniform);
  6625. condAlloc(it->second.input != nullptr, newLists.input);
  6626. condAlloc(it->second.output != nullptr, newLists.output);
  6627. }
  6628. }
  6629. }
  6630. if (newLists.uniform == nullptr &&
  6631. newLists.input == nullptr &&
  6632. newLists.output == nullptr) {
  6633. // Won't do any IO caching, clear up the type and get out now.
  6634. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
  6635. clearUniformInputOutput(member->type->getQualifier());
  6636. return;
  6637. }
  6638. // We have IO involved.
  6639. // Make a pure typeList for the symbol table, and cache side copies of IO versions.
  6640. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6641. const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
  6642. if (s != nullptr) {
  6643. ioMember.type = new TType;
  6644. ioMember.type->shallowCopy(*member->type);
  6645. ioMember.type->setStruct(s);
  6646. }
  6647. };
  6648. const auto newMember = [&](TTypeLoc& m) {
  6649. if (m.type == nullptr) {
  6650. m.type = new TType;
  6651. m.type->shallowCopy(*member->type);
  6652. }
  6653. };
  6654. TTypeLoc newUniformMember = { nullptr, member->loc };
  6655. TTypeLoc newInputMember = { nullptr, member->loc };
  6656. TTypeLoc newOutputMember = { nullptr, member->loc };
  6657. if (member->type->isStruct()) {
  6658. // swap in an IO child if there is one
  6659. auto it = ioTypeMap.find(member->type->getStruct());
  6660. if (it != ioTypeMap.end()) {
  6661. inheritStruct(it->second.uniform, newUniformMember);
  6662. inheritStruct(it->second.input, newInputMember);
  6663. inheritStruct(it->second.output, newOutputMember);
  6664. }
  6665. }
  6666. if (newLists.uniform) {
  6667. newMember(newUniformMember);
  6668. // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
  6669. if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
  6670. newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
  6671. correctUniform(newUniformMember.type->getQualifier());
  6672. newLists.uniform->push_back(newUniformMember);
  6673. }
  6674. if (newLists.input) {
  6675. newMember(newInputMember);
  6676. correctInput(newInputMember.type->getQualifier());
  6677. newLists.input->push_back(newInputMember);
  6678. }
  6679. if (newLists.output) {
  6680. newMember(newOutputMember);
  6681. correctOutput(newOutputMember.type->getQualifier());
  6682. newLists.output->push_back(newOutputMember);
  6683. }
  6684. // make original pure
  6685. clearUniformInputOutput(member->type->getQualifier());
  6686. }
  6687. ioTypeMap[type.getStruct()] = newLists;
  6688. }
  6689. // Lookup a user-type by name.
  6690. // If found, fill in the type and return the defining symbol.
  6691. // If not found, return nullptr.
  6692. TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
  6693. {
  6694. TSymbol* symbol = symbolTable.find(typeName);
  6695. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  6696. type.shallowCopy(symbol->getType());
  6697. return symbol;
  6698. } else
  6699. return nullptr;
  6700. }
  6701. //
  6702. // Do everything necessary to handle a variable (non-block) declaration.
  6703. // Either redeclaring a variable, or making a new one, updating the symbol
  6704. // table, and all error checking.
  6705. //
  6706. // Returns a subtree node that computes an initializer, if needed.
  6707. // Returns nullptr if there is no code to execute for initialization.
  6708. //
  6709. // 'parseType' is the type part of the declaration (to the left)
  6710. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6711. //
  6712. TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
  6713. TIntermTyped* initializer)
  6714. {
  6715. if (voidErrorCheck(loc, identifier, type.getBasicType()))
  6716. return nullptr;
  6717. // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
  6718. // This test is implicitly recursive, because initializers propagate constness
  6719. // up the aggregate node tree during creation. E.g, for:
  6720. // { { 1, 2 }, { 3, 4 } }
  6721. // the initializer list is marked EvqConst at the top node, and remains so here. However:
  6722. // { 1, { myvar, 2 }, 3 }
  6723. // is not a const intializer, and still becomes EvqGlobal here.
  6724. const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
  6725. if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
  6726. // Force to global
  6727. type.getQualifier().storage = EvqGlobal;
  6728. }
  6729. // make const and initialization consistent
  6730. fixConstInit(loc, identifier, type, initializer);
  6731. // Check for redeclaration of built-ins and/or attempting to declare a reserved name
  6732. TSymbol* symbol = nullptr;
  6733. inheritGlobalDefaults(type.getQualifier());
  6734. const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
  6735. // correct IO in the type
  6736. switch (type.getQualifier().storage) {
  6737. case EvqGlobal:
  6738. case EvqTemporary:
  6739. clearUniformInputOutput(type.getQualifier());
  6740. break;
  6741. case EvqUniform:
  6742. case EvqBuffer:
  6743. correctUniform(type.getQualifier());
  6744. if (type.isStruct()) {
  6745. auto it = ioTypeMap.find(type.getStruct());
  6746. if (it != ioTypeMap.end())
  6747. type.setStruct(it->second.uniform);
  6748. }
  6749. break;
  6750. default:
  6751. break;
  6752. }
  6753. // Declare the variable
  6754. if (type.isArray()) {
  6755. // array case
  6756. declareArray(loc, identifier, type, symbol, !flattenVar);
  6757. } else {
  6758. // non-array case
  6759. if (symbol == nullptr)
  6760. symbol = declareNonArray(loc, identifier, type, !flattenVar);
  6761. else if (type != symbol->getType())
  6762. error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
  6763. }
  6764. if (symbol == nullptr)
  6765. return nullptr;
  6766. if (flattenVar)
  6767. flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
  6768. if (initializer == nullptr)
  6769. return nullptr;
  6770. // Deal with initializer
  6771. TVariable* variable = symbol->getAsVariable();
  6772. if (variable == nullptr) {
  6773. error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
  6774. return nullptr;
  6775. }
  6776. return executeInitializer(loc, initializer, variable);
  6777. }
  6778. // Pick up global defaults from the provide global defaults into dst.
  6779. void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
  6780. {
  6781. if (dst.storage == EvqVaryingOut) {
  6782. if (! dst.hasStream() && language == EShLangGeometry)
  6783. dst.layoutStream = globalOutputDefaults.layoutStream;
  6784. if (! dst.hasXfbBuffer())
  6785. dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  6786. }
  6787. }
  6788. //
  6789. // Make an internal-only variable whose name is for debug purposes only
  6790. // and won't be searched for. Callers will only use the return value to use
  6791. // the variable, not the name to look it up. It is okay if the name
  6792. // is the same as other names; there won't be any conflict.
  6793. //
  6794. TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
  6795. {
  6796. TString* nameString = NewPoolTString(name);
  6797. TVariable* variable = new TVariable(nameString, type);
  6798. symbolTable.makeInternalVariable(*variable);
  6799. return variable;
  6800. }
  6801. // Make a symbol node holding a new internal temporary variable.
  6802. TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
  6803. const TType& type) const
  6804. {
  6805. TVariable* tmpVar = makeInternalVariable(name, type);
  6806. tmpVar->getWritableType().getQualifier().makeTemporary();
  6807. return intermediate.addSymbol(*tmpVar, loc);
  6808. }
  6809. //
  6810. // Declare a non-array variable, the main point being there is no redeclaration
  6811. // for resizing allowed.
  6812. //
  6813. // Return the successfully declared variable.
  6814. //
  6815. TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  6816. bool track)
  6817. {
  6818. // make a new variable
  6819. TVariable* variable = new TVariable(&identifier, type);
  6820. // add variable to symbol table
  6821. if (symbolTable.insert(*variable)) {
  6822. if (track && symbolTable.atGlobalLevel())
  6823. trackLinkage(*variable);
  6824. return variable;
  6825. }
  6826. error(loc, "redefinition", variable->getName().c_str(), "");
  6827. return nullptr;
  6828. }
  6829. //
  6830. // Handle all types of initializers from the grammar.
  6831. //
  6832. // Returning nullptr just means there is no code to execute to handle the
  6833. // initializer, which will, for example, be the case for constant initializers.
  6834. //
  6835. // Returns a subtree that accomplished the initialization.
  6836. //
  6837. TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
  6838. {
  6839. //
  6840. // Identifier must be of type constant, a global, or a temporary, and
  6841. // starting at version 120, desktop allows uniforms to have initializers.
  6842. //
  6843. TStorageQualifier qualifier = variable->getType().getQualifier().storage;
  6844. //
  6845. // If the initializer was from braces { ... }, we convert the whole subtree to a
  6846. // constructor-style subtree, allowing the rest of the code to operate
  6847. // identically for both kinds of initializers.
  6848. //
  6849. //
  6850. // Type can't be deduced from the initializer list, so a skeletal type to
  6851. // follow has to be passed in. Constness and specialization-constness
  6852. // should be deduced bottom up, not dictated by the skeletal type.
  6853. //
  6854. TType skeletalType;
  6855. skeletalType.shallowCopy(variable->getType());
  6856. skeletalType.getQualifier().makeTemporary();
  6857. if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
  6858. initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
  6859. if (initializer == nullptr) {
  6860. // error recovery; don't leave const without constant values
  6861. if (qualifier == EvqConst)
  6862. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6863. return nullptr;
  6864. }
  6865. // Fix outer arrayness if variable is unsized, getting size from the initializer
  6866. if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
  6867. variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
  6868. // Inner arrayness can also get set by an initializer
  6869. if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
  6870. initializer->getType().getArraySizes()->getNumDims() ==
  6871. variable->getType().getArraySizes()->getNumDims()) {
  6872. // adopt unsized sizes from the initializer's sizes
  6873. for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
  6874. if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
  6875. variable->getWritableType().getArraySizes()->setDimSize(d,
  6876. initializer->getType().getArraySizes()->getDimSize(d));
  6877. }
  6878. }
  6879. }
  6880. // Uniform and global consts require a constant initializer
  6881. if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
  6882. error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
  6883. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6884. return nullptr;
  6885. }
  6886. // Const variables require a constant initializer
  6887. if (qualifier == EvqConst) {
  6888. if (initializer->getType().getQualifier().storage != EvqConst) {
  6889. variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
  6890. qualifier = EvqConstReadOnly;
  6891. }
  6892. }
  6893. if (qualifier == EvqConst || qualifier == EvqUniform) {
  6894. // Compile-time tagging of the variable with its constant value...
  6895. initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
  6896. if (initializer != nullptr && variable->getType() != initializer->getType())
  6897. initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
  6898. if (initializer == nullptr || !initializer->getAsConstantUnion() ||
  6899. variable->getType() != initializer->getType()) {
  6900. error(loc, "non-matching or non-convertible constant type for const initializer",
  6901. variable->getType().getStorageQualifierString(), "");
  6902. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6903. return nullptr;
  6904. }
  6905. variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
  6906. } else {
  6907. // normal assigning of a value to a variable...
  6908. specializationCheck(loc, initializer->getType(), "initializer");
  6909. TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
  6910. TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
  6911. if (initNode == nullptr)
  6912. assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
  6913. return initNode;
  6914. }
  6915. return nullptr;
  6916. }
  6917. //
  6918. // Reprocess any initializer-list { ... } parts of the initializer.
  6919. // Need to hierarchically assign correct types and implicit
  6920. // conversions. Will do this mimicking the same process used for
  6921. // creating a constructor-style initializer, ensuring we get the
  6922. // same form.
  6923. //
  6924. // Returns a node representing an expression for the initializer list expressed
  6925. // as the correct type.
  6926. //
  6927. // Returns nullptr if there is an error.
  6928. //
  6929. TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
  6930. TIntermTyped* initializer, TIntermTyped* scalarInit)
  6931. {
  6932. // Will operate recursively. Once a subtree is found that is constructor style,
  6933. // everything below it is already good: Only the "top part" of the initializer
  6934. // can be an initializer list, where "top part" can extend for several (or all) levels.
  6935. // see if we have bottomed out in the tree within the initializer-list part
  6936. TIntermAggregate* initList = initializer->getAsAggregate();
  6937. if (initList == nullptr || initList->getOp() != EOpNull) {
  6938. // We don't have a list, but if it's a scalar and the 'type' is a
  6939. // composite, we need to lengthen below to make it useful.
  6940. // Otherwise, this is an already formed object to initialize with.
  6941. if (type.isScalar() || !initializer->getType().isScalar())
  6942. return initializer;
  6943. else
  6944. initList = intermediate.makeAggregate(initializer);
  6945. }
  6946. // Of the initializer-list set of nodes, need to process bottom up,
  6947. // so recurse deep, then process on the way up.
  6948. // Go down the tree here...
  6949. if (type.isArray()) {
  6950. // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
  6951. // Later on, initializer execution code will deal with array size logic.
  6952. TType arrayType;
  6953. arrayType.shallowCopy(type); // sharing struct stuff is fine
  6954. arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
  6955. // edit array sizes to fill in unsized dimensions
  6956. if (type.isUnsizedArray())
  6957. arrayType.changeOuterArraySize((int)initList->getSequence().size());
  6958. // set unsized array dimensions that can be derived from the initializer's first element
  6959. if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
  6960. TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
  6961. if (firstInit->getType().isArray() &&
  6962. arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
  6963. for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
  6964. if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
  6965. arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
  6966. }
  6967. }
  6968. }
  6969. // lengthen list to be long enough
  6970. lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
  6971. // recursively process each element
  6972. TType elementType(arrayType, 0); // dereferenced type
  6973. for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
  6974. initList->getSequence()[i] = convertInitializerList(loc, elementType,
  6975. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6976. if (initList->getSequence()[i] == nullptr)
  6977. return nullptr;
  6978. }
  6979. return addConstructor(loc, initList, arrayType);
  6980. } else if (type.isStruct()) {
  6981. // do we have implicit assignments to opaques?
  6982. for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
  6983. if ((*type.getStruct())[i].type->containsOpaque()) {
  6984. error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
  6985. return nullptr;
  6986. }
  6987. }
  6988. // lengthen list to be long enough
  6989. lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
  6990. if (type.getStruct()->size() != initList->getSequence().size()) {
  6991. error(loc, "wrong number of structure members", "initializer list", "");
  6992. return nullptr;
  6993. }
  6994. for (size_t i = 0; i < type.getStruct()->size(); ++i) {
  6995. initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
  6996. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6997. if (initList->getSequence()[i] == nullptr)
  6998. return nullptr;
  6999. }
  7000. } else if (type.isMatrix()) {
  7001. if (type.computeNumComponents() == (int)initList->getSequence().size()) {
  7002. // This means the matrix is initialized component-wise, rather than as
  7003. // a series of rows and columns. We can just use the list directly as
  7004. // a constructor; no further processing needed.
  7005. } else {
  7006. // lengthen list to be long enough
  7007. lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
  7008. if (type.getMatrixCols() != (int)initList->getSequence().size()) {
  7009. error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
  7010. return nullptr;
  7011. }
  7012. TType vectorType(type, 0); // dereferenced type
  7013. for (int i = 0; i < type.getMatrixCols(); ++i) {
  7014. initList->getSequence()[i] = convertInitializerList(loc, vectorType,
  7015. initList->getSequence()[i]->getAsTyped(), scalarInit);
  7016. if (initList->getSequence()[i] == nullptr)
  7017. return nullptr;
  7018. }
  7019. }
  7020. } else if (type.isVector()) {
  7021. // lengthen list to be long enough
  7022. lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
  7023. // error check; we're at bottom, so work is finished below
  7024. if (type.getVectorSize() != (int)initList->getSequence().size()) {
  7025. error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
  7026. type.getCompleteString().c_str());
  7027. return nullptr;
  7028. }
  7029. } else if (type.isScalar()) {
  7030. // lengthen list to be long enough
  7031. lengthenList(loc, initList->getSequence(), 1, scalarInit);
  7032. if ((int)initList->getSequence().size() != 1) {
  7033. error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
  7034. return nullptr;
  7035. }
  7036. } else {
  7037. error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
  7038. return nullptr;
  7039. }
  7040. // Now that the subtree is processed, process this node as if the
  7041. // initializer list is a set of arguments to a constructor.
  7042. TIntermTyped* emulatedConstructorArguments;
  7043. if (initList->getSequence().size() == 1)
  7044. emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
  7045. else
  7046. emulatedConstructorArguments = initList;
  7047. return addConstructor(loc, emulatedConstructorArguments, type);
  7048. }
  7049. // Lengthen list to be long enough to cover any gap from the current list size
  7050. // to 'size'. If the list is longer, do nothing.
  7051. // The value to lengthen with is the default for short lists.
  7052. //
  7053. // By default, lists that are too short due to lack of initializers initialize to zero.
  7054. // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
  7055. // based on whether something is passed in as 'scalarInit'.
  7056. //
  7057. // 'scalarInit' must be safe to use each time this is called (no side effects replication).
  7058. //
  7059. void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
  7060. {
  7061. for (int c = (int)list.size(); c < size; ++c) {
  7062. if (scalarInit == nullptr)
  7063. list.push_back(intermediate.addConstantUnion(0, loc));
  7064. else
  7065. list.push_back(scalarInit);
  7066. }
  7067. }
  7068. //
  7069. // Test for the correctness of the parameters passed to various constructor functions
  7070. // and also convert them to the right data type, if allowed and required.
  7071. //
  7072. // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
  7073. //
  7074. TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  7075. {
  7076. if (node == nullptr)
  7077. return nullptr;
  7078. // Construct identical type
  7079. if (type == node->getType())
  7080. return node;
  7081. // Handle the idiom "(struct type)<scalar value>"
  7082. if (type.isStruct() && isScalarConstructor(node)) {
  7083. // 'node' will almost always get used multiple times, so should not be used directly,
  7084. // it would create a DAG instead of a tree, which might be okay (would
  7085. // like to formalize that for constants and symbols), but if it has
  7086. // side effects, they would get executed multiple times, which is not okay.
  7087. if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
  7088. TIntermAggregate* seq = intermediate.makeAggregate(loc);
  7089. TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
  7090. seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
  7091. seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
  7092. seq->setOp(EOpComma);
  7093. seq->setType(type);
  7094. return seq;
  7095. } else
  7096. return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
  7097. }
  7098. return addConstructor(loc, node, type);
  7099. }
  7100. // Add a constructor, either from the grammar, or other programmatic reasons.
  7101. //
  7102. // 'node' is what to construct from.
  7103. // 'type' is what type to construct.
  7104. //
  7105. // Returns the constructed object.
  7106. // Return nullptr if it can't be done.
  7107. //
  7108. TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  7109. {
  7110. TIntermAggregate* aggrNode = node->getAsAggregate();
  7111. TOperator op = intermediate.mapTypeToConstructorOp(type);
  7112. if (op == EOpConstructTextureSampler)
  7113. return intermediate.setAggregateOperator(aggrNode, op, type, loc);
  7114. TTypeList::const_iterator memberTypes;
  7115. if (op == EOpConstructStruct)
  7116. memberTypes = type.getStruct()->begin();
  7117. TType elementType;
  7118. if (type.isArray()) {
  7119. TType dereferenced(type, 0);
  7120. elementType.shallowCopy(dereferenced);
  7121. } else
  7122. elementType.shallowCopy(type);
  7123. bool singleArg;
  7124. if (aggrNode != nullptr) {
  7125. if (aggrNode->getOp() != EOpNull)
  7126. singleArg = true;
  7127. else
  7128. singleArg = false;
  7129. } else
  7130. singleArg = true;
  7131. TIntermTyped *newNode;
  7132. if (singleArg) {
  7133. // Handle array -> array conversion
  7134. // Constructing an array of one type from an array of another type is allowed,
  7135. // assuming there are enough components available (semantic-checked earlier).
  7136. if (type.isArray() && node->isArray())
  7137. newNode = convertArray(node, type);
  7138. // If structure constructor or array constructor is being called
  7139. // for only one parameter inside the aggregate, we need to call constructAggregate function once.
  7140. else if (type.isArray())
  7141. newNode = constructAggregate(node, elementType, 1, node->getLoc());
  7142. else if (op == EOpConstructStruct)
  7143. newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
  7144. else {
  7145. // shape conversion for matrix constructor from scalar. HLSL semantics are: scalar
  7146. // is replicated into every element of the matrix (not just the diagnonal), so
  7147. // that is handled specially here.
  7148. if (type.isMatrix() && node->getType().isScalarOrVec1())
  7149. node = intermediate.addShapeConversion(type, node);
  7150. newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
  7151. }
  7152. if (newNode && (type.isArray() || op == EOpConstructStruct))
  7153. newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
  7154. return newNode;
  7155. }
  7156. //
  7157. // Handle list of arguments.
  7158. //
  7159. TIntermSequence& sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
  7160. // if the structure constructor contains more than one parameter, then construct
  7161. // each parameter
  7162. int paramCount = 0; // keeps a track of the constructor parameter number being checked
  7163. // for each parameter to the constructor call, check to see if the right type is passed or convert them
  7164. // to the right type if possible (and allowed).
  7165. // for structure constructors, just check if the right type is passed, no conversion is allowed.
  7166. for (TIntermSequence::iterator p = sequenceVector.begin();
  7167. p != sequenceVector.end(); p++, paramCount++) {
  7168. if (type.isArray())
  7169. newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
  7170. else if (op == EOpConstructStruct)
  7171. newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
  7172. else
  7173. newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
  7174. if (newNode)
  7175. *p = newNode;
  7176. else
  7177. return nullptr;
  7178. }
  7179. TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
  7180. return constructor;
  7181. }
  7182. // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
  7183. // for the parameter to the constructor (passed to this function). Essentially, it converts
  7184. // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
  7185. // float, then float is converted to int.
  7186. //
  7187. // Returns nullptr for an error or the constructed node.
  7188. //
  7189. TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
  7190. const TSourceLoc& loc, bool subset)
  7191. {
  7192. TIntermTyped* newNode;
  7193. TOperator basicOp;
  7194. //
  7195. // First, convert types as needed.
  7196. //
  7197. switch (op) {
  7198. case EOpConstructF16Vec2:
  7199. case EOpConstructF16Vec3:
  7200. case EOpConstructF16Vec4:
  7201. case EOpConstructF16Mat2x2:
  7202. case EOpConstructF16Mat2x3:
  7203. case EOpConstructF16Mat2x4:
  7204. case EOpConstructF16Mat3x2:
  7205. case EOpConstructF16Mat3x3:
  7206. case EOpConstructF16Mat3x4:
  7207. case EOpConstructF16Mat4x2:
  7208. case EOpConstructF16Mat4x3:
  7209. case EOpConstructF16Mat4x4:
  7210. case EOpConstructFloat16:
  7211. basicOp = EOpConstructFloat16;
  7212. break;
  7213. case EOpConstructVec2:
  7214. case EOpConstructVec3:
  7215. case EOpConstructVec4:
  7216. case EOpConstructMat2x2:
  7217. case EOpConstructMat2x3:
  7218. case EOpConstructMat2x4:
  7219. case EOpConstructMat3x2:
  7220. case EOpConstructMat3x3:
  7221. case EOpConstructMat3x4:
  7222. case EOpConstructMat4x2:
  7223. case EOpConstructMat4x3:
  7224. case EOpConstructMat4x4:
  7225. case EOpConstructFloat:
  7226. basicOp = EOpConstructFloat;
  7227. break;
  7228. case EOpConstructDVec2:
  7229. case EOpConstructDVec3:
  7230. case EOpConstructDVec4:
  7231. case EOpConstructDMat2x2:
  7232. case EOpConstructDMat2x3:
  7233. case EOpConstructDMat2x4:
  7234. case EOpConstructDMat3x2:
  7235. case EOpConstructDMat3x3:
  7236. case EOpConstructDMat3x4:
  7237. case EOpConstructDMat4x2:
  7238. case EOpConstructDMat4x3:
  7239. case EOpConstructDMat4x4:
  7240. case EOpConstructDouble:
  7241. basicOp = EOpConstructDouble;
  7242. break;
  7243. case EOpConstructI16Vec2:
  7244. case EOpConstructI16Vec3:
  7245. case EOpConstructI16Vec4:
  7246. case EOpConstructInt16:
  7247. basicOp = EOpConstructInt16;
  7248. break;
  7249. case EOpConstructIVec2:
  7250. case EOpConstructIVec3:
  7251. case EOpConstructIVec4:
  7252. case EOpConstructIMat2x2:
  7253. case EOpConstructIMat2x3:
  7254. case EOpConstructIMat2x4:
  7255. case EOpConstructIMat3x2:
  7256. case EOpConstructIMat3x3:
  7257. case EOpConstructIMat3x4:
  7258. case EOpConstructIMat4x2:
  7259. case EOpConstructIMat4x3:
  7260. case EOpConstructIMat4x4:
  7261. case EOpConstructInt:
  7262. basicOp = EOpConstructInt;
  7263. break;
  7264. case EOpConstructU16Vec2:
  7265. case EOpConstructU16Vec3:
  7266. case EOpConstructU16Vec4:
  7267. case EOpConstructUint16:
  7268. basicOp = EOpConstructUint16;
  7269. break;
  7270. case EOpConstructUVec2:
  7271. case EOpConstructUVec3:
  7272. case EOpConstructUVec4:
  7273. case EOpConstructUMat2x2:
  7274. case EOpConstructUMat2x3:
  7275. case EOpConstructUMat2x4:
  7276. case EOpConstructUMat3x2:
  7277. case EOpConstructUMat3x3:
  7278. case EOpConstructUMat3x4:
  7279. case EOpConstructUMat4x2:
  7280. case EOpConstructUMat4x3:
  7281. case EOpConstructUMat4x4:
  7282. case EOpConstructUint:
  7283. basicOp = EOpConstructUint;
  7284. break;
  7285. case EOpConstructBVec2:
  7286. case EOpConstructBVec3:
  7287. case EOpConstructBVec4:
  7288. case EOpConstructBMat2x2:
  7289. case EOpConstructBMat2x3:
  7290. case EOpConstructBMat2x4:
  7291. case EOpConstructBMat3x2:
  7292. case EOpConstructBMat3x3:
  7293. case EOpConstructBMat3x4:
  7294. case EOpConstructBMat4x2:
  7295. case EOpConstructBMat4x3:
  7296. case EOpConstructBMat4x4:
  7297. case EOpConstructBool:
  7298. basicOp = EOpConstructBool;
  7299. break;
  7300. default:
  7301. error(loc, "unsupported construction", "", "");
  7302. return nullptr;
  7303. }
  7304. newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
  7305. if (newNode == nullptr) {
  7306. error(loc, "can't convert", "constructor", "");
  7307. return nullptr;
  7308. }
  7309. //
  7310. // Now, if there still isn't an operation to do the construction, and we need one, add one.
  7311. //
  7312. // Otherwise, skip out early.
  7313. if (subset || (newNode != node && newNode->getType() == type))
  7314. return newNode;
  7315. // setAggregateOperator will insert a new node for the constructor, as needed.
  7316. return intermediate.setAggregateOperator(newNode, op, type, loc);
  7317. }
  7318. // Convert the array in node to the requested type, which is also an array.
  7319. // Returns nullptr on failure, otherwise returns aggregate holding the list of
  7320. // elements needed to construct the array.
  7321. TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
  7322. {
  7323. assert(node->isArray() && type.isArray());
  7324. if (node->getType().computeNumComponents() < type.computeNumComponents())
  7325. return nullptr;
  7326. // TODO: write an argument replicator, for the case the argument should not be
  7327. // executed multiple times, yet multiple copies are needed.
  7328. TIntermTyped* constructee = node->getAsTyped();
  7329. // track where we are in consuming the argument
  7330. int constructeeElement = 0;
  7331. int constructeeComponent = 0;
  7332. // bump up to the next component to consume
  7333. const auto getNextComponent = [&]() {
  7334. TIntermTyped* component;
  7335. component = handleBracketDereference(node->getLoc(), constructee,
  7336. intermediate.addConstantUnion(constructeeElement, node->getLoc()));
  7337. if (component->isVector())
  7338. component = handleBracketDereference(node->getLoc(), component,
  7339. intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
  7340. // bump component pointer up
  7341. ++constructeeComponent;
  7342. if (constructeeComponent == constructee->getVectorSize()) {
  7343. constructeeComponent = 0;
  7344. ++constructeeElement;
  7345. }
  7346. return component;
  7347. };
  7348. // make one subnode per constructed array element
  7349. TIntermAggregate* constructor = nullptr;
  7350. TType derefType(type, 0);
  7351. TType speculativeComponentType(derefType, 0);
  7352. TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
  7353. TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
  7354. TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
  7355. for (int e = 0; e < type.getOuterArraySize(); ++e) {
  7356. // construct an element
  7357. TIntermTyped* elementArg;
  7358. if (type.getVectorSize() == constructee->getVectorSize()) {
  7359. // same element shape
  7360. elementArg = handleBracketDereference(node->getLoc(), constructee,
  7361. intermediate.addConstantUnion(e, node->getLoc()));
  7362. } else {
  7363. // mismatched element shapes
  7364. if (type.getVectorSize() == 1)
  7365. elementArg = getNextComponent();
  7366. else {
  7367. // make a vector
  7368. TIntermAggregate* elementConstructee = nullptr;
  7369. for (int c = 0; c < type.getVectorSize(); ++c)
  7370. elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
  7371. elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
  7372. }
  7373. }
  7374. // convert basic types
  7375. elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
  7376. if (elementArg == nullptr)
  7377. return nullptr;
  7378. // combine with top-level constructor
  7379. constructor = intermediate.growAggregate(constructor, elementArg);
  7380. }
  7381. return constructor;
  7382. }
  7383. // This function tests for the type of the parameters to the structure or array constructor. Raises
  7384. // an error message if the expected type does not match the parameter passed to the constructor.
  7385. //
  7386. // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
  7387. //
  7388. TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
  7389. const TSourceLoc& loc)
  7390. {
  7391. // Handle cases that map more 1:1 between constructor arguments and constructed.
  7392. TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
  7393. if (converted == nullptr || converted->getType() != type) {
  7394. error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
  7395. node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
  7396. return nullptr;
  7397. }
  7398. return converted;
  7399. }
  7400. //
  7401. // Do everything needed to add an interface block.
  7402. //
  7403. void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
  7404. {
  7405. assert(type.getWritableStruct() != nullptr);
  7406. // Clean up top-level decorations that don't belong.
  7407. switch (type.getQualifier().storage) {
  7408. case EvqUniform:
  7409. case EvqBuffer:
  7410. correctUniform(type.getQualifier());
  7411. break;
  7412. case EvqVaryingIn:
  7413. correctInput(type.getQualifier());
  7414. break;
  7415. case EvqVaryingOut:
  7416. correctOutput(type.getQualifier());
  7417. break;
  7418. default:
  7419. break;
  7420. }
  7421. TTypeList& typeList = *type.getWritableStruct();
  7422. // fix and check for member storage qualifiers and types that don't belong within a block
  7423. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7424. TType& memberType = *typeList[member].type;
  7425. TQualifier& memberQualifier = memberType.getQualifier();
  7426. const TSourceLoc& memberLoc = typeList[member].loc;
  7427. globalQualifierFix(memberLoc, memberQualifier);
  7428. memberQualifier.storage = type.getQualifier().storage;
  7429. if (memberType.isStruct()) {
  7430. // clean up and pick up the right set of decorations
  7431. auto it = ioTypeMap.find(memberType.getStruct());
  7432. switch (type.getQualifier().storage) {
  7433. case EvqUniform:
  7434. case EvqBuffer:
  7435. correctUniform(type.getQualifier());
  7436. if (it != ioTypeMap.end() && it->second.uniform)
  7437. memberType.setStruct(it->second.uniform);
  7438. break;
  7439. case EvqVaryingIn:
  7440. correctInput(type.getQualifier());
  7441. if (it != ioTypeMap.end() && it->second.input)
  7442. memberType.setStruct(it->second.input);
  7443. break;
  7444. case EvqVaryingOut:
  7445. correctOutput(type.getQualifier());
  7446. if (it != ioTypeMap.end() && it->second.output)
  7447. memberType.setStruct(it->second.output);
  7448. break;
  7449. default:
  7450. break;
  7451. }
  7452. }
  7453. }
  7454. // Make default block qualification, and adjust the member qualifications
  7455. TQualifier defaultQualification;
  7456. switch (type.getQualifier().storage) {
  7457. case EvqUniform: defaultQualification = globalUniformDefaults; break;
  7458. case EvqBuffer: defaultQualification = globalBufferDefaults; break;
  7459. case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
  7460. case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
  7461. default: defaultQualification.clear(); break;
  7462. }
  7463. // Special case for "push_constant uniform", which has a default of std430,
  7464. // contrary to normal uniform defaults, and can't have a default tracked for it.
  7465. if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
  7466. type.getQualifier().layoutPacking = ElpStd430;
  7467. // fix and check for member layout qualifiers
  7468. mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
  7469. bool memberWithLocation = false;
  7470. bool memberWithoutLocation = false;
  7471. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7472. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7473. const TSourceLoc& memberLoc = typeList[member].loc;
  7474. if (memberQualifier.hasStream()) {
  7475. if (defaultQualification.layoutStream != memberQualifier.layoutStream)
  7476. error(memberLoc, "member cannot contradict block", "stream", "");
  7477. }
  7478. // "This includes a block's inheritance of the
  7479. // current global default buffer, a block member's inheritance of the block's
  7480. // buffer, and the requirement that any *xfb_buffer* declared on a block
  7481. // member must match the buffer inherited from the block."
  7482. if (memberQualifier.hasXfbBuffer()) {
  7483. if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
  7484. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
  7485. }
  7486. if (memberQualifier.hasLocation()) {
  7487. switch (type.getQualifier().storage) {
  7488. case EvqVaryingIn:
  7489. case EvqVaryingOut:
  7490. memberWithLocation = true;
  7491. break;
  7492. default:
  7493. break;
  7494. }
  7495. } else
  7496. memberWithoutLocation = true;
  7497. TQualifier newMemberQualification = defaultQualification;
  7498. mergeQualifiers(newMemberQualification, memberQualifier);
  7499. memberQualifier = newMemberQualification;
  7500. }
  7501. // Process the members
  7502. fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
  7503. fixXfbOffsets(type.getQualifier(), typeList);
  7504. fixBlockUniformOffsets(type.getQualifier(), typeList);
  7505. // reverse merge, so that currentBlockQualifier now has all layout information
  7506. // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
  7507. mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
  7508. //
  7509. // Build and add the interface block as a new type named 'blockName'
  7510. //
  7511. // Use the instance name as the interface name if one exists, else the block name.
  7512. const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
  7513. TType blockType(&typeList, interfaceName, type.getQualifier());
  7514. if (type.isArray())
  7515. blockType.transferArraySizes(type.getArraySizes());
  7516. // Add the variable, as anonymous or named instanceName.
  7517. // Make an anonymous variable if no name was provided.
  7518. if (instanceName == nullptr)
  7519. instanceName = NewPoolTString("");
  7520. TVariable& variable = *new TVariable(instanceName, blockType);
  7521. if (! symbolTable.insert(variable)) {
  7522. if (*instanceName == "")
  7523. error(loc, "nameless block contains a member that already has a name at global scope",
  7524. "" /* blockName->c_str() */, "");
  7525. else
  7526. error(loc, "block instance name redefinition", variable.getName().c_str(), "");
  7527. return;
  7528. }
  7529. // Save it in the AST for linker use.
  7530. if (symbolTable.atGlobalLevel())
  7531. trackLinkage(variable);
  7532. }
  7533. //
  7534. // "For a block, this process applies to the entire block, or until the first member
  7535. // is reached that has a location layout qualifier. When a block member is declared with a location
  7536. // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
  7537. // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
  7538. // until the next member declared with a location qualifier. The values used for locations do not have to be
  7539. // declared in increasing order."
  7540. void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
  7541. {
  7542. // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
  7543. // have a location layout qualifier, or a compile-time error results."
  7544. if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
  7545. error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
  7546. else {
  7547. if (memberWithLocation) {
  7548. // remove any block-level location and make it per *every* member
  7549. int nextLocation = 0; // by the rule above, initial value is not relevant
  7550. if (qualifier.hasAnyLocation()) {
  7551. nextLocation = qualifier.layoutLocation;
  7552. qualifier.layoutLocation = TQualifier::layoutLocationEnd;
  7553. if (qualifier.hasComponent()) {
  7554. // "It is a compile-time error to apply the *component* qualifier to a ... block"
  7555. error(loc, "cannot apply to a block", "component", "");
  7556. }
  7557. if (qualifier.hasIndex()) {
  7558. error(loc, "cannot apply to a block", "index", "");
  7559. }
  7560. }
  7561. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7562. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7563. const TSourceLoc& memberLoc = typeList[member].loc;
  7564. if (! memberQualifier.hasLocation()) {
  7565. if (nextLocation >= (int)TQualifier::layoutLocationEnd)
  7566. error(memberLoc, "location is too large", "location", "");
  7567. memberQualifier.layoutLocation = nextLocation;
  7568. memberQualifier.layoutComponent = 0;
  7569. }
  7570. nextLocation = memberQualifier.layoutLocation +
  7571. intermediate.computeTypeLocationSize(*typeList[member].type, language);
  7572. }
  7573. }
  7574. }
  7575. }
  7576. void HlslParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
  7577. {
  7578. // "If a block is qualified with xfb_offset, all its
  7579. // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
  7580. // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
  7581. // offsets."
  7582. if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
  7583. return;
  7584. int nextOffset = qualifier.layoutXfbOffset;
  7585. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7586. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7587. bool contains64BitType = false;
  7588. bool contains32BitType = false;
  7589. bool contains16BitType = false;
  7590. int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
  7591. // see if we need to auto-assign an offset to this member
  7592. if (! memberQualifier.hasXfbOffset()) {
  7593. // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
  7594. if (contains64BitType)
  7595. RoundToPow2(nextOffset, 8);
  7596. else if (contains32BitType)
  7597. RoundToPow2(nextOffset, 4);
  7598. // "if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2"
  7599. else if (contains16BitType)
  7600. RoundToPow2(nextOffset, 2);
  7601. memberQualifier.layoutXfbOffset = nextOffset;
  7602. } else
  7603. nextOffset = memberQualifier.layoutXfbOffset;
  7604. nextOffset += memberSize;
  7605. }
  7606. // The above gave all block members an offset, so we can take it off the block now,
  7607. // which will avoid double counting the offset usage.
  7608. qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
  7609. }
  7610. // Calculate and save the offset of each block member, using the recursively
  7611. // defined block offset rules and the user-provided offset and align.
  7612. //
  7613. // Also, compute and save the total size of the block. For the block's size, arrayness
  7614. // is not taken into account, as each element is backed by a separate buffer.
  7615. //
  7616. void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
  7617. {
  7618. if (! qualifier.isUniformOrBuffer())
  7619. return;
  7620. if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
  7621. return;
  7622. int offset = 0;
  7623. int memberSize;
  7624. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7625. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7626. const TSourceLoc& memberLoc = typeList[member].loc;
  7627. // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
  7628. // modify just the children's view of matrix layout, if there is one for this member
  7629. TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
  7630. int dummyStride;
  7631. int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride,
  7632. qualifier.layoutPacking,
  7633. subMatrixLayout != ElmNone
  7634. ? subMatrixLayout == ElmRowMajor
  7635. : qualifier.layoutMatrix == ElmRowMajor);
  7636. if (memberQualifier.hasOffset()) {
  7637. // "The specified offset must be a multiple
  7638. // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
  7639. if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
  7640. error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
  7641. // "The offset qualifier forces the qualified member to start at or after the specified
  7642. // integral-constant expression, which will be its byte offset from the beginning of the buffer.
  7643. // "The actual offset of a member is computed as
  7644. // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
  7645. offset = std::max(offset, memberQualifier.layoutOffset);
  7646. }
  7647. // "The actual alignment of a member will be the greater of the specified align alignment and the standard
  7648. // (e.g., std140) base alignment for the member's type."
  7649. if (memberQualifier.hasAlign())
  7650. memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
  7651. // "If the resulting offset is not a multiple of the actual alignment,
  7652. // increase it to the first offset that is a multiple of
  7653. // the actual alignment."
  7654. RoundToPow2(offset, memberAlignment);
  7655. typeList[member].type->getQualifier().layoutOffset = offset;
  7656. offset += memberSize;
  7657. }
  7658. }
  7659. // For an identifier that is already declared, add more qualification to it.
  7660. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
  7661. {
  7662. TSymbol* symbol = symbolTable.find(identifier);
  7663. if (symbol == nullptr) {
  7664. error(loc, "identifier not previously declared", identifier.c_str(), "");
  7665. return;
  7666. }
  7667. if (symbol->getAsFunction()) {
  7668. error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
  7669. return;
  7670. }
  7671. if (qualifier.isAuxiliary() ||
  7672. qualifier.isMemory() ||
  7673. qualifier.isInterpolation() ||
  7674. qualifier.hasLayout() ||
  7675. qualifier.storage != EvqTemporary ||
  7676. qualifier.precision != EpqNone) {
  7677. error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
  7678. return;
  7679. }
  7680. // For read-only built-ins, add a new symbol for holding the modified qualifier.
  7681. // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
  7682. if (symbol->isReadOnly())
  7683. symbol = symbolTable.copyUp(symbol);
  7684. if (qualifier.invariant) {
  7685. if (intermediate.inIoAccessed(identifier))
  7686. error(loc, "cannot change qualification after use", "invariant", "");
  7687. symbol->getWritableType().getQualifier().invariant = true;
  7688. } else if (qualifier.noContraction) {
  7689. if (intermediate.inIoAccessed(identifier))
  7690. error(loc, "cannot change qualification after use", "precise", "");
  7691. symbol->getWritableType().getQualifier().noContraction = true;
  7692. } else if (qualifier.specConstant) {
  7693. symbol->getWritableType().getQualifier().makeSpecConstant();
  7694. if (qualifier.hasSpecConstantId())
  7695. symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
  7696. } else
  7697. warn(loc, "unknown requalification", "", "");
  7698. }
  7699. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
  7700. {
  7701. for (unsigned int i = 0; i < identifiers.size(); ++i)
  7702. addQualifierToExisting(loc, qualifier, *identifiers[i]);
  7703. }
  7704. //
  7705. // Update the intermediate for the given input geometry
  7706. //
  7707. bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7708. {
  7709. // these can be declared on non-entry-points, in which case they lose their meaning
  7710. if (! parsingEntrypointParameters)
  7711. return true;
  7712. switch (geometry) {
  7713. case ElgPoints: // fall through
  7714. case ElgLines: // ...
  7715. case ElgTriangles: // ...
  7716. case ElgLinesAdjacency: // ...
  7717. case ElgTrianglesAdjacency: // ...
  7718. if (! intermediate.setInputPrimitive(geometry)) {
  7719. error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7720. return false;
  7721. }
  7722. break;
  7723. default:
  7724. error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
  7725. return false;
  7726. }
  7727. return true;
  7728. }
  7729. //
  7730. // Update the intermediate for the given output geometry
  7731. //
  7732. bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7733. {
  7734. // If this is not a geometry shader, ignore. It might be a mixed shader including several stages.
  7735. // Since that's an OK situation, return true for success.
  7736. if (language != EShLangGeometry)
  7737. return true;
  7738. // these can be declared on non-entry-points, in which case they lose their meaning
  7739. if (! parsingEntrypointParameters)
  7740. return true;
  7741. switch (geometry) {
  7742. case ElgPoints:
  7743. case ElgLineStrip:
  7744. case ElgTriangleStrip:
  7745. if (! intermediate.setOutputPrimitive(geometry)) {
  7746. error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7747. return false;
  7748. }
  7749. break;
  7750. default:
  7751. error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
  7752. return false;
  7753. }
  7754. return true;
  7755. }
  7756. //
  7757. // Selection attributes
  7758. //
  7759. void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
  7760. const TAttributes& attributes)
  7761. {
  7762. if (selection == nullptr)
  7763. return;
  7764. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7765. switch (it->name) {
  7766. case EatFlatten:
  7767. selection->setFlatten();
  7768. break;
  7769. case EatBranch:
  7770. selection->setDontFlatten();
  7771. break;
  7772. default:
  7773. warn(loc, "attribute does not apply to a selection", "", "");
  7774. break;
  7775. }
  7776. }
  7777. }
  7778. //
  7779. // Switch attributes
  7780. //
  7781. void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
  7782. const TAttributes& attributes)
  7783. {
  7784. if (selection == nullptr)
  7785. return;
  7786. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7787. switch (it->name) {
  7788. case EatFlatten:
  7789. selection->setFlatten();
  7790. break;
  7791. case EatBranch:
  7792. selection->setDontFlatten();
  7793. break;
  7794. default:
  7795. warn(loc, "attribute does not apply to a switch", "", "");
  7796. break;
  7797. }
  7798. }
  7799. }
  7800. //
  7801. // Loop attributes
  7802. //
  7803. void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
  7804. const TAttributes& attributes)
  7805. {
  7806. if (loop == nullptr)
  7807. return;
  7808. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7809. switch (it->name) {
  7810. case EatUnroll:
  7811. loop->setUnroll();
  7812. break;
  7813. case EatLoop:
  7814. loop->setDontUnroll();
  7815. break;
  7816. default:
  7817. warn(loc, "attribute does not apply to a loop", "", "");
  7818. break;
  7819. }
  7820. }
  7821. }
  7822. //
  7823. // Updating default qualifier for the case of a declaration with just a qualifier,
  7824. // no type, block, or identifier.
  7825. //
  7826. void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
  7827. {
  7828. if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
  7829. assert(language == EShLangTessControl || language == EShLangGeometry);
  7830. // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
  7831. }
  7832. if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
  7833. if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
  7834. error(loc, "cannot change previously set layout value", "invocations", "");
  7835. }
  7836. if (publicType.shaderQualifiers.geometry != ElgNone) {
  7837. if (publicType.qualifier.storage == EvqVaryingIn) {
  7838. switch (publicType.shaderQualifiers.geometry) {
  7839. case ElgPoints:
  7840. case ElgLines:
  7841. case ElgLinesAdjacency:
  7842. case ElgTriangles:
  7843. case ElgTrianglesAdjacency:
  7844. case ElgQuads:
  7845. case ElgIsolines:
  7846. break;
  7847. default:
  7848. error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7849. "");
  7850. }
  7851. } else if (publicType.qualifier.storage == EvqVaryingOut) {
  7852. handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
  7853. } else
  7854. error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7855. GetStorageQualifierString(publicType.qualifier.storage));
  7856. }
  7857. if (publicType.shaderQualifiers.spacing != EvsNone)
  7858. intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
  7859. if (publicType.shaderQualifiers.order != EvoNone)
  7860. intermediate.setVertexOrder(publicType.shaderQualifiers.order);
  7861. if (publicType.shaderQualifiers.pointMode)
  7862. intermediate.setPointMode();
  7863. for (int i = 0; i < 3; ++i) {
  7864. if (publicType.shaderQualifiers.localSize[i] > 1) {
  7865. int max = 0;
  7866. switch (i) {
  7867. case 0: max = resources.maxComputeWorkGroupSizeX; break;
  7868. case 1: max = resources.maxComputeWorkGroupSizeY; break;
  7869. case 2: max = resources.maxComputeWorkGroupSizeZ; break;
  7870. default: break;
  7871. }
  7872. if (intermediate.getLocalSize(i) > (unsigned int)max)
  7873. error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
  7874. // Fix the existing constant gl_WorkGroupSize with this new information.
  7875. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7876. workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
  7877. }
  7878. if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
  7879. intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
  7880. // Set the workgroup built-in variable as a specialization constant
  7881. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7882. workGroupSize->getWritableType().getQualifier().specConstant = true;
  7883. }
  7884. }
  7885. if (publicType.shaderQualifiers.earlyFragmentTests)
  7886. intermediate.setEarlyFragmentTests();
  7887. const TQualifier& qualifier = publicType.qualifier;
  7888. switch (qualifier.storage) {
  7889. case EvqUniform:
  7890. if (qualifier.hasMatrix())
  7891. globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
  7892. if (qualifier.hasPacking())
  7893. globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
  7894. break;
  7895. case EvqBuffer:
  7896. if (qualifier.hasMatrix())
  7897. globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
  7898. if (qualifier.hasPacking())
  7899. globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
  7900. break;
  7901. case EvqVaryingIn:
  7902. break;
  7903. case EvqVaryingOut:
  7904. if (qualifier.hasStream())
  7905. globalOutputDefaults.layoutStream = qualifier.layoutStream;
  7906. if (qualifier.hasXfbBuffer())
  7907. globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
  7908. if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
  7909. if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
  7910. error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
  7911. qualifier.layoutXfbBuffer);
  7912. }
  7913. break;
  7914. default:
  7915. error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
  7916. return;
  7917. }
  7918. }
  7919. //
  7920. // Take the sequence of statements that has been built up since the last case/default,
  7921. // put it on the list of top-level nodes for the current (inner-most) switch statement,
  7922. // and follow that by the case/default we are on now. (See switch topology comment on
  7923. // TIntermSwitch.)
  7924. //
  7925. void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
  7926. {
  7927. TIntermSequence* switchSequence = switchSequenceStack.back();
  7928. if (statements) {
  7929. statements->setOperator(EOpSequence);
  7930. switchSequence->push_back(statements);
  7931. }
  7932. if (branchNode) {
  7933. // check all previous cases for the same label (or both are 'default')
  7934. for (unsigned int s = 0; s < switchSequence->size(); ++s) {
  7935. TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
  7936. if (prevBranch) {
  7937. TIntermTyped* prevExpression = prevBranch->getExpression();
  7938. TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
  7939. if (prevExpression == nullptr && newExpression == nullptr)
  7940. error(branchNode->getLoc(), "duplicate label", "default", "");
  7941. else if (prevExpression != nullptr &&
  7942. newExpression != nullptr &&
  7943. prevExpression->getAsConstantUnion() &&
  7944. newExpression->getAsConstantUnion() &&
  7945. prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
  7946. newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
  7947. error(branchNode->getLoc(), "duplicated value", "case", "");
  7948. }
  7949. }
  7950. switchSequence->push_back(branchNode);
  7951. }
  7952. }
  7953. //
  7954. // Turn the top-level node sequence built up of wrapupSwitchSubsequence
  7955. // into a switch node.
  7956. //
  7957. TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
  7958. TIntermAggregate* lastStatements, const TAttributes& attributes)
  7959. {
  7960. wrapupSwitchSubsequence(lastStatements, nullptr);
  7961. if (expression == nullptr ||
  7962. (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
  7963. expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
  7964. error(loc, "condition must be a scalar integer expression", "switch", "");
  7965. // If there is nothing to do, drop the switch but still execute the expression
  7966. TIntermSequence* switchSequence = switchSequenceStack.back();
  7967. if (switchSequence->size() == 0)
  7968. return expression;
  7969. if (lastStatements == nullptr) {
  7970. // emulate a break for error recovery
  7971. lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
  7972. lastStatements->setOperator(EOpSequence);
  7973. switchSequence->push_back(lastStatements);
  7974. }
  7975. TIntermAggregate* body = new TIntermAggregate(EOpSequence);
  7976. body->getSequence() = *switchSequenceStack.back();
  7977. body->setLoc(loc);
  7978. TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
  7979. switchNode->setLoc(loc);
  7980. handleSwitchAttributes(loc, switchNode, attributes);
  7981. return switchNode;
  7982. }
  7983. // Make a new symbol-table level that is made out of the members of a structure.
  7984. // This should be done as an anonymous struct (name is "") so that the symbol table
  7985. // finds the members with no explicit reference to a 'this' variable.
  7986. void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
  7987. {
  7988. // member variables
  7989. TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
  7990. symbolTable.pushThis(thisVariable);
  7991. // member functions
  7992. for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
  7993. // member should have a prefix matching currentTypePrefix.back()
  7994. // but, symbol lookup within the class scope will just use the
  7995. // unprefixed name. Hence, there are two: one fully prefixed and
  7996. // one with no prefix.
  7997. TFunction& member = *it->function->clone();
  7998. member.removePrefix(currentTypePrefix.back());
  7999. symbolTable.insert(member);
  8000. }
  8001. }
  8002. // Track levels of class/struct/namespace nesting with a prefix string using
  8003. // the type names separated by the scoping operator. E.g., two levels
  8004. // would look like:
  8005. //
  8006. // outer::inner
  8007. //
  8008. // The string is empty when at normal global level.
  8009. //
  8010. void HlslParseContext::pushNamespace(const TString& typeName)
  8011. {
  8012. // make new type prefix
  8013. TString newPrefix;
  8014. if (currentTypePrefix.size() > 0)
  8015. newPrefix = currentTypePrefix.back();
  8016. newPrefix.append(typeName);
  8017. newPrefix.append(scopeMangler);
  8018. currentTypePrefix.push_back(newPrefix);
  8019. }
  8020. // Opposite of pushNamespace(), see above
  8021. void HlslParseContext::popNamespace()
  8022. {
  8023. currentTypePrefix.pop_back();
  8024. }
  8025. // Use the class/struct nesting string to create a global name for
  8026. // a member of a class/struct.
  8027. void HlslParseContext::getFullNamespaceName(TString*& name) const
  8028. {
  8029. if (currentTypePrefix.size() == 0)
  8030. return;
  8031. TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
  8032. fullName->append(*name);
  8033. name = fullName;
  8034. }
  8035. // Helper function to add the namespace scope mangling syntax to a string.
  8036. void HlslParseContext::addScopeMangler(TString& name)
  8037. {
  8038. name.append(scopeMangler);
  8039. }
  8040. // Return true if this has uniform-interface like decorations.
  8041. bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
  8042. {
  8043. return qualifier.hasUniformLayout() ||
  8044. qualifier.layoutPushConstant;
  8045. }
  8046. // Potentially not the opposite of hasUniform(), as if some characteristic is
  8047. // ever used for more than one thing (e.g., uniform or input), hasUniform() should
  8048. // say it exists, but clearUniform() should leave it in place.
  8049. void HlslParseContext::clearUniform(TQualifier& qualifier)
  8050. {
  8051. qualifier.clearUniformLayout();
  8052. qualifier.layoutPushConstant = false;
  8053. }
  8054. // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
  8055. bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
  8056. {
  8057. switch (qualifier.builtIn) {
  8058. case EbvPosition:
  8059. case EbvPointSize:
  8060. return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
  8061. case EbvClipDistance:
  8062. case EbvCullDistance:
  8063. return language != EShLangVertex && language != EShLangCompute;
  8064. case EbvFragCoord:
  8065. case EbvFace:
  8066. case EbvHelperInvocation:
  8067. case EbvLayer:
  8068. case EbvPointCoord:
  8069. case EbvSampleId:
  8070. case EbvSampleMask:
  8071. case EbvSamplePosition:
  8072. case EbvViewportIndex:
  8073. return language == EShLangFragment;
  8074. case EbvGlobalInvocationId:
  8075. case EbvLocalInvocationIndex:
  8076. case EbvLocalInvocationId:
  8077. case EbvNumWorkGroups:
  8078. case EbvWorkGroupId:
  8079. case EbvWorkGroupSize:
  8080. return language == EShLangCompute;
  8081. case EbvInvocationId:
  8082. return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
  8083. case EbvPatchVertices:
  8084. return language == EShLangTessControl || language == EShLangTessEvaluation;
  8085. case EbvInstanceId:
  8086. case EbvInstanceIndex:
  8087. case EbvVertexId:
  8088. case EbvVertexIndex:
  8089. return language == EShLangVertex;
  8090. case EbvPrimitiveId:
  8091. return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
  8092. case EbvTessLevelInner:
  8093. case EbvTessLevelOuter:
  8094. return language == EShLangTessEvaluation;
  8095. case EbvTessCoord:
  8096. return language == EShLangTessEvaluation;
  8097. default:
  8098. return false;
  8099. }
  8100. }
  8101. // Return true if there are decorations to preserve for input-like storage.
  8102. bool HlslParseContext::hasInput(const TQualifier& qualifier) const
  8103. {
  8104. if (qualifier.hasAnyLocation())
  8105. return true;
  8106. if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
  8107. return true;
  8108. if (language == EShLangTessEvaluation && qualifier.patch)
  8109. return true;
  8110. if (isInputBuiltIn(qualifier))
  8111. return true;
  8112. return false;
  8113. }
  8114. // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
  8115. bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
  8116. {
  8117. switch (qualifier.builtIn) {
  8118. case EbvPosition:
  8119. case EbvPointSize:
  8120. case EbvClipVertex:
  8121. case EbvClipDistance:
  8122. case EbvCullDistance:
  8123. return language != EShLangFragment && language != EShLangCompute;
  8124. case EbvFragDepth:
  8125. case EbvFragDepthGreater:
  8126. case EbvFragDepthLesser:
  8127. case EbvSampleMask:
  8128. return language == EShLangFragment;
  8129. case EbvLayer:
  8130. case EbvViewportIndex:
  8131. return language == EShLangGeometry || language == EShLangVertex;
  8132. case EbvPrimitiveId:
  8133. return language == EShLangGeometry;
  8134. case EbvTessLevelInner:
  8135. case EbvTessLevelOuter:
  8136. return language == EShLangTessControl;
  8137. default:
  8138. return false;
  8139. }
  8140. }
  8141. // Return true if there are decorations to preserve for output-like storage.
  8142. bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
  8143. {
  8144. if (qualifier.hasAnyLocation())
  8145. return true;
  8146. if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
  8147. return true;
  8148. if (language == EShLangTessControl && qualifier.patch)
  8149. return true;
  8150. if (language == EShLangGeometry && qualifier.hasStream())
  8151. return true;
  8152. if (isOutputBuiltIn(qualifier))
  8153. return true;
  8154. return false;
  8155. }
  8156. // Make the IO decorations etc. be appropriate only for an input interface.
  8157. void HlslParseContext::correctInput(TQualifier& qualifier)
  8158. {
  8159. clearUniform(qualifier);
  8160. if (language == EShLangVertex)
  8161. qualifier.clearInterstage();
  8162. if (language != EShLangTessEvaluation)
  8163. qualifier.patch = false;
  8164. if (language != EShLangFragment) {
  8165. qualifier.clearInterpolation();
  8166. qualifier.sample = false;
  8167. }
  8168. qualifier.clearStreamLayout();
  8169. qualifier.clearXfbLayout();
  8170. if (! isInputBuiltIn(qualifier))
  8171. qualifier.builtIn = EbvNone;
  8172. }
  8173. // Make the IO decorations etc. be appropriate only for an output interface.
  8174. void HlslParseContext::correctOutput(TQualifier& qualifier)
  8175. {
  8176. clearUniform(qualifier);
  8177. if (language == EShLangFragment)
  8178. qualifier.clearInterstage();
  8179. if (language != EShLangGeometry)
  8180. qualifier.clearStreamLayout();
  8181. if (language == EShLangFragment)
  8182. qualifier.clearXfbLayout();
  8183. if (language != EShLangTessControl)
  8184. qualifier.patch = false;
  8185. switch (qualifier.builtIn) {
  8186. case EbvFragDepth:
  8187. intermediate.setDepthReplacing();
  8188. intermediate.setDepth(EldAny);
  8189. break;
  8190. case EbvFragDepthGreater:
  8191. intermediate.setDepthReplacing();
  8192. intermediate.setDepth(EldGreater);
  8193. qualifier.builtIn = EbvFragDepth;
  8194. break;
  8195. case EbvFragDepthLesser:
  8196. intermediate.setDepthReplacing();
  8197. intermediate.setDepth(EldLess);
  8198. qualifier.builtIn = EbvFragDepth;
  8199. break;
  8200. default:
  8201. break;
  8202. }
  8203. if (! isOutputBuiltIn(qualifier))
  8204. qualifier.builtIn = EbvNone;
  8205. }
  8206. // Make the IO decorations etc. be appropriate only for uniform type interfaces.
  8207. void HlslParseContext::correctUniform(TQualifier& qualifier)
  8208. {
  8209. if (qualifier.declaredBuiltIn == EbvNone)
  8210. qualifier.declaredBuiltIn = qualifier.builtIn;
  8211. qualifier.builtIn = EbvNone;
  8212. qualifier.clearInterstage();
  8213. qualifier.clearInterstageLayout();
  8214. }
  8215. // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
  8216. void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
  8217. {
  8218. clearUniform(qualifier);
  8219. correctUniform(qualifier);
  8220. }
  8221. // Set texture return type. Returns success (not all types are valid).
  8222. bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
  8223. {
  8224. // Seed the output with an invalid index. We will set it to a valid one if we can.
  8225. sampler.structReturnIndex = TSampler::noReturnStruct;
  8226. // Arrays aren't supported.
  8227. if (retType.isArray()) {
  8228. error(loc, "Arrays not supported in texture template types", "", "");
  8229. return false;
  8230. }
  8231. // If return type is a vector, remember the vector size in the sampler, and return.
  8232. if (retType.isVector() || retType.isScalar()) {
  8233. sampler.vectorSize = retType.getVectorSize();
  8234. return true;
  8235. }
  8236. // If it wasn't a vector, it must be a struct meeting certain requirements. The requirements
  8237. // are checked below: just check for struct-ness here.
  8238. if (!retType.isStruct()) {
  8239. error(loc, "Invalid texture template type", "", "");
  8240. return false;
  8241. }
  8242. // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
  8243. if (sampler.isSubpass()) {
  8244. error(loc, "Unimplemented: structure template type in subpass input", "", "");
  8245. return false;
  8246. }
  8247. TTypeList* members = retType.getWritableStruct();
  8248. // Check for too many or not enough structure members.
  8249. if (members->size() > 4 || members->size() == 0) {
  8250. error(loc, "Invalid member count in texture template structure", "", "");
  8251. return false;
  8252. }
  8253. // Error checking: We must have <= 4 total components, all of the same basic type.
  8254. unsigned totalComponents = 0;
  8255. for (unsigned m = 0; m < members->size(); ++m) {
  8256. // Check for bad member types
  8257. if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
  8258. error(loc, "Invalid texture template struct member type", "", "");
  8259. return false;
  8260. }
  8261. const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
  8262. totalComponents += memberVectorSize;
  8263. // too many total member components
  8264. if (totalComponents > 4) {
  8265. error(loc, "Too many components in texture template structure type", "", "");
  8266. return false;
  8267. }
  8268. // All members must be of a common basic type
  8269. if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
  8270. error(loc, "Texture template structure members must same basic type", "", "");
  8271. return false;
  8272. }
  8273. }
  8274. // If the structure in the return type already exists in the table, we'll use it. Otherwise, we'll make
  8275. // a new entry. This is a linear search, but it hardly ever happens, and the list cannot be very large.
  8276. for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
  8277. if (textureReturnStruct[idx] == members) {
  8278. sampler.structReturnIndex = idx;
  8279. return true;
  8280. }
  8281. }
  8282. // It wasn't found as an existing entry. See if we have room for a new one.
  8283. if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
  8284. error(loc, "Texture template struct return slots exceeded", "", "");
  8285. return false;
  8286. }
  8287. // Insert it in the vector that tracks struct return types.
  8288. sampler.structReturnIndex = unsigned(textureReturnStruct.size());
  8289. textureReturnStruct.push_back(members);
  8290. // Success!
  8291. return true;
  8292. }
  8293. // Return the sampler return type in retType.
  8294. void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
  8295. {
  8296. if (sampler.hasReturnStruct()) {
  8297. assert(textureReturnStruct.size() >= sampler.structReturnIndex);
  8298. // We land here if the texture return is a structure.
  8299. TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
  8300. const TType resultType(blockStruct, "");
  8301. retType.shallowCopy(resultType);
  8302. } else {
  8303. // We land here if the texture return is a vector or scalar.
  8304. const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
  8305. retType.shallowCopy(resultType);
  8306. }
  8307. }
  8308. // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
  8309. TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
  8310. {
  8311. const auto it = builtInTessLinkageSymbols.find(biType);
  8312. if (it == builtInTessLinkageSymbols.end()) // if it wasn't declared by the user, return nullptr
  8313. return nullptr;
  8314. return intermediate.addSymbol(*it->second->getAsVariable());
  8315. }
  8316. // Find the patch constant function (issues error, returns nullptr if not found)
  8317. const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
  8318. {
  8319. if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
  8320. error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
  8321. return nullptr;
  8322. }
  8323. const TString mangledName = patchConstantFunctionName + "(";
  8324. // create list of PCF candidates
  8325. TVector<const TFunction*> candidateList;
  8326. bool builtIn;
  8327. symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
  8328. // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
  8329. // allow any disambiguation of overloads.
  8330. if (candidateList.empty()) {
  8331. error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
  8332. return nullptr;
  8333. }
  8334. // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
  8335. // HLSL picks the last one in shader source order. Since that isn't yet implemented here, error
  8336. // out if there is more than one candidate.
  8337. if (candidateList.size() > 1) {
  8338. error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
  8339. return nullptr;
  8340. }
  8341. return candidateList[0];
  8342. }
  8343. // Finalization step: Add patch constant function invocation
  8344. void HlslParseContext::addPatchConstantInvocation()
  8345. {
  8346. TSourceLoc loc;
  8347. loc.init();
  8348. // If there's no patch constant function, or we're not a HS, do nothing.
  8349. if (patchConstantFunctionName.empty() || language != EShLangTessControl)
  8350. return;
  8351. // Look for built-in variables in a function's parameter list.
  8352. const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
  8353. for (int p=0; p<function.getParamCount(); ++p) {
  8354. TStorageQualifier storage = function[p].type->getQualifier().storage;
  8355. if (storage == EvqConstReadOnly) // treated identically to input
  8356. storage = EvqIn;
  8357. if (function[p].getDeclaredBuiltIn() != EbvNone)
  8358. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
  8359. else
  8360. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
  8361. }
  8362. };
  8363. // If we synthesize a built-in interface variable, we must add it to the linkage.
  8364. const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
  8365. if (name == nullptr) {
  8366. error(loc, "unable to locate patch function parameter name", "", "");
  8367. return;
  8368. } else {
  8369. TVariable& variable = *new TVariable(name, type);
  8370. if (! symbolTable.insert(variable)) {
  8371. error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
  8372. return;
  8373. }
  8374. globalQualifierFix(loc, variable.getWritableType().getQualifier());
  8375. if (symbolNode != nullptr)
  8376. *symbolNode = intermediate.addSymbol(variable);
  8377. trackLinkage(variable);
  8378. }
  8379. };
  8380. const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
  8381. const TType& type = *patchConstantFunction[param].type;
  8382. const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
  8383. return type.isSizedArray() && biType == EbvOutputPatch;
  8384. };
  8385. // We will perform these steps. Each is in a scoped block for separation: they could
  8386. // become separate functions to make addPatchConstantInvocation shorter.
  8387. //
  8388. // 1. Union the interfaces, and create built-ins for anything present in the PCF and
  8389. // declared as a built-in variable that isn't present in the entry point's signature.
  8390. //
  8391. // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
  8392. // or the ones we created. Matching is based on built-in type. We may use synthesized
  8393. // variables from (1) above.
  8394. //
  8395. // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
  8396. //
  8397. // 3. Create a return sequence: copy the return value (if any) from the PCF to a
  8398. // (non-sanitized) output variable. In case this may involve multiple copies, such as for
  8399. // an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
  8400. // indirections into a complex R-value coming from the call to the PCF.
  8401. //
  8402. // 4. Create a barrier.
  8403. //
  8404. // 5/5B. Call the PCF inside an if test for (invocation id == 0).
  8405. TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
  8406. if (patchConstantFunctionPtr == nullptr)
  8407. return;
  8408. TFunction& patchConstantFunction = *patchConstantFunctionPtr;
  8409. const int pcfParamCount = patchConstantFunction.getParamCount();
  8410. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  8411. TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
  8412. int outPatchParam = -1; // -1 means there isn't one.
  8413. // ================ Step 1A: Union Interfaces ================
  8414. // Our patch constant function.
  8415. {
  8416. std::set<tInterstageIoData> pcfBuiltIns; // patch constant function built-ins
  8417. std::set<tInterstageIoData> epfBuiltIns; // entry point function built-ins
  8418. assert(entryPointFunction);
  8419. assert(entryPointFunctionBody);
  8420. findBuiltIns(patchConstantFunction, pcfBuiltIns);
  8421. findBuiltIns(*entryPointFunction, epfBuiltIns);
  8422. // Find the set of built-ins in the PCF that are not present in the entry point.
  8423. std::set<tInterstageIoData> notInEntryPoint;
  8424. notInEntryPoint = pcfBuiltIns;
  8425. // std::set_difference not usable on unordered containers
  8426. for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
  8427. notInEntryPoint.erase(*bi);
  8428. // Now we'll add those to the entry and to the linkage.
  8429. for (int p=0; p<pcfParamCount; ++p) {
  8430. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8431. TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
  8432. // Track whether there is an output patch param
  8433. if (isOutputPatch(patchConstantFunction, p)) {
  8434. if (outPatchParam >= 0) {
  8435. // Presently we only support one per ctrl pt input.
  8436. error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
  8437. return;
  8438. }
  8439. outPatchParam = p;
  8440. }
  8441. if (biType != EbvNone) {
  8442. TType* paramType = patchConstantFunction[p].type->clone();
  8443. if (storage == EvqConstReadOnly) // treated identically to input
  8444. storage = EvqIn;
  8445. // Presently, the only non-built-in we support is InputPatch, which is treated as
  8446. // a pseudo-built-in.
  8447. if (biType == EbvInputPatch) {
  8448. builtInTessLinkageSymbols[biType] = inputPatch;
  8449. } else if (biType == EbvOutputPatch) {
  8450. // Nothing...
  8451. } else {
  8452. // Use the original declaration type for the linkage
  8453. paramType->getQualifier().builtIn = biType;
  8454. if (biType == EbvTessLevelInner || biType == EbvTessLevelOuter)
  8455. paramType->getQualifier().patch = true;
  8456. if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
  8457. addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
  8458. }
  8459. }
  8460. }
  8461. // If we didn't find it because the shader made one, add our own.
  8462. if (invocationIdSym == nullptr) {
  8463. TType invocationIdType(EbtUint, EvqIn, 1);
  8464. TString* invocationIdName = NewPoolTString("InvocationId");
  8465. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  8466. addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
  8467. }
  8468. assert(invocationIdSym);
  8469. }
  8470. TIntermTyped* pcfArguments = nullptr;
  8471. TVariable* perCtrlPtVar = nullptr;
  8472. // ================ Step 1B: Argument synthesis ================
  8473. // Create pcfArguments for synthesis of patchconstantfunction invocation
  8474. {
  8475. for (int p=0; p<pcfParamCount; ++p) {
  8476. TIntermTyped* inputArg = nullptr;
  8477. if (p == outPatchParam) {
  8478. if (perCtrlPtVar == nullptr) {
  8479. perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
  8480. *patchConstantFunction[outPatchParam].type);
  8481. perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
  8482. }
  8483. inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
  8484. } else {
  8485. // find which built-in it is
  8486. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8487. if (biType == EbvInputPatch && inputPatch == nullptr) {
  8488. error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
  8489. return;
  8490. }
  8491. inputArg = findTessLinkageSymbol(biType);
  8492. if (inputArg == nullptr) {
  8493. error(loc, "unable to find patch constant function built-in variable", "", "");
  8494. return;
  8495. }
  8496. }
  8497. if (pcfParamCount == 1)
  8498. pcfArguments = inputArg;
  8499. else
  8500. pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
  8501. }
  8502. }
  8503. // ================ Step 2: Synthesize call to PCF ================
  8504. TIntermAggregate* pcfCallSequence = nullptr;
  8505. TIntermTyped* pcfCall = nullptr;
  8506. {
  8507. // Create a function call to the patchconstantfunction
  8508. if (pcfArguments)
  8509. addInputArgumentConversions(patchConstantFunction, pcfArguments);
  8510. // Synthetic call.
  8511. pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
  8512. pcfCall->getAsAggregate()->setUserDefined();
  8513. pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
  8514. intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
  8515. patchConstantFunction.getMangledName());
  8516. if (pcfCall->getAsAggregate()) {
  8517. TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
  8518. for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
  8519. TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
  8520. qualifierList.push_back(qual);
  8521. }
  8522. pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
  8523. }
  8524. }
  8525. // ================ Step 2B: Per Control Point synthesis ================
  8526. // If there is per control point data, we must either emulate that with multiple
  8527. // invocations of the entry point to build up an array, or (TODO:) use a yet
  8528. // unavailable extension to look across the SIMD lanes. This is the former
  8529. // as a placeholder for the latter.
  8530. if (outPatchParam >= 0) {
  8531. // We must introduce a local temp variable of the type wanted by the PCF input.
  8532. const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
  8533. if (entryPointFunction->getType().getBasicType() == EbtVoid) {
  8534. error(loc, "entry point must return a value for use with patch constant function", "", "");
  8535. return;
  8536. }
  8537. // Create calls to wrapped main to fill in the array. We will substitute fixed values
  8538. // of invocation ID when calling the wrapped main.
  8539. // This is the type of the each member of the per ctrl point array.
  8540. const TType derefType(perCtrlPtVar->getType(), 0);
  8541. for (int cpt = 0; cpt < arraySize; ++cpt) {
  8542. // TODO: improve. substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
  8543. // for this function.
  8544. const TString origName = entryPointFunction->getName().substr(1);
  8545. TFunction callee(&origName, TType(EbtVoid));
  8546. TIntermTyped* callingArgs = nullptr;
  8547. for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
  8548. TParameter& param = (*entryPointFunction)[i];
  8549. TType& paramType = *param.type;
  8550. if (paramType.getQualifier().isParamOutput()) {
  8551. error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
  8552. return;
  8553. }
  8554. if (paramType.getQualifier().isParamInput()) {
  8555. TIntermTyped* arg = nullptr;
  8556. if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
  8557. // substitute invocation ID with the array element ID
  8558. arg = intermediate.addConstantUnion(cpt, loc);
  8559. } else {
  8560. TVariable* argVar = makeInternalVariable(*param.name, *param.type);
  8561. argVar->getWritableType().getQualifier().makeTemporary();
  8562. arg = intermediate.addSymbol(*argVar);
  8563. }
  8564. handleFunctionArgument(&callee, callingArgs, arg);
  8565. }
  8566. }
  8567. // Call and assign to per ctrl point variable
  8568. currentCaller = intermediate.getEntryPointMangledName().c_str();
  8569. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  8570. TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
  8571. TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
  8572. TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
  8573. element->setType(derefType);
  8574. element->setLoc(loc);
  8575. pcfCallSequence = intermediate.growAggregate(pcfCallSequence,
  8576. handleAssign(loc, EOpAssign, element, callReturn));
  8577. }
  8578. }
  8579. // ================ Step 3: Create return Sequence ================
  8580. // Return sequence: copy PCF result to a temporary, then to shader output variable.
  8581. if (pcfCall->getBasicType() != EbtVoid) {
  8582. const TType* retType = &patchConstantFunction.getType(); // return type from the PCF
  8583. TType outType; // output type that goes with the return type.
  8584. outType.shallowCopy(*retType);
  8585. // substitute the output type
  8586. const auto newLists = ioTypeMap.find(retType->getStruct());
  8587. if (newLists != ioTypeMap.end())
  8588. outType.setStruct(newLists->second.output);
  8589. // Substitute the top level type's built-in type
  8590. if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
  8591. outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
  8592. outType.getQualifier().patch = true; // make it a per-patch variable
  8593. TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
  8594. pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
  8595. if (pcfOutput->getType().isStruct())
  8596. flatten(*pcfOutput, false);
  8597. assignToInterface(*pcfOutput);
  8598. TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
  8599. // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
  8600. // repeated calls to the PCF:
  8601. TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
  8602. pcfCallResult->getWritableType().getQualifier().makeTemporary();
  8603. TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
  8604. TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
  8605. TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
  8606. intermediate.addSymbol(*pcfCallResult, loc));
  8607. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
  8608. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
  8609. } else {
  8610. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
  8611. }
  8612. // ================ Step 4: Barrier ================
  8613. TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
  8614. barrier->setLoc(loc);
  8615. barrier->setType(TType(EbtVoid));
  8616. epBodySeq.insert(epBodySeq.end(), barrier);
  8617. // ================ Step 5: Test on invocation ID ================
  8618. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  8619. TIntermTyped* cmp = intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
  8620. // ================ Step 5B: Create if statement on Invocation ID == 0 ================
  8621. intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
  8622. TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
  8623. invocationIdTest->setLoc(loc);
  8624. // add our test sequence before the return.
  8625. epBodySeq.insert(epBodySeq.end(), invocationIdTest);
  8626. }
  8627. // Finalization step: remove unused buffer blocks from linkage (we don't know until the
  8628. // shader is entirely compiled).
  8629. // Preserve order of remaining symbols.
  8630. void HlslParseContext::removeUnusedStructBufferCounters()
  8631. {
  8632. const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
  8633. [this](const TSymbol* sym) {
  8634. const auto sbcIt = structBufferCounter.find(sym->getName());
  8635. return sbcIt != structBufferCounter.end() && !sbcIt->second;
  8636. });
  8637. linkageSymbols.erase(endIt, linkageSymbols.end());
  8638. }
  8639. // Finalization step: patch texture shadow modes to match samplers they were combined with
  8640. void HlslParseContext::fixTextureShadowModes()
  8641. {
  8642. for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
  8643. TSampler& sampler = (*symbol)->getWritableType().getSampler();
  8644. if (sampler.isTexture()) {
  8645. const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
  8646. if (shadowMode != textureShadowVariant.end()) {
  8647. if (shadowMode->second->overloaded())
  8648. // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
  8649. intermediate.setNeedsLegalization();
  8650. sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
  8651. }
  8652. }
  8653. }
  8654. }
  8655. // Finalization step: patch append methods to use proper stream output, which isn't known until
  8656. // main is parsed, which could happen after the append method is parsed.
  8657. void HlslParseContext::finalizeAppendMethods()
  8658. {
  8659. TSourceLoc loc;
  8660. loc.init();
  8661. // Nothing to do: bypass test for valid stream output.
  8662. if (gsAppends.empty())
  8663. return;
  8664. if (gsStreamOutput == nullptr) {
  8665. error(loc, "unable to find output symbol for Append()", "", "");
  8666. return;
  8667. }
  8668. // Patch append sequences, now that we know the stream output symbol.
  8669. for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
  8670. append->node->getSequence()[0] =
  8671. handleAssign(append->loc, EOpAssign,
  8672. intermediate.addSymbol(*gsStreamOutput, append->loc),
  8673. append->node->getSequence()[0]->getAsTyped());
  8674. }
  8675. }
  8676. // post-processing
  8677. void HlslParseContext::finish()
  8678. {
  8679. // Error check: There was a dangling .mips operator. These are not nested constructs in the grammar, so
  8680. // cannot be detected there. This is not strictly needed in a non-validating parser; it's just helpful.
  8681. if (! mipsOperatorMipArg.empty()) {
  8682. error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
  8683. }
  8684. removeUnusedStructBufferCounters();
  8685. addPatchConstantInvocation();
  8686. fixTextureShadowModes();
  8687. finalizeAppendMethods();
  8688. // Communicate out (esp. for command line) that we formed AST that will make
  8689. // illegal AST SPIR-V and it needs transforms to legalize it.
  8690. if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
  8691. infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
  8692. TParseContextBase::finish();
  8693. }
  8694. } // end namespace glslang