hlslParseHelper.cpp 416 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991
  1. //
  2. // Copyright (C) 2017-2018 Google, Inc.
  3. // Copyright (C) 2017 LunarG, Inc.
  4. //
  5. // All rights reserved.
  6. //
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions
  9. // are met:
  10. //
  11. // Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. //
  14. // Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following
  16. // disclaimer in the documentation and/or other materials provided
  17. // with the distribution.
  18. //
  19. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  20. // contributors may be used to endorse or promote products derived
  21. // from this software without specific prior written permission.
  22. //
  23. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  26. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  27. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  28. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  29. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  30. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  31. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  33. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  34. // POSSIBILITY OF SUCH DAMAGE.
  35. //
  36. #include "hlslParseHelper.h"
  37. #include "hlslScanContext.h"
  38. #include "hlslGrammar.h"
  39. #include "hlslAttributes.h"
  40. #include "../glslang/Include/Common.h"
  41. #include "../glslang/MachineIndependent/Scan.h"
  42. #include "../glslang/MachineIndependent/preprocessor/PpContext.h"
  43. #include "../glslang/OSDependent/osinclude.h"
  44. #include <algorithm>
  45. #include <functional>
  46. #include <cctype>
  47. #include <array>
  48. #include <set>
  49. namespace glslang {
  50. HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
  51. int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
  52. TInfoSink& infoSink,
  53. const TString sourceEntryPointName,
  54. bool forwardCompatible, EShMessages messages) :
  55. TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language, infoSink,
  56. forwardCompatible, messages, &sourceEntryPointName),
  57. annotationNestingLevel(0),
  58. inputPatch(nullptr),
  59. nextInLocation(0), nextOutLocation(0),
  60. entryPointFunction(nullptr),
  61. entryPointFunctionBody(nullptr),
  62. gsStreamOutput(nullptr),
  63. clipDistanceOutput(nullptr),
  64. cullDistanceOutput(nullptr),
  65. clipDistanceInput(nullptr),
  66. cullDistanceInput(nullptr)
  67. {
  68. globalUniformDefaults.clear();
  69. globalUniformDefaults.layoutMatrix = ElmRowMajor;
  70. globalUniformDefaults.layoutPacking = ElpStd140;
  71. globalBufferDefaults.clear();
  72. globalBufferDefaults.layoutMatrix = ElmRowMajor;
  73. globalBufferDefaults.layoutPacking = ElpStd430;
  74. globalInputDefaults.clear();
  75. globalOutputDefaults.clear();
  76. clipSemanticNSizeIn.fill(0);
  77. cullSemanticNSizeIn.fill(0);
  78. clipSemanticNSizeOut.fill(0);
  79. cullSemanticNSizeOut.fill(0);
  80. // "Shaders in the transform
  81. // feedback capturing mode have an initial global default of
  82. // layout(xfb_buffer = 0) out;"
  83. if (language == EShLangVertex ||
  84. language == EShLangTessControl ||
  85. language == EShLangTessEvaluation ||
  86. language == EShLangGeometry)
  87. globalOutputDefaults.layoutXfbBuffer = 0;
  88. if (language == EShLangGeometry)
  89. globalOutputDefaults.layoutStream = 0;
  90. }
  91. HlslParseContext::~HlslParseContext()
  92. {
  93. }
  94. void HlslParseContext::initializeExtensionBehavior()
  95. {
  96. TParseContextBase::initializeExtensionBehavior();
  97. // HLSL allows #line by default.
  98. extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
  99. }
  100. void HlslParseContext::setLimits(const TBuiltInResource& r)
  101. {
  102. resources = r;
  103. intermediate.setLimits(resources);
  104. }
  105. //
  106. // Parse an array of strings using the parser in HlslRules.
  107. //
  108. // Returns true for successful acceptance of the shader, false if any errors.
  109. //
  110. bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
  111. {
  112. currentScanner = &input;
  113. ppContext.setInput(input, versionWillBeError);
  114. HlslScanContext scanContext(*this, ppContext);
  115. HlslGrammar grammar(scanContext, *this);
  116. if (!grammar.parse()) {
  117. // Print a message formated such that if you click on the message it will take you right to
  118. // the line through most UIs.
  119. const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
  120. infoSink.info << sourceLoc.getFilenameStr() << "(" << sourceLoc.line << "): error at column " << sourceLoc.column
  121. << ", HLSL parsing failed.\n";
  122. ++numErrors;
  123. return false;
  124. }
  125. finish();
  126. return numErrors == 0;
  127. }
  128. //
  129. // Return true if this l-value node should be converted in some manner.
  130. // For instance: turning a load aggregate into a store in an l-value.
  131. //
  132. bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
  133. {
  134. if (node == nullptr || node->getAsTyped() == nullptr)
  135. return false;
  136. const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  137. const TIntermBinary* lhsAsBinary = node->getAsBinaryNode();
  138. // If it's a swizzled/indexed aggregate, look at the left node instead.
  139. if (lhsAsBinary != nullptr &&
  140. (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect))
  141. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  142. if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
  143. return true;
  144. return false;
  145. }
  146. void HlslParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName,
  147. TTypeList* newTypeList)
  148. {
  149. newTypeList = nullptr;
  150. correctUniform(memberType.getQualifier());
  151. if (memberType.isStruct()) {
  152. auto it = ioTypeMap.find(memberType.getStruct());
  153. if (it != ioTypeMap.end() && it->second.uniform)
  154. newTypeList = it->second.uniform;
  155. }
  156. TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, newTypeList);
  157. }
  158. //
  159. // Return a TLayoutFormat corresponding to the given texture type.
  160. //
  161. TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
  162. {
  163. if (txType.isStruct()) {
  164. // TODO: implement.
  165. error(loc, "unimplemented: structure type in image or buffer", "", "");
  166. return ElfNone;
  167. }
  168. const int components = txType.getVectorSize();
  169. const TBasicType txBasicType = txType.getBasicType();
  170. const auto selectFormat = [this,&components](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) -> TLayoutFormat {
  171. if (intermediate.getNoStorageFormat())
  172. return ElfNone;
  173. return components == 1 ? v1 :
  174. components == 2 ? v2 : v4;
  175. };
  176. switch (txBasicType) {
  177. case EbtFloat: return selectFormat(ElfR32f, ElfRg32f, ElfRgba32f);
  178. case EbtInt: return selectFormat(ElfR32i, ElfRg32i, ElfRgba32i);
  179. case EbtUint: return selectFormat(ElfR32ui, ElfRg32ui, ElfRgba32ui);
  180. default:
  181. error(loc, "unknown basic type in image format", "", "");
  182. return ElfNone;
  183. }
  184. }
  185. //
  186. // Both test and if necessary, spit out an error, to see if the node is really
  187. // an l-value that can be operated on this way.
  188. //
  189. // Returns true if there was an error.
  190. //
  191. bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
  192. {
  193. if (shouldConvertLValue(node)) {
  194. // if we're writing to a texture, it must be an RW form.
  195. TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
  196. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  197. if (!object->getType().getSampler().isImage()) {
  198. error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
  199. return true;
  200. }
  201. }
  202. // We tolerate samplers as l-values, even though they are nominally
  203. // illegal, because we expect a later optimization to eliminate them.
  204. if (node->getType().getBasicType() == EbtSampler) {
  205. intermediate.setNeedsLegalization();
  206. return false;
  207. }
  208. // Let the base class check errors
  209. return TParseContextBase::lValueErrorCheck(loc, op, node);
  210. }
  211. //
  212. // This function handles l-value conversions and verifications. It uses, but is not synonymous
  213. // with lValueErrorCheck. That function accepts an l-value directly, while this one must be
  214. // given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
  215. // series of other image operations.
  216. //
  217. // Most things are passed through unmodified, except for error checking.
  218. //
  219. TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped*& node)
  220. {
  221. if (node == nullptr)
  222. return nullptr;
  223. TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
  224. TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
  225. TIntermAggregate* sequence = nullptr;
  226. TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
  227. nodeAsBinary ? nodeAsBinary->getLeft() :
  228. nullptr;
  229. // Early bail out if there is no conversion to apply
  230. if (!shouldConvertLValue(lhs)) {
  231. if (lhs != nullptr)
  232. if (lValueErrorCheck(loc, op, lhs))
  233. return nullptr;
  234. return node;
  235. }
  236. // *** If we get here, we're going to apply some conversion to an l-value.
  237. // Helper to create a load.
  238. const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
  239. TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
  240. loadOp->setLoc(loc);
  241. loadOp->getSequence().push_back(object);
  242. loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
  243. loadOp->setType(derefType);
  244. sequence = intermediate.growAggregate(sequence,
  245. intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
  246. loc);
  247. };
  248. // Helper to create a store.
  249. const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
  250. TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
  251. storeOp->getSequence().push_back(object);
  252. storeOp->getSequence().push_back(coord);
  253. storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
  254. storeOp->setLoc(loc);
  255. storeOp->setType(TType(EbtVoid));
  256. sequence = intermediate.growAggregate(sequence, storeOp);
  257. };
  258. // Helper to create an assign.
  259. const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
  260. sequence = intermediate.growAggregate(sequence,
  261. intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
  262. loc);
  263. };
  264. // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
  265. const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) -> TIntermAggregate* {
  266. // Add a trailing use of the temp, so the sequence returns the proper value.
  267. sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
  268. sequence->setOperator(EOpSequence);
  269. sequence->setLoc(loc);
  270. sequence->setType(derefType);
  271. return sequence;
  272. };
  273. // Helper to add unary op
  274. const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
  275. sequence = intermediate.growAggregate(sequence,
  276. intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
  277. rhsTmp->getType()),
  278. loc);
  279. };
  280. // Return true if swizzle or index writes all components of the given variable.
  281. const auto writesAllComponents = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> bool {
  282. if (swizzle == nullptr) // not a swizzle or index
  283. return true;
  284. // Track which components are being set.
  285. std::array<bool, 4> compIsSet;
  286. compIsSet.fill(false);
  287. const TIntermConstantUnion* asConst = swizzle->getRight()->getAsConstantUnion();
  288. const TIntermAggregate* asAggregate = swizzle->getRight()->getAsAggregate();
  289. // This could be either a direct index, or a swizzle.
  290. if (asConst) {
  291. compIsSet[asConst->getConstArray()[0].getIConst()] = true;
  292. } else if (asAggregate) {
  293. const TIntermSequence& seq = asAggregate->getSequence();
  294. for (int comp=0; comp<int(seq.size()); ++comp)
  295. compIsSet[seq[comp]->getAsConstantUnion()->getConstArray()[0].getIConst()] = true;
  296. } else {
  297. assert(0);
  298. }
  299. // Return true if all components are being set by the index or swizzle
  300. return std::all_of(compIsSet.begin(), compIsSet.begin() + var->getType().getVectorSize(),
  301. [](bool isSet) { return isSet; } );
  302. };
  303. // Create swizzle matching input swizzle
  304. const auto addSwizzle = [&](TIntermSymbol* var, TIntermBinary* swizzle) -> TIntermTyped* {
  305. if (swizzle)
  306. return intermediate.addBinaryNode(swizzle->getOp(), var, swizzle->getRight(), loc, swizzle->getType());
  307. else
  308. return var;
  309. };
  310. TIntermBinary* lhsAsBinary = lhs->getAsBinaryNode();
  311. TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
  312. bool lhsIsSwizzle = false;
  313. // If it's a swizzled L-value, remember the swizzle, and use the LHS.
  314. if (lhsAsBinary != nullptr && (lhsAsBinary->getOp() == EOpVectorSwizzle || lhsAsBinary->getOp() == EOpIndexDirect)) {
  315. lhsAsAggregate = lhsAsBinary->getLeft()->getAsAggregate();
  316. lhsIsSwizzle = true;
  317. }
  318. TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
  319. TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
  320. const TSampler& texSampler = object->getType().getSampler();
  321. TType objDerefType;
  322. getTextureReturnType(texSampler, objDerefType);
  323. if (nodeAsBinary) {
  324. TIntermTyped* rhs = nodeAsBinary->getRight();
  325. const TOperator assignOp = nodeAsBinary->getOp();
  326. bool isModifyOp = false;
  327. switch (assignOp) {
  328. case EOpAddAssign:
  329. case EOpSubAssign:
  330. case EOpMulAssign:
  331. case EOpVectorTimesMatrixAssign:
  332. case EOpVectorTimesScalarAssign:
  333. case EOpMatrixTimesScalarAssign:
  334. case EOpMatrixTimesMatrixAssign:
  335. case EOpDivAssign:
  336. case EOpModAssign:
  337. case EOpAndAssign:
  338. case EOpInclusiveOrAssign:
  339. case EOpExclusiveOrAssign:
  340. case EOpLeftShiftAssign:
  341. case EOpRightShiftAssign:
  342. isModifyOp = true;
  343. // fall through...
  344. case EOpAssign:
  345. {
  346. // Since this is an lvalue, we'll convert an image load to a sequence like this
  347. // (to still provide the value):
  348. // OpSequence
  349. // OpImageStore(object, lhs, rhs)
  350. // rhs
  351. // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS,
  352. // so we'll convert instead to this:
  353. // OpSequence
  354. // rhsTmp = rhs
  355. // OpImageStore(object, coord, rhsTmp)
  356. // rhsTmp
  357. // If this is a read-modify-write op, like +=, we issue:
  358. // OpSequence
  359. // coordtmp = load's param1
  360. // rhsTmp = OpImageLoad(object, coordTmp)
  361. // rhsTmp op= rhs
  362. // OpImageStore(object, coordTmp, rhsTmp)
  363. // rhsTmp
  364. //
  365. // If the lvalue is swizzled, we apply that when writing the temp variable, like so:
  366. // ...
  367. // rhsTmp.some_swizzle = ...
  368. // For partial writes, an error is generated.
  369. TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
  370. TIntermTyped* coordTmp = coord;
  371. if (rhsTmp == nullptr || isModifyOp || lhsIsSwizzle) {
  372. rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  373. // Partial updates not yet supported
  374. if (!writesAllComponents(rhsTmp, lhsAsBinary)) {
  375. error(loc, "unimplemented: partial image updates", "", "");
  376. }
  377. // Assign storeTemp = rhs
  378. if (isModifyOp) {
  379. // We have to make a temp var for the coordinate, to avoid evaluating it twice.
  380. coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  381. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  382. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  383. }
  384. // rhsTmp op= rhs.
  385. makeBinary(assignOp, addSwizzle(intermediate.addSymbol(*rhsTmp), lhsAsBinary), rhs);
  386. }
  387. makeStore(object, coordTmp, rhsTmp); // add a store
  388. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  389. }
  390. default:
  391. break;
  392. }
  393. }
  394. if (nodeAsUnary) {
  395. const TOperator assignOp = nodeAsUnary->getOp();
  396. switch (assignOp) {
  397. case EOpPreIncrement:
  398. case EOpPreDecrement:
  399. {
  400. // We turn this into:
  401. // OpSequence
  402. // coordtmp = load's param1
  403. // rhsTmp = OpImageLoad(object, coordTmp)
  404. // rhsTmp op
  405. // OpImageStore(object, coordTmp, rhsTmp)
  406. // rhsTmp
  407. TIntermSymbol* rhsTmp = makeInternalVariableNode(loc, "storeTemp", objDerefType);
  408. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  409. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  410. makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
  411. makeUnary(assignOp, rhsTmp); // op rhsTmp
  412. makeStore(object, coordTmp, rhsTmp); // OpImageStore(object, coordTmp, rhsTmp)
  413. return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
  414. }
  415. case EOpPostIncrement:
  416. case EOpPostDecrement:
  417. {
  418. // We turn this into:
  419. // OpSequence
  420. // coordtmp = load's param1
  421. // rhsTmp1 = OpImageLoad(object, coordTmp)
  422. // rhsTmp2 = rhsTmp1
  423. // rhsTmp2 op
  424. // OpImageStore(object, coordTmp, rhsTmp2)
  425. // rhsTmp1 (pre-op value)
  426. TIntermSymbol* rhsTmp1 = makeInternalVariableNode(loc, "storeTempPre", objDerefType);
  427. TIntermSymbol* rhsTmp2 = makeInternalVariableNode(loc, "storeTempPost", objDerefType);
  428. TIntermTyped* coordTmp = makeInternalVariableNode(loc, "coordTemp", coord->getType());
  429. makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
  430. makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
  431. makeBinary(EOpAssign, rhsTmp2, rhsTmp1); // rhsTmp2 = rhsTmp1
  432. makeUnary(assignOp, rhsTmp2); // rhsTmp op
  433. makeStore(object, coordTmp, rhsTmp2); // OpImageStore(object, coordTmp, rhsTmp2)
  434. return finishSequence(rhsTmp1, objDerefType); // return rhsTmp from sequence
  435. }
  436. default:
  437. break;
  438. }
  439. }
  440. if (lhs)
  441. if (lValueErrorCheck(loc, op, lhs))
  442. return nullptr;
  443. return node;
  444. }
  445. void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
  446. {
  447. if (pragmaCallback)
  448. pragmaCallback(loc.line, tokens);
  449. if (tokens.size() == 0)
  450. return;
  451. // These pragmas are case insensitive in HLSL, so we'll compare in lower case.
  452. TVector<TString> lowerTokens = tokens;
  453. for (auto it = lowerTokens.begin(); it != lowerTokens.end(); ++it)
  454. std::transform(it->begin(), it->end(), it->begin(), ::tolower);
  455. // Handle pack_matrix
  456. if (tokens.size() == 4 && lowerTokens[0] == "pack_matrix" && tokens[1] == "(" && tokens[3] == ")") {
  457. // Note that HLSL semantic order is Mrc, not Mcr like SPIR-V, so we reverse the sense.
  458. // Row major becomes column major and vice versa.
  459. if (lowerTokens[2] == "row_major") {
  460. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmColumnMajor;
  461. } else if (lowerTokens[2] == "column_major") {
  462. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  463. } else {
  464. // unknown majorness strings are treated as (HLSL column major)==(SPIR-V row major)
  465. warn(loc, "unknown pack_matrix pragma value", tokens[2].c_str(), "");
  466. globalUniformDefaults.layoutMatrix = globalBufferDefaults.layoutMatrix = ElmRowMajor;
  467. }
  468. return;
  469. }
  470. // Handle once
  471. if (lowerTokens[0] == "once") {
  472. warn(loc, "not implemented", "#pragma once", "");
  473. return;
  474. }
  475. }
  476. //
  477. // Look at a '.' matrix selector string and change it into components
  478. // for a matrix. There are two types:
  479. //
  480. // _21 second row, first column (one based)
  481. // _m21 third row, second column (zero based)
  482. //
  483. // Returns true if there is no error.
  484. //
  485. bool HlslParseContext::parseMatrixSwizzleSelector(const TSourceLoc& loc, const TString& fields, int cols, int rows,
  486. TSwizzleSelectors<TMatrixSelector>& components)
  487. {
  488. int startPos[MaxSwizzleSelectors];
  489. int numComps = 0;
  490. TString compString = fields;
  491. // Find where each component starts,
  492. // recording the first character position after the '_'.
  493. for (size_t c = 0; c < compString.size(); ++c) {
  494. if (compString[c] == '_') {
  495. if (numComps >= MaxSwizzleSelectors) {
  496. error(loc, "matrix component swizzle has too many components", compString.c_str(), "");
  497. return false;
  498. }
  499. if (c > compString.size() - 3 ||
  500. ((compString[c+1] == 'm' || compString[c+1] == 'M') && c > compString.size() - 4)) {
  501. error(loc, "matrix component swizzle missing", compString.c_str(), "");
  502. return false;
  503. }
  504. startPos[numComps++] = (int)c + 1;
  505. }
  506. }
  507. // Process each component
  508. for (int i = 0; i < numComps; ++i) {
  509. int pos = startPos[i];
  510. int bias = -1;
  511. if (compString[pos] == 'm' || compString[pos] == 'M') {
  512. bias = 0;
  513. ++pos;
  514. }
  515. TMatrixSelector comp;
  516. comp.coord1 = compString[pos+0] - '0' + bias;
  517. comp.coord2 = compString[pos+1] - '0' + bias;
  518. if (comp.coord1 < 0 || comp.coord1 >= cols) {
  519. error(loc, "matrix row component out of range", compString.c_str(), "");
  520. return false;
  521. }
  522. if (comp.coord2 < 0 || comp.coord2 >= rows) {
  523. error(loc, "matrix column component out of range", compString.c_str(), "");
  524. return false;
  525. }
  526. components.push_back(comp);
  527. }
  528. return true;
  529. }
  530. // If the 'comps' express a column of a matrix,
  531. // return the column. Column means the first coords all match.
  532. //
  533. // Otherwise, return -1.
  534. //
  535. int HlslParseContext::getMatrixComponentsColumn(int rows, const TSwizzleSelectors<TMatrixSelector>& selector)
  536. {
  537. int col = -1;
  538. // right number of comps?
  539. if (selector.size() != rows)
  540. return -1;
  541. // all comps in the same column?
  542. // rows in order?
  543. col = selector[0].coord1;
  544. for (int i = 0; i < rows; ++i) {
  545. if (col != selector[i].coord1)
  546. return -1;
  547. if (i != selector[i].coord2)
  548. return -1;
  549. }
  550. return col;
  551. }
  552. //
  553. // Handle seeing a variable identifier in the grammar.
  554. //
  555. TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, const TString* string)
  556. {
  557. int thisDepth;
  558. TSymbol* symbol = symbolTable.find(*string, thisDepth);
  559. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  560. error(loc, "expected symbol, not user-defined type", string->c_str(), "");
  561. return nullptr;
  562. }
  563. const TVariable* variable = nullptr;
  564. const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
  565. TIntermTyped* node = nullptr;
  566. if (anon) {
  567. // It was a member of an anonymous container, which could be a 'this' structure.
  568. // Create a subtree for its dereference.
  569. if (thisDepth > 0) {
  570. variable = getImplicitThis(thisDepth);
  571. if (variable == nullptr)
  572. error(loc, "cannot access member variables (static member function?)", "this", "");
  573. }
  574. if (variable == nullptr)
  575. variable = anon->getAnonContainer().getAsVariable();
  576. TIntermTyped* container = intermediate.addSymbol(*variable, loc);
  577. TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
  578. node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
  579. node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
  580. if (node->getType().hiddenMember())
  581. error(loc, "member of nameless block was not redeclared", string->c_str(), "");
  582. } else {
  583. // Not a member of an anonymous container.
  584. // The symbol table search was done in the lexical phase.
  585. // See if it was a variable.
  586. variable = symbol ? symbol->getAsVariable() : nullptr;
  587. if (variable) {
  588. if ((variable->getType().getBasicType() == EbtBlock ||
  589. variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
  590. error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
  591. variable = nullptr;
  592. }
  593. } else {
  594. if (symbol)
  595. error(loc, "variable name expected", string->c_str(), "");
  596. }
  597. // Recovery, if it wasn't found or was not a variable.
  598. if (variable == nullptr) {
  599. error(loc, "unknown variable", string->c_str(), "");
  600. variable = new TVariable(string, TType(EbtVoid));
  601. }
  602. if (variable->getType().getQualifier().isFrontEndConstant())
  603. node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
  604. else
  605. node = intermediate.addSymbol(*variable, loc);
  606. }
  607. if (variable->getType().getQualifier().isIo())
  608. intermediate.addIoAccessed(*string);
  609. return node;
  610. }
  611. //
  612. // Handle operator[] on any objects it applies to. Currently:
  613. // Textures
  614. // Buffers
  615. //
  616. TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  617. {
  618. // handle r-value operator[] on textures and images. l-values will be processed later.
  619. if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
  620. const TSampler& sampler = base->getType().getSampler();
  621. if (sampler.isImage() || sampler.isTexture()) {
  622. if (! mipsOperatorMipArg.empty() && mipsOperatorMipArg.back().mipLevel == nullptr) {
  623. // The first operator[] to a .mips[] sequence is the mip level. We'll remember it.
  624. mipsOperatorMipArg.back().mipLevel = index;
  625. return base; // next [] index is to the same base.
  626. } else {
  627. TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
  628. TType sampReturnType;
  629. getTextureReturnType(sampler, sampReturnType);
  630. load->setType(sampReturnType);
  631. load->setLoc(loc);
  632. load->getSequence().push_back(base);
  633. load->getSequence().push_back(index);
  634. // Textures need a MIP. If we saw one go by, use it. Otherwise, use zero.
  635. if (sampler.isTexture()) {
  636. if (! mipsOperatorMipArg.empty()) {
  637. load->getSequence().push_back(mipsOperatorMipArg.back().mipLevel);
  638. mipsOperatorMipArg.pop_back();
  639. } else {
  640. load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
  641. }
  642. }
  643. return load;
  644. }
  645. }
  646. }
  647. // Handle operator[] on structured buffers: this indexes into the array element of the buffer.
  648. // indexStructBufferContent returns nullptr if it isn't a structuredbuffer (SSBO).
  649. TIntermTyped* sbArray = indexStructBufferContent(loc, base);
  650. if (sbArray != nullptr) {
  651. if (sbArray == nullptr)
  652. return nullptr;
  653. // Now we'll apply the [] index to that array
  654. const TOperator idxOp = (index->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  655. TIntermTyped* element = intermediate.addIndex(idxOp, sbArray, index, loc);
  656. const TType derefType(sbArray->getType(), 0);
  657. element->setType(derefType);
  658. return element;
  659. }
  660. return nullptr;
  661. }
  662. //
  663. // Cast index value to a uint if it isn't already (for operator[], load indexes, etc)
  664. TIntermTyped* HlslParseContext::makeIntegerIndex(TIntermTyped* index)
  665. {
  666. const TBasicType indexBasicType = index->getType().getBasicType();
  667. const int vecSize = index->getType().getVectorSize();
  668. // We can use int types directly as the index
  669. if (indexBasicType == EbtInt || indexBasicType == EbtUint ||
  670. indexBasicType == EbtInt64 || indexBasicType == EbtUint64)
  671. return index;
  672. // Cast index to unsigned integer if it isn't one.
  673. return intermediate.addConversion(EOpConstructUint, TType(EbtUint, EvqTemporary, vecSize), index);
  674. }
  675. //
  676. // Handle seeing a base[index] dereference in the grammar.
  677. //
  678. TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  679. {
  680. index = makeIntegerIndex(index);
  681. if (index == nullptr) {
  682. error(loc, " unknown index type ", "", "");
  683. return nullptr;
  684. }
  685. TIntermTyped* result = handleBracketOperator(loc, base, index);
  686. if (result != nullptr)
  687. return result; // it was handled as an operator[]
  688. bool flattened = false;
  689. int indexValue = 0;
  690. if (index->getQualifier().isFrontEndConstant())
  691. indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
  692. variableCheck(base);
  693. if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
  694. if (base->getAsSymbolNode())
  695. error(loc, " left of '[' is not of type array, matrix, or vector ",
  696. base->getAsSymbolNode()->getName().c_str(), "");
  697. else
  698. error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
  699. } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst) {
  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)
  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. // the item is a map pair, so first->second is the TFlattenData itself.
  1030. flatten(variable, type, entry.first->second, variable.getName(), linkage, type.getQualifier(), nullptr);
  1031. }
  1032. // Recursively flatten the given variable at the provided type, building the flattenData as we go.
  1033. //
  1034. // This is mutually recursive with flattenStruct and flattenArray.
  1035. // We are going to flatten an arbitrarily nested composite structure into a linear sequence of
  1036. // members, and later on, we want to turn a path through the tree structure into a final
  1037. // location in this linear sequence.
  1038. //
  1039. // If the tree was N-ary, that can be directly calculated. However, we are dealing with
  1040. // arbitrary numbers - perhaps a struct of 7 members containing an array of 3. Thus, we must
  1041. // build a data structure to allow the sequence of bracket and dot operators on arrays and
  1042. // structs to arrive at the proper member.
  1043. //
  1044. // To avoid storing a tree with pointers, we are going to flatten the tree into a vector of integers.
  1045. // The leaves are the indexes into the flattened member array.
  1046. // Each level will have the next location for the Nth item stored sequentially, so for instance:
  1047. //
  1048. // struct { float2 a[2]; int b; float4 c[3] };
  1049. //
  1050. // This will produce the following flattened tree:
  1051. // Pos: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  1052. // (3, 7, 8, 5, 6, 0, 1, 2, 11, 12, 13, 3, 4, 5}
  1053. //
  1054. // Given a reference to mystruct.c[1], the access chain is (2,1), so we traverse:
  1055. // (0+2) = 8 --> (8+1) = 12 --> 12 = 4
  1056. //
  1057. // so the 4th flattened member in traversal order is ours.
  1058. //
  1059. int HlslParseContext::flatten(const TVariable& variable, const TType& type,
  1060. TFlattenData& flattenData, TString name, bool linkage,
  1061. const TQualifier& outerQualifier,
  1062. const TArraySizes* builtInArraySizes)
  1063. {
  1064. // If something is an arrayed struct, the array flattener will recursively call flatten()
  1065. // to then flatten the struct, so this is an "if else": we don't do both.
  1066. if (type.isArray())
  1067. return flattenArray(variable, type, flattenData, name, linkage, outerQualifier);
  1068. else if (type.isStruct())
  1069. return flattenStruct(variable, type, flattenData, name, linkage, outerQualifier, builtInArraySizes);
  1070. else {
  1071. assert(0); // should never happen
  1072. return -1;
  1073. }
  1074. }
  1075. // Add a single flattened member to the flattened data being tracked for the composite
  1076. // Returns true for the final flattening level.
  1077. int HlslParseContext::addFlattenedMember(const TVariable& variable, const TType& type, TFlattenData& flattenData,
  1078. const TString& memberName, bool linkage,
  1079. const TQualifier& outerQualifier,
  1080. const TArraySizes* builtInArraySizes)
  1081. {
  1082. if (!shouldFlatten(type, outerQualifier.storage, false)) {
  1083. // This is as far as we flatten. Insert the variable.
  1084. TVariable* memberVariable = makeInternalVariable(memberName, type);
  1085. mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
  1086. if (flattenData.nextBinding != TQualifier::layoutBindingEnd)
  1087. memberVariable->getWritableType().getQualifier().layoutBinding = flattenData.nextBinding++;
  1088. if (memberVariable->getType().isBuiltIn()) {
  1089. // inherited locations are nonsensical for built-ins (TODO: what if semantic had a number)
  1090. memberVariable->getWritableType().getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  1091. } else {
  1092. // inherited locations must be auto bumped, not replicated
  1093. if (flattenData.nextLocation != TQualifier::layoutLocationEnd) {
  1094. memberVariable->getWritableType().getQualifier().layoutLocation = flattenData.nextLocation;
  1095. flattenData.nextLocation += intermediate.computeTypeLocationSize(memberVariable->getType(), language);
  1096. nextOutLocation = std::max(nextOutLocation, flattenData.nextLocation);
  1097. }
  1098. }
  1099. flattenData.offsets.push_back(static_cast<int>(flattenData.members.size()));
  1100. flattenData.members.push_back(memberVariable);
  1101. if (linkage)
  1102. trackLinkage(*memberVariable);
  1103. return static_cast<int>(flattenData.offsets.size()) - 1; // location of the member reference
  1104. } else {
  1105. // Further recursion required
  1106. return flatten(variable, type, flattenData, memberName, linkage, outerQualifier, builtInArraySizes);
  1107. }
  1108. }
  1109. // Figure out the mapping between an aggregate's top members and an
  1110. // equivalent set of individual variables.
  1111. //
  1112. // Assumes shouldFlatten() or equivalent was called first.
  1113. int HlslParseContext::flattenStruct(const TVariable& variable, const TType& type,
  1114. TFlattenData& flattenData, TString name, bool linkage,
  1115. const TQualifier& outerQualifier,
  1116. const TArraySizes* builtInArraySizes)
  1117. {
  1118. assert(type.isStruct());
  1119. auto members = *type.getStruct();
  1120. // Reserve space for this tree level.
  1121. int start = static_cast<int>(flattenData.offsets.size());
  1122. int pos = start;
  1123. flattenData.offsets.resize(int(pos + members.size()), -1);
  1124. for (int member = 0; member < (int)members.size(); ++member) {
  1125. TType& dereferencedType = *members[member].type;
  1126. if (dereferencedType.isBuiltIn())
  1127. splitBuiltIn(variable.getName(), dereferencedType, builtInArraySizes, outerQualifier);
  1128. else {
  1129. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1130. name + "." + dereferencedType.getFieldName(),
  1131. linkage, outerQualifier,
  1132. builtInArraySizes == nullptr && dereferencedType.isArray()
  1133. ? dereferencedType.getArraySizes()
  1134. : builtInArraySizes);
  1135. flattenData.offsets[pos++] = mpos;
  1136. }
  1137. }
  1138. return start;
  1139. }
  1140. // Figure out mapping between an array's members and an
  1141. // equivalent set of individual variables.
  1142. //
  1143. // Assumes shouldFlatten() or equivalent was called first.
  1144. int HlslParseContext::flattenArray(const TVariable& variable, const TType& type,
  1145. TFlattenData& flattenData, TString name, bool linkage,
  1146. const TQualifier& outerQualifier)
  1147. {
  1148. assert(type.isSizedArray());
  1149. const int size = type.getOuterArraySize();
  1150. const TType dereferencedType(type, 0);
  1151. if (name.empty())
  1152. name = variable.getName();
  1153. // Reserve space for this tree level.
  1154. int start = static_cast<int>(flattenData.offsets.size());
  1155. int pos = start;
  1156. flattenData.offsets.resize(int(pos + size), -1);
  1157. for (int element=0; element < size; ++element) {
  1158. char elementNumBuf[20]; // sufficient for MAXINT
  1159. snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
  1160. const int mpos = addFlattenedMember(variable, dereferencedType, flattenData,
  1161. name + elementNumBuf, linkage, outerQualifier,
  1162. type.getArraySizes());
  1163. flattenData.offsets[pos++] = mpos;
  1164. }
  1165. return start;
  1166. }
  1167. // Return true if we have flattened this node.
  1168. bool HlslParseContext::wasFlattened(const TIntermTyped* node) const
  1169. {
  1170. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1171. wasFlattened(node->getAsSymbolNode()->getId());
  1172. }
  1173. // Return true if we have split this structure
  1174. bool HlslParseContext::wasSplit(const TIntermTyped* node) const
  1175. {
  1176. return node != nullptr && node->getAsSymbolNode() != nullptr &&
  1177. wasSplit(node->getAsSymbolNode()->getId());
  1178. }
  1179. // Turn an access into an aggregate that was flattened to instead be
  1180. // an access to the individual variable the member was flattened to.
  1181. // Assumes wasFlattened() or equivalent was called first.
  1182. TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
  1183. {
  1184. const TType dereferencedType(base->getType(), member); // dereferenced type
  1185. const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
  1186. TIntermTyped* flattened = flattenAccess(symbolNode.getId(), member, base->getQualifier().storage,
  1187. dereferencedType, symbolNode.getFlattenSubset());
  1188. return flattened ? flattened : base;
  1189. }
  1190. TIntermTyped* HlslParseContext::flattenAccess(int uniqueId, int member, TStorageQualifier outerStorage,
  1191. const TType& dereferencedType, int subset)
  1192. {
  1193. const auto flattenData = flattenMap.find(uniqueId);
  1194. if (flattenData == flattenMap.end())
  1195. return nullptr;
  1196. // Calculate new cumulative offset from the packed tree
  1197. int newSubset = flattenData->second.offsets[subset >= 0 ? subset + member : member];
  1198. TIntermSymbol* subsetSymbol;
  1199. if (!shouldFlatten(dereferencedType, outerStorage, false)) {
  1200. // Finished flattening: create symbol for variable
  1201. member = flattenData->second.offsets[newSubset];
  1202. const TVariable* memberVariable = flattenData->second.members[member];
  1203. subsetSymbol = intermediate.addSymbol(*memberVariable);
  1204. subsetSymbol->setFlattenSubset(-1);
  1205. } else {
  1206. // If this is not the final flattening, accumulate the position and return
  1207. // an object of the partially dereferenced type.
  1208. subsetSymbol = new TIntermSymbol(uniqueId, "flattenShadow", dereferencedType);
  1209. subsetSymbol->setFlattenSubset(newSubset);
  1210. }
  1211. return subsetSymbol;
  1212. }
  1213. // For finding where the first leaf is in a subtree of a multi-level aggregate
  1214. // that is just getting a subset assigned. Follows the same logic as flattenAccess,
  1215. // but logically going down the "left-most" tree branch each step of the way.
  1216. //
  1217. // Returns the offset into the first leaf of the subset.
  1218. int HlslParseContext::findSubtreeOffset(const TIntermNode& node) const
  1219. {
  1220. const TIntermSymbol* sym = node.getAsSymbolNode();
  1221. if (sym == nullptr)
  1222. return 0;
  1223. if (!sym->isArray() && !sym->isStruct())
  1224. return 0;
  1225. int subset = sym->getFlattenSubset();
  1226. if (subset == -1)
  1227. return 0;
  1228. // Getting this far means a partial aggregate is identified by the flatten subset.
  1229. // Find the first leaf of the subset.
  1230. const auto flattenData = flattenMap.find(sym->getId());
  1231. if (flattenData == flattenMap.end())
  1232. return 0;
  1233. return findSubtreeOffset(sym->getType(), subset, flattenData->second.offsets);
  1234. do {
  1235. subset = flattenData->second.offsets[subset];
  1236. } while (true);
  1237. }
  1238. // Recursively do the desent
  1239. int HlslParseContext::findSubtreeOffset(const TType& type, int subset, const TVector<int>& offsets) const
  1240. {
  1241. if (!type.isArray() && !type.isStruct())
  1242. return offsets[subset];
  1243. TType derefType(type, 0);
  1244. return findSubtreeOffset(derefType, offsets[subset], offsets);
  1245. };
  1246. // Find and return the split IO TVariable for id, or nullptr if none.
  1247. TVariable* HlslParseContext::getSplitNonIoVar(int id) const
  1248. {
  1249. const auto splitNonIoVar = splitNonIoVars.find(id);
  1250. if (splitNonIoVar == splitNonIoVars.end())
  1251. return nullptr;
  1252. return splitNonIoVar->second;
  1253. }
  1254. // Pass through to base class after remembering built-in mappings.
  1255. void HlslParseContext::trackLinkage(TSymbol& symbol)
  1256. {
  1257. TBuiltInVariable biType = symbol.getType().getQualifier().builtIn;
  1258. if (biType != EbvNone)
  1259. builtInTessLinkageSymbols[biType] = symbol.clone();
  1260. TParseContextBase::trackLinkage(symbol);
  1261. }
  1262. // Returns true if the built-in is a clip or cull distance variable.
  1263. bool HlslParseContext::isClipOrCullDistance(TBuiltInVariable builtIn)
  1264. {
  1265. return builtIn == EbvClipDistance || builtIn == EbvCullDistance;
  1266. }
  1267. // Some types require fixed array sizes in SPIR-V, but can be scalars or
  1268. // arrays of sizes SPIR-V doesn't allow. For example, tessellation factors.
  1269. // This creates the right size. A conversion is performed when the internal
  1270. // type is copied to or from the external type. This corrects the externally
  1271. // facing input or output type to abide downstream semantics.
  1272. void HlslParseContext::fixBuiltInIoType(TType& type)
  1273. {
  1274. int requiredArraySize = 0;
  1275. int requiredVectorSize = 0;
  1276. switch (type.getQualifier().builtIn) {
  1277. case EbvTessLevelOuter: requiredArraySize = 4; break;
  1278. case EbvTessLevelInner: requiredArraySize = 2; break;
  1279. case EbvSampleMask:
  1280. {
  1281. // Promote scalar to array of size 1. Leave existing arrays alone.
  1282. if (!type.isArray())
  1283. requiredArraySize = 1;
  1284. break;
  1285. }
  1286. case EbvWorkGroupId: requiredVectorSize = 3; break;
  1287. case EbvGlobalInvocationId: requiredVectorSize = 3; break;
  1288. case EbvLocalInvocationId: requiredVectorSize = 3; break;
  1289. case EbvTessCoord: requiredVectorSize = 3; break;
  1290. default:
  1291. if (isClipOrCullDistance(type)) {
  1292. const int loc = type.getQualifier().layoutLocation;
  1293. if (type.getQualifier().builtIn == EbvClipDistance) {
  1294. if (type.getQualifier().storage == EvqVaryingIn)
  1295. clipSemanticNSizeIn[loc] = type.getVectorSize();
  1296. else
  1297. clipSemanticNSizeOut[loc] = type.getVectorSize();
  1298. } else {
  1299. if (type.getQualifier().storage == EvqVaryingIn)
  1300. cullSemanticNSizeIn[loc] = type.getVectorSize();
  1301. else
  1302. cullSemanticNSizeOut[loc] = type.getVectorSize();
  1303. }
  1304. }
  1305. return;
  1306. }
  1307. // Alter or set vector size as needed.
  1308. if (requiredVectorSize > 0) {
  1309. TType newType(type.getBasicType(), type.getQualifier().storage, requiredVectorSize);
  1310. newType.getQualifier() = type.getQualifier();
  1311. type.shallowCopy(newType);
  1312. }
  1313. // Alter or set array size as needed.
  1314. if (requiredArraySize > 0) {
  1315. if (!type.isArray() || type.getOuterArraySize() != requiredArraySize) {
  1316. TArraySizes* arraySizes = new TArraySizes;
  1317. arraySizes->addInnerSize(requiredArraySize);
  1318. type.transferArraySizes(arraySizes);
  1319. }
  1320. }
  1321. }
  1322. // Variables that correspond to the user-interface in and out of a stage
  1323. // (not the built-in interface) are
  1324. // - assigned locations
  1325. // - registered as a linkage node (part of the stage's external interface).
  1326. // Assumes it is called in the order in which locations should be assigned.
  1327. void HlslParseContext::assignToInterface(TVariable& variable)
  1328. {
  1329. const auto assignLocation = [&](TVariable& variable) {
  1330. TType& type = variable.getWritableType();
  1331. if (!type.isStruct() || type.getStruct()->size() > 0) {
  1332. TQualifier& qualifier = type.getQualifier();
  1333. if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
  1334. if (qualifier.builtIn == EbvNone && !qualifier.hasLocation()) {
  1335. // Strip off the outer array dimension for those having an extra one.
  1336. int size;
  1337. if (type.isArray() && qualifier.isArrayedIo(language)) {
  1338. TType elementType(type, 0);
  1339. size = intermediate.computeTypeLocationSize(elementType, language);
  1340. } else
  1341. size = intermediate.computeTypeLocationSize(type, language);
  1342. if (qualifier.storage == EvqVaryingIn) {
  1343. variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
  1344. nextInLocation += size;
  1345. } else {
  1346. variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
  1347. nextOutLocation += size;
  1348. }
  1349. }
  1350. trackLinkage(variable);
  1351. }
  1352. }
  1353. };
  1354. if (wasFlattened(variable.getUniqueId())) {
  1355. auto& memberList = flattenMap[variable.getUniqueId()].members;
  1356. for (auto member = memberList.begin(); member != memberList.end(); ++member)
  1357. assignLocation(**member);
  1358. } else if (wasSplit(variable.getUniqueId())) {
  1359. TVariable* splitIoVar = getSplitNonIoVar(variable.getUniqueId());
  1360. assignLocation(*splitIoVar);
  1361. } else {
  1362. assignLocation(variable);
  1363. }
  1364. }
  1365. //
  1366. // Handle seeing a function declarator in the grammar. This is the precursor
  1367. // to recognizing a function prototype or function definition.
  1368. //
  1369. void HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
  1370. {
  1371. //
  1372. // Multiple declarations of the same function name are allowed.
  1373. //
  1374. // If this is a definition, the definition production code will check for redefinitions
  1375. // (we don't know at this point if it's a definition or not).
  1376. //
  1377. bool builtIn;
  1378. TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
  1379. const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
  1380. if (prototype) {
  1381. // All built-in functions are defined, even though they don't have a body.
  1382. // Count their prototype as a definition instead.
  1383. if (symbolTable.atBuiltInLevel())
  1384. function.setDefined();
  1385. else {
  1386. if (prevDec && ! builtIn)
  1387. symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
  1388. function.setPrototyped();
  1389. }
  1390. }
  1391. // This insert won't actually insert it if it's a duplicate signature, but it will still check for
  1392. // other forms of name collisions.
  1393. if (! symbolTable.insert(function))
  1394. error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
  1395. }
  1396. // For struct buffers with counters, we must pass the counter buffer as hidden parameter.
  1397. // This adds the hidden parameter to the parameter list in 'paramNodes' if needed.
  1398. // Otherwise, it's a no-op
  1399. void HlslParseContext::addStructBufferHiddenCounterParam(const TSourceLoc& loc, TParameter& param,
  1400. TIntermAggregate*& paramNodes)
  1401. {
  1402. if (! hasStructBuffCounter(*param.type))
  1403. return;
  1404. const TString counterBlockName(intermediate.addCounterBufferName(*param.name));
  1405. TType counterType;
  1406. counterBufferType(loc, counterType);
  1407. TVariable *variable = makeInternalVariable(counterBlockName, counterType);
  1408. if (! symbolTable.insert(*variable))
  1409. error(loc, "redefinition", variable->getName().c_str(), "");
  1410. paramNodes = intermediate.growAggregate(paramNodes,
  1411. intermediate.addSymbol(*variable, loc),
  1412. loc);
  1413. }
  1414. //
  1415. // Handle seeing the function prototype in front of a function definition in the grammar.
  1416. // The body is handled after this function returns.
  1417. //
  1418. // Returns an aggregate of parameter-symbol nodes.
  1419. //
  1420. TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function,
  1421. const TAttributes& attributes,
  1422. TIntermNode*& entryPointTree)
  1423. {
  1424. currentCaller = function.getMangledName();
  1425. TSymbol* symbol = symbolTable.find(function.getMangledName());
  1426. TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
  1427. if (prevDec == nullptr)
  1428. error(loc, "can't find function", function.getName().c_str(), "");
  1429. // Note: 'prevDec' could be 'function' if this is the first time we've seen function
  1430. // as it would have just been put in the symbol table. Otherwise, we're looking up
  1431. // an earlier occurrence.
  1432. if (prevDec && prevDec->isDefined()) {
  1433. // Then this function already has a body.
  1434. error(loc, "function already has a body", function.getName().c_str(), "");
  1435. }
  1436. if (prevDec && ! prevDec->isDefined()) {
  1437. prevDec->setDefined();
  1438. // Remember the return type for later checking for RETURN statements.
  1439. currentFunctionType = &(prevDec->getType());
  1440. } else
  1441. currentFunctionType = new TType(EbtVoid);
  1442. functionReturnsValue = false;
  1443. // Entry points need different I/O and other handling, transform it so the
  1444. // rest of this function doesn't care.
  1445. entryPointTree = transformEntryPoint(loc, function, attributes);
  1446. //
  1447. // New symbol table scope for body of function plus its arguments
  1448. //
  1449. pushScope();
  1450. //
  1451. // Insert parameters into the symbol table.
  1452. // If the parameter has no name, it's not an error, just don't insert it
  1453. // (could be used for unused args).
  1454. //
  1455. // Also, accumulate the list of parameters into the AST, so lower level code
  1456. // knows where to find parameters.
  1457. //
  1458. TIntermAggregate* paramNodes = new TIntermAggregate;
  1459. for (int i = 0; i < function.getParamCount(); i++) {
  1460. TParameter& param = function[i];
  1461. if (param.name != nullptr) {
  1462. TVariable *variable = new TVariable(param.name, *param.type);
  1463. if (i == 0 && function.hasImplicitThis()) {
  1464. // Anonymous 'this' members are already in a symbol-table level,
  1465. // and we need to know what function parameter to map them to.
  1466. symbolTable.makeInternalVariable(*variable);
  1467. pushImplicitThis(variable);
  1468. }
  1469. // Insert the parameters with name in the symbol table.
  1470. if (! symbolTable.insert(*variable))
  1471. error(loc, "redefinition", variable->getName().c_str(), "");
  1472. // Add parameters to the AST list.
  1473. if (shouldFlatten(variable->getType(), variable->getType().getQualifier().storage, true)) {
  1474. // Expand the AST parameter nodes (but not the name mangling or symbol table view)
  1475. // for structures that need to be flattened.
  1476. flatten(*variable, false);
  1477. const TTypeList* structure = variable->getType().getStruct();
  1478. for (int mem = 0; mem < (int)structure->size(); ++mem) {
  1479. paramNodes = intermediate.growAggregate(paramNodes,
  1480. flattenAccess(variable->getUniqueId(), mem,
  1481. variable->getType().getQualifier().storage,
  1482. *(*structure)[mem].type),
  1483. loc);
  1484. }
  1485. } else {
  1486. // Add the parameter to the AST
  1487. paramNodes = intermediate.growAggregate(paramNodes,
  1488. intermediate.addSymbol(*variable, loc),
  1489. loc);
  1490. }
  1491. // Add hidden AST parameter for struct buffer counters, if needed.
  1492. addStructBufferHiddenCounterParam(loc, param, paramNodes);
  1493. } else
  1494. paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
  1495. }
  1496. if (function.hasIllegalImplicitThis())
  1497. pushImplicitThis(nullptr);
  1498. intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
  1499. loopNestingLevel = 0;
  1500. controlFlowNestingLevel = 0;
  1501. postEntryPointReturn = false;
  1502. return paramNodes;
  1503. }
  1504. // Handle all [attrib] attribute for the shader entry point
  1505. void HlslParseContext::handleEntryPointAttributes(const TSourceLoc& loc, const TAttributes& attributes)
  1506. {
  1507. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1508. switch (it->name) {
  1509. case EatNumThreads:
  1510. {
  1511. const TIntermSequence& sequence = it->args->getSequence();
  1512. for (int lid = 0; lid < int(sequence.size()); ++lid)
  1513. intermediate.setLocalSize(lid, sequence[lid]->getAsConstantUnion()->getConstArray()[0].getIConst());
  1514. break;
  1515. }
  1516. case EatMaxVertexCount:
  1517. {
  1518. int maxVertexCount;
  1519. if (! it->getInt(maxVertexCount)) {
  1520. error(loc, "invalid maxvertexcount", "", "");
  1521. } else {
  1522. if (! intermediate.setVertices(maxVertexCount))
  1523. error(loc, "cannot change previously set maxvertexcount attribute", "", "");
  1524. }
  1525. break;
  1526. }
  1527. case EatPatchConstantFunc:
  1528. {
  1529. TString pcfName;
  1530. if (! it->getString(pcfName, 0, false)) {
  1531. error(loc, "invalid patch constant function", "", "");
  1532. } else {
  1533. patchConstantFunctionName = pcfName;
  1534. }
  1535. break;
  1536. }
  1537. case EatDomain:
  1538. {
  1539. // Handle [domain("...")]
  1540. TString domainStr;
  1541. if (! it->getString(domainStr)) {
  1542. error(loc, "invalid domain", "", "");
  1543. } else {
  1544. TLayoutGeometry domain = ElgNone;
  1545. if (domainStr == "tri") {
  1546. domain = ElgTriangles;
  1547. } else if (domainStr == "quad") {
  1548. domain = ElgQuads;
  1549. } else if (domainStr == "isoline") {
  1550. domain = ElgIsolines;
  1551. } else {
  1552. error(loc, "unsupported domain type", domainStr.c_str(), "");
  1553. }
  1554. if (language == EShLangTessEvaluation) {
  1555. if (! intermediate.setInputPrimitive(domain))
  1556. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1557. } else {
  1558. if (! intermediate.setOutputPrimitive(domain))
  1559. error(loc, "cannot change previously set domain", TQualifier::getGeometryString(domain), "");
  1560. }
  1561. }
  1562. break;
  1563. }
  1564. case EatOutputTopology:
  1565. {
  1566. // Handle [outputtopology("...")]
  1567. TString topologyStr;
  1568. if (! it->getString(topologyStr)) {
  1569. error(loc, "invalid outputtopology", "", "");
  1570. } else {
  1571. TVertexOrder vertexOrder = EvoNone;
  1572. TLayoutGeometry primitive = ElgNone;
  1573. if (topologyStr == "point") {
  1574. intermediate.setPointMode();
  1575. } else if (topologyStr == "line") {
  1576. primitive = ElgIsolines;
  1577. } else if (topologyStr == "triangle_cw") {
  1578. vertexOrder = EvoCw;
  1579. primitive = ElgTriangles;
  1580. } else if (topologyStr == "triangle_ccw") {
  1581. vertexOrder = EvoCcw;
  1582. primitive = ElgTriangles;
  1583. } else {
  1584. error(loc, "unsupported outputtopology type", topologyStr.c_str(), "");
  1585. }
  1586. if (vertexOrder != EvoNone) {
  1587. if (! intermediate.setVertexOrder(vertexOrder)) {
  1588. error(loc, "cannot change previously set outputtopology",
  1589. TQualifier::getVertexOrderString(vertexOrder), "");
  1590. }
  1591. }
  1592. if (primitive != ElgNone)
  1593. intermediate.setOutputPrimitive(primitive);
  1594. }
  1595. break;
  1596. }
  1597. case EatPartitioning:
  1598. {
  1599. // Handle [partitioning("...")]
  1600. TString partitionStr;
  1601. if (! it->getString(partitionStr)) {
  1602. error(loc, "invalid partitioning", "", "");
  1603. } else {
  1604. TVertexSpacing partitioning = EvsNone;
  1605. if (partitionStr == "integer") {
  1606. partitioning = EvsEqual;
  1607. } else if (partitionStr == "fractional_even") {
  1608. partitioning = EvsFractionalEven;
  1609. } else if (partitionStr == "fractional_odd") {
  1610. partitioning = EvsFractionalOdd;
  1611. //} else if (partition == "pow2") { // TODO: currently nothing to map this to.
  1612. } else {
  1613. error(loc, "unsupported partitioning type", partitionStr.c_str(), "");
  1614. }
  1615. if (! intermediate.setVertexSpacing(partitioning))
  1616. error(loc, "cannot change previously set partitioning",
  1617. TQualifier::getVertexSpacingString(partitioning), "");
  1618. }
  1619. break;
  1620. }
  1621. case EatOutputControlPoints:
  1622. {
  1623. // Handle [outputcontrolpoints("...")]
  1624. int ctrlPoints;
  1625. if (! it->getInt(ctrlPoints)) {
  1626. error(loc, "invalid outputcontrolpoints", "", "");
  1627. } else {
  1628. if (! intermediate.setVertices(ctrlPoints)) {
  1629. error(loc, "cannot change previously set outputcontrolpoints attribute", "", "");
  1630. }
  1631. }
  1632. break;
  1633. }
  1634. case EatEarlyDepthStencil:
  1635. intermediate.setEarlyFragmentTests();
  1636. break;
  1637. case EatBuiltIn:
  1638. case EatLocation:
  1639. // tolerate these because of dual use of entrypoint and type attributes
  1640. break;
  1641. default:
  1642. warn(loc, "attribute does not apply to entry point", "", "");
  1643. break;
  1644. }
  1645. }
  1646. }
  1647. // Update the given type with any type-like attribute information in the
  1648. // attributes.
  1649. void HlslParseContext::transferTypeAttributes(const TSourceLoc& loc, const TAttributes& attributes, TType& type,
  1650. bool allowEntry)
  1651. {
  1652. if (attributes.size() == 0)
  1653. return;
  1654. int value;
  1655. TString builtInString;
  1656. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  1657. switch (it->name) {
  1658. case EatLocation:
  1659. // location
  1660. if (it->getInt(value))
  1661. type.getQualifier().layoutLocation = value;
  1662. else
  1663. error(loc, "needs a literal integer", "location", "");
  1664. break;
  1665. case EatBinding:
  1666. // binding
  1667. if (it->getInt(value)) {
  1668. type.getQualifier().layoutBinding = value;
  1669. type.getQualifier().layoutSet = 0;
  1670. } else
  1671. error(loc, "needs a literal integer", "binding", "");
  1672. // set
  1673. if (it->getInt(value, 1))
  1674. type.getQualifier().layoutSet = value;
  1675. break;
  1676. case EatGlobalBinding:
  1677. // global cbuffer binding
  1678. if (it->getInt(value))
  1679. globalUniformBinding = value;
  1680. else
  1681. error(loc, "needs a literal integer", "global binding", "");
  1682. // global cbuffer set
  1683. if (it->getInt(value, 1))
  1684. globalUniformSet = value;
  1685. break;
  1686. case EatInputAttachment:
  1687. // input attachment
  1688. if (it->getInt(value))
  1689. type.getQualifier().layoutAttachment = value;
  1690. else
  1691. error(loc, "needs a literal integer", "input attachment", "");
  1692. break;
  1693. case EatBuiltIn:
  1694. // PointSize built-in
  1695. if (it->getString(builtInString, 0, false)) {
  1696. if (builtInString == "PointSize")
  1697. type.getQualifier().builtIn = EbvPointSize;
  1698. }
  1699. break;
  1700. case EatPushConstant:
  1701. // push_constant
  1702. type.getQualifier().layoutPushConstant = true;
  1703. break;
  1704. case EatConstantId:
  1705. // specialization constant
  1706. if (it->getInt(value)) {
  1707. TSourceLoc loc;
  1708. loc.init();
  1709. setSpecConstantId(loc, type.getQualifier(), value);
  1710. }
  1711. break;
  1712. default:
  1713. if (! allowEntry)
  1714. warn(loc, "attribute does not apply to a type", "", "");
  1715. break;
  1716. }
  1717. }
  1718. }
  1719. //
  1720. // Do all special handling for the entry point, including wrapping
  1721. // the shader's entry point with the official entry point that will call it.
  1722. //
  1723. // The following:
  1724. //
  1725. // retType shaderEntryPoint(args...) // shader declared entry point
  1726. // { body }
  1727. //
  1728. // Becomes
  1729. //
  1730. // out retType ret;
  1731. // in iargs<that are input>...;
  1732. // out oargs<that are output> ...;
  1733. //
  1734. // void shaderEntryPoint() // synthesized, but official, entry point
  1735. // {
  1736. // args<that are input> = iargs...;
  1737. // ret = @shaderEntryPoint(args...);
  1738. // oargs = args<that are output>...;
  1739. // }
  1740. // retType @shaderEntryPoint(args...)
  1741. // { body }
  1742. //
  1743. // The symbol table will still map the original entry point name to the
  1744. // the modified function and its new name:
  1745. //
  1746. // symbol table: shaderEntryPoint -> @shaderEntryPoint
  1747. //
  1748. // Returns nullptr if no entry-point tree was built, otherwise, returns
  1749. // a subtree that creates the entry point.
  1750. //
  1751. TIntermNode* HlslParseContext::transformEntryPoint(const TSourceLoc& loc, TFunction& userFunction,
  1752. const TAttributes& attributes)
  1753. {
  1754. // Return true if this is a tessellation patch constant function input to a domain shader.
  1755. const auto isDsPcfInput = [this](const TType& type) {
  1756. return language == EShLangTessEvaluation &&
  1757. type.contains([](const TType* t) {
  1758. return t->getQualifier().builtIn == EbvTessLevelOuter ||
  1759. t->getQualifier().builtIn == EbvTessLevelInner;
  1760. });
  1761. };
  1762. // if we aren't in the entry point, fix the IO as such and exit
  1763. if (userFunction.getName().compare(intermediate.getEntryPointName().c_str()) != 0) {
  1764. remapNonEntryPointIO(userFunction);
  1765. return nullptr;
  1766. }
  1767. entryPointFunction = &userFunction; // needed in finish()
  1768. // Handle entry point attributes
  1769. handleEntryPointAttributes(loc, attributes);
  1770. // entry point logic...
  1771. // Move parameters and return value to shader in/out
  1772. TVariable* entryPointOutput; // gets created in remapEntryPointIO
  1773. TVector<TVariable*> inputs;
  1774. TVector<TVariable*> outputs;
  1775. remapEntryPointIO(userFunction, entryPointOutput, inputs, outputs);
  1776. // Further this return/in/out transform by flattening, splitting, and assigning locations
  1777. const auto makeVariableInOut = [&](TVariable& variable) {
  1778. if (variable.getType().isStruct()) {
  1779. if (variable.getType().getQualifier().isArrayedIo(language)) {
  1780. if (variable.getType().containsBuiltIn())
  1781. split(variable);
  1782. } else if (shouldFlatten(variable.getType(), EvqVaryingIn /* not assigned yet, but close enough */, true))
  1783. flatten(variable, false /* don't track linkage here, it will be tracked in assignToInterface() */);
  1784. }
  1785. // TODO: flatten arrays too
  1786. // TODO: flatten everything in I/O
  1787. // TODO: replace all split with flatten, make all paths can create flattened I/O, then split code can be removed
  1788. // For clip and cull distance, multiple output variables potentially get merged
  1789. // into one in assignClipCullDistance. That code in assignClipCullDistance
  1790. // handles the interface logic, so we avoid it here in that case.
  1791. if (!isClipOrCullDistance(variable.getType()))
  1792. assignToInterface(variable);
  1793. };
  1794. if (entryPointOutput != nullptr)
  1795. makeVariableInOut(*entryPointOutput);
  1796. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1797. if (!isDsPcfInput((*it)->getType())) // wait until the end for PCF input (see comment below)
  1798. makeVariableInOut(*(*it));
  1799. for (auto it = outputs.begin(); it != outputs.end(); ++it)
  1800. makeVariableInOut(*(*it));
  1801. // In the domain shader, PCF input must be at the end of the linkage. That's because in the
  1802. // hull shader there is no ordering: the output comes from the separate PCF, which does not
  1803. // participate in the argument list. That is always put at the end of the HS linkage, so the
  1804. // input side of the DS must match. The argument may be in any position in the DS argument list
  1805. // however, so this ensures the linkage is built in the correct order regardless of argument order.
  1806. if (language == EShLangTessEvaluation) {
  1807. for (auto it = inputs.begin(); it != inputs.end(); ++it)
  1808. if (isDsPcfInput((*it)->getType()))
  1809. makeVariableInOut(*(*it));
  1810. }
  1811. // Synthesize the call
  1812. pushScope(); // matches the one in handleFunctionBody()
  1813. // new signature
  1814. TType voidType(EbtVoid);
  1815. TFunction synthEntryPoint(&userFunction.getName(), voidType);
  1816. TIntermAggregate* synthParams = new TIntermAggregate();
  1817. intermediate.setAggregateOperator(synthParams, EOpParameters, voidType, loc);
  1818. intermediate.setEntryPointMangledName(synthEntryPoint.getMangledName().c_str());
  1819. intermediate.incrementEntryPointCount();
  1820. TFunction callee(&userFunction.getName(), voidType); // call based on old name, which is still in the symbol table
  1821. // change original name
  1822. userFunction.addPrefix("@"); // change the name in the function, but not in the symbol table
  1823. // Copy inputs (shader-in -> calling arg), while building up the call node
  1824. TVector<TVariable*> argVars;
  1825. TIntermAggregate* synthBody = new TIntermAggregate();
  1826. auto inputIt = inputs.begin();
  1827. TIntermTyped* callingArgs = nullptr;
  1828. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1829. TParameter& param = userFunction[i];
  1830. argVars.push_back(makeInternalVariable(*param.name, *param.type));
  1831. argVars.back()->getWritableType().getQualifier().makeTemporary();
  1832. // Track the input patch, which is the only non-builtin supported by hull shader PCF.
  1833. if (param.getDeclaredBuiltIn() == EbvInputPatch)
  1834. inputPatch = argVars.back();
  1835. TIntermSymbol* arg = intermediate.addSymbol(*argVars.back());
  1836. handleFunctionArgument(&callee, callingArgs, arg);
  1837. if (param.type->getQualifier().isParamInput()) {
  1838. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign, arg,
  1839. intermediate.addSymbol(**inputIt)));
  1840. inputIt++;
  1841. }
  1842. }
  1843. // Call
  1844. currentCaller = synthEntryPoint.getMangledName();
  1845. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  1846. currentCaller = userFunction.getMangledName();
  1847. // Return value
  1848. if (entryPointOutput) {
  1849. TIntermTyped* returnAssign;
  1850. // For hull shaders, the wrapped entry point return value is written to
  1851. // an array element as indexed by invocation ID, which we might have to make up.
  1852. // This is required to match SPIR-V semantics.
  1853. if (language == EShLangTessControl) {
  1854. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  1855. // If there is no user declared invocation ID, we must make one.
  1856. if (invocationIdSym == nullptr) {
  1857. TType invocationIdType(EbtUint, EvqIn, 1);
  1858. TString* invocationIdName = NewPoolTString("InvocationId");
  1859. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  1860. TVariable* variable = makeInternalVariable(*invocationIdName, invocationIdType);
  1861. globalQualifierFix(loc, variable->getWritableType().getQualifier());
  1862. trackLinkage(*variable);
  1863. invocationIdSym = intermediate.addSymbol(*variable);
  1864. }
  1865. TIntermTyped* element = intermediate.addIndex(EOpIndexIndirect, intermediate.addSymbol(*entryPointOutput),
  1866. invocationIdSym, loc);
  1867. // Set the type of the array element being dereferenced
  1868. const TType derefElementType(entryPointOutput->getType(), 0);
  1869. element->setType(derefElementType);
  1870. returnAssign = handleAssign(loc, EOpAssign, element, callReturn);
  1871. } else {
  1872. returnAssign = handleAssign(loc, EOpAssign, intermediate.addSymbol(*entryPointOutput), callReturn);
  1873. }
  1874. intermediate.growAggregate(synthBody, returnAssign);
  1875. } else
  1876. intermediate.growAggregate(synthBody, callReturn);
  1877. // Output copies
  1878. auto outputIt = outputs.begin();
  1879. for (int i = 0; i < userFunction.getParamCount(); i++) {
  1880. TParameter& param = userFunction[i];
  1881. // GS outputs are via emit, so we do not copy them here.
  1882. if (param.type->getQualifier().isParamOutput()) {
  1883. if (param.getDeclaredBuiltIn() == EbvGsOutputStream) {
  1884. // GS output stream does not assign outputs here: it's the Append() method
  1885. // which writes to the output, probably multiple times separated by Emit.
  1886. // We merely remember the output to use, here.
  1887. gsStreamOutput = *outputIt;
  1888. } else {
  1889. intermediate.growAggregate(synthBody, handleAssign(loc, EOpAssign,
  1890. intermediate.addSymbol(**outputIt),
  1891. intermediate.addSymbol(*argVars[i])));
  1892. }
  1893. outputIt++;
  1894. }
  1895. }
  1896. // Put the pieces together to form a full function subtree
  1897. // for the synthesized entry point.
  1898. synthBody->setOperator(EOpSequence);
  1899. TIntermNode* synthFunctionDef = synthParams;
  1900. handleFunctionBody(loc, synthEntryPoint, synthBody, synthFunctionDef);
  1901. entryPointFunctionBody = synthBody;
  1902. return synthFunctionDef;
  1903. }
  1904. void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody,
  1905. TIntermNode*& node)
  1906. {
  1907. node = intermediate.growAggregate(node, functionBody);
  1908. intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
  1909. node->getAsAggregate()->setName(function.getMangledName().c_str());
  1910. popScope();
  1911. if (function.hasImplicitThis())
  1912. popImplicitThis();
  1913. if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
  1914. error(loc, "function does not return a value:", "", function.getName().c_str());
  1915. }
  1916. // AST I/O is done through shader globals declared in the 'in' or 'out'
  1917. // storage class. An HLSL entry point has a return value, input parameters
  1918. // and output parameters. These need to get remapped to the AST I/O.
  1919. void HlslParseContext::remapEntryPointIO(TFunction& function, TVariable*& returnValue,
  1920. TVector<TVariable*>& inputs, TVector<TVariable*>& outputs)
  1921. {
  1922. // We might have in input structure type with no decorations that caused it
  1923. // to look like an input type, yet it has (e.g.) interpolation types that
  1924. // must be modified that turn it into an input type.
  1925. // Hence, a missing ioTypeMap for 'input' might need to be synthesized.
  1926. const auto synthesizeEditedInput = [this](TType& type) {
  1927. // True if a type needs to be 'flat'
  1928. const auto needsFlat = [](const TType& type) {
  1929. return type.containsBasicType(EbtInt) ||
  1930. type.containsBasicType(EbtUint) ||
  1931. type.containsBasicType(EbtInt64) ||
  1932. type.containsBasicType(EbtUint64) ||
  1933. type.containsBasicType(EbtBool) ||
  1934. type.containsBasicType(EbtDouble);
  1935. };
  1936. if (language == EShLangFragment && needsFlat(type)) {
  1937. if (type.isStruct()) {
  1938. TTypeList* finalList = nullptr;
  1939. auto it = ioTypeMap.find(type.getStruct());
  1940. if (it == ioTypeMap.end() || it->second.input == nullptr) {
  1941. // Getting here means we have no input struct, but we need one.
  1942. auto list = new TTypeList;
  1943. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  1944. TType* newType = new TType;
  1945. newType->shallowCopy(*member->type);
  1946. TTypeLoc typeLoc = { newType, member->loc };
  1947. list->push_back(typeLoc);
  1948. }
  1949. // install the new input type
  1950. if (it == ioTypeMap.end()) {
  1951. tIoKinds newLists = { list, nullptr, nullptr };
  1952. ioTypeMap[type.getStruct()] = newLists;
  1953. } else
  1954. it->second.input = list;
  1955. finalList = list;
  1956. } else
  1957. finalList = it->second.input;
  1958. // edit for 'flat'
  1959. for (auto member = finalList->begin(); member != finalList->end(); ++member) {
  1960. if (needsFlat(*member->type)) {
  1961. member->type->getQualifier().clearInterpolation();
  1962. member->type->getQualifier().flat = true;
  1963. }
  1964. }
  1965. } else {
  1966. type.getQualifier().clearInterpolation();
  1967. type.getQualifier().flat = true;
  1968. }
  1969. }
  1970. };
  1971. // Do the actual work to make a type be a shader input or output variable,
  1972. // and clear the original to be non-IO (for use as a normal function parameter/return).
  1973. const auto makeIoVariable = [this](const char* name, TType& type, TStorageQualifier storage) -> TVariable* {
  1974. TVariable* ioVariable = makeInternalVariable(name, type);
  1975. clearUniformInputOutput(type.getQualifier());
  1976. if (type.isStruct()) {
  1977. auto newLists = ioTypeMap.find(ioVariable->getType().getStruct());
  1978. if (newLists != ioTypeMap.end()) {
  1979. if (storage == EvqVaryingIn && newLists->second.input)
  1980. ioVariable->getWritableType().setStruct(newLists->second.input);
  1981. else if (storage == EvqVaryingOut && newLists->second.output)
  1982. ioVariable->getWritableType().setStruct(newLists->second.output);
  1983. }
  1984. }
  1985. if (storage == EvqVaryingIn) {
  1986. correctInput(ioVariable->getWritableType().getQualifier());
  1987. if (language == EShLangTessEvaluation)
  1988. if (!ioVariable->getType().isArray())
  1989. ioVariable->getWritableType().getQualifier().patch = true;
  1990. } else {
  1991. correctOutput(ioVariable->getWritableType().getQualifier());
  1992. }
  1993. ioVariable->getWritableType().getQualifier().storage = storage;
  1994. fixBuiltInIoType(ioVariable->getWritableType());
  1995. return ioVariable;
  1996. };
  1997. // return value is actually a shader-scoped output (out)
  1998. if (function.getType().getBasicType() == EbtVoid) {
  1999. returnValue = nullptr;
  2000. } else {
  2001. if (language == EShLangTessControl) {
  2002. // tessellation evaluation in HLSL writes a per-ctrl-pt value, but it needs to be an
  2003. // array in SPIR-V semantics. We'll write to it indexed by invocation ID.
  2004. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2005. TType outputType;
  2006. outputType.shallowCopy(function.getType());
  2007. // vertices has necessarily already been set when handling entry point attributes.
  2008. TArraySizes* arraySizes = new TArraySizes;
  2009. arraySizes->addInnerSize(intermediate.getVertices());
  2010. outputType.transferArraySizes(arraySizes);
  2011. clearUniformInputOutput(function.getWritableType().getQualifier());
  2012. returnValue = makeIoVariable("@entryPointOutput", outputType, EvqVaryingOut);
  2013. } else {
  2014. returnValue = makeIoVariable("@entryPointOutput", function.getWritableType(), EvqVaryingOut);
  2015. }
  2016. }
  2017. // parameters are actually shader-scoped inputs and outputs (in or out)
  2018. for (int i = 0; i < function.getParamCount(); i++) {
  2019. TType& paramType = *function[i].type;
  2020. if (paramType.getQualifier().isParamInput()) {
  2021. synthesizeEditedInput(paramType);
  2022. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingIn);
  2023. inputs.push_back(argAsGlobal);
  2024. }
  2025. if (paramType.getQualifier().isParamOutput()) {
  2026. TVariable* argAsGlobal = makeIoVariable(function[i].name->c_str(), paramType, EvqVaryingOut);
  2027. outputs.push_back(argAsGlobal);
  2028. }
  2029. }
  2030. }
  2031. // An HLSL function that looks like an entry point, but is not,
  2032. // declares entry point IO built-ins, but these have to be undone.
  2033. void HlslParseContext::remapNonEntryPointIO(TFunction& function)
  2034. {
  2035. // return value
  2036. if (function.getType().getBasicType() != EbtVoid)
  2037. clearUniformInputOutput(function.getWritableType().getQualifier());
  2038. // parameters.
  2039. // References to structuredbuffer types are left unmodified
  2040. for (int i = 0; i < function.getParamCount(); i++)
  2041. if (!isReference(*function[i].type))
  2042. clearUniformInputOutput(function[i].type->getQualifier());
  2043. }
  2044. // Handle function returns, including type conversions to the function return type
  2045. // if necessary.
  2046. TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
  2047. {
  2048. functionReturnsValue = true;
  2049. if (currentFunctionType->getBasicType() == EbtVoid) {
  2050. error(loc, "void function cannot return a value", "return", "");
  2051. return intermediate.addBranch(EOpReturn, loc);
  2052. } else if (*currentFunctionType != value->getType()) {
  2053. value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
  2054. if (value && *currentFunctionType != value->getType())
  2055. value = intermediate.addUniShapeConversion(EOpReturn, *currentFunctionType, value);
  2056. if (value == nullptr || *currentFunctionType != value->getType()) {
  2057. error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
  2058. return value;
  2059. }
  2060. }
  2061. return intermediate.addBranch(EOpReturn, value, loc);
  2062. }
  2063. void HlslParseContext::handleFunctionArgument(TFunction* function,
  2064. TIntermTyped*& arguments, TIntermTyped* newArg)
  2065. {
  2066. TParameter param = { 0, new TType, nullptr };
  2067. param.type->shallowCopy(newArg->getType());
  2068. function->addParameter(param);
  2069. if (arguments)
  2070. arguments = intermediate.growAggregate(arguments, newArg);
  2071. else
  2072. arguments = newArg;
  2073. }
  2074. // Position may require special handling: we can optionally invert Y.
  2075. // See: https://github.com/KhronosGroup/glslang/issues/1173
  2076. // https://github.com/KhronosGroup/glslang/issues/494
  2077. TIntermTyped* HlslParseContext::assignPosition(const TSourceLoc& loc, TOperator op,
  2078. TIntermTyped* left, TIntermTyped* right)
  2079. {
  2080. // If we are not asked for Y inversion, use a plain old assign.
  2081. if (!intermediate.getInvertY())
  2082. return intermediate.addAssign(op, left, right, loc);
  2083. // If we get here, we should invert Y.
  2084. TIntermAggregate* assignList = nullptr;
  2085. // If this is a complex rvalue, we don't want to dereference it many times. Create a temporary.
  2086. TVariable* rhsTempVar = nullptr;
  2087. rhsTempVar = makeInternalVariable("@position", right->getType());
  2088. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2089. {
  2090. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2091. assignList = intermediate.growAggregate(assignList,
  2092. intermediate.addAssign(EOpAssign, rhsTempSym, right, loc), loc);
  2093. }
  2094. // pos.y = -pos.y
  2095. {
  2096. const int Y = 1;
  2097. TIntermTyped* tempSymL = intermediate.addSymbol(*rhsTempVar, loc);
  2098. TIntermTyped* tempSymR = intermediate.addSymbol(*rhsTempVar, loc);
  2099. TIntermTyped* index = intermediate.addConstantUnion(Y, loc);
  2100. TIntermTyped* lhsElement = intermediate.addIndex(EOpIndexDirect, tempSymL, index, loc);
  2101. TIntermTyped* rhsElement = intermediate.addIndex(EOpIndexDirect, tempSymR, index, loc);
  2102. const TType derefType(right->getType(), 0);
  2103. lhsElement->setType(derefType);
  2104. rhsElement->setType(derefType);
  2105. TIntermTyped* yNeg = intermediate.addUnaryMath(EOpNegative, rhsElement, loc);
  2106. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(EOpAssign, lhsElement, yNeg, loc));
  2107. }
  2108. // Assign the rhs temp (now with Y inversion) to the final output
  2109. {
  2110. TIntermTyped* rhsTempSym = intermediate.addSymbol(*rhsTempVar, loc);
  2111. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, rhsTempSym, loc));
  2112. }
  2113. assert(assignList != nullptr);
  2114. assignList->setOperator(EOpSequence);
  2115. return assignList;
  2116. }
  2117. // Clip and cull distance require special handling due to a semantic mismatch. In HLSL,
  2118. // these can be float scalar, float vector, or arrays of float scalar or float vector.
  2119. // In SPIR-V, they are arrays of scalar floats in all cases. We must copy individual components
  2120. // (e.g, both x and y components of a float2) out into the destination float array.
  2121. //
  2122. // The values are assigned to sequential members of the output array. The inner dimension
  2123. // is vector components. The outer dimension is array elements.
  2124. TIntermAggregate* HlslParseContext::assignClipCullDistance(const TSourceLoc& loc, TOperator op, int semanticId,
  2125. TIntermTyped* left, TIntermTyped* right)
  2126. {
  2127. switch (language) {
  2128. case EShLangFragment:
  2129. case EShLangVertex:
  2130. case EShLangGeometry:
  2131. break;
  2132. default:
  2133. error(loc, "unimplemented: clip/cull not currently implemented for this stage", "", "");
  2134. return nullptr;
  2135. }
  2136. TVariable** clipCullVar = nullptr;
  2137. // Figure out if we are assigning to, or from, clip or cull distance.
  2138. const bool isOutput = isClipOrCullDistance(left->getType());
  2139. // This is the rvalue or lvalue holding the clip or cull distance.
  2140. TIntermTyped* clipCullNode = isOutput ? left : right;
  2141. // This is the value going into or out of the clip or cull distance.
  2142. TIntermTyped* internalNode = isOutput ? right : left;
  2143. const TBuiltInVariable builtInType = clipCullNode->getQualifier().builtIn;
  2144. decltype(clipSemanticNSizeIn)* semanticNSize = nullptr;
  2145. // Refer to either the clip or the cull distance, depending on semantic.
  2146. switch (builtInType) {
  2147. case EbvClipDistance:
  2148. clipCullVar = isOutput ? &clipDistanceOutput : &clipDistanceInput;
  2149. semanticNSize = isOutput ? &clipSemanticNSizeOut : &clipSemanticNSizeIn;
  2150. break;
  2151. case EbvCullDistance:
  2152. clipCullVar = isOutput ? &cullDistanceOutput : &cullDistanceInput;
  2153. semanticNSize = isOutput ? &cullSemanticNSizeOut : &cullSemanticNSizeIn;
  2154. break;
  2155. // called invalidly: we expected a clip or a cull distance.
  2156. // static compile time problem: should not happen.
  2157. default: assert(0); return nullptr;
  2158. }
  2159. // This is the offset in the destination array of a given semantic's data
  2160. std::array<int, maxClipCullRegs> semanticOffset;
  2161. // Calculate offset of variable of semantic N in destination array
  2162. int arrayLoc = 0;
  2163. int vecItems = 0;
  2164. for (int x = 0; x < maxClipCullRegs; ++x) {
  2165. // See if we overflowed the vec4 packing
  2166. if ((vecItems + (*semanticNSize)[x]) > 4) {
  2167. arrayLoc = (arrayLoc + 3) & (~0x3); // round up to next multiple of 4
  2168. vecItems = 0;
  2169. }
  2170. semanticOffset[x] = arrayLoc;
  2171. vecItems += (*semanticNSize)[x];
  2172. arrayLoc += (*semanticNSize)[x];
  2173. }
  2174. // It can have up to 2 array dimensions (in the case of geometry shader inputs)
  2175. const TArraySizes* const internalArraySizes = internalNode->getType().getArraySizes();
  2176. const int internalArrayDims = internalNode->getType().isArray() ? internalArraySizes->getNumDims() : 0;
  2177. // vector sizes:
  2178. const int internalVectorSize = internalNode->getType().getVectorSize();
  2179. // array sizes, or 1 if it's not an array:
  2180. const int internalInnerArraySize = (internalArrayDims > 0 ? internalArraySizes->getDimSize(internalArrayDims-1) : 1);
  2181. const int internalOuterArraySize = (internalArrayDims > 1 ? internalArraySizes->getDimSize(0) : 1);
  2182. // The created type may be an array of arrays, e.g, for geometry shader inputs.
  2183. const bool isImplicitlyArrayed = (language == EShLangGeometry && !isOutput);
  2184. // If we haven't created the output already, create it now.
  2185. if (*clipCullVar == nullptr) {
  2186. // ClipDistance and CullDistance are handled specially in the entry point input/output copy
  2187. // algorithm, because they may need to be unpacked from components of vectors (or a scalar)
  2188. // into a float array, or vice versa. Here, we make the array the right size and type,
  2189. // which depends on the incoming data, which has several potential dimensions:
  2190. // * Semantic ID
  2191. // * vector size
  2192. // * array size
  2193. // Of those, semantic ID and array size cannot appear simultaneously.
  2194. //
  2195. // Also to note: for implicitly arrayed forms (e.g, geometry shader inputs), we need to create two
  2196. // array dimensions. The shader's declaration may have one or two array dimensions. One is always
  2197. // the geometry's dimension.
  2198. const bool useInnerSize = internalArrayDims > 1 || !isImplicitlyArrayed;
  2199. const int requiredInnerArraySize = arrayLoc * (useInnerSize ? internalInnerArraySize : 1);
  2200. const int requiredOuterArraySize = (internalArrayDims > 0) ? internalArraySizes->getDimSize(0) : 1;
  2201. TType clipCullType(EbtFloat, clipCullNode->getType().getQualifier().storage, 1);
  2202. clipCullType.getQualifier() = clipCullNode->getType().getQualifier();
  2203. // Create required array dimension
  2204. TArraySizes* arraySizes = new TArraySizes;
  2205. if (isImplicitlyArrayed)
  2206. arraySizes->addInnerSize(requiredOuterArraySize);
  2207. arraySizes->addInnerSize(requiredInnerArraySize);
  2208. clipCullType.transferArraySizes(arraySizes);
  2209. // Obtain symbol name: we'll use that for the symbol we introduce.
  2210. TIntermSymbol* sym = clipCullNode->getAsSymbolNode();
  2211. assert(sym != nullptr);
  2212. // We are moving the semantic ID from the layout location, so it is no longer needed or
  2213. // desired there.
  2214. clipCullType.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  2215. // Create variable and track its linkage
  2216. *clipCullVar = makeInternalVariable(sym->getName().c_str(), clipCullType);
  2217. trackLinkage(**clipCullVar);
  2218. }
  2219. // Create symbol for the clip or cull variable.
  2220. TIntermSymbol* clipCullSym = intermediate.addSymbol(**clipCullVar);
  2221. // vector sizes:
  2222. const int clipCullVectorSize = clipCullSym->getType().getVectorSize();
  2223. // array sizes, or 1 if it's not an array:
  2224. const TArraySizes* const clipCullArraySizes = clipCullSym->getType().getArraySizes();
  2225. const int clipCullOuterArraySize = isImplicitlyArrayed ? clipCullArraySizes->getDimSize(0) : 1;
  2226. const int clipCullInnerArraySize = clipCullArraySizes->getDimSize(isImplicitlyArrayed ? 1 : 0);
  2227. // clipCullSym has got to be an array of scalar floats, per SPIR-V semantics.
  2228. // fixBuiltInIoType() should have handled that upstream.
  2229. assert(clipCullSym->getType().isArray());
  2230. assert(clipCullSym->getType().getVectorSize() == 1);
  2231. assert(clipCullSym->getType().getBasicType() == EbtFloat);
  2232. // We may be creating multiple sub-assignments. This is an aggregate to hold them.
  2233. // TODO: it would be possible to be clever sometimes and avoid the sequence node if not needed.
  2234. TIntermAggregate* assignList = nullptr;
  2235. // Holds individual component assignments as we make them.
  2236. TIntermTyped* clipCullAssign = nullptr;
  2237. // If the types are homomorphic, use a simple assign. No need to mess about with
  2238. // individual components.
  2239. if (clipCullSym->getType().isArray() == internalNode->getType().isArray() &&
  2240. clipCullInnerArraySize == internalInnerArraySize &&
  2241. clipCullOuterArraySize == internalOuterArraySize &&
  2242. clipCullVectorSize == internalVectorSize) {
  2243. if (isOutput)
  2244. clipCullAssign = intermediate.addAssign(op, clipCullSym, internalNode, loc);
  2245. else
  2246. clipCullAssign = intermediate.addAssign(op, internalNode, clipCullSym, loc);
  2247. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2248. assignList->setOperator(EOpSequence);
  2249. return assignList;
  2250. }
  2251. // We are going to copy each component of the internal (per array element if indicated) to sequential
  2252. // array elements of the clipCullSym. This tracks the lhs element we're writing to as we go along.
  2253. // We may be starting in the middle - e.g, for a non-zero semantic ID calculated above.
  2254. int clipCullInnerArrayPos = semanticOffset[semanticId];
  2255. int clipCullOuterArrayPos = 0;
  2256. // Lambda to add an index to a node, set the type of the result, and return the new node.
  2257. const auto addIndex = [this, &loc](TIntermTyped* node, int pos) -> TIntermTyped* {
  2258. const TType derefType(node->getType(), 0);
  2259. node = intermediate.addIndex(EOpIndexDirect, node, intermediate.addConstantUnion(pos, loc), loc);
  2260. node->setType(derefType);
  2261. return node;
  2262. };
  2263. // Loop through every component of every element of the internal, and copy to or from the matching external.
  2264. for (int internalOuterArrayPos = 0; internalOuterArrayPos < internalOuterArraySize; ++internalOuterArrayPos) {
  2265. for (int internalInnerArrayPos = 0; internalInnerArrayPos < internalInnerArraySize; ++internalInnerArrayPos) {
  2266. for (int internalComponent = 0; internalComponent < internalVectorSize; ++internalComponent) {
  2267. // clip/cull array member to read from / write to:
  2268. TIntermTyped* clipCullMember = clipCullSym;
  2269. // If implicitly arrayed, there is an outer array dimension involved
  2270. if (isImplicitlyArrayed)
  2271. clipCullMember = addIndex(clipCullMember, clipCullOuterArrayPos);
  2272. // Index into proper array position for clip cull member
  2273. clipCullMember = addIndex(clipCullMember, clipCullInnerArrayPos++);
  2274. // if needed, start over with next outer array slice.
  2275. if (isImplicitlyArrayed && clipCullInnerArrayPos >= clipCullInnerArraySize) {
  2276. clipCullInnerArrayPos = semanticOffset[semanticId];
  2277. ++clipCullOuterArrayPos;
  2278. }
  2279. // internal member to read from / write to:
  2280. TIntermTyped* internalMember = internalNode;
  2281. // If internal node has outer array dimension, index appropriately.
  2282. if (internalArrayDims > 1)
  2283. internalMember = addIndex(internalMember, internalOuterArrayPos);
  2284. // If internal node has inner array dimension, index appropriately.
  2285. if (internalArrayDims > 0)
  2286. internalMember = addIndex(internalMember, internalInnerArrayPos);
  2287. // If internal node is a vector, extract the component of interest.
  2288. if (internalNode->getType().isVector())
  2289. internalMember = addIndex(internalMember, internalComponent);
  2290. // Create an assignment: output from internal to clip cull, or input from clip cull to internal.
  2291. if (isOutput)
  2292. clipCullAssign = intermediate.addAssign(op, clipCullMember, internalMember, loc);
  2293. else
  2294. clipCullAssign = intermediate.addAssign(op, internalMember, clipCullMember, loc);
  2295. // Track assignment in the sequence.
  2296. assignList = intermediate.growAggregate(assignList, clipCullAssign);
  2297. }
  2298. }
  2299. }
  2300. assert(assignList != nullptr);
  2301. assignList->setOperator(EOpSequence);
  2302. return assignList;
  2303. }
  2304. // Some simple source assignments need to be flattened to a sequence
  2305. // of AST assignments. Catch these and flatten, otherwise, pass through
  2306. // to intermediate.addAssign().
  2307. //
  2308. // Also, assignment to matrix swizzles requires multiple component assignments,
  2309. // intercept those as well.
  2310. TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2311. TIntermTyped* right)
  2312. {
  2313. if (left == nullptr || right == nullptr)
  2314. return nullptr;
  2315. // writing to opaques will require fixing transforms
  2316. if (left->getType().containsOpaque())
  2317. intermediate.setNeedsLegalization();
  2318. if (left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle)
  2319. return handleAssignToMatrixSwizzle(loc, op, left, right);
  2320. // Return true if the given node is an index operation into a split variable.
  2321. const auto indexesSplit = [this](const TIntermTyped* node) -> bool {
  2322. const TIntermBinary* binaryNode = node->getAsBinaryNode();
  2323. if (binaryNode == nullptr)
  2324. return false;
  2325. return (binaryNode->getOp() == EOpIndexDirect || binaryNode->getOp() == EOpIndexIndirect) &&
  2326. wasSplit(binaryNode->getLeft());
  2327. };
  2328. // Return true if this stage assigns clip position with potentially inverted Y
  2329. const auto assignsClipPos = [this](const TIntermTyped* node) -> bool {
  2330. return node->getType().getQualifier().builtIn == EbvPosition &&
  2331. (language == EShLangVertex || language == EShLangGeometry || language == EShLangTessEvaluation);
  2332. };
  2333. const bool isSplitLeft = wasSplit(left) || indexesSplit(left);
  2334. const bool isSplitRight = wasSplit(right) || indexesSplit(right);
  2335. const bool isFlattenLeft = wasFlattened(left);
  2336. const bool isFlattenRight = wasFlattened(right);
  2337. // OK to do a single assign if neither side is split or flattened. Otherwise,
  2338. // fall through to a member-wise copy.
  2339. if (!isFlattenLeft && !isFlattenRight && !isSplitLeft && !isSplitRight) {
  2340. // Clip and cull distance requires more processing. See comment above assignClipCullDistance.
  2341. if (isClipOrCullDistance(left->getType()) || isClipOrCullDistance(right->getType())) {
  2342. const bool isOutput = isClipOrCullDistance(left->getType());
  2343. const int semanticId = (isOutput ? left : right)->getType().getQualifier().layoutLocation;
  2344. return assignClipCullDistance(loc, op, semanticId, left, right);
  2345. } else if (assignsClipPos(left)) {
  2346. // Position can require special handling: see comment above assignPosition
  2347. return assignPosition(loc, op, left, right);
  2348. } else if (left->getQualifier().builtIn == EbvSampleMask) {
  2349. // Certain builtins are required to be arrayed outputs in SPIR-V, but may internally be scalars
  2350. // in the shader. Copy the scalar RHS into the LHS array element zero, if that happens.
  2351. if (left->isArray() && !right->isArray()) {
  2352. const TType derefType(left->getType(), 0);
  2353. left = intermediate.addIndex(EOpIndexDirect, left, intermediate.addConstantUnion(0, loc), loc);
  2354. left->setType(derefType);
  2355. // Fall through to add assign.
  2356. }
  2357. }
  2358. return intermediate.addAssign(op, left, right, loc);
  2359. }
  2360. TIntermAggregate* assignList = nullptr;
  2361. const TVector<TVariable*>* leftVariables = nullptr;
  2362. const TVector<TVariable*>* rightVariables = nullptr;
  2363. // A temporary to store the right node's value, so we don't keep indirecting into it
  2364. // if it's not a simple symbol.
  2365. TVariable* rhsTempVar = nullptr;
  2366. // If the RHS is a simple symbol node, we'll copy it for each member.
  2367. TIntermSymbol* cloneSymNode = nullptr;
  2368. int memberCount = 0;
  2369. // Track how many items there are to copy.
  2370. if (left->getType().isStruct())
  2371. memberCount = (int)left->getType().getStruct()->size();
  2372. if (left->getType().isArray())
  2373. memberCount = left->getType().getCumulativeArraySize();
  2374. if (isFlattenLeft)
  2375. leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second.members;
  2376. if (isFlattenRight) {
  2377. rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second.members;
  2378. } else {
  2379. // The RHS is not flattened. There are several cases:
  2380. // 1. 1 item to copy: Use the RHS directly.
  2381. // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
  2382. // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
  2383. if (memberCount <= 1) {
  2384. // case 1: we'll use the symbol directly below. Nothing to do.
  2385. } else {
  2386. if (right->getAsSymbolNode() != nullptr) {
  2387. // case 2: we'll copy the symbol per iteration below.
  2388. cloneSymNode = right->getAsSymbolNode();
  2389. } else {
  2390. // case 3: assign to a temp, and indirect into that.
  2391. rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
  2392. rhsTempVar->getWritableType().getQualifier().makeTemporary();
  2393. TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
  2394. // Add this to the aggregate being built.
  2395. assignList = intermediate.growAggregate(assignList,
  2396. intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
  2397. }
  2398. }
  2399. }
  2400. // When dealing with split arrayed structures of built-ins, the arrayness is moved to the extracted built-in
  2401. // variables, which is awkward when copying between split and unsplit structures. This variable tracks
  2402. // array indirections so they can be percolated from outer structs to inner variables.
  2403. std::vector <int> arrayElement;
  2404. TStorageQualifier leftStorage = left->getType().getQualifier().storage;
  2405. TStorageQualifier rightStorage = right->getType().getQualifier().storage;
  2406. int leftOffset = findSubtreeOffset(*left);
  2407. int rightOffset = findSubtreeOffset(*right);
  2408. const auto getMember = [&](bool isLeft, const TType& type, int member, TIntermTyped* splitNode, int splitMember,
  2409. bool flattened)
  2410. -> TIntermTyped * {
  2411. const bool split = isLeft ? isSplitLeft : isSplitRight;
  2412. TIntermTyped* subTree;
  2413. const TType derefType(type, member);
  2414. const TVariable* builtInVar = nullptr;
  2415. if ((flattened || split) && derefType.isBuiltIn()) {
  2416. auto splitPair = splitBuiltIns.find(HlslParseContext::tInterstageIoData(
  2417. derefType.getQualifier().builtIn,
  2418. isLeft ? leftStorage : rightStorage));
  2419. if (splitPair != splitBuiltIns.end())
  2420. builtInVar = splitPair->second;
  2421. }
  2422. if (builtInVar != nullptr) {
  2423. // copy from interstage IO built-in if needed
  2424. subTree = intermediate.addSymbol(*builtInVar);
  2425. if (subTree->getType().isArray()) {
  2426. // Arrayness of builtIn symbols isn't handled by the normal recursion:
  2427. // it's been extracted and moved to the built-in.
  2428. if (!arrayElement.empty()) {
  2429. const TType splitDerefType(subTree->getType(), arrayElement.back());
  2430. subTree = intermediate.addIndex(EOpIndexDirect, subTree,
  2431. intermediate.addConstantUnion(arrayElement.back(), loc), loc);
  2432. subTree->setType(splitDerefType);
  2433. } else if (splitNode->getAsOperator() != nullptr && (splitNode->getAsOperator()->getOp() == EOpIndexIndirect)) {
  2434. // This might also be a stage with arrayed outputs, in which case there's an index
  2435. // operation we should transfer to the output builtin.
  2436. const TType splitDerefType(subTree->getType(), 0);
  2437. subTree = intermediate.addIndex(splitNode->getAsOperator()->getOp(), subTree,
  2438. splitNode->getAsBinaryNode()->getRight(), loc);
  2439. subTree->setType(splitDerefType);
  2440. }
  2441. }
  2442. } else if (flattened && !shouldFlatten(derefType, isLeft ? leftStorage : rightStorage, false)) {
  2443. if (isLeft)
  2444. subTree = intermediate.addSymbol(*(*leftVariables)[leftOffset++]);
  2445. else
  2446. subTree = intermediate.addSymbol(*(*rightVariables)[rightOffset++]);
  2447. } else {
  2448. // Index operator if it's an aggregate, else EOpNull
  2449. const TOperator accessOp = type.isArray() ? EOpIndexDirect
  2450. : type.isStruct() ? EOpIndexDirectStruct
  2451. : EOpNull;
  2452. if (accessOp == EOpNull) {
  2453. subTree = splitNode;
  2454. } else {
  2455. subTree = intermediate.addIndex(accessOp, splitNode, intermediate.addConstantUnion(splitMember, loc),
  2456. loc);
  2457. const TType splitDerefType(splitNode->getType(), splitMember);
  2458. subTree->setType(splitDerefType);
  2459. }
  2460. }
  2461. return subTree;
  2462. };
  2463. // Use the proper RHS node: a new symbol from a TVariable, copy
  2464. // of an TIntermSymbol node, or sometimes the right node directly.
  2465. right = rhsTempVar != nullptr ? intermediate.addSymbol(*rhsTempVar, loc) :
  2466. cloneSymNode != nullptr ? intermediate.addSymbol(*cloneSymNode) :
  2467. right;
  2468. // Cannot use auto here, because this is recursive, and auto can't work out the type without seeing the
  2469. // whole thing. So, we'll resort to an explicit type via std::function.
  2470. const std::function<void(TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2471. bool topLevel)>
  2472. traverse = [&](TIntermTyped* left, TIntermTyped* right, TIntermTyped* splitLeft, TIntermTyped* splitRight,
  2473. bool topLevel) -> void {
  2474. // If we get here, we are assigning to or from a whole array or struct that must be
  2475. // flattened, so have to do member-by-member assignment:
  2476. bool shouldFlattenSubsetLeft = isFlattenLeft && shouldFlatten(left->getType(), leftStorage, topLevel);
  2477. bool shouldFlattenSubsetRight = isFlattenRight && shouldFlatten(right->getType(), rightStorage, topLevel);
  2478. if ((left->getType().isArray() || right->getType().isArray()) &&
  2479. (shouldFlattenSubsetLeft || isSplitLeft ||
  2480. shouldFlattenSubsetRight || isSplitRight)) {
  2481. const int elementsL = left->getType().isArray() ? left->getType().getOuterArraySize() : 1;
  2482. const int elementsR = right->getType().isArray() ? right->getType().getOuterArraySize() : 1;
  2483. // The arrays might not be the same size,
  2484. // e.g., if the size has been forced for EbvTessLevelInner/Outer.
  2485. const int elementsToCopy = std::min(elementsL, elementsR);
  2486. // array case
  2487. for (int element = 0; element < elementsToCopy; ++element) {
  2488. arrayElement.push_back(element);
  2489. // Add a new AST symbol node if we have a temp variable holding a complex RHS.
  2490. TIntermTyped* subLeft = getMember(true, left->getType(), element, left, element,
  2491. shouldFlattenSubsetLeft);
  2492. TIntermTyped* subRight = getMember(false, right->getType(), element, right, element,
  2493. shouldFlattenSubsetRight);
  2494. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), element, splitLeft,
  2495. element, shouldFlattenSubsetLeft)
  2496. : subLeft;
  2497. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), element, splitRight,
  2498. element, shouldFlattenSubsetRight)
  2499. : subRight;
  2500. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2501. arrayElement.pop_back();
  2502. }
  2503. } else if (left->getType().isStruct() && (shouldFlattenSubsetLeft || isSplitLeft ||
  2504. shouldFlattenSubsetRight || isSplitRight)) {
  2505. // struct case
  2506. const auto& membersL = *left->getType().getStruct();
  2507. const auto& membersR = *right->getType().getStruct();
  2508. // These track the members in the split structures corresponding to the same in the unsplit structures,
  2509. // which we traverse in parallel.
  2510. int memberL = 0;
  2511. int memberR = 0;
  2512. // Handle empty structure assignment
  2513. if (int(membersL.size()) == 0 && int(membersR.size()) == 0)
  2514. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2515. for (int member = 0; member < int(membersL.size()); ++member) {
  2516. const TType& typeL = *membersL[member].type;
  2517. const TType& typeR = *membersR[member].type;
  2518. TIntermTyped* subLeft = getMember(true, left->getType(), member, left, member,
  2519. shouldFlattenSubsetLeft);
  2520. TIntermTyped* subRight = getMember(false, right->getType(), member, right, member,
  2521. shouldFlattenSubsetRight);
  2522. // If there is no splitting, use the same values to avoid inefficiency.
  2523. TIntermTyped* subSplitLeft = isSplitLeft ? getMember(true, left->getType(), member, splitLeft,
  2524. memberL, shouldFlattenSubsetLeft)
  2525. : subLeft;
  2526. TIntermTyped* subSplitRight = isSplitRight ? getMember(false, right->getType(), member, splitRight,
  2527. memberR, shouldFlattenSubsetRight)
  2528. : subRight;
  2529. if (isClipOrCullDistance(subSplitLeft->getType()) || isClipOrCullDistance(subSplitRight->getType())) {
  2530. // Clip and cull distance built-in assignment is complex in its own right, and is handled in
  2531. // a separate function dedicated to that task. See comment above assignClipCullDistance;
  2532. const bool isOutput = isClipOrCullDistance(subSplitLeft->getType());
  2533. // Since all clip/cull semantics boil down to the same built-in type, we need to get the
  2534. // semantic ID from the dereferenced type's layout location, to avoid an N-1 mapping.
  2535. const TType derefType((isOutput ? left : right)->getType(), member);
  2536. const int semanticId = derefType.getQualifier().layoutLocation;
  2537. TIntermAggregate* clipCullAssign = assignClipCullDistance(loc, op, semanticId,
  2538. subSplitLeft, subSplitRight);
  2539. assignList = intermediate.growAggregate(assignList, clipCullAssign, loc);
  2540. } else if (assignsClipPos(subSplitLeft)) {
  2541. // Position can require special handling: see comment above assignPosition
  2542. TIntermTyped* positionAssign = assignPosition(loc, op, subSplitLeft, subSplitRight);
  2543. assignList = intermediate.growAggregate(assignList, positionAssign, loc);
  2544. } else if (!shouldFlattenSubsetLeft && !shouldFlattenSubsetRight &&
  2545. !typeL.containsBuiltIn() && !typeR.containsBuiltIn()) {
  2546. // If this is the final flattening (no nested types below to flatten)
  2547. // we'll copy the member, else recurse into the type hierarchy.
  2548. // However, if splitting the struct, that means we can copy a whole
  2549. // subtree here IFF it does not itself contain any interstage built-in
  2550. // IO variables, so we only have to recurse into it if there's something
  2551. // for splitting to do. That can save a lot of AST verbosity for
  2552. // a bunch of memberwise copies.
  2553. assignList = intermediate.growAggregate(assignList,
  2554. intermediate.addAssign(op, subSplitLeft, subSplitRight, loc),
  2555. loc);
  2556. } else {
  2557. traverse(subLeft, subRight, subSplitLeft, subSplitRight, false);
  2558. }
  2559. memberL += (typeL.isBuiltIn() ? 0 : 1);
  2560. memberR += (typeR.isBuiltIn() ? 0 : 1);
  2561. }
  2562. } else {
  2563. // Member copy
  2564. assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, left, right, loc), loc);
  2565. }
  2566. };
  2567. TIntermTyped* splitLeft = left;
  2568. TIntermTyped* splitRight = right;
  2569. // If either left or right was a split structure, we must read or write it, but still have to
  2570. // parallel-recurse through the unsplit structure to identify the built-in IO vars.
  2571. // The left can be either a symbol, or an index into a symbol (e.g, array reference)
  2572. if (isSplitLeft) {
  2573. if (indexesSplit(left)) {
  2574. // Index case: Refer to the indexed symbol, if the left is an index operator.
  2575. const TIntermSymbol* symNode = left->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2576. TIntermTyped* splitLeftNonIo = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2577. splitLeft = intermediate.addIndex(left->getAsBinaryNode()->getOp(), splitLeftNonIo,
  2578. left->getAsBinaryNode()->getRight(), loc);
  2579. const TType derefType(splitLeftNonIo->getType(), 0);
  2580. splitLeft->setType(derefType);
  2581. } else {
  2582. // Symbol case: otherwise, if not indexed, we have the symbol directly.
  2583. const TIntermSymbol* symNode = left->getAsSymbolNode();
  2584. splitLeft = intermediate.addSymbol(*getSplitNonIoVar(symNode->getId()), loc);
  2585. }
  2586. }
  2587. if (isSplitRight)
  2588. splitRight = intermediate.addSymbol(*getSplitNonIoVar(right->getAsSymbolNode()->getId()), loc);
  2589. // This makes the whole assignment, recursing through subtypes as needed.
  2590. traverse(left, right, splitLeft, splitRight, true);
  2591. assert(assignList != nullptr);
  2592. assignList->setOperator(EOpSequence);
  2593. return assignList;
  2594. }
  2595. // An assignment to matrix swizzle must be decomposed into individual assignments.
  2596. // These must be selected component-wise from the RHS and stored component-wise
  2597. // into the LHS.
  2598. TIntermTyped* HlslParseContext::handleAssignToMatrixSwizzle(const TSourceLoc& loc, TOperator op, TIntermTyped* left,
  2599. TIntermTyped* right)
  2600. {
  2601. assert(left->getAsOperator() && left->getAsOperator()->getOp() == EOpMatrixSwizzle);
  2602. if (op != EOpAssign)
  2603. error(loc, "only simple assignment to non-simple matrix swizzle is supported", "assign", "");
  2604. // isolate the matrix and swizzle nodes
  2605. TIntermTyped* matrix = left->getAsBinaryNode()->getLeft()->getAsTyped();
  2606. const TIntermSequence& swizzle = left->getAsBinaryNode()->getRight()->getAsAggregate()->getSequence();
  2607. // if the RHS isn't already a simple vector, let's store into one
  2608. TIntermSymbol* vector = right->getAsSymbolNode();
  2609. TIntermTyped* vectorAssign = nullptr;
  2610. if (vector == nullptr) {
  2611. // create a new intermediate vector variable to assign to
  2612. TType vectorType(matrix->getBasicType(), EvqTemporary, matrix->getQualifier().precision, (int)swizzle.size()/2);
  2613. vector = intermediate.addSymbol(*makeInternalVariable("intermVec", vectorType), loc);
  2614. // assign the right to the new vector
  2615. vectorAssign = handleAssign(loc, op, vector, right);
  2616. }
  2617. // Assign the vector components to the matrix components.
  2618. // Store this as a sequence, so a single aggregate node represents this
  2619. // entire operation.
  2620. TIntermAggregate* result = intermediate.makeAggregate(vectorAssign);
  2621. TType columnType(matrix->getType(), 0);
  2622. TType componentType(columnType, 0);
  2623. TType indexType(EbtInt);
  2624. for (int i = 0; i < (int)swizzle.size(); i += 2) {
  2625. // the right component, single index into the RHS vector
  2626. TIntermTyped* rightComp = intermediate.addIndex(EOpIndexDirect, vector,
  2627. intermediate.addConstantUnion(i/2, loc), loc);
  2628. // the left component, double index into the LHS matrix
  2629. TIntermTyped* leftComp = intermediate.addIndex(EOpIndexDirect, matrix,
  2630. intermediate.addConstantUnion(swizzle[i]->getAsConstantUnion()->getConstArray(),
  2631. indexType, loc),
  2632. loc);
  2633. leftComp->setType(columnType);
  2634. leftComp = intermediate.addIndex(EOpIndexDirect, leftComp,
  2635. intermediate.addConstantUnion(swizzle[i+1]->getAsConstantUnion()->getConstArray(),
  2636. indexType, loc),
  2637. loc);
  2638. leftComp->setType(componentType);
  2639. // Add the assignment to the aggregate
  2640. result = intermediate.growAggregate(result, intermediate.addAssign(op, leftComp, rightComp, loc));
  2641. }
  2642. result->setOp(EOpSequence);
  2643. return result;
  2644. }
  2645. //
  2646. // HLSL atomic operations have slightly different arguments than
  2647. // GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
  2648. // This provides the post-decomposition equivalent opcode.
  2649. //
  2650. TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
  2651. {
  2652. switch (op) {
  2653. case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
  2654. case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
  2655. case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
  2656. case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
  2657. case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
  2658. case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
  2659. case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
  2660. case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
  2661. case EOpInterlockedCompareStore: // TODO: ...
  2662. default:
  2663. error(loc, "unknown atomic operation", "unknown op", "");
  2664. return EOpNull;
  2665. }
  2666. }
  2667. //
  2668. // Create a combined sampler/texture from separate sampler and texture.
  2669. //
  2670. TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex,
  2671. TIntermTyped* argSampler)
  2672. {
  2673. TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
  2674. txcombine->getSequence().push_back(argTex);
  2675. txcombine->getSequence().push_back(argSampler);
  2676. TSampler samplerType = argTex->getType().getSampler();
  2677. samplerType.combined = true;
  2678. // TODO:
  2679. // This block exists until the spec no longer requires shadow modes on texture objects.
  2680. // It can be deleted after that, along with the shadowTextureVariant member.
  2681. {
  2682. const bool shadowMode = argSampler->getType().getSampler().shadow;
  2683. TIntermSymbol* texSymbol = argTex->getAsSymbolNode();
  2684. if (texSymbol == nullptr)
  2685. texSymbol = argTex->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  2686. if (texSymbol == nullptr) {
  2687. error(loc, "unable to find texture symbol", "", "");
  2688. return nullptr;
  2689. }
  2690. // This forces the texture's shadow state to be the sampler's
  2691. // shadow state. This depends on downstream optimization to
  2692. // DCE one variant in [shadow, nonshadow] if both are present,
  2693. // or the SPIR-V module would be invalid.
  2694. int newId = texSymbol->getId();
  2695. // Check to see if this texture has been given a shadow mode already.
  2696. // If so, look up the one we already have.
  2697. const auto textureShadowEntry = textureShadowVariant.find(texSymbol->getId());
  2698. if (textureShadowEntry != textureShadowVariant.end())
  2699. newId = textureShadowEntry->second->get(shadowMode);
  2700. else
  2701. textureShadowVariant[texSymbol->getId()] = NewPoolObject(tShadowTextureSymbols(), 1);
  2702. // Sometimes we have to create another symbol (if this texture has been seen before,
  2703. // and we haven't created the form for this shadow mode).
  2704. if (newId == -1) {
  2705. TType texType;
  2706. texType.shallowCopy(argTex->getType());
  2707. texType.getSampler().shadow = shadowMode; // set appropriate shadow mode.
  2708. globalQualifierFix(loc, texType.getQualifier());
  2709. TVariable* newTexture = makeInternalVariable(texSymbol->getName(), texType);
  2710. trackLinkage(*newTexture);
  2711. newId = newTexture->getUniqueId();
  2712. }
  2713. assert(newId != -1);
  2714. if (textureShadowVariant.find(newId) == textureShadowVariant.end())
  2715. textureShadowVariant[newId] = textureShadowVariant[texSymbol->getId()];
  2716. textureShadowVariant[newId]->set(shadowMode, newId);
  2717. // Remember this shadow mode in the texture and the merged type.
  2718. argTex->getWritableType().getSampler().shadow = shadowMode;
  2719. samplerType.shadow = shadowMode;
  2720. texSymbol->switchId(newId);
  2721. }
  2722. txcombine->setType(TType(samplerType, EvqTemporary));
  2723. txcombine->setLoc(loc);
  2724. return txcombine;
  2725. }
  2726. // Return true if this a buffer type that has an associated counter buffer.
  2727. bool HlslParseContext::hasStructBuffCounter(const TType& type) const
  2728. {
  2729. switch (type.getQualifier().declaredBuiltIn) {
  2730. case EbvAppendConsume: // fall through...
  2731. case EbvRWStructuredBuffer: // ...
  2732. return true;
  2733. default:
  2734. return false; // the other structuredbuffer types do not have a counter.
  2735. }
  2736. }
  2737. void HlslParseContext::counterBufferType(const TSourceLoc& loc, TType& type)
  2738. {
  2739. // Counter type
  2740. TType* counterType = new TType(EbtUint, EvqBuffer);
  2741. counterType->setFieldName(intermediate.implicitCounterName);
  2742. TTypeList* blockStruct = new TTypeList;
  2743. TTypeLoc member = { counterType, loc };
  2744. blockStruct->push_back(member);
  2745. TType blockType(blockStruct, "", counterType->getQualifier());
  2746. blockType.getQualifier().storage = EvqBuffer;
  2747. type.shallowCopy(blockType);
  2748. shareStructBufferType(type);
  2749. }
  2750. // declare counter for a structured buffer type
  2751. void HlslParseContext::declareStructBufferCounter(const TSourceLoc& loc, const TType& bufferType, const TString& name)
  2752. {
  2753. // Bail out if not a struct buffer
  2754. if (! isStructBufferType(bufferType))
  2755. return;
  2756. if (! hasStructBuffCounter(bufferType))
  2757. return;
  2758. TType blockType;
  2759. counterBufferType(loc, blockType);
  2760. TString* blockName = NewPoolTString(intermediate.addCounterBufferName(name).c_str());
  2761. // Counter buffer is not yet in use
  2762. structBufferCounter[*blockName] = false;
  2763. shareStructBufferType(blockType);
  2764. declareBlock(loc, blockType, blockName);
  2765. }
  2766. // return the counter that goes with a given structuredbuffer
  2767. TIntermTyped* HlslParseContext::getStructBufferCounter(const TSourceLoc& loc, TIntermTyped* buffer)
  2768. {
  2769. // Bail out if not a struct buffer
  2770. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  2771. return nullptr;
  2772. const TString counterBlockName(intermediate.addCounterBufferName(buffer->getAsSymbolNode()->getName()));
  2773. // Mark the counter as being used
  2774. structBufferCounter[counterBlockName] = true;
  2775. TIntermTyped* counterVar = handleVariable(loc, &counterBlockName); // find the block structure
  2776. TIntermTyped* index = intermediate.addConstantUnion(0, loc); // index to counter inside block struct
  2777. TIntermTyped* counterMember = intermediate.addIndex(EOpIndexDirectStruct, counterVar, index, loc);
  2778. counterMember->setType(TType(EbtUint));
  2779. return counterMember;
  2780. }
  2781. //
  2782. // Decompose structure buffer methods into AST
  2783. //
  2784. void HlslParseContext::decomposeStructBufferMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  2785. {
  2786. if (node == nullptr || node->getAsOperator() == nullptr || arguments == nullptr)
  2787. return;
  2788. const TOperator op = node->getAsOperator()->getOp();
  2789. TIntermAggregate* argAggregate = arguments->getAsAggregate();
  2790. // Buffer is the object upon which method is called, so always arg 0
  2791. TIntermTyped* bufferObj = nullptr;
  2792. // The parameters can be an aggregate, or just a the object as a symbol if there are no fn params.
  2793. if (argAggregate) {
  2794. if (argAggregate->getSequence().empty())
  2795. return;
  2796. if (argAggregate->getSequence()[0])
  2797. bufferObj = argAggregate->getSequence()[0]->getAsTyped();
  2798. } else {
  2799. bufferObj = arguments->getAsSymbolNode();
  2800. }
  2801. if (bufferObj == nullptr || bufferObj->getAsSymbolNode() == nullptr)
  2802. return;
  2803. // Some methods require a hidden internal counter, obtained via getStructBufferCounter().
  2804. // This lambda adds something to it and returns the old value.
  2805. const auto incDecCounter = [&](int incval) -> TIntermTyped* {
  2806. TIntermTyped* incrementValue = intermediate.addConstantUnion(static_cast<unsigned int>(incval), loc, true);
  2807. TIntermTyped* counter = getStructBufferCounter(loc, bufferObj); // obtain the counter member
  2808. if (counter == nullptr)
  2809. return nullptr;
  2810. TIntermAggregate* counterIncrement = new TIntermAggregate(EOpAtomicAdd);
  2811. counterIncrement->setType(TType(EbtUint, EvqTemporary));
  2812. counterIncrement->setLoc(loc);
  2813. counterIncrement->getSequence().push_back(counter);
  2814. counterIncrement->getSequence().push_back(incrementValue);
  2815. return counterIncrement;
  2816. };
  2817. // Index to obtain the runtime sized array out of the buffer.
  2818. TIntermTyped* argArray = indexStructBufferContent(loc, bufferObj);
  2819. if (argArray == nullptr)
  2820. return; // It might not be a struct buffer method.
  2821. switch (op) {
  2822. case EOpMethodLoad:
  2823. {
  2824. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2825. const TType& bufferType = bufferObj->getType();
  2826. const TBuiltInVariable builtInType = bufferType.getQualifier().declaredBuiltIn;
  2827. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2828. // buffer then, but that's what it calls itself.
  2829. const bool isByteAddressBuffer = (builtInType == EbvByteAddressBuffer ||
  2830. builtInType == EbvRWByteAddressBuffer);
  2831. if (isByteAddressBuffer)
  2832. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2833. intermediate.addConstantUnion(2, loc, true),
  2834. loc, TType(EbtInt));
  2835. // Index into the array to find the item being loaded.
  2836. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2837. node = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2838. const TType derefType(argArray->getType(), 0);
  2839. node->setType(derefType);
  2840. }
  2841. break;
  2842. case EOpMethodLoad2:
  2843. case EOpMethodLoad3:
  2844. case EOpMethodLoad4:
  2845. {
  2846. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2847. TOperator constructOp = EOpNull;
  2848. int size = 0;
  2849. switch (op) {
  2850. case EOpMethodLoad2: size = 2; constructOp = EOpConstructVec2; break;
  2851. case EOpMethodLoad3: size = 3; constructOp = EOpConstructVec3; break;
  2852. case EOpMethodLoad4: size = 4; constructOp = EOpConstructVec4; break;
  2853. default: assert(0);
  2854. }
  2855. TIntermTyped* body = nullptr;
  2856. // First, we'll store the address in a variable to avoid multiple shifts
  2857. // (we must convert the byte address to an item address)
  2858. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2859. intermediate.addConstantUnion(2, loc, true),
  2860. loc, TType(EbtInt));
  2861. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2862. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2863. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2864. TIntermTyped* vec = nullptr;
  2865. // These are only valid on (rw)byteaddressbuffers, so we can always perform the >>2
  2866. // address conversion.
  2867. for (int idx=0; idx<size; ++idx) {
  2868. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2869. // add index offset
  2870. if (idx != 0)
  2871. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx,
  2872. intermediate.addConstantUnion(idx, loc, true),
  2873. loc, TType(EbtInt));
  2874. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2875. : EOpIndexIndirect;
  2876. TIntermTyped* indexVal = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2877. TType derefType(argArray->getType(), 0);
  2878. derefType.getQualifier().makeTemporary();
  2879. indexVal->setType(derefType);
  2880. vec = intermediate.growAggregate(vec, indexVal);
  2881. }
  2882. vec->setType(TType(argArray->getBasicType(), EvqTemporary, size));
  2883. vec->getAsAggregate()->setOperator(constructOp);
  2884. body = intermediate.growAggregate(body, vec);
  2885. body->setType(vec->getType());
  2886. body->getAsAggregate()->setOperator(EOpSequence);
  2887. node = body;
  2888. }
  2889. break;
  2890. case EOpMethodStore:
  2891. case EOpMethodStore2:
  2892. case EOpMethodStore3:
  2893. case EOpMethodStore4:
  2894. {
  2895. TIntermTyped* argIndex = makeIntegerIndex(argAggregate->getSequence()[1]->getAsTyped()); // index
  2896. TIntermTyped* argValue = argAggregate->getSequence()[2]->getAsTyped(); // value
  2897. // Index into the array to find the item being loaded.
  2898. // Byte address buffers index in bytes (only multiples of 4 permitted... not so much a byte address
  2899. // buffer then, but that's what it calls itself).
  2900. int size = 0;
  2901. switch (op) {
  2902. case EOpMethodStore: size = 1; break;
  2903. case EOpMethodStore2: size = 2; break;
  2904. case EOpMethodStore3: size = 3; break;
  2905. case EOpMethodStore4: size = 4; break;
  2906. default: assert(0);
  2907. }
  2908. TIntermAggregate* body = nullptr;
  2909. // First, we'll store the address in a variable to avoid multiple shifts
  2910. // (we must convert the byte address to an item address)
  2911. TIntermTyped* byteAddrIdx = intermediate.addBinaryNode(EOpRightShift, argIndex,
  2912. intermediate.addConstantUnion(2, loc, true), loc, TType(EbtInt));
  2913. TVariable* byteAddrSym = makeInternalVariable("byteAddrTemp", TType(EbtInt, EvqTemporary));
  2914. TIntermTyped* byteAddrIdxVar = intermediate.addSymbol(*byteAddrSym, loc);
  2915. body = intermediate.growAggregate(body, intermediate.addAssign(EOpAssign, byteAddrIdxVar, byteAddrIdx, loc));
  2916. for (int idx=0; idx<size; ++idx) {
  2917. TIntermTyped* offsetIdx = byteAddrIdxVar;
  2918. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  2919. // add index offset
  2920. if (idx != 0)
  2921. offsetIdx = intermediate.addBinaryNode(EOpAdd, offsetIdx, idxConst, loc, TType(EbtInt));
  2922. const TOperator idxOp = (offsetIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect
  2923. : EOpIndexIndirect;
  2924. TIntermTyped* lValue = intermediate.addIndex(idxOp, argArray, offsetIdx, loc);
  2925. const TType derefType(argArray->getType(), 0);
  2926. lValue->setType(derefType);
  2927. TIntermTyped* rValue;
  2928. if (size == 1) {
  2929. rValue = argValue;
  2930. } else {
  2931. rValue = intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc);
  2932. const TType indexType(argValue->getType(), 0);
  2933. rValue->setType(indexType);
  2934. }
  2935. TIntermTyped* assign = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  2936. body = intermediate.growAggregate(body, assign);
  2937. }
  2938. body->setOperator(EOpSequence);
  2939. node = body;
  2940. }
  2941. break;
  2942. case EOpMethodGetDimensions:
  2943. {
  2944. const int numArgs = (int)argAggregate->getSequence().size();
  2945. TIntermTyped* argNumItems = argAggregate->getSequence()[1]->getAsTyped(); // out num items
  2946. TIntermTyped* argStride = numArgs > 2 ? argAggregate->getSequence()[2]->getAsTyped() : nullptr; // out stride
  2947. TIntermAggregate* body = nullptr;
  2948. // Length output:
  2949. if (argArray->getType().isSizedArray()) {
  2950. const int length = argArray->getType().getOuterArraySize();
  2951. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems,
  2952. intermediate.addConstantUnion(length, loc, true), loc);
  2953. body = intermediate.growAggregate(body, assign, loc);
  2954. } else {
  2955. TIntermTyped* lengthCall = intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, argArray,
  2956. argNumItems->getType());
  2957. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argNumItems, lengthCall, loc);
  2958. body = intermediate.growAggregate(body, assign, loc);
  2959. }
  2960. // Stride output:
  2961. if (argStride != nullptr) {
  2962. int size;
  2963. int stride;
  2964. intermediate.getMemberAlignment(argArray->getType(), size, stride, argArray->getType().getQualifier().layoutPacking,
  2965. argArray->getType().getQualifier().layoutMatrix == ElmRowMajor);
  2966. TIntermTyped* assign = intermediate.addAssign(EOpAssign, argStride,
  2967. intermediate.addConstantUnion(stride, loc, true), loc);
  2968. body = intermediate.growAggregate(body, assign);
  2969. }
  2970. body->setOperator(EOpSequence);
  2971. node = body;
  2972. }
  2973. break;
  2974. case EOpInterlockedAdd:
  2975. case EOpInterlockedAnd:
  2976. case EOpInterlockedExchange:
  2977. case EOpInterlockedMax:
  2978. case EOpInterlockedMin:
  2979. case EOpInterlockedOr:
  2980. case EOpInterlockedXor:
  2981. case EOpInterlockedCompareExchange:
  2982. case EOpInterlockedCompareStore:
  2983. {
  2984. // We'll replace the first argument with the block dereference, and let
  2985. // downstream decomposition handle the rest.
  2986. TIntermSequence& sequence = argAggregate->getSequence();
  2987. TIntermTyped* argIndex = makeIntegerIndex(sequence[1]->getAsTyped()); // index
  2988. argIndex = intermediate.addBinaryNode(EOpRightShift, argIndex, intermediate.addConstantUnion(2, loc, true),
  2989. loc, TType(EbtInt));
  2990. const TOperator idxOp = (argIndex->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  2991. TIntermTyped* element = intermediate.addIndex(idxOp, argArray, argIndex, loc);
  2992. const TType derefType(argArray->getType(), 0);
  2993. element->setType(derefType);
  2994. // Replace the numeric byte offset parameter with array reference.
  2995. sequence[1] = element;
  2996. sequence.erase(sequence.begin(), sequence.begin()+1);
  2997. }
  2998. break;
  2999. case EOpMethodIncrementCounter:
  3000. {
  3001. node = incDecCounter(1);
  3002. break;
  3003. }
  3004. case EOpMethodDecrementCounter:
  3005. {
  3006. TIntermTyped* preIncValue = incDecCounter(-1); // result is original value
  3007. node = intermediate.addBinaryNode(EOpAdd, preIncValue, intermediate.addConstantUnion(-1, loc, true), loc,
  3008. preIncValue->getType());
  3009. break;
  3010. }
  3011. case EOpMethodAppend:
  3012. {
  3013. TIntermTyped* oldCounter = incDecCounter(1);
  3014. TIntermTyped* lValue = intermediate.addIndex(EOpIndexIndirect, argArray, oldCounter, loc);
  3015. TIntermTyped* rValue = argAggregate->getSequence()[1]->getAsTyped();
  3016. const TType derefType(argArray->getType(), 0);
  3017. lValue->setType(derefType);
  3018. node = intermediate.addAssign(EOpAssign, lValue, rValue, loc);
  3019. break;
  3020. }
  3021. case EOpMethodConsume:
  3022. {
  3023. TIntermTyped* oldCounter = incDecCounter(-1);
  3024. TIntermTyped* newCounter = intermediate.addBinaryNode(EOpAdd, oldCounter,
  3025. intermediate.addConstantUnion(-1, loc, true), loc,
  3026. oldCounter->getType());
  3027. node = intermediate.addIndex(EOpIndexIndirect, argArray, newCounter, loc);
  3028. const TType derefType(argArray->getType(), 0);
  3029. node->setType(derefType);
  3030. break;
  3031. }
  3032. default:
  3033. break; // most pass through unchanged
  3034. }
  3035. }
  3036. // Create array of standard sample positions for given sample count.
  3037. // TODO: remove when a real method to query sample pos exists in SPIR-V.
  3038. TIntermConstantUnion* HlslParseContext::getSamplePosArray(int count)
  3039. {
  3040. struct tSamplePos { float x, y; };
  3041. static const tSamplePos pos1[] = {
  3042. { 0.0/16.0, 0.0/16.0 },
  3043. };
  3044. // standard sample positions for 2, 4, 8, and 16 samples.
  3045. static const tSamplePos pos2[] = {
  3046. { 4.0/16.0, 4.0/16.0 }, {-4.0/16.0, -4.0/16.0 },
  3047. };
  3048. static const tSamplePos pos4[] = {
  3049. {-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 },
  3050. };
  3051. static const tSamplePos pos8[] = {
  3052. { 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 },
  3053. {-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 },
  3054. };
  3055. static const tSamplePos pos16[] = {
  3056. { 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 },
  3057. {-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 },
  3058. {-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 },
  3059. {-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 },
  3060. };
  3061. const tSamplePos* sampleLoc = nullptr;
  3062. int numSamples = count;
  3063. switch (count) {
  3064. case 2: sampleLoc = pos2; break;
  3065. case 4: sampleLoc = pos4; break;
  3066. case 8: sampleLoc = pos8; break;
  3067. case 16: sampleLoc = pos16; break;
  3068. default:
  3069. sampleLoc = pos1;
  3070. numSamples = 1;
  3071. }
  3072. TConstUnionArray* values = new TConstUnionArray(numSamples*2);
  3073. for (int pos=0; pos<count; ++pos) {
  3074. TConstUnion x, y;
  3075. x.setDConst(sampleLoc[pos].x);
  3076. y.setDConst(sampleLoc[pos].y);
  3077. (*values)[pos*2+0] = x;
  3078. (*values)[pos*2+1] = y;
  3079. }
  3080. TType retType(EbtFloat, EvqConst, 2);
  3081. if (numSamples != 1) {
  3082. TArraySizes* arraySizes = new TArraySizes;
  3083. arraySizes->addInnerSize(numSamples);
  3084. retType.transferArraySizes(arraySizes);
  3085. }
  3086. return new TIntermConstantUnion(*values, retType);
  3087. }
  3088. //
  3089. // Decompose DX9 and DX10 sample intrinsics & object methods into AST
  3090. //
  3091. void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3092. {
  3093. if (node == nullptr || !node->getAsOperator())
  3094. return;
  3095. // Sampler return must always be a vec4, but we can construct a shorter vector or a structure from it.
  3096. const auto convertReturn = [&loc, &node, this](TIntermTyped* result, const TSampler& sampler) -> TIntermTyped* {
  3097. result->setType(TType(node->getType().getBasicType(), EvqTemporary, node->getVectorSize()));
  3098. TIntermTyped* convertedResult = nullptr;
  3099. TType retType;
  3100. getTextureReturnType(sampler, retType);
  3101. if (retType.isStruct()) {
  3102. // For type convenience, conversionAggregate points to the convertedResult (we know it's an aggregate here)
  3103. TIntermAggregate* conversionAggregate = new TIntermAggregate;
  3104. convertedResult = conversionAggregate;
  3105. // Convert vector output to return structure. We will need a temp symbol to copy the results to.
  3106. TVariable* structVar = makeInternalVariable("@sampleStructTemp", retType);
  3107. // We also need a temp symbol to hold the result of the texture. We don't want to re-fetch the
  3108. // sample each time we'll index into the result, so we'll copy to this, and index into the copy.
  3109. TVariable* sampleShadow = makeInternalVariable("@sampleResultShadow", result->getType());
  3110. // Initial copy from texture to our sample result shadow.
  3111. TIntermTyped* shadowCopy = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*sampleShadow, loc),
  3112. result, loc);
  3113. conversionAggregate->getSequence().push_back(shadowCopy);
  3114. unsigned vec4Pos = 0;
  3115. for (unsigned m = 0; m < unsigned(retType.getStruct()->size()); ++m) {
  3116. const TType memberType(retType, m); // dereferenced type of the member we're about to assign.
  3117. // Check for bad struct members. This should have been caught upstream. Complain, because
  3118. // wwe don't know what to do with it. This algorithm could be generalized to handle
  3119. // other things, e.g, sub-structures, but HLSL doesn't allow them.
  3120. if (!memberType.isVector() && !memberType.isScalar()) {
  3121. error(loc, "expected: scalar or vector type in texture structure", "", "");
  3122. return nullptr;
  3123. }
  3124. // Index into the struct variable to find the member to assign.
  3125. TIntermTyped* structMember = intermediate.addIndex(EOpIndexDirectStruct,
  3126. intermediate.addSymbol(*structVar, loc),
  3127. intermediate.addConstantUnion(m, loc), loc);
  3128. structMember->setType(memberType);
  3129. // Assign each component of (possible) vector in struct member.
  3130. for (int component = 0; component < memberType.getVectorSize(); ++component) {
  3131. TIntermTyped* vec4Member = intermediate.addIndex(EOpIndexDirect,
  3132. intermediate.addSymbol(*sampleShadow, loc),
  3133. intermediate.addConstantUnion(vec4Pos++, loc), loc);
  3134. vec4Member->setType(TType(memberType.getBasicType(), EvqTemporary, 1));
  3135. TIntermTyped* memberAssign = nullptr;
  3136. if (memberType.isVector()) {
  3137. // Vector member: we need to create an access chain to the vector component.
  3138. TIntermTyped* structVecComponent = intermediate.addIndex(EOpIndexDirect, structMember,
  3139. intermediate.addConstantUnion(component, loc), loc);
  3140. memberAssign = intermediate.addAssign(EOpAssign, structVecComponent, vec4Member, loc);
  3141. } else {
  3142. // Scalar member: we can assign to it directly.
  3143. memberAssign = intermediate.addAssign(EOpAssign, structMember, vec4Member, loc);
  3144. }
  3145. conversionAggregate->getSequence().push_back(memberAssign);
  3146. }
  3147. }
  3148. // Add completed variable so the expression results in the whole struct value we just built.
  3149. conversionAggregate->getSequence().push_back(intermediate.addSymbol(*structVar, loc));
  3150. // Make it a sequence.
  3151. intermediate.setAggregateOperator(conversionAggregate, EOpSequence, retType, loc);
  3152. } else {
  3153. // vector clamp the output if template vector type is smaller than sample result.
  3154. if (retType.getVectorSize() < node->getVectorSize()) {
  3155. // Too many components. Construct shorter vector from it.
  3156. const TOperator op = intermediate.mapTypeToConstructorOp(retType);
  3157. convertedResult = constructBuiltIn(retType, op, result, loc, false);
  3158. } else {
  3159. // Enough components. Use directly.
  3160. convertedResult = result;
  3161. }
  3162. }
  3163. convertedResult->setLoc(loc);
  3164. return convertedResult;
  3165. };
  3166. const TOperator op = node->getAsOperator()->getOp();
  3167. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3168. // Bail out if not a sampler method.
  3169. // Note though this is odd to do before checking the op, because the op
  3170. // could be something that takes the arguments, and the function in question
  3171. // takes the result of the op. So, this is not the final word.
  3172. if (arguments != nullptr) {
  3173. if (argAggregate == nullptr) {
  3174. if (arguments->getAsTyped()->getBasicType() != EbtSampler)
  3175. return;
  3176. } else {
  3177. if (argAggregate->getSequence().size() == 0 ||
  3178. argAggregate->getSequence()[0] == nullptr ||
  3179. argAggregate->getSequence()[0]->getAsTyped()->getBasicType() != EbtSampler)
  3180. return;
  3181. }
  3182. }
  3183. switch (op) {
  3184. // **** DX9 intrinsics: ****
  3185. case EOpTexture:
  3186. {
  3187. // Texture with ddx & ddy is really gradient form in HLSL
  3188. if (argAggregate->getSequence().size() == 4)
  3189. node->getAsAggregate()->setOperator(EOpTextureGrad);
  3190. break;
  3191. }
  3192. case EOpTextureLod: //is almost EOpTextureBias (only args & operations are different)
  3193. {
  3194. TIntermTyped *argSamp = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3195. TIntermTyped *argCoord = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3196. assert(argCoord->getVectorSize() == 4);
  3197. TIntermTyped *w = intermediate.addConstantUnion(3, loc, true);
  3198. TIntermTyped *argLod = intermediate.addIndex(EOpIndexDirect, argCoord, w, loc);
  3199. TOperator constructOp = EOpNull;
  3200. const TSampler &sampler = argSamp->getType().getSampler();
  3201. int coordSize = 0;
  3202. switch (sampler.dim)
  3203. {
  3204. case Esd1D: constructOp = EOpConstructFloat; coordSize = 1; break; // 1D
  3205. case Esd2D: constructOp = EOpConstructVec2; coordSize = 2; break; // 2D
  3206. case Esd3D: constructOp = EOpConstructVec3; coordSize = 3; break; // 3D
  3207. case EsdCube: constructOp = EOpConstructVec3; coordSize = 3; break; // also 3D
  3208. default:
  3209. break;
  3210. }
  3211. TIntermAggregate *constructCoord = new TIntermAggregate(constructOp);
  3212. constructCoord->getSequence().push_back(argCoord);
  3213. constructCoord->setLoc(loc);
  3214. constructCoord->setType(TType(argCoord->getBasicType(), EvqTemporary, coordSize));
  3215. TIntermAggregate *tex = new TIntermAggregate(EOpTextureLod);
  3216. tex->getSequence().push_back(argSamp); // sampler
  3217. tex->getSequence().push_back(constructCoord); // coordinate
  3218. tex->getSequence().push_back(argLod); // lod
  3219. node = convertReturn(tex, sampler);
  3220. break;
  3221. }
  3222. case EOpTextureBias:
  3223. {
  3224. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
  3225. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
  3226. // HLSL puts bias in W component of coordinate. We extract it and add it to
  3227. // the argument list, instead
  3228. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  3229. TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  3230. TOperator constructOp = EOpNull;
  3231. const TSampler& sampler = arg0->getType().getSampler();
  3232. switch (sampler.dim) {
  3233. case Esd1D: constructOp = EOpConstructFloat; break; // 1D
  3234. case Esd2D: constructOp = EOpConstructVec2; break; // 2D
  3235. case Esd3D: constructOp = EOpConstructVec3; break; // 3D
  3236. case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
  3237. default: break;
  3238. }
  3239. TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
  3240. constructCoord->getSequence().push_back(arg1);
  3241. constructCoord->setLoc(loc);
  3242. // The input vector should never be less than 2, since there's always a bias.
  3243. // The max is for safety, and should be a no-op.
  3244. constructCoord->setType(TType(arg1->getBasicType(), EvqTemporary, std::max(arg1->getVectorSize() - 1, 0)));
  3245. TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
  3246. tex->getSequence().push_back(arg0); // sampler
  3247. tex->getSequence().push_back(constructCoord); // coordinate
  3248. tex->getSequence().push_back(bias); // bias
  3249. node = convertReturn(tex, sampler);
  3250. break;
  3251. }
  3252. // **** DX10 methods: ****
  3253. case EOpMethodSample: // fall through
  3254. case EOpMethodSampleBias: // ...
  3255. {
  3256. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3257. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3258. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3259. TIntermTyped* argBias = nullptr;
  3260. TIntermTyped* argOffset = nullptr;
  3261. const TSampler& sampler = argTex->getType().getSampler();
  3262. int nextArg = 3;
  3263. if (op == EOpMethodSampleBias) // SampleBias has a bias arg
  3264. argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3265. TOperator textureOp = EOpTexture;
  3266. if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
  3267. textureOp = EOpTextureOffset;
  3268. argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
  3269. }
  3270. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3271. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3272. txsample->getSequence().push_back(txcombine);
  3273. txsample->getSequence().push_back(argCoord);
  3274. if (argBias != nullptr)
  3275. txsample->getSequence().push_back(argBias);
  3276. if (argOffset != nullptr)
  3277. txsample->getSequence().push_back(argOffset);
  3278. node = convertReturn(txsample, sampler);
  3279. break;
  3280. }
  3281. case EOpMethodSampleGrad: // ...
  3282. {
  3283. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3284. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3285. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3286. TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
  3287. TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
  3288. TIntermTyped* argOffset = nullptr;
  3289. const TSampler& sampler = argTex->getType().getSampler();
  3290. TOperator textureOp = EOpTextureGrad;
  3291. if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
  3292. textureOp = EOpTextureGradOffset;
  3293. argOffset = argAggregate->getSequence()[5]->getAsTyped();
  3294. }
  3295. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3296. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3297. txsample->getSequence().push_back(txcombine);
  3298. txsample->getSequence().push_back(argCoord);
  3299. txsample->getSequence().push_back(argDDX);
  3300. txsample->getSequence().push_back(argDDY);
  3301. if (argOffset != nullptr)
  3302. txsample->getSequence().push_back(argOffset);
  3303. node = convertReturn(txsample, sampler);
  3304. break;
  3305. }
  3306. case EOpMethodGetDimensions:
  3307. {
  3308. // AST returns a vector of results, which we break apart component-wise into
  3309. // separate values to assign to the HLSL method's outputs, ala:
  3310. // tx . GetDimensions(width, height);
  3311. // float2 sizeQueryTemp = EOpTextureQuerySize
  3312. // width = sizeQueryTemp.X;
  3313. // height = sizeQueryTemp.Y;
  3314. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3315. const TType& texType = argTex->getType();
  3316. assert(texType.getBasicType() == EbtSampler);
  3317. const TSampler& sampler = texType.getSampler();
  3318. const TSamplerDim dim = sampler.dim;
  3319. const bool isImage = sampler.isImage();
  3320. const bool isMs = sampler.isMultiSample();
  3321. const int numArgs = (int)argAggregate->getSequence().size();
  3322. int numDims = 0;
  3323. switch (dim) {
  3324. case Esd1D: numDims = 1; break; // W
  3325. case Esd2D: numDims = 2; break; // W, H
  3326. case Esd3D: numDims = 3; break; // W, H, D
  3327. case EsdCube: numDims = 2; break; // W, H (cube)
  3328. case EsdBuffer: numDims = 1; break; // W (buffers)
  3329. case EsdRect: numDims = 2; break; // W, H (rect)
  3330. default:
  3331. assert(0 && "unhandled texture dimension");
  3332. }
  3333. // Arrayed adds another dimension for the number of array elements
  3334. if (sampler.isArrayed())
  3335. ++numDims;
  3336. // Establish whether the method itself is querying mip levels. This can be false even
  3337. // if the underlying query requires a MIP level, due to the available HLSL method overloads.
  3338. const bool mipQuery = (numArgs > (numDims + 1 + (isMs ? 1 : 0)));
  3339. // Establish whether we must use the LOD form of query (even if the method did not supply a mip level to query).
  3340. // True if:
  3341. // 1. 1D/2D/3D/Cube AND multisample==0 AND NOT image (those can be sent to the non-LOD query)
  3342. // or,
  3343. // 2. There is a LOD (because the non-LOD query cannot be used in that case, per spec)
  3344. const bool mipRequired =
  3345. ((dim == Esd1D || dim == Esd2D || dim == Esd3D || dim == EsdCube) && !isMs && !isImage) || // 1...
  3346. mipQuery; // 2...
  3347. // AST assumes integer return. Will be converted to float if required.
  3348. TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
  3349. sizeQuery->getSequence().push_back(argTex);
  3350. // If we're building an LOD query, add the LOD.
  3351. if (mipRequired) {
  3352. // If the base HLSL query had no MIP level given, use level 0.
  3353. TIntermTyped* queryLod = mipQuery ? argAggregate->getSequence()[1]->getAsTyped() :
  3354. intermediate.addConstantUnion(0, loc, true);
  3355. sizeQuery->getSequence().push_back(queryLod);
  3356. }
  3357. sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
  3358. sizeQuery->setLoc(loc);
  3359. // Return value from size query
  3360. TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
  3361. tempArg->getWritableType().getQualifier().makeTemporary();
  3362. TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
  3363. intermediate.addSymbol(*tempArg, loc),
  3364. sizeQuery, loc);
  3365. // Compound statement for assigning outputs
  3366. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
  3367. // Index of first output parameter
  3368. const int outParamBase = mipQuery ? 2 : 1;
  3369. for (int compNum = 0; compNum < numDims; ++compNum) {
  3370. TIntermTyped* indexedOut = nullptr;
  3371. TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
  3372. if (numDims > 1) {
  3373. TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
  3374. indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
  3375. indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
  3376. indexedOut->setLoc(loc);
  3377. } else {
  3378. indexedOut = sizeQueryReturn;
  3379. }
  3380. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
  3381. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
  3382. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3383. }
  3384. // handle mip level parameter
  3385. if (mipQuery) {
  3386. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3387. TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
  3388. levelsQuery->getSequence().push_back(argTex);
  3389. levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3390. levelsQuery->setLoc(loc);
  3391. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
  3392. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3393. }
  3394. // 2DMS formats query # samples, which needs a different query op
  3395. if (sampler.isMultiSample()) {
  3396. TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
  3397. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3398. samplesQuery->getSequence().push_back(argTex);
  3399. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3400. samplesQuery->setLoc(loc);
  3401. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
  3402. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3403. }
  3404. compoundStatement->setOperator(EOpSequence);
  3405. compoundStatement->setLoc(loc);
  3406. compoundStatement->setType(TType(EbtVoid));
  3407. node = compoundStatement;
  3408. break;
  3409. }
  3410. case EOpMethodSampleCmp: // fall through...
  3411. case EOpMethodSampleCmpLevelZero:
  3412. {
  3413. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3414. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3415. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3416. TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
  3417. TIntermTyped* argOffset = nullptr;
  3418. // Sampler argument should be a sampler.
  3419. if (argSamp->getType().getBasicType() != EbtSampler) {
  3420. error(loc, "expected: sampler type", "", "");
  3421. return;
  3422. }
  3423. // Sampler should be a SamplerComparisonState
  3424. if (! argSamp->getType().getSampler().isShadow()) {
  3425. error(loc, "expected: SamplerComparisonState", "", "");
  3426. return;
  3427. }
  3428. // optional offset value
  3429. if (argAggregate->getSequence().size() > 4)
  3430. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3431. const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
  3432. // AST wants comparison value as one of the texture coordinates
  3433. TOperator constructOp = EOpNull;
  3434. switch (coordDimWithCmpVal) {
  3435. // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
  3436. case 2: constructOp = EOpConstructVec2; break;
  3437. case 3: constructOp = EOpConstructVec3; break;
  3438. case 4: constructOp = EOpConstructVec4; break;
  3439. case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
  3440. default: assert(0); break;
  3441. }
  3442. TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
  3443. coordWithCmp->getSequence().push_back(argCoord);
  3444. if (coordDimWithCmpVal != 5) // cube array shadow is special.
  3445. coordWithCmp->getSequence().push_back(argCmpVal);
  3446. coordWithCmp->setLoc(loc);
  3447. coordWithCmp->setType(TType(argCoord->getBasicType(), EvqTemporary, std::min(coordDimWithCmpVal, 4)));
  3448. TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
  3449. if (argOffset != nullptr)
  3450. textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
  3451. // Create combined sampler & texture op
  3452. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3453. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3454. txsample->getSequence().push_back(txcombine);
  3455. txsample->getSequence().push_back(coordWithCmp);
  3456. if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
  3457. txsample->getSequence().push_back(argCmpVal);
  3458. // the LevelZero form uses 0 as an explicit LOD
  3459. if (op == EOpMethodSampleCmpLevelZero)
  3460. txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
  3461. // Add offset if present
  3462. if (argOffset != nullptr)
  3463. txsample->getSequence().push_back(argOffset);
  3464. txsample->setType(node->getType());
  3465. txsample->setLoc(loc);
  3466. node = txsample;
  3467. break;
  3468. }
  3469. case EOpMethodLoad:
  3470. {
  3471. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3472. TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
  3473. TIntermTyped* argOffset = nullptr;
  3474. TIntermTyped* lodComponent = nullptr;
  3475. TIntermTyped* coordSwizzle = nullptr;
  3476. const TSampler& sampler = argTex->getType().getSampler();
  3477. const bool isMS = sampler.isMultiSample();
  3478. const bool isBuffer = sampler.dim == EsdBuffer;
  3479. const bool isImage = sampler.isImage();
  3480. const TBasicType coordBaseType = argCoord->getType().getBasicType();
  3481. // Last component of coordinate is the mip level, for non-MS. we separate them here:
  3482. if (isMS || isBuffer || isImage) {
  3483. // MS, Buffer, and Image have no LOD
  3484. coordSwizzle = argCoord;
  3485. } else {
  3486. // Extract coordinate
  3487. int swizzleSize = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
  3488. TSwizzleSelectors<TVectorSelector> coordFields;
  3489. for (int i = 0; i < swizzleSize; ++i)
  3490. coordFields.push_back(i);
  3491. TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
  3492. coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
  3493. coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.size()));
  3494. // Extract LOD
  3495. TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.size(), loc, true);
  3496. lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
  3497. lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
  3498. }
  3499. const int numArgs = (int)argAggregate->getSequence().size();
  3500. const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
  3501. // Create texel fetch
  3502. const TOperator fetchOp = (isImage ? EOpImageLoad :
  3503. hasOffset ? EOpTextureFetchOffset :
  3504. EOpTextureFetch);
  3505. TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
  3506. // Build up the fetch
  3507. txfetch->getSequence().push_back(argTex);
  3508. txfetch->getSequence().push_back(coordSwizzle);
  3509. if (isMS) {
  3510. // add 2DMS sample index
  3511. TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
  3512. txfetch->getSequence().push_back(argSampleIdx);
  3513. } else if (isBuffer) {
  3514. // Nothing else to do for buffers.
  3515. } else if (isImage) {
  3516. // Nothing else to do for images.
  3517. } else {
  3518. // 2DMS and buffer have no LOD, but everything else does.
  3519. txfetch->getSequence().push_back(lodComponent);
  3520. }
  3521. // Obtain offset arg, if there is one.
  3522. if (hasOffset) {
  3523. const int offsetPos = (isMS ? 3 : 2);
  3524. argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
  3525. txfetch->getSequence().push_back(argOffset);
  3526. }
  3527. node = convertReturn(txfetch, sampler);
  3528. break;
  3529. }
  3530. case EOpMethodSampleLevel:
  3531. {
  3532. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3533. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3534. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3535. TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
  3536. TIntermTyped* argOffset = nullptr;
  3537. const TSampler& sampler = argTex->getType().getSampler();
  3538. const int numArgs = (int)argAggregate->getSequence().size();
  3539. if (numArgs == 5) // offset, if present
  3540. argOffset = argAggregate->getSequence()[4]->getAsTyped();
  3541. const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
  3542. TIntermAggregate* txsample = new TIntermAggregate(textureOp);
  3543. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3544. txsample->getSequence().push_back(txcombine);
  3545. txsample->getSequence().push_back(argCoord);
  3546. txsample->getSequence().push_back(argLod);
  3547. if (argOffset != nullptr)
  3548. txsample->getSequence().push_back(argOffset);
  3549. node = convertReturn(txsample, sampler);
  3550. break;
  3551. }
  3552. case EOpMethodGather:
  3553. {
  3554. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3555. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3556. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3557. TIntermTyped* argOffset = nullptr;
  3558. // Offset is optional
  3559. if (argAggregate->getSequence().size() > 3)
  3560. argOffset = argAggregate->getSequence()[3]->getAsTyped();
  3561. const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
  3562. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3563. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3564. txgather->getSequence().push_back(txcombine);
  3565. txgather->getSequence().push_back(argCoord);
  3566. // Offset if not given is implicitly channel 0 (red)
  3567. if (argOffset != nullptr)
  3568. txgather->getSequence().push_back(argOffset);
  3569. txgather->setType(node->getType());
  3570. txgather->setLoc(loc);
  3571. node = txgather;
  3572. break;
  3573. }
  3574. case EOpMethodGatherRed: // fall through...
  3575. case EOpMethodGatherGreen: // ...
  3576. case EOpMethodGatherBlue: // ...
  3577. case EOpMethodGatherAlpha: // ...
  3578. case EOpMethodGatherCmpRed: // ...
  3579. case EOpMethodGatherCmpGreen: // ...
  3580. case EOpMethodGatherCmpBlue: // ...
  3581. case EOpMethodGatherCmpAlpha: // ...
  3582. {
  3583. int channel = 0; // the channel we are gathering
  3584. int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
  3585. switch (op) {
  3586. case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
  3587. case EOpMethodGatherRed: channel = 0; break;
  3588. case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
  3589. case EOpMethodGatherGreen: channel = 1; break;
  3590. case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
  3591. case EOpMethodGatherBlue: channel = 2; break;
  3592. case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
  3593. case EOpMethodGatherAlpha: channel = 3; break;
  3594. default: assert(0); break;
  3595. }
  3596. // For now, we have nothing to map the component-wise comparison forms
  3597. // to, because neither GLSL nor SPIR-V has such an opcode. Issue an
  3598. // unimplemented error instead. Most of the machinery is here if that
  3599. // should ever become available. However, red can be passed through
  3600. // to OpImageDrefGather. G/B/A cannot, because that opcode does not
  3601. // accept a component.
  3602. if (cmpValues != 0 && op != EOpMethodGatherCmpRed) {
  3603. error(loc, "unimplemented: component-level gather compare", "", "");
  3604. return;
  3605. }
  3606. int arg = 0;
  3607. TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
  3608. TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
  3609. TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
  3610. TIntermTyped* argOffset = nullptr;
  3611. TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
  3612. // TIntermTyped* argStatus = nullptr; // TODO: residency
  3613. TIntermTyped* argCmp = nullptr;
  3614. const TSamplerDim dim = argTex->getType().getSampler().dim;
  3615. const int argSize = (int)argAggregate->getSequence().size();
  3616. bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
  3617. bool hasOffset1 = false;
  3618. bool hasOffset4 = false;
  3619. // Sampler argument should be a sampler.
  3620. if (argSamp->getType().getBasicType() != EbtSampler) {
  3621. error(loc, "expected: sampler type", "", "");
  3622. return;
  3623. }
  3624. // Cmp forms require SamplerComparisonState
  3625. if (cmpValues > 0 && ! argSamp->getType().getSampler().isShadow()) {
  3626. error(loc, "expected: SamplerComparisonState", "", "");
  3627. return;
  3628. }
  3629. // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
  3630. if (dim == Esd2D) {
  3631. hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
  3632. hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
  3633. }
  3634. assert(!(hasOffset1 && hasOffset4));
  3635. TOperator textureOp = EOpTextureGather;
  3636. // Compare forms have compare value
  3637. if (cmpValues != 0)
  3638. argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3639. // Some forms have single offset
  3640. if (hasOffset1) {
  3641. textureOp = EOpTextureGatherOffset; // single offset form
  3642. argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
  3643. }
  3644. // Some forms have 4 gather offsets
  3645. if (hasOffset4) {
  3646. textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
  3647. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3648. argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
  3649. }
  3650. // Residency status
  3651. if (hasStatus) {
  3652. // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
  3653. error(loc, "unimplemented: residency status", "", "");
  3654. return;
  3655. }
  3656. TIntermAggregate* txgather = new TIntermAggregate(textureOp);
  3657. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3658. TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
  3659. txgather->getSequence().push_back(txcombine);
  3660. txgather->getSequence().push_back(argCoord);
  3661. // AST wants an array of 4 offsets, where HLSL has separate args. Here
  3662. // we construct an array from the separate args.
  3663. if (hasOffset4) {
  3664. TType arrayType(EbtInt, EvqTemporary, 2);
  3665. TArraySizes* arraySizes = new TArraySizes;
  3666. arraySizes->addInnerSize(4);
  3667. arrayType.transferArraySizes(arraySizes);
  3668. TIntermAggregate* initList = new TIntermAggregate(EOpNull);
  3669. for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
  3670. initList->getSequence().push_back(argOffsets[offsetNum]);
  3671. argOffset = addConstructor(loc, initList, arrayType);
  3672. }
  3673. // Add comparison value if we have one
  3674. if (argCmp != nullptr)
  3675. txgather->getSequence().push_back(argCmp);
  3676. // Add offset (either 1, or an array of 4) if we have one
  3677. if (argOffset != nullptr)
  3678. txgather->getSequence().push_back(argOffset);
  3679. // Add channel value if the sampler is not shadow
  3680. if (! argSamp->getType().getSampler().isShadow())
  3681. txgather->getSequence().push_back(argChannel);
  3682. txgather->setType(node->getType());
  3683. txgather->setLoc(loc);
  3684. node = txgather;
  3685. break;
  3686. }
  3687. case EOpMethodCalculateLevelOfDetail:
  3688. case EOpMethodCalculateLevelOfDetailUnclamped:
  3689. {
  3690. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3691. TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
  3692. TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
  3693. TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
  3694. TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
  3695. txquerylod->getSequence().push_back(txcombine);
  3696. txquerylod->getSequence().push_back(argCoord);
  3697. TIntermTyped* lodComponent = intermediate.addConstantUnion(
  3698. op == EOpMethodCalculateLevelOfDetail ? 0 : 1,
  3699. loc, true);
  3700. TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
  3701. lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
  3702. node = lodComponentIdx;
  3703. break;
  3704. }
  3705. case EOpMethodGetSamplePosition:
  3706. {
  3707. // TODO: this entire decomposition exists because there is not yet a way to query
  3708. // the sample position directly through SPIR-V. Instead, we return fixed sample
  3709. // positions for common cases. *** If the sample positions are set differently,
  3710. // this will be wrong. ***
  3711. TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
  3712. TIntermTyped* argSampIdx = argAggregate->getSequence()[1]->getAsTyped();
  3713. TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
  3714. samplesQuery->getSequence().push_back(argTex);
  3715. samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
  3716. samplesQuery->setLoc(loc);
  3717. TIntermAggregate* compoundStatement = nullptr;
  3718. TVariable* outSampleCount = makeInternalVariable("@sampleCount", TType(EbtUint));
  3719. outSampleCount->getWritableType().getQualifier().makeTemporary();
  3720. TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, intermediate.addSymbol(*outSampleCount, loc),
  3721. samplesQuery, loc);
  3722. compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
  3723. TIntermTyped* idxtest[4];
  3724. // Create tests against 2, 4, 8, and 16 sample values
  3725. int count = 0;
  3726. for (int val = 2; val <= 16; val *= 2)
  3727. idxtest[count++] =
  3728. intermediate.addBinaryNode(EOpEqual,
  3729. intermediate.addSymbol(*outSampleCount, loc),
  3730. intermediate.addConstantUnion(val, loc),
  3731. loc, TType(EbtBool));
  3732. const TOperator idxOp = (argSampIdx->getQualifier().storage == EvqConst) ? EOpIndexDirect : EOpIndexIndirect;
  3733. // Create index ops into position arrays given sample index.
  3734. // TODO: should it be clamped?
  3735. TIntermTyped* index[4];
  3736. count = 0;
  3737. for (int val = 2; val <= 16; val *= 2) {
  3738. index[count] = intermediate.addIndex(idxOp, getSamplePosArray(val), argSampIdx, loc);
  3739. index[count++]->setType(TType(EbtFloat, EvqTemporary, 2));
  3740. }
  3741. // Create expression as:
  3742. // (sampleCount == 2) ? pos2[idx] :
  3743. // (sampleCount == 4) ? pos4[idx] :
  3744. // (sampleCount == 8) ? pos8[idx] :
  3745. // (sampleCount == 16) ? pos16[idx] : float2(0,0);
  3746. TIntermTyped* test =
  3747. intermediate.addSelection(idxtest[0], index[0],
  3748. intermediate.addSelection(idxtest[1], index[1],
  3749. intermediate.addSelection(idxtest[2], index[2],
  3750. intermediate.addSelection(idxtest[3], index[3],
  3751. getSamplePosArray(1), loc), loc), loc), loc);
  3752. compoundStatement = intermediate.growAggregate(compoundStatement, test);
  3753. compoundStatement->setOperator(EOpSequence);
  3754. compoundStatement->setLoc(loc);
  3755. compoundStatement->setType(TType(EbtFloat, EvqTemporary, 2));
  3756. node = compoundStatement;
  3757. break;
  3758. }
  3759. case EOpSubpassLoad:
  3760. {
  3761. const TIntermTyped* argSubpass =
  3762. argAggregate ? argAggregate->getSequence()[0]->getAsTyped() :
  3763. arguments->getAsTyped();
  3764. const TSampler& sampler = argSubpass->getType().getSampler();
  3765. // subpass load: the multisample form is overloaded. Here, we convert that to
  3766. // the EOpSubpassLoadMS opcode.
  3767. if (argAggregate != nullptr && argAggregate->getSequence().size() > 1)
  3768. node->getAsOperator()->setOp(EOpSubpassLoadMS);
  3769. node = convertReturn(node, sampler);
  3770. break;
  3771. }
  3772. default:
  3773. break; // most pass through unchanged
  3774. }
  3775. }
  3776. //
  3777. // Decompose geometry shader methods
  3778. //
  3779. void HlslParseContext::decomposeGeometryMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3780. {
  3781. if (node == nullptr || !node->getAsOperator())
  3782. return;
  3783. const TOperator op = node->getAsOperator()->getOp();
  3784. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3785. switch (op) {
  3786. case EOpMethodAppend:
  3787. if (argAggregate) {
  3788. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3789. if (language != EShLangGeometry) {
  3790. node = nullptr;
  3791. return;
  3792. }
  3793. TIntermAggregate* sequence = nullptr;
  3794. TIntermAggregate* emit = new TIntermAggregate(EOpEmitVertex);
  3795. emit->setLoc(loc);
  3796. emit->setType(TType(EbtVoid));
  3797. TIntermTyped* data = argAggregate->getSequence()[1]->getAsTyped();
  3798. // This will be patched in finalization during finalizeAppendMethods()
  3799. sequence = intermediate.growAggregate(sequence, data, loc);
  3800. sequence = intermediate.growAggregate(sequence, emit);
  3801. sequence->setOperator(EOpSequence);
  3802. sequence->setLoc(loc);
  3803. sequence->setType(TType(EbtVoid));
  3804. gsAppends.push_back({sequence, loc});
  3805. node = sequence;
  3806. }
  3807. break;
  3808. case EOpMethodRestartStrip:
  3809. {
  3810. // Don't emit these for non-GS stage, since we won't have the gsStreamOutput symbol.
  3811. if (language != EShLangGeometry) {
  3812. node = nullptr;
  3813. return;
  3814. }
  3815. TIntermAggregate* cut = new TIntermAggregate(EOpEndPrimitive);
  3816. cut->setLoc(loc);
  3817. cut->setType(TType(EbtVoid));
  3818. node = cut;
  3819. }
  3820. break;
  3821. default:
  3822. break; // most pass through unchanged
  3823. }
  3824. }
  3825. //
  3826. // Optionally decompose intrinsics to AST opcodes.
  3827. //
  3828. void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
  3829. {
  3830. // Helper to find image data for image atomics:
  3831. // OpImageLoad(image[idx])
  3832. // We take the image load apart and add its params to the atomic op aggregate node
  3833. const auto imageAtomicParams = [this, &loc, &node](TIntermAggregate* atomic, TIntermTyped* load) {
  3834. TIntermAggregate* loadOp = load->getAsAggregate();
  3835. if (loadOp == nullptr) {
  3836. error(loc, "unknown image type in atomic operation", "", "");
  3837. node = nullptr;
  3838. return;
  3839. }
  3840. atomic->getSequence().push_back(loadOp->getSequence()[0]);
  3841. atomic->getSequence().push_back(loadOp->getSequence()[1]);
  3842. };
  3843. // Return true if this is an imageLoad, which we will change to an image atomic.
  3844. const auto isImageParam = [](TIntermTyped* image) -> bool {
  3845. TIntermAggregate* imageAggregate = image->getAsAggregate();
  3846. return imageAggregate != nullptr && imageAggregate->getOp() == EOpImageLoad;
  3847. };
  3848. const auto lookupBuiltinVariable = [&](const char* name, TBuiltInVariable builtin, TType& type) -> TIntermTyped* {
  3849. TSymbol* symbol = symbolTable.find(name);
  3850. if (nullptr == symbol) {
  3851. type.getQualifier().builtIn = builtin;
  3852. TVariable* variable = new TVariable(NewPoolTString(name), type);
  3853. symbolTable.insert(*variable);
  3854. symbol = symbolTable.find(name);
  3855. assert(symbol && "Inserted symbol could not be found!");
  3856. }
  3857. return intermediate.addSymbol(*(symbol->getAsVariable()), loc);
  3858. };
  3859. // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
  3860. // opcodes for compatibility with existing software stacks.
  3861. static const bool decomposeHlslIntrinsics = true;
  3862. if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
  3863. return;
  3864. const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
  3865. TIntermUnary* fnUnary = node->getAsUnaryNode();
  3866. const TOperator op = node->getAsOperator()->getOp();
  3867. switch (op) {
  3868. case EOpGenMul:
  3869. {
  3870. // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
  3871. // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
  3872. // we must reverse the operand order here. Hence, arg0 gets sequence[1], etc.
  3873. TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
  3874. TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
  3875. if (arg0->isVector() && arg1->isVector()) { // vec * vec
  3876. node->getAsAggregate()->setOperator(EOpDot);
  3877. } else {
  3878. node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
  3879. }
  3880. break;
  3881. }
  3882. case EOpRcp:
  3883. {
  3884. // rcp(a) -> 1 / a
  3885. TIntermTyped* arg0 = fnUnary->getOperand();
  3886. TBasicType type0 = arg0->getBasicType();
  3887. TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
  3888. node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
  3889. break;
  3890. }
  3891. case EOpAny: // fall through
  3892. case EOpAll:
  3893. {
  3894. TIntermTyped* typedArg = arguments->getAsTyped();
  3895. // HLSL allows float/etc types here, and the SPIR-V opcode requires a bool.
  3896. // We'll convert here. Note that for efficiency, we could add a smarter
  3897. // decomposition for some type cases, e.g, maybe by decomposing a dot product.
  3898. if (typedArg->getType().getBasicType() != EbtBool) {
  3899. const TType boolType(EbtBool, EvqTemporary,
  3900. typedArg->getVectorSize(),
  3901. typedArg->getMatrixCols(),
  3902. typedArg->getMatrixRows(),
  3903. typedArg->isVector());
  3904. typedArg = intermediate.addConversion(EOpConstructBool, boolType, typedArg);
  3905. node->getAsUnaryNode()->setOperand(typedArg);
  3906. }
  3907. break;
  3908. }
  3909. case EOpSaturate:
  3910. {
  3911. // saturate(a) -> clamp(a,0,1)
  3912. TIntermTyped* arg0 = fnUnary->getOperand();
  3913. TBasicType type0 = arg0->getBasicType();
  3914. TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
  3915. clamp->getSequence().push_back(arg0);
  3916. clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
  3917. clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
  3918. clamp->setLoc(loc);
  3919. clamp->setType(node->getType());
  3920. clamp->getWritableType().getQualifier().makeTemporary();
  3921. node = clamp;
  3922. break;
  3923. }
  3924. case EOpSinCos:
  3925. {
  3926. // sincos(a,b,c) -> b = sin(a), c = cos(a)
  3927. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  3928. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  3929. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
  3930. TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
  3931. TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
  3932. TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
  3933. TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
  3934. TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
  3935. compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
  3936. compoundStatement->setOperator(EOpSequence);
  3937. compoundStatement->setLoc(loc);
  3938. compoundStatement->setType(TType(EbtVoid));
  3939. node = compoundStatement;
  3940. break;
  3941. }
  3942. case EOpClip:
  3943. {
  3944. // clip(a) -> if (any(a<0)) discard;
  3945. TIntermTyped* arg0 = fnUnary->getOperand();
  3946. TBasicType type0 = arg0->getBasicType();
  3947. TIntermTyped* compareNode = nullptr;
  3948. // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
  3949. if (!arg0->isScalar()) {
  3950. // component-wise compare: a < 0
  3951. TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
  3952. less->getSequence().push_back(arg0);
  3953. less->setLoc(loc);
  3954. // make vec or mat of bool matching dimensions of input
  3955. less->setType(TType(EbtBool, EvqTemporary,
  3956. arg0->getType().getVectorSize(),
  3957. arg0->getType().getMatrixCols(),
  3958. arg0->getType().getMatrixRows(),
  3959. arg0->getType().isVector()));
  3960. // calculate # of components for comparison const
  3961. const int constComponentCount =
  3962. std::max(arg0->getType().getVectorSize(), 1) *
  3963. std::max(arg0->getType().getMatrixCols(), 1) *
  3964. std::max(arg0->getType().getMatrixRows(), 1);
  3965. TConstUnion zero;
  3966. if (arg0->getType().isIntegerDomain())
  3967. zero.setDConst(0);
  3968. else
  3969. zero.setDConst(0.0);
  3970. TConstUnionArray zeros(constComponentCount, zero);
  3971. less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
  3972. compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
  3973. } else {
  3974. TIntermTyped* zero;
  3975. if (arg0->getType().isIntegerDomain())
  3976. zero = intermediate.addConstantUnion(0, loc, true);
  3977. else
  3978. zero = intermediate.addConstantUnion(0.0, type0, loc, true);
  3979. compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
  3980. }
  3981. TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
  3982. node = new TIntermSelection(compareNode, killNode, nullptr);
  3983. node->setLoc(loc);
  3984. break;
  3985. }
  3986. case EOpLog10:
  3987. {
  3988. // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
  3989. TIntermTyped* arg0 = fnUnary->getOperand();
  3990. TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
  3991. TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
  3992. node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
  3993. break;
  3994. }
  3995. case EOpDst:
  3996. {
  3997. // dest.x = 1;
  3998. // dest.y = src0.y * src1.y;
  3999. // dest.z = src0.z;
  4000. // dest.w = src1.w;
  4001. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4002. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4003. TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
  4004. TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
  4005. TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
  4006. TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
  4007. TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
  4008. TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
  4009. TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
  4010. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4011. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4012. dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
  4013. dst->getSequence().push_back(src0z);
  4014. dst->getSequence().push_back(src1w);
  4015. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4016. dst->setLoc(loc);
  4017. node = dst;
  4018. break;
  4019. }
  4020. case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
  4021. case EOpInterlockedMin: // ...
  4022. case EOpInterlockedMax: // ...
  4023. case EOpInterlockedAnd: // ...
  4024. case EOpInterlockedOr: // ...
  4025. case EOpInterlockedXor: // ...
  4026. case EOpInterlockedExchange: // always has output arg
  4027. {
  4028. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4029. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // value
  4030. TIntermTyped* arg2 = nullptr;
  4031. if (argAggregate->getSequence().size() > 2)
  4032. arg2 = argAggregate->getSequence()[2]->getAsTyped();
  4033. const bool isImage = isImageParam(arg0);
  4034. const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
  4035. TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
  4036. atomic->setType(arg0->getType());
  4037. atomic->getWritableType().getQualifier().makeTemporary();
  4038. atomic->setLoc(loc);
  4039. if (isImage) {
  4040. // orig_value = imageAtomicOp(image, loc, data)
  4041. imageAtomicParams(atomic, arg0);
  4042. atomic->getSequence().push_back(arg1);
  4043. if (argAggregate->getSequence().size() > 2) {
  4044. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4045. } else {
  4046. node = atomic; // no assignment needed, as there was no out var.
  4047. }
  4048. } else {
  4049. // Normal memory variable:
  4050. // arg0 = mem, arg1 = data, arg2(optional,out) = orig_value
  4051. if (argAggregate->getSequence().size() > 2) {
  4052. // optional output param is present. return value goes to arg2.
  4053. atomic->getSequence().push_back(arg0);
  4054. atomic->getSequence().push_back(arg1);
  4055. node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
  4056. } else {
  4057. // Set the matching operator. Since output is absent, this is all we need to do.
  4058. node->getAsAggregate()->setOperator(atomicOp);
  4059. node->setType(atomic->getType());
  4060. }
  4061. }
  4062. break;
  4063. }
  4064. case EOpInterlockedCompareExchange:
  4065. {
  4066. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
  4067. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
  4068. TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
  4069. TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
  4070. const bool isImage = isImageParam(arg0);
  4071. TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
  4072. atomic->setLoc(loc);
  4073. atomic->setType(arg2->getType());
  4074. atomic->getWritableType().getQualifier().makeTemporary();
  4075. if (isImage) {
  4076. imageAtomicParams(atomic, arg0);
  4077. } else {
  4078. atomic->getSequence().push_back(arg0);
  4079. }
  4080. atomic->getSequence().push_back(arg1);
  4081. atomic->getSequence().push_back(arg2);
  4082. node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
  4083. break;
  4084. }
  4085. case EOpEvaluateAttributeSnapped:
  4086. {
  4087. // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
  4088. // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
  4089. // iU = (iU<<28)>>28
  4090. // fU = ((float)iU)/16
  4091. // Targets might handle this natively, in which case they can disable
  4092. // decompositions.
  4093. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
  4094. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
  4095. TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
  4096. TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
  4097. handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
  4098. i28);
  4099. TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
  4100. TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
  4101. intermediate.addConversion(EOpConstructFloat,
  4102. TType(EbtFloat, EvqTemporary, 2), iU),
  4103. recip16);
  4104. TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
  4105. interp->getSequence().push_back(arg0);
  4106. interp->getSequence().push_back(floatOffset);
  4107. interp->setLoc(loc);
  4108. interp->setType(arg0->getType());
  4109. interp->getWritableType().getQualifier().makeTemporary();
  4110. node = interp;
  4111. break;
  4112. }
  4113. case EOpLit:
  4114. {
  4115. TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
  4116. TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
  4117. TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
  4118. TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
  4119. // Ambient
  4120. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4121. // Diffuse:
  4122. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4123. TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
  4124. diffuse->getSequence().push_back(n_dot_l);
  4125. diffuse->getSequence().push_back(zero);
  4126. diffuse->setLoc(loc);
  4127. diffuse->setType(TType(EbtFloat));
  4128. dst->getSequence().push_back(diffuse);
  4129. // Specular:
  4130. TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
  4131. min_ndot->getSequence().push_back(n_dot_l);
  4132. min_ndot->getSequence().push_back(n_dot_h);
  4133. min_ndot->setLoc(loc);
  4134. min_ndot->setType(TType(EbtFloat));
  4135. TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
  4136. TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
  4137. dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
  4138. // One:
  4139. dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
  4140. dst->setLoc(loc);
  4141. dst->setType(TType(EbtFloat, EvqTemporary, 4));
  4142. node = dst;
  4143. break;
  4144. }
  4145. case EOpAsDouble:
  4146. {
  4147. // asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
  4148. // first construct a uint64.
  4149. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4150. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4151. if (arg0->getType().isVector()) { // TODO: ...
  4152. error(loc, "double2 conversion not implemented", "asdouble", "");
  4153. break;
  4154. }
  4155. TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
  4156. uint64->getSequence().push_back(arg0);
  4157. uint64->getSequence().push_back(arg1);
  4158. uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
  4159. uint64->setLoc(loc);
  4160. // bitcast uint2 to a double
  4161. TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
  4162. convert->getAsUnaryNode()->setOperand(uint64);
  4163. convert->setLoc(loc);
  4164. convert->setType(TType(EbtDouble, EvqTemporary));
  4165. node = convert;
  4166. break;
  4167. }
  4168. case EOpF16tof32:
  4169. {
  4170. // input uvecN with low 16 bits of each component holding a float16. convert to float32.
  4171. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4172. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  4173. const int vecSize = argValue->getType().getVectorSize();
  4174. TOperator constructOp = EOpNull;
  4175. switch (vecSize) {
  4176. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4177. case 2: constructOp = EOpConstructVec2; break;
  4178. case 3: constructOp = EOpConstructVec3; break;
  4179. case 4: constructOp = EOpConstructVec4; break;
  4180. default: assert(0); break;
  4181. }
  4182. // For scalar case, we don't need to construct another type.
  4183. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4184. if (result) {
  4185. result->setType(TType(EbtFloat, EvqTemporary, vecSize));
  4186. result->setLoc(loc);
  4187. }
  4188. for (int idx = 0; idx < vecSize; ++idx) {
  4189. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4190. TIntermTyped* component = argValue->getType().isVector() ?
  4191. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4192. if (component != argValue)
  4193. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4194. TIntermTyped* unpackOp = new TIntermUnary(EOpUnpackHalf2x16);
  4195. unpackOp->setType(TType(EbtFloat, EvqTemporary, 2));
  4196. unpackOp->getAsUnaryNode()->setOperand(component);
  4197. unpackOp->setLoc(loc);
  4198. TIntermTyped* lowOrder = intermediate.addIndex(EOpIndexDirect, unpackOp, zero, loc);
  4199. if (result != nullptr) {
  4200. result->getSequence().push_back(lowOrder);
  4201. node = result;
  4202. } else {
  4203. node = lowOrder;
  4204. }
  4205. }
  4206. break;
  4207. }
  4208. case EOpF32tof16:
  4209. {
  4210. // input floatN converted to 16 bit float in low order bits of each component of uintN
  4211. TIntermTyped* argValue = node->getAsUnaryNode()->getOperand();
  4212. TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
  4213. const int vecSize = argValue->getType().getVectorSize();
  4214. TOperator constructOp = EOpNull;
  4215. switch (vecSize) {
  4216. case 1: constructOp = EOpNull; break; // direct use, no construct needed
  4217. case 2: constructOp = EOpConstructUVec2; break;
  4218. case 3: constructOp = EOpConstructUVec3; break;
  4219. case 4: constructOp = EOpConstructUVec4; break;
  4220. default: assert(0); break;
  4221. }
  4222. // For scalar case, we don't need to construct another type.
  4223. TIntermAggregate* result = (vecSize > 1) ? new TIntermAggregate(constructOp) : nullptr;
  4224. if (result) {
  4225. result->setType(TType(EbtUint, EvqTemporary, vecSize));
  4226. result->setLoc(loc);
  4227. }
  4228. for (int idx = 0; idx < vecSize; ++idx) {
  4229. TIntermTyped* idxConst = intermediate.addConstantUnion(idx, loc, true);
  4230. TIntermTyped* component = argValue->getType().isVector() ?
  4231. intermediate.addIndex(EOpIndexDirect, argValue, idxConst, loc) : argValue;
  4232. if (component != argValue)
  4233. component->setType(TType(argValue->getBasicType(), EvqTemporary));
  4234. TIntermAggregate* vec2ComponentAndZero = new TIntermAggregate(EOpConstructVec2);
  4235. vec2ComponentAndZero->getSequence().push_back(component);
  4236. vec2ComponentAndZero->getSequence().push_back(zero);
  4237. vec2ComponentAndZero->setType(TType(EbtFloat, EvqTemporary, 2));
  4238. vec2ComponentAndZero->setLoc(loc);
  4239. TIntermTyped* packOp = new TIntermUnary(EOpPackHalf2x16);
  4240. packOp->getAsUnaryNode()->setOperand(vec2ComponentAndZero);
  4241. packOp->setLoc(loc);
  4242. packOp->setType(TType(EbtUint, EvqTemporary));
  4243. if (result != nullptr) {
  4244. result->getSequence().push_back(packOp);
  4245. node = result;
  4246. } else {
  4247. node = packOp;
  4248. }
  4249. }
  4250. break;
  4251. }
  4252. case EOpD3DCOLORtoUBYTE4:
  4253. {
  4254. // ivec4 ( x.zyxw * 255.001953 );
  4255. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4256. TSwizzleSelectors<TVectorSelector> selectors;
  4257. selectors.push_back(2);
  4258. selectors.push_back(1);
  4259. selectors.push_back(0);
  4260. selectors.push_back(3);
  4261. TIntermTyped* swizzleIdx = intermediate.addSwizzle(selectors, loc);
  4262. TIntermTyped* swizzled = intermediate.addIndex(EOpVectorSwizzle, arg0, swizzleIdx, loc);
  4263. swizzled->setType(arg0->getType());
  4264. swizzled->getWritableType().getQualifier().makeTemporary();
  4265. TIntermTyped* conversion = intermediate.addConstantUnion(255.001953f, EbtFloat, loc, true);
  4266. TIntermTyped* rangeConverted = handleBinaryMath(loc, "mul", EOpMul, conversion, swizzled);
  4267. rangeConverted->setType(arg0->getType());
  4268. rangeConverted->getWritableType().getQualifier().makeTemporary();
  4269. node = intermediate.addConversion(EOpConstructInt, TType(EbtInt, EvqTemporary, 4), rangeConverted);
  4270. node->setLoc(loc);
  4271. node->setType(TType(EbtInt, EvqTemporary, 4));
  4272. break;
  4273. }
  4274. case EOpIsFinite:
  4275. {
  4276. // Since OPIsFinite in SPIR-V is only supported with the Kernel capability, we translate
  4277. // it to !isnan && !isinf
  4278. TIntermTyped* arg0 = node->getAsUnaryNode()->getOperand();
  4279. // We'll make a temporary in case the RHS is cmoplex
  4280. TVariable* tempArg = makeInternalVariable("@finitetmp", arg0->getType());
  4281. tempArg->getWritableType().getQualifier().makeTemporary();
  4282. TIntermTyped* tmpArgAssign = intermediate.addAssign(EOpAssign,
  4283. intermediate.addSymbol(*tempArg, loc),
  4284. arg0, loc);
  4285. TIntermAggregate* compoundStatement = intermediate.makeAggregate(tmpArgAssign, loc);
  4286. const TType boolType(EbtBool, EvqTemporary, arg0->getVectorSize(), arg0->getMatrixCols(),
  4287. arg0->getMatrixRows());
  4288. TIntermTyped* isnan = handleUnaryMath(loc, "isnan", EOpIsNan, intermediate.addSymbol(*tempArg, loc));
  4289. isnan->setType(boolType);
  4290. TIntermTyped* notnan = handleUnaryMath(loc, "!", EOpLogicalNot, isnan);
  4291. notnan->setType(boolType);
  4292. TIntermTyped* isinf = handleUnaryMath(loc, "isinf", EOpIsInf, intermediate.addSymbol(*tempArg, loc));
  4293. isinf->setType(boolType);
  4294. TIntermTyped* notinf = handleUnaryMath(loc, "!", EOpLogicalNot, isinf);
  4295. notinf->setType(boolType);
  4296. TIntermTyped* andNode = handleBinaryMath(loc, "and", EOpLogicalAnd, notnan, notinf);
  4297. andNode->setType(boolType);
  4298. compoundStatement = intermediate.growAggregate(compoundStatement, andNode);
  4299. compoundStatement->setOperator(EOpSequence);
  4300. compoundStatement->setLoc(loc);
  4301. compoundStatement->setType(boolType);
  4302. node = compoundStatement;
  4303. break;
  4304. }
  4305. case EOpWaveGetLaneCount:
  4306. {
  4307. // Mapped to gl_SubgroupSize builtin (We preprend @ to the symbol
  4308. // so that it inhabits the symbol table, but has a user-invalid name
  4309. // in-case some source HLSL defined the symbol also).
  4310. TType type(EbtUint, EvqVaryingIn);
  4311. node = lookupBuiltinVariable("@gl_SubgroupSize", EbvSubgroupSize2, type);
  4312. break;
  4313. }
  4314. case EOpWaveGetLaneIndex:
  4315. {
  4316. // Mapped to gl_SubgroupInvocationID builtin (We preprend @ to the
  4317. // symbol so that it inhabits the symbol table, but has a
  4318. // user-invalid name in-case some source HLSL defined the symbol
  4319. // also).
  4320. TType type(EbtUint, EvqVaryingIn);
  4321. node = lookupBuiltinVariable("@gl_SubgroupInvocationID", EbvSubgroupInvocation2, type);
  4322. break;
  4323. }
  4324. case EOpWaveActiveCountBits:
  4325. {
  4326. // Mapped to subgroupBallotBitCount(subgroupBallot()) builtin
  4327. // uvec4 type.
  4328. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4329. // Get the uvec4 return from subgroupBallot().
  4330. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4331. EOpSubgroupBallot, true, arguments, uvec4Type);
  4332. // uint type.
  4333. TType uintType(EbtUint, EvqTemporary);
  4334. node = intermediate.addBuiltInFunctionCall(loc,
  4335. EOpSubgroupBallotBitCount, true, res, uintType);
  4336. break;
  4337. }
  4338. case EOpWavePrefixCountBits:
  4339. {
  4340. // Mapped to subgroupBallotInclusiveBitCount(subgroupBallot())
  4341. // builtin
  4342. // uvec4 type.
  4343. TType uvec4Type(EbtUint, EvqTemporary, 4);
  4344. // Get the uvec4 return from subgroupBallot().
  4345. TIntermTyped* res = intermediate.addBuiltInFunctionCall(loc,
  4346. EOpSubgroupBallot, true, arguments, uvec4Type);
  4347. // uint type.
  4348. TType uintType(EbtUint, EvqTemporary);
  4349. node = intermediate.addBuiltInFunctionCall(loc,
  4350. EOpSubgroupBallotInclusiveBitCount, true, res, uintType);
  4351. break;
  4352. }
  4353. default:
  4354. break; // most pass through unchanged
  4355. }
  4356. }
  4357. //
  4358. // Handle seeing function call syntax in the grammar, which could be any of
  4359. // - .length() method
  4360. // - constructor
  4361. // - a call to a built-in function mapped to an operator
  4362. // - a call to a built-in function that will remain a function call (e.g., texturing)
  4363. // - user function
  4364. // - subroutine call (not implemented yet)
  4365. //
  4366. TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermTyped* arguments)
  4367. {
  4368. TIntermTyped* result = nullptr;
  4369. TOperator op = function->getBuiltInOp();
  4370. if (op != EOpNull) {
  4371. //
  4372. // Then this should be a constructor.
  4373. // Don't go through the symbol table for constructors.
  4374. // Their parameters will be verified algorithmically.
  4375. //
  4376. TType type(EbtVoid); // use this to get the type back
  4377. if (! constructorError(loc, arguments, *function, op, type)) {
  4378. //
  4379. // It's a constructor, of type 'type'.
  4380. //
  4381. result = handleConstructor(loc, arguments, type);
  4382. if (result == nullptr) {
  4383. error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
  4384. return nullptr;
  4385. }
  4386. }
  4387. } else {
  4388. //
  4389. // Find it in the symbol table.
  4390. //
  4391. const TFunction* fnCandidate = nullptr;
  4392. bool builtIn = false;
  4393. int thisDepth = 0;
  4394. // For mat mul, the situation is unusual: we have to compare vector sizes to mat row or col sizes,
  4395. // and clamp the opposite arg. Since that's complex, we farm it off to a separate method.
  4396. // It doesn't naturally fall out of processing an argument at a time in isolation.
  4397. if (function->getName() == "mul")
  4398. addGenMulArgumentConversion(loc, *function, arguments);
  4399. TIntermAggregate* aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4400. // TODO: this needs improvement: there's no way at present to look up a signature in
  4401. // the symbol table for an arbitrary type. This is a temporary hack until that ability exists.
  4402. // It will have false positives, since it doesn't check arg counts or types.
  4403. if (arguments) {
  4404. // Check if first argument is struct buffer type. It may be an aggregate or a symbol, so we
  4405. // look for either case.
  4406. TIntermTyped* arg0 = nullptr;
  4407. if (aggregate && aggregate->getSequence().size() > 0 && aggregate->getSequence()[0])
  4408. arg0 = aggregate->getSequence()[0]->getAsTyped();
  4409. else if (arguments->getAsSymbolNode())
  4410. arg0 = arguments->getAsSymbolNode();
  4411. if (arg0 != nullptr && isStructBufferType(arg0->getType())) {
  4412. static const int methodPrefixSize = sizeof(BUILTIN_PREFIX)-1;
  4413. if (function->getName().length() > methodPrefixSize &&
  4414. isStructBufferMethod(function->getName().substr(methodPrefixSize))) {
  4415. const TString mangle = function->getName() + "(";
  4416. TSymbol* symbol = symbolTable.find(mangle, &builtIn);
  4417. if (symbol)
  4418. fnCandidate = symbol->getAsFunction();
  4419. }
  4420. }
  4421. }
  4422. if (fnCandidate == nullptr)
  4423. fnCandidate = findFunction(loc, *function, builtIn, thisDepth, arguments);
  4424. if (fnCandidate) {
  4425. // This is a declared function that might map to
  4426. // - a built-in operator,
  4427. // - a built-in function not mapped to an operator, or
  4428. // - a user function.
  4429. // turn an implicit member-function resolution into an explicit call
  4430. TString callerName;
  4431. if (thisDepth == 0)
  4432. callerName = fnCandidate->getMangledName();
  4433. else {
  4434. // get the explicit (full) name of the function
  4435. callerName = currentTypePrefix[currentTypePrefix.size() - thisDepth];
  4436. callerName += fnCandidate->getMangledName();
  4437. // insert the implicit calling argument
  4438. pushFrontArguments(intermediate.addSymbol(*getImplicitThis(thisDepth)), arguments);
  4439. }
  4440. // Convert 'in' arguments, so that types match.
  4441. // However, skip those that need expansion, that is covered next.
  4442. if (arguments)
  4443. addInputArgumentConversions(*fnCandidate, arguments);
  4444. // Expand arguments. Some arguments must physically expand to a different set
  4445. // than what the shader declared and passes.
  4446. if (arguments && !builtIn)
  4447. expandArguments(loc, *fnCandidate, arguments);
  4448. // Expansion may have changed the form of arguments
  4449. aggregate = arguments ? arguments->getAsAggregate() : nullptr;
  4450. op = fnCandidate->getBuiltInOp();
  4451. if (builtIn && op != EOpNull) {
  4452. // A function call mapped to a built-in operation.
  4453. result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments,
  4454. fnCandidate->getType());
  4455. if (result == nullptr) {
  4456. error(arguments->getLoc(), " wrong operand type", "Internal Error",
  4457. "built in unary operator function. Type: %s",
  4458. static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
  4459. } else if (result->getAsOperator()) {
  4460. builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
  4461. }
  4462. } else {
  4463. // This is a function call not mapped to built-in operator.
  4464. // It could still be a built-in function, but only if PureOperatorBuiltins == false.
  4465. result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
  4466. TIntermAggregate* call = result->getAsAggregate();
  4467. call->setName(callerName);
  4468. // this is how we know whether the given function is a built-in function or a user-defined function
  4469. // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
  4470. // if builtIn == true, it's definitely a built-in function with EOpNull
  4471. if (! builtIn) {
  4472. call->setUserDefined();
  4473. intermediate.addToCallGraph(infoSink, currentCaller, callerName);
  4474. }
  4475. }
  4476. // for decompositions, since we want to operate on the function node, not the aggregate holding
  4477. // output conversions.
  4478. const TIntermTyped* fnNode = result;
  4479. decomposeStructBufferMethods(loc, result, arguments); // HLSL->AST struct buffer method decompositions
  4480. decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
  4481. decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
  4482. decomposeGeometryMethods(loc, result, arguments); // HLSL->AST geometry method decompositions
  4483. // Create the qualifier list, carried in the AST for the call.
  4484. // Because some arguments expand to multiple arguments, the qualifier list will
  4485. // be longer than the formal parameter list.
  4486. if (result == fnNode && result->getAsAggregate()) {
  4487. TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
  4488. for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
  4489. TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
  4490. if (hasStructBuffCounter(*(*fnCandidate)[i].type)) {
  4491. // add buffer and counter buffer argument qualifier
  4492. qualifierList.push_back(qual);
  4493. qualifierList.push_back(qual);
  4494. } else if (shouldFlatten(*(*fnCandidate)[i].type, (*fnCandidate)[i].type->getQualifier().storage,
  4495. true)) {
  4496. // add structure member expansion
  4497. for (int memb = 0; memb < (int)(*fnCandidate)[i].type->getStruct()->size(); ++memb)
  4498. qualifierList.push_back(qual);
  4499. } else {
  4500. // Normal 1:1 case
  4501. qualifierList.push_back(qual);
  4502. }
  4503. }
  4504. }
  4505. // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
  4506. // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
  4507. // Also, build the qualifier list for user function calls, which are always called with an aggregate.
  4508. // We don't do this is if there has been a decomposition, which will have added its own conversions
  4509. // for output parameters.
  4510. if (result == fnNode && result->getAsAggregate())
  4511. result = addOutputArgumentConversions(*fnCandidate, *result->getAsOperator());
  4512. }
  4513. }
  4514. // generic error recovery
  4515. // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to
  4516. // reduce cascades
  4517. if (result == nullptr)
  4518. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  4519. return result;
  4520. }
  4521. // An initial argument list is difficult: it can be null, or a single node,
  4522. // or an aggregate if more than one argument. Add one to the front, maintaining
  4523. // this lack of uniformity.
  4524. void HlslParseContext::pushFrontArguments(TIntermTyped* front, TIntermTyped*& arguments)
  4525. {
  4526. if (arguments == nullptr)
  4527. arguments = front;
  4528. else if (arguments->getAsAggregate() != nullptr)
  4529. arguments->getAsAggregate()->getSequence().insert(arguments->getAsAggregate()->getSequence().begin(), front);
  4530. else
  4531. arguments = intermediate.growAggregate(front, arguments);
  4532. }
  4533. //
  4534. // HLSL allows mismatched dimensions on vec*mat, mat*vec, vec*vec, and mat*mat. This is a
  4535. // situation not well suited to resolution in intrinsic selection, but we can do so here, since we
  4536. // can look at both arguments insert explicit shape changes if required.
  4537. //
  4538. void HlslParseContext::addGenMulArgumentConversion(const TSourceLoc& loc, TFunction& call, TIntermTyped*& args)
  4539. {
  4540. TIntermAggregate* argAggregate = args ? args->getAsAggregate() : nullptr;
  4541. if (argAggregate == nullptr || argAggregate->getSequence().size() != 2) {
  4542. // It really ought to have two arguments.
  4543. error(loc, "expected: mul arguments", "", "");
  4544. return;
  4545. }
  4546. TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
  4547. TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
  4548. if (arg0->isVector() && arg1->isVector()) {
  4549. // For:
  4550. // vec * vec: it's handled during intrinsic selection, so while we could do it here,
  4551. // we can also ignore it, which is easier.
  4552. } else if (arg0->isVector() && arg1->isMatrix()) {
  4553. // vec * mat: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4554. if (arg0->getVectorSize() < arg1->getMatrixCols()) {
  4555. // vec is smaller, so truncate larger mat dimension
  4556. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4557. 0, arg0->getVectorSize(), arg1->getMatrixRows());
  4558. arg1 = addConstructor(loc, arg1, truncType);
  4559. } else if (arg0->getVectorSize() > arg1->getMatrixCols()) {
  4560. // vec is larger, so truncate vec to mat size
  4561. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4562. arg1->getMatrixCols());
  4563. arg0 = addConstructor(loc, arg0, truncType);
  4564. }
  4565. } else if (arg0->isMatrix() && arg1->isVector()) {
  4566. // mat * vec: we clamp the vec if the mat col is smaller, else clamp the mat col.
  4567. if (arg1->getVectorSize() < arg0->getMatrixRows()) {
  4568. // vec is smaller, so truncate larger mat dimension
  4569. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4570. 0, arg0->getMatrixCols(), arg1->getVectorSize());
  4571. arg0 = addConstructor(loc, arg0, truncType);
  4572. } else if (arg1->getVectorSize() > arg0->getMatrixRows()) {
  4573. // vec is larger, so truncate vec to mat size
  4574. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4575. arg0->getMatrixRows());
  4576. arg1 = addConstructor(loc, arg1, truncType);
  4577. }
  4578. } else if (arg0->isMatrix() && arg1->isMatrix()) {
  4579. // mat * mat: we clamp the smaller inner dimension to match the other matrix size.
  4580. // Remember, HLSL Mrc = GLSL/SPIRV Mcr.
  4581. if (arg0->getMatrixRows() > arg1->getMatrixCols()) {
  4582. const TType truncType(arg0->getBasicType(), arg0->getQualifier().storage, arg0->getQualifier().precision,
  4583. 0, arg0->getMatrixCols(), arg1->getMatrixCols());
  4584. arg0 = addConstructor(loc, arg0, truncType);
  4585. } else if (arg0->getMatrixRows() < arg1->getMatrixCols()) {
  4586. const TType truncType(arg1->getBasicType(), arg1->getQualifier().storage, arg1->getQualifier().precision,
  4587. 0, arg0->getMatrixRows(), arg1->getMatrixRows());
  4588. arg1 = addConstructor(loc, arg1, truncType);
  4589. }
  4590. } else {
  4591. // It's something with scalars: we'll just leave it alone. Function selection will handle it
  4592. // downstream.
  4593. }
  4594. // Warn if we altered one of the arguments
  4595. if (arg0 != argAggregate->getSequence()[0] || arg1 != argAggregate->getSequence()[1])
  4596. warn(loc, "mul() matrix size mismatch", "", "");
  4597. // Put arguments back. (They might be unchanged, in which case this is harmless).
  4598. argAggregate->getSequence()[0] = arg0;
  4599. argAggregate->getSequence()[1] = arg1;
  4600. call[0].type = &arg0->getWritableType();
  4601. call[1].type = &arg1->getWritableType();
  4602. }
  4603. //
  4604. // Add any needed implicit conversions for function-call arguments to input parameters.
  4605. //
  4606. void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermTyped*& arguments)
  4607. {
  4608. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4609. // Replace a single argument with a single argument.
  4610. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4611. if (function.getParamCount() == 1)
  4612. arguments = arg;
  4613. else {
  4614. if (aggregate == nullptr)
  4615. arguments = arg;
  4616. else
  4617. aggregate->getSequence()[paramNum] = arg;
  4618. }
  4619. };
  4620. // Process each argument's conversion
  4621. for (int param = 0; param < function.getParamCount(); ++param) {
  4622. if (! function[param].type->getQualifier().isParamInput())
  4623. continue;
  4624. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4625. // is the single argument itself or its children are the arguments. Only one argument
  4626. // means take 'arguments' itself as the one argument.
  4627. TIntermTyped* arg = function.getParamCount() == 1
  4628. ? arguments->getAsTyped()
  4629. : (aggregate ?
  4630. aggregate->getSequence()[param]->getAsTyped() :
  4631. arguments->getAsTyped());
  4632. if (*function[param].type != arg->getType()) {
  4633. // In-qualified arguments just need an extra node added above the argument to
  4634. // convert to the correct type.
  4635. TIntermTyped* convArg = intermediate.addConversion(EOpFunctionCall, *function[param].type, arg);
  4636. if (convArg != nullptr)
  4637. convArg = intermediate.addUniShapeConversion(EOpFunctionCall, *function[param].type, convArg);
  4638. if (convArg != nullptr)
  4639. setArg(param, convArg);
  4640. else
  4641. error(arg->getLoc(), "cannot convert input argument, argument", "", "%d", param);
  4642. } else {
  4643. if (wasFlattened(arg)) {
  4644. // If both formal and calling arg are to be flattened, leave that to argument
  4645. // expansion, not conversion.
  4646. if (!shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4647. // Will make a two-level subtree.
  4648. // The deepest will copy member-by-member to build the structure to pass.
  4649. // The level above that will be a two-operand EOpComma sequence that follows the copy by the
  4650. // object itself.
  4651. TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[param].type);
  4652. internalAggregate->getWritableType().getQualifier().makeTemporary();
  4653. TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
  4654. internalAggregate->getName(),
  4655. internalAggregate->getType());
  4656. internalSymbolNode->setLoc(arg->getLoc());
  4657. // This makes the deepest level, the member-wise copy
  4658. TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign,
  4659. internalSymbolNode, arg)->getAsAggregate();
  4660. // Now, pair that with the resulting aggregate.
  4661. assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
  4662. assignAgg->setOperator(EOpComma);
  4663. assignAgg->setType(internalAggregate->getType());
  4664. setArg(param, assignAgg);
  4665. }
  4666. }
  4667. }
  4668. }
  4669. }
  4670. //
  4671. // Add any needed implicit expansion of calling arguments from what the shader listed to what's
  4672. // internally needed for the AST (given the constraints downstream).
  4673. //
  4674. void HlslParseContext::expandArguments(const TSourceLoc& loc, const TFunction& function, TIntermTyped*& arguments)
  4675. {
  4676. TIntermAggregate* aggregate = arguments->getAsAggregate();
  4677. int functionParamNumberOffset = 0;
  4678. // Replace a single argument with a single argument.
  4679. const auto setArg = [&](int paramNum, TIntermTyped* arg) {
  4680. if (function.getParamCount() + functionParamNumberOffset == 1)
  4681. arguments = arg;
  4682. else {
  4683. if (aggregate == nullptr)
  4684. arguments = arg;
  4685. else
  4686. aggregate->getSequence()[paramNum] = arg;
  4687. }
  4688. };
  4689. // Replace a single argument with a list of arguments
  4690. const auto setArgList = [&](int paramNum, const TVector<TIntermTyped*>& args) {
  4691. if (args.size() == 1)
  4692. setArg(paramNum, args.front());
  4693. else if (args.size() > 1) {
  4694. if (function.getParamCount() + functionParamNumberOffset == 1) {
  4695. arguments = intermediate.makeAggregate(args.front());
  4696. std::for_each(args.begin() + 1, args.end(),
  4697. [&](TIntermTyped* arg) {
  4698. arguments = intermediate.growAggregate(arguments, arg);
  4699. });
  4700. } else {
  4701. auto it = aggregate->getSequence().erase(aggregate->getSequence().begin() + paramNum);
  4702. aggregate->getSequence().insert(it, args.begin(), args.end());
  4703. }
  4704. functionParamNumberOffset += (int)(args.size() - 1);
  4705. }
  4706. };
  4707. // Process each argument's conversion
  4708. for (int param = 0; param < function.getParamCount(); ++param) {
  4709. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  4710. // is the single argument itself or its children are the arguments. Only one argument
  4711. // means take 'arguments' itself as the one argument.
  4712. TIntermTyped* arg = function.getParamCount() == 1
  4713. ? arguments->getAsTyped()
  4714. : (aggregate ?
  4715. aggregate->getSequence()[param + functionParamNumberOffset]->getAsTyped() :
  4716. arguments->getAsTyped());
  4717. if (wasFlattened(arg) && shouldFlatten(*function[param].type, function[param].type->getQualifier().storage, true)) {
  4718. // Need to pass the structure members instead of the structure.
  4719. TVector<TIntermTyped*> memberArgs;
  4720. for (int memb = 0; memb < (int)arg->getType().getStruct()->size(); ++memb)
  4721. memberArgs.push_back(flattenAccess(arg, memb));
  4722. setArgList(param + functionParamNumberOffset, memberArgs);
  4723. }
  4724. }
  4725. // TODO: if we need both hidden counter args (below) and struct expansion (above)
  4726. // the two algorithms need to be merged: Each assumes the list starts out 1:1 between
  4727. // parameters and arguments.
  4728. // If any argument is a pass-by-reference struct buffer with an associated counter
  4729. // buffer, we have to add another hidden parameter for that counter.
  4730. if (aggregate)
  4731. addStructBuffArguments(loc, aggregate);
  4732. }
  4733. //
  4734. // Add any needed implicit output conversions for function-call arguments. This
  4735. // can require a new tree topology, complicated further by whether the function
  4736. // has a return value.
  4737. //
  4738. // Returns a node of a subtree that evaluates to the return value of the function.
  4739. //
  4740. TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermOperator& intermNode)
  4741. {
  4742. assert (intermNode.getAsAggregate() != nullptr || intermNode.getAsUnaryNode() != nullptr);
  4743. const TSourceLoc& loc = intermNode.getLoc();
  4744. TIntermSequence argSequence; // temp sequence for unary node args
  4745. if (intermNode.getAsUnaryNode())
  4746. argSequence.push_back(intermNode.getAsUnaryNode()->getOperand());
  4747. TIntermSequence& arguments = argSequence.empty() ? intermNode.getAsAggregate()->getSequence() : argSequence;
  4748. const auto needsConversion = [&](int argNum) {
  4749. return function[argNum].type->getQualifier().isParamOutput() &&
  4750. (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
  4751. shouldConvertLValue(arguments[argNum]) ||
  4752. wasFlattened(arguments[argNum]->getAsTyped()));
  4753. };
  4754. // Will there be any output conversions?
  4755. bool outputConversions = false;
  4756. for (int i = 0; i < function.getParamCount(); ++i) {
  4757. if (needsConversion(i)) {
  4758. outputConversions = true;
  4759. break;
  4760. }
  4761. }
  4762. if (! outputConversions)
  4763. return &intermNode;
  4764. // Setup for the new tree, if needed:
  4765. //
  4766. // Output conversions need a different tree topology.
  4767. // Out-qualified arguments need a temporary of the correct type, with the call
  4768. // followed by an assignment of the temporary to the original argument:
  4769. // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
  4770. // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
  4771. // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
  4772. TIntermTyped* conversionTree = nullptr;
  4773. TVariable* tempRet = nullptr;
  4774. if (intermNode.getBasicType() != EbtVoid) {
  4775. // do the "tempRet = function(...), " bit from above
  4776. tempRet = makeInternalVariable("tempReturn", intermNode.getType());
  4777. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4778. conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, loc);
  4779. } else
  4780. conversionTree = &intermNode;
  4781. conversionTree = intermediate.makeAggregate(conversionTree);
  4782. // Process each argument's conversion
  4783. for (int i = 0; i < function.getParamCount(); ++i) {
  4784. if (needsConversion(i)) {
  4785. // Out-qualified arguments needing conversion need to use the topology setup above.
  4786. // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
  4787. // Make a temporary for what the function expects the argument to look like.
  4788. TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
  4789. tempArg->getWritableType().getQualifier().makeTemporary();
  4790. TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, loc);
  4791. // This makes the deepest level, the member-wise copy
  4792. TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(),
  4793. tempArgNode);
  4794. tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
  4795. conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
  4796. // replace the argument with another node for the same tempArg variable
  4797. arguments[i] = intermediate.addSymbol(*tempArg, loc);
  4798. }
  4799. }
  4800. // Finalize the tree topology (see bigger comment above).
  4801. if (tempRet) {
  4802. // do the "..., tempRet" bit from above
  4803. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, loc);
  4804. conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, loc);
  4805. }
  4806. conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), loc);
  4807. return conversionTree;
  4808. }
  4809. //
  4810. // Add any needed "hidden" counter buffer arguments for function calls.
  4811. //
  4812. // Modifies the 'aggregate' argument if needed. Otherwise, is no-op.
  4813. //
  4814. void HlslParseContext::addStructBuffArguments(const TSourceLoc& loc, TIntermAggregate*& aggregate)
  4815. {
  4816. // See if there are any SB types with counters.
  4817. const bool hasStructBuffArg =
  4818. std::any_of(aggregate->getSequence().begin(),
  4819. aggregate->getSequence().end(),
  4820. [this](const TIntermNode* node) {
  4821. return (node && node->getAsTyped() != nullptr) && hasStructBuffCounter(node->getAsTyped()->getType());
  4822. });
  4823. // Nothing to do, if we didn't find one.
  4824. if (! hasStructBuffArg)
  4825. return;
  4826. TIntermSequence argsWithCounterBuffers;
  4827. for (int param = 0; param < int(aggregate->getSequence().size()); ++param) {
  4828. argsWithCounterBuffers.push_back(aggregate->getSequence()[param]);
  4829. if (hasStructBuffCounter(aggregate->getSequence()[param]->getAsTyped()->getType())) {
  4830. const TIntermSymbol* blockSym = aggregate->getSequence()[param]->getAsSymbolNode();
  4831. if (blockSym != nullptr) {
  4832. TType counterType;
  4833. counterBufferType(loc, counterType);
  4834. const TString counterBlockName(intermediate.addCounterBufferName(blockSym->getName()));
  4835. TVariable* variable = makeInternalVariable(counterBlockName, counterType);
  4836. // Mark this buffer's counter block as being in use
  4837. structBufferCounter[counterBlockName] = true;
  4838. TIntermSymbol* sym = intermediate.addSymbol(*variable, loc);
  4839. argsWithCounterBuffers.push_back(sym);
  4840. }
  4841. }
  4842. }
  4843. // Swap with the temp list we've built up.
  4844. aggregate->getSequence().swap(argsWithCounterBuffers);
  4845. }
  4846. //
  4847. // Do additional checking of built-in function calls that is not caught
  4848. // by normal semantic checks on argument type, extension tagging, etc.
  4849. //
  4850. // Assumes there has been a semantically correct match to a built-in function prototype.
  4851. //
  4852. void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
  4853. {
  4854. // Set up convenience accessors to the argument(s). There is almost always
  4855. // multiple arguments for the cases below, but when there might be one,
  4856. // check the unaryArg first.
  4857. const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
  4858. const TIntermTyped* unaryArg = nullptr;
  4859. const TIntermTyped* arg0 = nullptr;
  4860. if (callNode.getAsAggregate()) {
  4861. argp = &callNode.getAsAggregate()->getSequence();
  4862. if (argp->size() > 0)
  4863. arg0 = (*argp)[0]->getAsTyped();
  4864. } else {
  4865. assert(callNode.getAsUnaryNode());
  4866. unaryArg = callNode.getAsUnaryNode()->getOperand();
  4867. arg0 = unaryArg;
  4868. }
  4869. const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
  4870. switch (callNode.getOp()) {
  4871. case EOpTextureGather:
  4872. case EOpTextureGatherOffset:
  4873. case EOpTextureGatherOffsets:
  4874. {
  4875. // Figure out which variants are allowed by what extensions,
  4876. // and what arguments must be constant for which situations.
  4877. TString featureString = fnCandidate.getName() + "(...)";
  4878. const char* feature = featureString.c_str();
  4879. int compArg = -1; // track which argument, if any, is the constant component argument
  4880. switch (callNode.getOp()) {
  4881. case EOpTextureGather:
  4882. // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
  4883. // otherwise, need GL_ARB_texture_gather.
  4884. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect ||
  4885. fnCandidate[0].type->getSampler().shadow) {
  4886. if (! fnCandidate[0].type->getSampler().shadow)
  4887. compArg = 2;
  4888. }
  4889. break;
  4890. case EOpTextureGatherOffset:
  4891. // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
  4892. if (! fnCandidate[0].type->getSampler().shadow)
  4893. compArg = 3;
  4894. break;
  4895. case EOpTextureGatherOffsets:
  4896. if (! fnCandidate[0].type->getSampler().shadow)
  4897. compArg = 3;
  4898. break;
  4899. default:
  4900. break;
  4901. }
  4902. if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
  4903. if (aggArgs[compArg]->getAsConstantUnion()) {
  4904. int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
  4905. if (value < 0 || value > 3)
  4906. error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
  4907. } else
  4908. error(loc, "must be a compile-time constant:", feature, "component argument");
  4909. }
  4910. break;
  4911. }
  4912. case EOpTextureOffset:
  4913. case EOpTextureFetchOffset:
  4914. case EOpTextureProjOffset:
  4915. case EOpTextureLodOffset:
  4916. case EOpTextureProjLodOffset:
  4917. case EOpTextureGradOffset:
  4918. case EOpTextureProjGradOffset:
  4919. {
  4920. // Handle texture-offset limits checking
  4921. // Pick which argument has to hold constant offsets
  4922. int arg = -1;
  4923. switch (callNode.getOp()) {
  4924. case EOpTextureOffset: arg = 2; break;
  4925. case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
  4926. case EOpTextureProjOffset: arg = 2; break;
  4927. case EOpTextureLodOffset: arg = 3; break;
  4928. case EOpTextureProjLodOffset: arg = 3; break;
  4929. case EOpTextureGradOffset: arg = 4; break;
  4930. case EOpTextureProjGradOffset: arg = 4; break;
  4931. default:
  4932. assert(0);
  4933. break;
  4934. }
  4935. if (arg > 0) {
  4936. if (aggArgs[arg]->getAsConstantUnion() == nullptr)
  4937. error(loc, "argument must be compile-time constant", "texel offset", "");
  4938. else {
  4939. const TType& type = aggArgs[arg]->getAsTyped()->getType();
  4940. for (int c = 0; c < type.getVectorSize(); ++c) {
  4941. int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
  4942. if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
  4943. error(loc, "value is out of range:", "texel offset",
  4944. "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
  4945. }
  4946. }
  4947. }
  4948. break;
  4949. }
  4950. case EOpTextureQuerySamples:
  4951. case EOpImageQuerySamples:
  4952. break;
  4953. case EOpImageAtomicAdd:
  4954. case EOpImageAtomicMin:
  4955. case EOpImageAtomicMax:
  4956. case EOpImageAtomicAnd:
  4957. case EOpImageAtomicOr:
  4958. case EOpImageAtomicXor:
  4959. case EOpImageAtomicExchange:
  4960. case EOpImageAtomicCompSwap:
  4961. break;
  4962. case EOpInterpolateAtCentroid:
  4963. case EOpInterpolateAtSample:
  4964. case EOpInterpolateAtOffset:
  4965. // Make sure the first argument is an interpolant, or an array element of an interpolant
  4966. if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
  4967. // It might still be an array element.
  4968. //
  4969. // We could check more, but the semantics of the first argument are already met; the
  4970. // only way to turn an array into a float/vec* is array dereference and swizzle.
  4971. //
  4972. // ES and desktop 4.3 and earlier: swizzles may not be used
  4973. // desktop 4.4 and later: swizzles may be used
  4974. const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
  4975. if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
  4976. error(loc, "first argument must be an interpolant, or interpolant-array element",
  4977. fnCandidate.getName().c_str(), "");
  4978. }
  4979. break;
  4980. default:
  4981. break;
  4982. }
  4983. }
  4984. //
  4985. // Handle seeing something in a grammar production that can be done by calling
  4986. // a constructor.
  4987. //
  4988. // The constructor still must be "handled" by handleFunctionCall(), which will
  4989. // then call handleConstructor().
  4990. //
  4991. TFunction* HlslParseContext::makeConstructorCall(const TSourceLoc& loc, const TType& type)
  4992. {
  4993. TOperator op = intermediate.mapTypeToConstructorOp(type);
  4994. if (op == EOpNull) {
  4995. error(loc, "cannot construct this type", type.getBasicString(), "");
  4996. return nullptr;
  4997. }
  4998. TString empty("");
  4999. return new TFunction(&empty, type, op);
  5000. }
  5001. //
  5002. // Handle seeing a "COLON semantic" at the end of a type declaration,
  5003. // by updating the type according to the semantic.
  5004. //
  5005. void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, TBuiltInVariable builtIn,
  5006. const TString& upperCase)
  5007. {
  5008. // Parse and return semantic number. If limit is 0, it will be ignored. Otherwise, if the parsed
  5009. // semantic number is >= limit, errorMsg is issued and 0 is returned.
  5010. // TODO: it would be nicer if limit and errorMsg had default parameters, but some compilers don't yet
  5011. // accept those in lambda functions.
  5012. const auto getSemanticNumber = [this, loc](const TString& semantic, unsigned int limit, const char* errorMsg) -> unsigned int {
  5013. size_t pos = semantic.find_last_not_of("0123456789");
  5014. if (pos == std::string::npos)
  5015. return 0u;
  5016. unsigned int semanticNum = (unsigned int)atoi(semantic.c_str() + pos + 1);
  5017. if (limit != 0 && semanticNum >= limit) {
  5018. error(loc, errorMsg, semantic.c_str(), "");
  5019. return 0u;
  5020. }
  5021. return semanticNum;
  5022. };
  5023. switch(builtIn) {
  5024. case EbvNone:
  5025. // Get location numbers from fragment outputs, instead of
  5026. // auto-assigning them.
  5027. if (language == EShLangFragment && upperCase.compare(0, 9, "SV_TARGET") == 0) {
  5028. qualifier.layoutLocation = getSemanticNumber(upperCase, 0, nullptr);
  5029. nextOutLocation = std::max(nextOutLocation, qualifier.layoutLocation + 1u);
  5030. } else if (upperCase.compare(0, 15, "SV_CLIPDISTANCE") == 0) {
  5031. builtIn = EbvClipDistance;
  5032. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid clip semantic");
  5033. } else if (upperCase.compare(0, 15, "SV_CULLDISTANCE") == 0) {
  5034. builtIn = EbvCullDistance;
  5035. qualifier.layoutLocation = getSemanticNumber(upperCase, maxClipCullRegs, "invalid cull semantic");
  5036. }
  5037. break;
  5038. case EbvPosition:
  5039. // adjust for stage in/out
  5040. if (language == EShLangFragment)
  5041. builtIn = EbvFragCoord;
  5042. break;
  5043. case EbvFragStencilRef:
  5044. error(loc, "unimplemented; need ARB_shader_stencil_export", "SV_STENCILREF", "");
  5045. break;
  5046. case EbvTessLevelInner:
  5047. case EbvTessLevelOuter:
  5048. qualifier.patch = true;
  5049. break;
  5050. default:
  5051. break;
  5052. }
  5053. if (qualifier.builtIn == EbvNone)
  5054. qualifier.builtIn = builtIn;
  5055. qualifier.semanticName = intermediate.addSemanticName(upperCase);
  5056. }
  5057. //
  5058. // Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
  5059. //
  5060. // 'location' has the "c[Subcomponent]" part.
  5061. // 'component' points to the "component" part, or nullptr if not present.
  5062. //
  5063. void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
  5064. const glslang::TString* component)
  5065. {
  5066. if (location.size() == 0 || location[0] != 'c') {
  5067. error(loc, "expected 'c'", "packoffset", "");
  5068. return;
  5069. }
  5070. if (location.size() == 1)
  5071. return;
  5072. if (! isdigit(location[1])) {
  5073. error(loc, "expected number after 'c'", "packoffset", "");
  5074. return;
  5075. }
  5076. qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
  5077. if (component != nullptr) {
  5078. int componentOffset = 0;
  5079. switch ((*component)[0]) {
  5080. case 'x': componentOffset = 0; break;
  5081. case 'y': componentOffset = 4; break;
  5082. case 'z': componentOffset = 8; break;
  5083. case 'w': componentOffset = 12; break;
  5084. default:
  5085. componentOffset = -1;
  5086. break;
  5087. }
  5088. if (componentOffset < 0 || component->size() > 1) {
  5089. error(loc, "expected {x, y, z, w} for component", "packoffset", "");
  5090. return;
  5091. }
  5092. qualifier.layoutOffset += componentOffset;
  5093. }
  5094. }
  5095. //
  5096. // Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
  5097. //
  5098. // 'profile' points to the shader_profile part, or nullptr if not present.
  5099. // 'desc' is the type# part.
  5100. //
  5101. void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
  5102. const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
  5103. {
  5104. if (profile != nullptr)
  5105. warn(loc, "ignoring shader_profile", "register", "");
  5106. if (desc.size() < 1) {
  5107. error(loc, "expected register type", "register", "");
  5108. return;
  5109. }
  5110. int regNumber = 0;
  5111. if (desc.size() > 1) {
  5112. if (isdigit(desc[1]))
  5113. regNumber = atoi(desc.substr(1, desc.size()).c_str());
  5114. else {
  5115. error(loc, "expected register number after register type", "register", "");
  5116. return;
  5117. }
  5118. }
  5119. // more information about register types see
  5120. // https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-variable-register
  5121. const std::vector<std::string>& resourceInfo = intermediate.getResourceSetBinding();
  5122. switch (std::tolower(desc[0])) {
  5123. case 'c':
  5124. // c register is the register slot in the global const buffer
  5125. // each slot is a vector of 4 32 bit components
  5126. qualifier.layoutOffset = regNumber * 4 * 4;
  5127. break;
  5128. // const buffer register slot
  5129. case 'b':
  5130. // textrues and structured buffers
  5131. case 't':
  5132. // samplers
  5133. case 's':
  5134. // uav resources
  5135. case 'u':
  5136. // if nothing else has set the binding, do so now
  5137. // (other mechanisms override this one)
  5138. if (!qualifier.hasBinding())
  5139. qualifier.layoutBinding = regNumber + subComponent;
  5140. // This handles per-register layout sets numbers. For the global mode which sets
  5141. // every symbol to the same value, see setLinkageLayoutSets().
  5142. if ((resourceInfo.size() % 3) == 0) {
  5143. // Apply per-symbol resource set and binding.
  5144. for (auto it = resourceInfo.cbegin(); it != resourceInfo.cend(); it = it + 3) {
  5145. if (strcmp(desc.c_str(), it[0].c_str()) == 0) {
  5146. qualifier.layoutSet = atoi(it[1].c_str());
  5147. qualifier.layoutBinding = atoi(it[2].c_str()) + subComponent;
  5148. break;
  5149. }
  5150. }
  5151. }
  5152. break;
  5153. default:
  5154. warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
  5155. break;
  5156. }
  5157. // space
  5158. unsigned int setNumber;
  5159. const auto crackSpace = [&]() -> bool {
  5160. const int spaceLen = 5;
  5161. if (spaceDesc->size() < spaceLen + 1)
  5162. return false;
  5163. if (spaceDesc->compare(0, spaceLen, "space") != 0)
  5164. return false;
  5165. if (! isdigit((*spaceDesc)[spaceLen]))
  5166. return false;
  5167. setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
  5168. return true;
  5169. };
  5170. // if nothing else has set the set, do so now
  5171. // (other mechanisms override this one)
  5172. if (spaceDesc && !qualifier.hasSet()) {
  5173. if (! crackSpace()) {
  5174. error(loc, "expected spaceN", "register", "");
  5175. return;
  5176. }
  5177. qualifier.layoutSet = setNumber;
  5178. }
  5179. }
  5180. // Convert to a scalar boolean, or if not allowed by HLSL semantics,
  5181. // report an error and return nullptr.
  5182. TIntermTyped* HlslParseContext::convertConditionalExpression(const TSourceLoc& loc, TIntermTyped* condition,
  5183. bool mustBeScalar)
  5184. {
  5185. if (mustBeScalar && !condition->getType().isScalarOrVec1()) {
  5186. error(loc, "requires a scalar", "conditional expression", "");
  5187. return nullptr;
  5188. }
  5189. return intermediate.addConversion(EOpConstructBool, TType(EbtBool, EvqTemporary, condition->getVectorSize()),
  5190. condition);
  5191. }
  5192. //
  5193. // Same error message for all places assignments don't work.
  5194. //
  5195. void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5196. {
  5197. error(loc, "", op, "cannot convert from '%s' to '%s'",
  5198. right.c_str(), left.c_str());
  5199. }
  5200. //
  5201. // Same error message for all places unary operations don't work.
  5202. //
  5203. void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
  5204. {
  5205. error(loc, " wrong operand type", op,
  5206. "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
  5207. op, operand.c_str());
  5208. }
  5209. //
  5210. // Same error message for all binary operations don't work.
  5211. //
  5212. void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
  5213. {
  5214. error(loc, " wrong operand types:", op,
  5215. "no operation '%s' exists that takes a left-hand operand of type '%s' and "
  5216. "a right operand of type '%s' (or there is no acceptable conversion)",
  5217. op, left.c_str(), right.c_str());
  5218. }
  5219. //
  5220. // A basic type of EbtVoid is a key that the name string was seen in the source, but
  5221. // it was not found as a variable in the symbol table. If so, give the error
  5222. // message and insert a dummy variable in the symbol table to prevent future errors.
  5223. //
  5224. void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
  5225. {
  5226. TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
  5227. if (! symbol)
  5228. return;
  5229. if (symbol->getType().getBasicType() == EbtVoid) {
  5230. error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
  5231. // Add to symbol table to prevent future error messages on the same name
  5232. if (symbol->getName().size() > 0) {
  5233. TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
  5234. symbolTable.insert(*fakeVariable);
  5235. // substitute a symbol node for this new variable
  5236. nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
  5237. }
  5238. }
  5239. }
  5240. //
  5241. // Both test, and if necessary spit out an error, to see if the node is really
  5242. // a constant.
  5243. //
  5244. void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
  5245. {
  5246. if (node->getQualifier().storage != EvqConst)
  5247. error(node->getLoc(), "constant expression required", token, "");
  5248. }
  5249. //
  5250. // Both test, and if necessary spit out an error, to see if the node is really
  5251. // an integer.
  5252. //
  5253. void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
  5254. {
  5255. if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
  5256. return;
  5257. error(node->getLoc(), "scalar integer expression required", token, "");
  5258. }
  5259. //
  5260. // Both test, and if necessary spit out an error, to see if we are currently
  5261. // globally scoped.
  5262. //
  5263. void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
  5264. {
  5265. if (! symbolTable.atGlobalLevel())
  5266. error(loc, "not allowed in nested scope", token, "");
  5267. }
  5268. bool HlslParseContext::builtInName(const TString& /*identifier*/)
  5269. {
  5270. return false;
  5271. }
  5272. //
  5273. // Make sure there is enough data and not too many arguments provided to the
  5274. // constructor to build something of the type of the constructor. Also returns
  5275. // the type of the constructor.
  5276. //
  5277. // Returns true if there was an error in construction.
  5278. //
  5279. bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function,
  5280. TOperator op, TType& type)
  5281. {
  5282. type.shallowCopy(function.getType());
  5283. bool constructingMatrix = false;
  5284. switch (op) {
  5285. case EOpConstructTextureSampler:
  5286. error(loc, "unhandled texture constructor", "constructor", "");
  5287. return true;
  5288. case EOpConstructMat2x2:
  5289. case EOpConstructMat2x3:
  5290. case EOpConstructMat2x4:
  5291. case EOpConstructMat3x2:
  5292. case EOpConstructMat3x3:
  5293. case EOpConstructMat3x4:
  5294. case EOpConstructMat4x2:
  5295. case EOpConstructMat4x3:
  5296. case EOpConstructMat4x4:
  5297. case EOpConstructDMat2x2:
  5298. case EOpConstructDMat2x3:
  5299. case EOpConstructDMat2x4:
  5300. case EOpConstructDMat3x2:
  5301. case EOpConstructDMat3x3:
  5302. case EOpConstructDMat3x4:
  5303. case EOpConstructDMat4x2:
  5304. case EOpConstructDMat4x3:
  5305. case EOpConstructDMat4x4:
  5306. case EOpConstructIMat2x2:
  5307. case EOpConstructIMat2x3:
  5308. case EOpConstructIMat2x4:
  5309. case EOpConstructIMat3x2:
  5310. case EOpConstructIMat3x3:
  5311. case EOpConstructIMat3x4:
  5312. case EOpConstructIMat4x2:
  5313. case EOpConstructIMat4x3:
  5314. case EOpConstructIMat4x4:
  5315. case EOpConstructUMat2x2:
  5316. case EOpConstructUMat2x3:
  5317. case EOpConstructUMat2x4:
  5318. case EOpConstructUMat3x2:
  5319. case EOpConstructUMat3x3:
  5320. case EOpConstructUMat3x4:
  5321. case EOpConstructUMat4x2:
  5322. case EOpConstructUMat4x3:
  5323. case EOpConstructUMat4x4:
  5324. case EOpConstructBMat2x2:
  5325. case EOpConstructBMat2x3:
  5326. case EOpConstructBMat2x4:
  5327. case EOpConstructBMat3x2:
  5328. case EOpConstructBMat3x3:
  5329. case EOpConstructBMat3x4:
  5330. case EOpConstructBMat4x2:
  5331. case EOpConstructBMat4x3:
  5332. case EOpConstructBMat4x4:
  5333. constructingMatrix = true;
  5334. break;
  5335. default:
  5336. break;
  5337. }
  5338. //
  5339. // Walk the arguments for first-pass checks and collection of information.
  5340. //
  5341. int size = 0;
  5342. bool constType = true;
  5343. bool full = false;
  5344. bool overFull = false;
  5345. bool matrixInMatrix = false;
  5346. bool arrayArg = false;
  5347. for (int arg = 0; arg < function.getParamCount(); ++arg) {
  5348. if (function[arg].type->isArray()) {
  5349. if (function[arg].type->isUnsizedArray()) {
  5350. // Can't construct from an unsized array.
  5351. error(loc, "array argument must be sized", "constructor", "");
  5352. return true;
  5353. }
  5354. arrayArg = true;
  5355. }
  5356. if (constructingMatrix && function[arg].type->isMatrix())
  5357. matrixInMatrix = true;
  5358. // 'full' will go to true when enough args have been seen. If we loop
  5359. // again, there is an extra argument.
  5360. if (full) {
  5361. // For vectors and matrices, it's okay to have too many components
  5362. // available, but not okay to have unused arguments.
  5363. overFull = true;
  5364. }
  5365. size += function[arg].type->computeNumComponents();
  5366. if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
  5367. full = true;
  5368. if (function[arg].type->getQualifier().storage != EvqConst)
  5369. constType = false;
  5370. }
  5371. if (constType)
  5372. type.getQualifier().storage = EvqConst;
  5373. if (type.isArray()) {
  5374. if (function.getParamCount() == 0) {
  5375. error(loc, "array constructor must have at least one argument", "constructor", "");
  5376. return true;
  5377. }
  5378. if (type.isUnsizedArray()) {
  5379. // auto adapt the constructor type to the number of arguments
  5380. type.changeOuterArraySize(function.getParamCount());
  5381. } else if (type.getOuterArraySize() != function.getParamCount() && type.computeNumComponents() > size) {
  5382. error(loc, "array constructor needs one argument per array element", "constructor", "");
  5383. return true;
  5384. }
  5385. if (type.isArrayOfArrays()) {
  5386. // Types have to match, but we're still making the type.
  5387. // Finish making the type, and the comparison is done later
  5388. // when checking for conversion.
  5389. TArraySizes& arraySizes = *type.getArraySizes();
  5390. // At least the dimensionalities have to match.
  5391. if (! function[0].type->isArray() ||
  5392. arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
  5393. error(loc, "array constructor argument not correct type to construct array element", "constructor", "");
  5394. return true;
  5395. }
  5396. if (arraySizes.isInnerUnsized()) {
  5397. // "Arrays of arrays ..., and the size for any dimension is optional"
  5398. // That means we need to adopt (from the first argument) the other array sizes into the type.
  5399. for (int d = 1; d < arraySizes.getNumDims(); ++d) {
  5400. if (arraySizes.getDimSize(d) == UnsizedArraySize) {
  5401. arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
  5402. }
  5403. }
  5404. }
  5405. }
  5406. }
  5407. // Some array -> array type casts are okay
  5408. if (arrayArg && function.getParamCount() == 1 && op != EOpConstructStruct && type.isArray() &&
  5409. !type.isArrayOfArrays() && !function[0].type->isArrayOfArrays() &&
  5410. type.getVectorSize() >= 1 && function[0].type->getVectorSize() >= 1)
  5411. return false;
  5412. if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
  5413. error(loc, "constructing non-array constituent from array argument", "constructor", "");
  5414. return true;
  5415. }
  5416. if (matrixInMatrix && ! type.isArray()) {
  5417. return false;
  5418. }
  5419. if (overFull) {
  5420. error(loc, "too many arguments", "constructor", "");
  5421. return true;
  5422. }
  5423. if (op == EOpConstructStruct && ! type.isArray()) {
  5424. if (isScalarConstructor(node))
  5425. return false;
  5426. // Self-type construction: e.g, we can construct a struct from a single identically typed object.
  5427. if (function.getParamCount() == 1 && type == *function[0].type)
  5428. return false;
  5429. if ((int)type.getStruct()->size() != function.getParamCount()) {
  5430. error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
  5431. return true;
  5432. }
  5433. }
  5434. if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
  5435. (op == EOpConstructStruct && size < type.computeNumComponents())) {
  5436. error(loc, "not enough data provided for construction", "constructor", "");
  5437. return true;
  5438. }
  5439. return false;
  5440. }
  5441. // See if 'node', in the context of constructing aggregates, is a scalar argument
  5442. // to a constructor.
  5443. //
  5444. bool HlslParseContext::isScalarConstructor(const TIntermNode* node)
  5445. {
  5446. // Obviously, it must be a scalar, but an aggregate node might not be fully
  5447. // completed yet: holding a sequence of initializers under an aggregate
  5448. // would not yet be typed, so don't check it's type. This corresponds to
  5449. // the aggregate operator also not being set yet. (An aggregate operation
  5450. // that legitimately yields a scalar will have a getOp() of that operator,
  5451. // not EOpNull.)
  5452. return node->getAsTyped() != nullptr &&
  5453. node->getAsTyped()->isScalar() &&
  5454. (node->getAsAggregate() == nullptr || node->getAsAggregate()->getOp() != EOpNull);
  5455. }
  5456. // Checks to see if a void variable has been declared and raise an error message for such a case
  5457. //
  5458. // returns true in case of an error
  5459. //
  5460. bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
  5461. {
  5462. if (basicType == EbtVoid) {
  5463. error(loc, "illegal use of type 'void'", identifier.c_str(), "");
  5464. return true;
  5465. }
  5466. return false;
  5467. }
  5468. //
  5469. // Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
  5470. //
  5471. void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
  5472. {
  5473. // move from parameter/unknown qualifiers to pipeline in/out qualifiers
  5474. switch (qualifier.storage) {
  5475. case EvqIn:
  5476. qualifier.storage = EvqVaryingIn;
  5477. break;
  5478. case EvqOut:
  5479. qualifier.storage = EvqVaryingOut;
  5480. break;
  5481. default:
  5482. break;
  5483. }
  5484. }
  5485. //
  5486. // Merge characteristics of the 'src' qualifier into the 'dst'.
  5487. // If there is duplication, issue error messages, unless 'force'
  5488. // is specified, which means to just override default settings.
  5489. //
  5490. // Also, when force is false, it will be assumed that 'src' follows
  5491. // 'dst', for the purpose of error checking order for versions
  5492. // that require specific orderings of qualifiers.
  5493. //
  5494. void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
  5495. {
  5496. // Storage qualification
  5497. if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
  5498. dst.storage = src.storage;
  5499. else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
  5500. (dst.storage == EvqOut && src.storage == EvqIn))
  5501. dst.storage = EvqInOut;
  5502. else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
  5503. (dst.storage == EvqConst && src.storage == EvqIn))
  5504. dst.storage = EvqConstReadOnly;
  5505. // Layout qualifiers
  5506. mergeObjectLayoutQualifiers(dst, src, false);
  5507. // individual qualifiers
  5508. bool repeated = false;
  5509. #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
  5510. MERGE_SINGLETON(invariant);
  5511. MERGE_SINGLETON(noContraction);
  5512. MERGE_SINGLETON(centroid);
  5513. MERGE_SINGLETON(smooth);
  5514. MERGE_SINGLETON(flat);
  5515. MERGE_SINGLETON(nopersp);
  5516. MERGE_SINGLETON(patch);
  5517. MERGE_SINGLETON(sample);
  5518. MERGE_SINGLETON(coherent);
  5519. MERGE_SINGLETON(volatil);
  5520. MERGE_SINGLETON(restrict);
  5521. MERGE_SINGLETON(readonly);
  5522. MERGE_SINGLETON(writeonly);
  5523. MERGE_SINGLETON(specConstant);
  5524. MERGE_SINGLETON(nonUniform);
  5525. }
  5526. // used to flatten the sampler type space into a single dimension
  5527. // correlates with the declaration of defaultSamplerPrecision[]
  5528. int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
  5529. {
  5530. int arrayIndex = sampler.arrayed ? 1 : 0;
  5531. int shadowIndex = sampler.shadow ? 1 : 0;
  5532. int externalIndex = sampler.external ? 1 : 0;
  5533. return EsdNumDims *
  5534. (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
  5535. }
  5536. //
  5537. // Do size checking for an array type's size.
  5538. //
  5539. void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
  5540. {
  5541. bool isConst = false;
  5542. sizePair.size = 1;
  5543. sizePair.node = nullptr;
  5544. TIntermConstantUnion* constant = expr->getAsConstantUnion();
  5545. if (constant) {
  5546. // handle true (non-specialization) constant
  5547. sizePair.size = constant->getConstArray()[0].getIConst();
  5548. isConst = true;
  5549. } else {
  5550. // see if it's a specialization constant instead
  5551. if (expr->getQualifier().isSpecConstant()) {
  5552. isConst = true;
  5553. sizePair.node = expr;
  5554. TIntermSymbol* symbol = expr->getAsSymbolNode();
  5555. if (symbol && symbol->getConstArray().size() > 0)
  5556. sizePair.size = symbol->getConstArray()[0].getIConst();
  5557. }
  5558. }
  5559. if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
  5560. error(loc, "array size must be a constant integer expression", "", "");
  5561. return;
  5562. }
  5563. if (sizePair.size <= 0) {
  5564. error(loc, "array size must be a positive integer", "", "");
  5565. return;
  5566. }
  5567. }
  5568. //
  5569. // Require array to be completely sized
  5570. //
  5571. void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
  5572. {
  5573. if (arraySizes.hasUnsized())
  5574. error(loc, "array size required", "", "");
  5575. }
  5576. void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
  5577. {
  5578. const TTypeList& structure = *type.getStruct();
  5579. for (int m = 0; m < (int)structure.size(); ++m) {
  5580. const TType& member = *structure[m].type;
  5581. if (member.isArray())
  5582. arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
  5583. }
  5584. }
  5585. //
  5586. // Do all the semantic checking for declaring or redeclaring an array, with and
  5587. // without a size, and make the right changes to the symbol table.
  5588. //
  5589. void HlslParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  5590. TSymbol*& symbol, bool track)
  5591. {
  5592. if (symbol == nullptr) {
  5593. bool currentScope;
  5594. symbol = symbolTable.find(identifier, nullptr, &currentScope);
  5595. if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
  5596. // bad shader (errors already reported) trying to redeclare a built-in name as an array
  5597. return;
  5598. }
  5599. if (symbol == nullptr || ! currentScope) {
  5600. //
  5601. // Successfully process a new definition.
  5602. // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
  5603. //
  5604. symbol = new TVariable(&identifier, type);
  5605. symbolTable.insert(*symbol);
  5606. if (track && symbolTable.atGlobalLevel())
  5607. trackLinkage(*symbol);
  5608. return;
  5609. }
  5610. if (symbol->getAsAnonMember()) {
  5611. error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
  5612. symbol = nullptr;
  5613. return;
  5614. }
  5615. }
  5616. //
  5617. // Process a redeclaration.
  5618. //
  5619. if (symbol == nullptr) {
  5620. error(loc, "array variable name expected", identifier.c_str(), "");
  5621. return;
  5622. }
  5623. // redeclareBuiltinVariable() should have already done the copyUp()
  5624. TType& existingType = symbol->getWritableType();
  5625. if (existingType.isSizedArray()) {
  5626. // be more lenient for input arrays to geometry shaders and tessellation control outputs,
  5627. // where the redeclaration is the same size
  5628. return;
  5629. }
  5630. existingType.updateArraySizes(type);
  5631. }
  5632. //
  5633. // Enforce non-initializer type/qualifier rules.
  5634. //
  5635. void HlslParseContext::fixConstInit(const TSourceLoc& loc, const TString& identifier, TType& type,
  5636. TIntermTyped*& initializer)
  5637. {
  5638. //
  5639. // Make the qualifier make sense, given that there is an initializer.
  5640. //
  5641. if (initializer == nullptr) {
  5642. if (type.getQualifier().storage == EvqConst ||
  5643. type.getQualifier().storage == EvqConstReadOnly) {
  5644. initializer = intermediate.makeAggregate(loc);
  5645. warn(loc, "variable with qualifier 'const' not initialized; zero initializing", identifier.c_str(), "");
  5646. }
  5647. }
  5648. }
  5649. //
  5650. // See if the identifier is a built-in symbol that can be redeclared, and if so,
  5651. // copy the symbol table's read-only built-in variable to the current
  5652. // global level, where it can be modified based on the passed in type.
  5653. //
  5654. // Returns nullptr if no redeclaration took place; meaning a normal declaration still
  5655. // needs to occur for it, not necessarily an error.
  5656. //
  5657. // Returns a redeclared and type-modified variable if a redeclared occurred.
  5658. //
  5659. TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
  5660. const TQualifier& /*qualifier*/,
  5661. const TShaderQualifiers& /*publicType*/)
  5662. {
  5663. if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
  5664. return nullptr;
  5665. return nullptr;
  5666. }
  5667. //
  5668. // Generate index to the array element in a structure buffer (SSBO)
  5669. //
  5670. TIntermTyped* HlslParseContext::indexStructBufferContent(const TSourceLoc& loc, TIntermTyped* buffer) const
  5671. {
  5672. // Bail out if not a struct buffer
  5673. if (buffer == nullptr || ! isStructBufferType(buffer->getType()))
  5674. return nullptr;
  5675. // Runtime sized array is always the last element.
  5676. const TTypeList* bufferStruct = buffer->getType().getStruct();
  5677. TIntermTyped* arrayPosition = intermediate.addConstantUnion(unsigned(bufferStruct->size()-1), loc);
  5678. TIntermTyped* argArray = intermediate.addIndex(EOpIndexDirectStruct, buffer, arrayPosition, loc);
  5679. argArray->setType(*(*bufferStruct)[bufferStruct->size()-1].type);
  5680. return argArray;
  5681. }
  5682. //
  5683. // IFF type is a structuredbuffer/byteaddressbuffer type, return the content
  5684. // (template) type. E.g, StructuredBuffer<MyType> -> MyType. Else return nullptr.
  5685. //
  5686. TType* HlslParseContext::getStructBufferContentType(const TType& type) const
  5687. {
  5688. if (type.getBasicType() != EbtBlock || type.getQualifier().storage != EvqBuffer)
  5689. return nullptr;
  5690. const int memberCount = (int)type.getStruct()->size();
  5691. assert(memberCount > 0);
  5692. TType* contentType = (*type.getStruct())[memberCount-1].type;
  5693. return contentType->isUnsizedArray() ? contentType : nullptr;
  5694. }
  5695. //
  5696. // If an existing struct buffer has a sharable type, then share it.
  5697. //
  5698. void HlslParseContext::shareStructBufferType(TType& type)
  5699. {
  5700. // PackOffset must be equivalent to share types on a per-member basis.
  5701. // Note: cannot use auto type due to recursion. Thus, this is a std::function.
  5702. const std::function<bool(TType& lhs, TType& rhs)>
  5703. compareQualifiers = [&](TType& lhs, TType& rhs) -> bool {
  5704. if (lhs.getQualifier().layoutOffset != rhs.getQualifier().layoutOffset)
  5705. return false;
  5706. if (lhs.isStruct() != rhs.isStruct())
  5707. return false;
  5708. if (lhs.isStruct() && rhs.isStruct()) {
  5709. if (lhs.getStruct()->size() != rhs.getStruct()->size())
  5710. return false;
  5711. for (int i = 0; i < int(lhs.getStruct()->size()); ++i)
  5712. if (!compareQualifiers(*(*lhs.getStruct())[i].type, *(*rhs.getStruct())[i].type))
  5713. return false;
  5714. }
  5715. return true;
  5716. };
  5717. // We need to compare certain qualifiers in addition to the type.
  5718. const auto typeEqual = [compareQualifiers](TType& lhs, TType& rhs) -> bool {
  5719. if (lhs.getQualifier().readonly != rhs.getQualifier().readonly)
  5720. return false;
  5721. // If both are structures, recursively look for packOffset equality
  5722. // as well as type equality.
  5723. return compareQualifiers(lhs, rhs) && lhs == rhs;
  5724. };
  5725. // This is an exhaustive O(N) search, but real world shaders have
  5726. // only a small number of these.
  5727. for (int idx = 0; idx < int(structBufferTypes.size()); ++idx) {
  5728. // If the deep structure matches, modulo qualifiers, use it
  5729. if (typeEqual(*structBufferTypes[idx], type)) {
  5730. type.shallowCopy(*structBufferTypes[idx]);
  5731. return;
  5732. }
  5733. }
  5734. // Otherwise, remember it:
  5735. TType* typeCopy = new TType;
  5736. typeCopy->shallowCopy(type);
  5737. structBufferTypes.push_back(typeCopy);
  5738. }
  5739. void HlslParseContext::paramFix(TType& type)
  5740. {
  5741. switch (type.getQualifier().storage) {
  5742. case EvqConst:
  5743. type.getQualifier().storage = EvqConstReadOnly;
  5744. break;
  5745. case EvqGlobal:
  5746. case EvqUniform:
  5747. case EvqTemporary:
  5748. type.getQualifier().storage = EvqIn;
  5749. break;
  5750. case EvqBuffer:
  5751. {
  5752. // SSBO parameter. These do not go through the declareBlock path since they are fn parameters.
  5753. correctUniform(type.getQualifier());
  5754. TQualifier bufferQualifier = globalBufferDefaults;
  5755. mergeObjectLayoutQualifiers(bufferQualifier, type.getQualifier(), true);
  5756. bufferQualifier.storage = type.getQualifier().storage;
  5757. bufferQualifier.readonly = type.getQualifier().readonly;
  5758. bufferQualifier.coherent = type.getQualifier().coherent;
  5759. bufferQualifier.declaredBuiltIn = type.getQualifier().declaredBuiltIn;
  5760. type.getQualifier() = bufferQualifier;
  5761. break;
  5762. }
  5763. default:
  5764. break;
  5765. }
  5766. }
  5767. void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
  5768. {
  5769. if (type.containsSpecializationSize())
  5770. error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
  5771. }
  5772. //
  5773. // Layout qualifier stuff.
  5774. //
  5775. // Put the id's layout qualification into the public type, for qualifiers not having a number set.
  5776. // This is before we know any type information for error checking.
  5777. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
  5778. {
  5779. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5780. if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
  5781. qualifier.layoutMatrix = ElmRowMajor;
  5782. return;
  5783. }
  5784. if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
  5785. qualifier.layoutMatrix = ElmColumnMajor;
  5786. return;
  5787. }
  5788. if (id == "push_constant") {
  5789. requireVulkan(loc, "push_constant");
  5790. qualifier.layoutPushConstant = true;
  5791. return;
  5792. }
  5793. if (language == EShLangGeometry || language == EShLangTessEvaluation) {
  5794. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5795. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5796. warn(loc, "ignored", id.c_str(), "");
  5797. return;
  5798. }
  5799. if (language == EShLangGeometry) {
  5800. if (id == TQualifier::getGeometryString(ElgPoints)) {
  5801. // publicType.shaderQualifiers.geometry = ElgPoints;
  5802. warn(loc, "ignored", id.c_str(), "");
  5803. return;
  5804. }
  5805. if (id == TQualifier::getGeometryString(ElgLineStrip)) {
  5806. // publicType.shaderQualifiers.geometry = ElgLineStrip;
  5807. warn(loc, "ignored", id.c_str(), "");
  5808. return;
  5809. }
  5810. if (id == TQualifier::getGeometryString(ElgLines)) {
  5811. // publicType.shaderQualifiers.geometry = ElgLines;
  5812. warn(loc, "ignored", id.c_str(), "");
  5813. return;
  5814. }
  5815. if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
  5816. // publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
  5817. warn(loc, "ignored", id.c_str(), "");
  5818. return;
  5819. }
  5820. if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
  5821. // publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
  5822. warn(loc, "ignored", id.c_str(), "");
  5823. return;
  5824. }
  5825. if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
  5826. // publicType.shaderQualifiers.geometry = ElgTriangleStrip;
  5827. warn(loc, "ignored", id.c_str(), "");
  5828. return;
  5829. }
  5830. } else {
  5831. assert(language == EShLangTessEvaluation);
  5832. // input primitive
  5833. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  5834. // publicType.shaderQualifiers.geometry = ElgTriangles;
  5835. warn(loc, "ignored", id.c_str(), "");
  5836. return;
  5837. }
  5838. if (id == TQualifier::getGeometryString(ElgQuads)) {
  5839. // publicType.shaderQualifiers.geometry = ElgQuads;
  5840. warn(loc, "ignored", id.c_str(), "");
  5841. return;
  5842. }
  5843. if (id == TQualifier::getGeometryString(ElgIsolines)) {
  5844. // publicType.shaderQualifiers.geometry = ElgIsolines;
  5845. warn(loc, "ignored", id.c_str(), "");
  5846. return;
  5847. }
  5848. // vertex spacing
  5849. if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
  5850. // publicType.shaderQualifiers.spacing = EvsEqual;
  5851. warn(loc, "ignored", id.c_str(), "");
  5852. return;
  5853. }
  5854. if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
  5855. // publicType.shaderQualifiers.spacing = EvsFractionalEven;
  5856. warn(loc, "ignored", id.c_str(), "");
  5857. return;
  5858. }
  5859. if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
  5860. // publicType.shaderQualifiers.spacing = EvsFractionalOdd;
  5861. warn(loc, "ignored", id.c_str(), "");
  5862. return;
  5863. }
  5864. // triangle order
  5865. if (id == TQualifier::getVertexOrderString(EvoCw)) {
  5866. // publicType.shaderQualifiers.order = EvoCw;
  5867. warn(loc, "ignored", id.c_str(), "");
  5868. return;
  5869. }
  5870. if (id == TQualifier::getVertexOrderString(EvoCcw)) {
  5871. // publicType.shaderQualifiers.order = EvoCcw;
  5872. warn(loc, "ignored", id.c_str(), "");
  5873. return;
  5874. }
  5875. // point mode
  5876. if (id == "point_mode") {
  5877. // publicType.shaderQualifiers.pointMode = true;
  5878. warn(loc, "ignored", id.c_str(), "");
  5879. return;
  5880. }
  5881. }
  5882. }
  5883. if (language == EShLangFragment) {
  5884. if (id == "origin_upper_left") {
  5885. // publicType.shaderQualifiers.originUpperLeft = true;
  5886. warn(loc, "ignored", id.c_str(), "");
  5887. return;
  5888. }
  5889. if (id == "pixel_center_integer") {
  5890. // publicType.shaderQualifiers.pixelCenterInteger = true;
  5891. warn(loc, "ignored", id.c_str(), "");
  5892. return;
  5893. }
  5894. if (id == "early_fragment_tests") {
  5895. // publicType.shaderQualifiers.earlyFragmentTests = true;
  5896. warn(loc, "ignored", id.c_str(), "");
  5897. return;
  5898. }
  5899. for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
  5900. if (id == TQualifier::getLayoutDepthString(depth)) {
  5901. // publicType.shaderQualifiers.layoutDepth = depth;
  5902. warn(loc, "ignored", id.c_str(), "");
  5903. return;
  5904. }
  5905. }
  5906. if (id.compare(0, 13, "blend_support") == 0) {
  5907. bool found = false;
  5908. for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
  5909. if (id == TQualifier::getBlendEquationString(be)) {
  5910. requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
  5911. intermediate.addBlendEquation(be);
  5912. // publicType.shaderQualifiers.blendEquation = true;
  5913. warn(loc, "ignored", id.c_str(), "");
  5914. found = true;
  5915. break;
  5916. }
  5917. }
  5918. if (! found)
  5919. error(loc, "unknown blend equation", "blend_support", "");
  5920. return;
  5921. }
  5922. }
  5923. error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
  5924. }
  5925. // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
  5926. // This is before we know any type information for error checking.
  5927. void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id,
  5928. const TIntermTyped* node)
  5929. {
  5930. const char* feature = "layout-id value";
  5931. // const char* nonLiteralFeature = "non-literal layout-id value";
  5932. integerCheck(node, feature);
  5933. const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
  5934. int value = 0;
  5935. if (constUnion) {
  5936. value = constUnion->getConstArray()[0].getIConst();
  5937. }
  5938. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5939. if (id == "offset") {
  5940. qualifier.layoutOffset = value;
  5941. return;
  5942. } else if (id == "align") {
  5943. // "The specified alignment must be a power of 2, or a compile-time error results."
  5944. if (! IsPow2(value))
  5945. error(loc, "must be a power of 2", "align", "");
  5946. else
  5947. qualifier.layoutAlign = value;
  5948. return;
  5949. } else if (id == "location") {
  5950. if ((unsigned int)value >= TQualifier::layoutLocationEnd)
  5951. error(loc, "location is too large", id.c_str(), "");
  5952. else
  5953. qualifier.layoutLocation = value;
  5954. return;
  5955. } else if (id == "set") {
  5956. if ((unsigned int)value >= TQualifier::layoutSetEnd)
  5957. error(loc, "set is too large", id.c_str(), "");
  5958. else
  5959. qualifier.layoutSet = value;
  5960. return;
  5961. } else if (id == "binding") {
  5962. if ((unsigned int)value >= TQualifier::layoutBindingEnd)
  5963. error(loc, "binding is too large", id.c_str(), "");
  5964. else
  5965. qualifier.layoutBinding = value;
  5966. return;
  5967. } else if (id == "component") {
  5968. if ((unsigned)value >= TQualifier::layoutComponentEnd)
  5969. error(loc, "component is too large", id.c_str(), "");
  5970. else
  5971. qualifier.layoutComponent = value;
  5972. return;
  5973. } else if (id.compare(0, 4, "xfb_") == 0) {
  5974. // "Any shader making any static use (after preprocessing) of any of these
  5975. // *xfb_* qualifiers will cause the shader to be in a transform feedback
  5976. // capturing mode and hence responsible for describing the transform feedback
  5977. // setup."
  5978. intermediate.setXfbMode();
  5979. if (id == "xfb_buffer") {
  5980. // "It is a compile-time error to specify an *xfb_buffer* that is greater than
  5981. // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
  5982. if (value >= resources.maxTransformFeedbackBuffers)
  5983. error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d",
  5984. resources.maxTransformFeedbackBuffers);
  5985. if (value >= (int)TQualifier::layoutXfbBufferEnd)
  5986. error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
  5987. else
  5988. qualifier.layoutXfbBuffer = value;
  5989. return;
  5990. } else if (id == "xfb_offset") {
  5991. if (value >= (int)TQualifier::layoutXfbOffsetEnd)
  5992. error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
  5993. else
  5994. qualifier.layoutXfbOffset = value;
  5995. return;
  5996. } else if (id == "xfb_stride") {
  5997. // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
  5998. // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
  5999. if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
  6000. error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
  6001. resources.maxTransformFeedbackInterleavedComponents);
  6002. else if (value >= (int)TQualifier::layoutXfbStrideEnd)
  6003. error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
  6004. if (value < (int)TQualifier::layoutXfbStrideEnd)
  6005. qualifier.layoutXfbStride = value;
  6006. return;
  6007. }
  6008. }
  6009. if (id == "input_attachment_index") {
  6010. requireVulkan(loc, "input_attachment_index");
  6011. if (value >= (int)TQualifier::layoutAttachmentEnd)
  6012. error(loc, "attachment index is too large", id.c_str(), "");
  6013. else
  6014. qualifier.layoutAttachment = value;
  6015. return;
  6016. }
  6017. if (id == "constant_id") {
  6018. setSpecConstantId(loc, qualifier, value);
  6019. return;
  6020. }
  6021. switch (language) {
  6022. case EShLangVertex:
  6023. break;
  6024. case EShLangTessControl:
  6025. if (id == "vertices") {
  6026. if (value == 0)
  6027. error(loc, "must be greater than 0", "vertices", "");
  6028. else
  6029. // publicType.shaderQualifiers.vertices = value;
  6030. warn(loc, "ignored", id.c_str(), "");
  6031. return;
  6032. }
  6033. break;
  6034. case EShLangTessEvaluation:
  6035. break;
  6036. case EShLangGeometry:
  6037. if (id == "invocations") {
  6038. if (value == 0)
  6039. error(loc, "must be at least 1", "invocations", "");
  6040. else
  6041. // publicType.shaderQualifiers.invocations = value;
  6042. warn(loc, "ignored", id.c_str(), "");
  6043. return;
  6044. }
  6045. if (id == "max_vertices") {
  6046. // publicType.shaderQualifiers.vertices = value;
  6047. warn(loc, "ignored", id.c_str(), "");
  6048. if (value > resources.maxGeometryOutputVertices)
  6049. error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
  6050. return;
  6051. }
  6052. if (id == "stream") {
  6053. qualifier.layoutStream = value;
  6054. return;
  6055. }
  6056. break;
  6057. case EShLangFragment:
  6058. if (id == "index") {
  6059. qualifier.layoutIndex = value;
  6060. return;
  6061. }
  6062. break;
  6063. case EShLangCompute:
  6064. if (id.compare(0, 11, "local_size_") == 0) {
  6065. if (id == "local_size_x") {
  6066. // publicType.shaderQualifiers.localSize[0] = value;
  6067. warn(loc, "ignored", id.c_str(), "");
  6068. return;
  6069. }
  6070. if (id == "local_size_y") {
  6071. // publicType.shaderQualifiers.localSize[1] = value;
  6072. warn(loc, "ignored", id.c_str(), "");
  6073. return;
  6074. }
  6075. if (id == "local_size_z") {
  6076. // publicType.shaderQualifiers.localSize[2] = value;
  6077. warn(loc, "ignored", id.c_str(), "");
  6078. return;
  6079. }
  6080. if (spvVersion.spv != 0) {
  6081. if (id == "local_size_x_id") {
  6082. // publicType.shaderQualifiers.localSizeSpecId[0] = value;
  6083. warn(loc, "ignored", id.c_str(), "");
  6084. return;
  6085. }
  6086. if (id == "local_size_y_id") {
  6087. // publicType.shaderQualifiers.localSizeSpecId[1] = value;
  6088. warn(loc, "ignored", id.c_str(), "");
  6089. return;
  6090. }
  6091. if (id == "local_size_z_id") {
  6092. // publicType.shaderQualifiers.localSizeSpecId[2] = value;
  6093. warn(loc, "ignored", id.c_str(), "");
  6094. return;
  6095. }
  6096. }
  6097. }
  6098. break;
  6099. default:
  6100. break;
  6101. }
  6102. error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
  6103. }
  6104. void HlslParseContext::setSpecConstantId(const TSourceLoc& loc, TQualifier& qualifier, int value)
  6105. {
  6106. if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
  6107. error(loc, "specialization-constant id is too large", "constant_id", "");
  6108. } else {
  6109. qualifier.layoutSpecConstantId = value;
  6110. qualifier.specConstant = true;
  6111. if (! intermediate.addUsedConstantId(value))
  6112. error(loc, "specialization-constant id already used", "constant_id", "");
  6113. }
  6114. return;
  6115. }
  6116. // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
  6117. //
  6118. // "More than one layout qualifier may appear in a single declaration.
  6119. // Additionally, the same layout-qualifier-name can occur multiple times
  6120. // within a layout qualifier or across multiple layout qualifiers in the
  6121. // same declaration. When the same layout-qualifier-name occurs
  6122. // multiple times, in a single declaration, the last occurrence overrides
  6123. // the former occurrence(s). Further, if such a layout-qualifier-name
  6124. // will effect subsequent declarations or other observable behavior, it
  6125. // is only the last occurrence that will have any effect, behaving as if
  6126. // the earlier occurrence(s) within the declaration are not present.
  6127. // This is also true for overriding layout-qualifier-names, where one
  6128. // overrides the other (e.g., row_major vs. column_major); only the last
  6129. // occurrence has any effect."
  6130. //
  6131. void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
  6132. {
  6133. if (src.hasMatrix())
  6134. dst.layoutMatrix = src.layoutMatrix;
  6135. if (src.hasPacking())
  6136. dst.layoutPacking = src.layoutPacking;
  6137. if (src.hasStream())
  6138. dst.layoutStream = src.layoutStream;
  6139. if (src.hasFormat())
  6140. dst.layoutFormat = src.layoutFormat;
  6141. if (src.hasXfbBuffer())
  6142. dst.layoutXfbBuffer = src.layoutXfbBuffer;
  6143. if (src.hasAlign())
  6144. dst.layoutAlign = src.layoutAlign;
  6145. if (! inheritOnly) {
  6146. if (src.hasLocation())
  6147. dst.layoutLocation = src.layoutLocation;
  6148. if (src.hasComponent())
  6149. dst.layoutComponent = src.layoutComponent;
  6150. if (src.hasIndex())
  6151. dst.layoutIndex = src.layoutIndex;
  6152. if (src.hasOffset())
  6153. dst.layoutOffset = src.layoutOffset;
  6154. if (src.hasSet())
  6155. dst.layoutSet = src.layoutSet;
  6156. if (src.layoutBinding != TQualifier::layoutBindingEnd)
  6157. dst.layoutBinding = src.layoutBinding;
  6158. if (src.hasXfbStride())
  6159. dst.layoutXfbStride = src.layoutXfbStride;
  6160. if (src.hasXfbOffset())
  6161. dst.layoutXfbOffset = src.layoutXfbOffset;
  6162. if (src.hasAttachment())
  6163. dst.layoutAttachment = src.layoutAttachment;
  6164. if (src.hasSpecConstantId())
  6165. dst.layoutSpecConstantId = src.layoutSpecConstantId;
  6166. if (src.layoutPushConstant)
  6167. dst.layoutPushConstant = true;
  6168. }
  6169. }
  6170. //
  6171. // Look up a function name in the symbol table, and make sure it is a function.
  6172. //
  6173. // First, look for an exact match. If there is none, use the generic selector
  6174. // TParseContextBase::selectFunction() to find one, parameterized by the
  6175. // convertible() and better() predicates defined below.
  6176. //
  6177. // Return the function symbol if found, otherwise nullptr.
  6178. //
  6179. const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, TFunction& call, bool& builtIn, int& thisDepth,
  6180. TIntermTyped*& args)
  6181. {
  6182. if (symbolTable.isFunctionNameVariable(call.getName())) {
  6183. error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
  6184. return nullptr;
  6185. }
  6186. // first, look for an exact match
  6187. bool dummyScope;
  6188. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn, &dummyScope, &thisDepth);
  6189. if (symbol)
  6190. return symbol->getAsFunction();
  6191. // no exact match, use the generic selector, parameterized by the GLSL rules
  6192. // create list of candidates to send
  6193. TVector<const TFunction*> candidateList;
  6194. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6195. // These built-in ops can accept any type, so we bypass the argument selection
  6196. if (candidateList.size() == 1 && builtIn &&
  6197. (candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6198. candidateList[0]->getBuiltInOp() == EOpMethodRestartStrip ||
  6199. candidateList[0]->getBuiltInOp() == EOpMethodIncrementCounter ||
  6200. candidateList[0]->getBuiltInOp() == EOpMethodDecrementCounter ||
  6201. candidateList[0]->getBuiltInOp() == EOpMethodAppend ||
  6202. candidateList[0]->getBuiltInOp() == EOpMethodConsume)) {
  6203. return candidateList[0];
  6204. }
  6205. bool allowOnlyUpConversions = true;
  6206. // can 'from' convert to 'to'?
  6207. const auto convertible = [&](const TType& from, const TType& to, TOperator op, int arg) -> bool {
  6208. if (from == to)
  6209. return true;
  6210. // no aggregate conversions
  6211. if (from.isArray() || to.isArray() ||
  6212. from.isStruct() || to.isStruct())
  6213. return false;
  6214. switch (op) {
  6215. case EOpInterlockedAdd:
  6216. case EOpInterlockedAnd:
  6217. case EOpInterlockedCompareExchange:
  6218. case EOpInterlockedCompareStore:
  6219. case EOpInterlockedExchange:
  6220. case EOpInterlockedMax:
  6221. case EOpInterlockedMin:
  6222. case EOpInterlockedOr:
  6223. case EOpInterlockedXor:
  6224. // We do not promote the texture or image type for these ocodes. Normally that would not
  6225. // be an issue because it's a buffer, but we haven't decomposed the opcode yet, and at this
  6226. // stage it's merely e.g, a basic integer type.
  6227. //
  6228. // Instead, we want to promote other arguments, but stay within the same family. In other
  6229. // words, InterlockedAdd(RWBuffer<int>, ...) will always use the int flavor, never the uint flavor,
  6230. // but it is allowed to promote its other arguments.
  6231. if (arg == 0)
  6232. return false;
  6233. break;
  6234. case EOpMethodSample:
  6235. case EOpMethodSampleBias:
  6236. case EOpMethodSampleCmp:
  6237. case EOpMethodSampleCmpLevelZero:
  6238. case EOpMethodSampleGrad:
  6239. case EOpMethodSampleLevel:
  6240. case EOpMethodLoad:
  6241. case EOpMethodGetDimensions:
  6242. case EOpMethodGetSamplePosition:
  6243. case EOpMethodGather:
  6244. case EOpMethodCalculateLevelOfDetail:
  6245. case EOpMethodCalculateLevelOfDetailUnclamped:
  6246. case EOpMethodGatherRed:
  6247. case EOpMethodGatherGreen:
  6248. case EOpMethodGatherBlue:
  6249. case EOpMethodGatherAlpha:
  6250. case EOpMethodGatherCmp:
  6251. case EOpMethodGatherCmpRed:
  6252. case EOpMethodGatherCmpGreen:
  6253. case EOpMethodGatherCmpBlue:
  6254. case EOpMethodGatherCmpAlpha:
  6255. case EOpMethodAppend:
  6256. case EOpMethodRestartStrip:
  6257. // those are method calls, the object type can not be changed
  6258. // they are equal if the dim and type match (is dim sufficient?)
  6259. if (arg == 0)
  6260. return from.getSampler().type == to.getSampler().type &&
  6261. from.getSampler().arrayed == to.getSampler().arrayed &&
  6262. from.getSampler().shadow == to.getSampler().shadow &&
  6263. from.getSampler().ms == to.getSampler().ms &&
  6264. from.getSampler().dim == to.getSampler().dim;
  6265. break;
  6266. default:
  6267. break;
  6268. }
  6269. // basic types have to be convertible
  6270. if (allowOnlyUpConversions)
  6271. if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
  6272. return false;
  6273. // shapes have to be convertible
  6274. if ((from.isScalarOrVec1() && to.isScalarOrVec1()) ||
  6275. (from.isScalarOrVec1() && to.isVector()) ||
  6276. (from.isScalarOrVec1() && to.isMatrix()) ||
  6277. (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
  6278. return true;
  6279. // TODO: what are the matrix rules? they go here
  6280. return false;
  6281. };
  6282. // Is 'to2' a better conversion than 'to1'?
  6283. // Ties should not be considered as better.
  6284. // Assumes 'convertible' already said true.
  6285. const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
  6286. // exact match is always better than mismatch
  6287. if (from == to2)
  6288. return from != to1;
  6289. if (from == to1)
  6290. return false;
  6291. // shape changes are always worse
  6292. if (from.isScalar() || from.isVector()) {
  6293. if (from.getVectorSize() == to2.getVectorSize() &&
  6294. from.getVectorSize() != to1.getVectorSize())
  6295. return true;
  6296. if (from.getVectorSize() == to1.getVectorSize() &&
  6297. from.getVectorSize() != to2.getVectorSize())
  6298. return false;
  6299. }
  6300. // Handle sampler betterness: An exact sampler match beats a non-exact match.
  6301. // (If we just looked at basic type, all EbtSamplers would look the same).
  6302. // If any type is not a sampler, just use the linearize function below.
  6303. if (from.getBasicType() == EbtSampler && to1.getBasicType() == EbtSampler && to2.getBasicType() == EbtSampler) {
  6304. // We can ignore the vector size in the comparison.
  6305. TSampler to1Sampler = to1.getSampler();
  6306. TSampler to2Sampler = to2.getSampler();
  6307. to1Sampler.vectorSize = to2Sampler.vectorSize = from.getSampler().vectorSize;
  6308. if (from.getSampler() == to2Sampler)
  6309. return from.getSampler() != to1Sampler;
  6310. if (from.getSampler() == to1Sampler)
  6311. return false;
  6312. }
  6313. // Might or might not be changing shape, which means basic type might
  6314. // or might not match, so within that, the question is how big a
  6315. // basic-type conversion is being done.
  6316. //
  6317. // Use a hierarchy of domains, translated to order of magnitude
  6318. // in a linearized view:
  6319. // - floating-point vs. integer
  6320. // - 32 vs. 64 bit (or width in general)
  6321. // - bool vs. non bool
  6322. // - signed vs. not signed
  6323. const auto linearize = [](const TBasicType& basicType) -> int {
  6324. switch (basicType) {
  6325. case EbtBool: return 1;
  6326. case EbtInt: return 10;
  6327. case EbtUint: return 11;
  6328. case EbtInt64: return 20;
  6329. case EbtUint64: return 21;
  6330. case EbtFloat: return 100;
  6331. case EbtDouble: return 110;
  6332. default: return 0;
  6333. }
  6334. };
  6335. return abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
  6336. abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
  6337. };
  6338. // for ambiguity reporting
  6339. bool tie = false;
  6340. // send to the generic selector
  6341. const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6342. if (bestMatch == nullptr) {
  6343. // If there is nothing selected by allowing only up-conversions (to a larger linearize() value),
  6344. // we instead try down-conversions, which are valid in HLSL, but not preferred if there are any
  6345. // upconversions possible.
  6346. allowOnlyUpConversions = false;
  6347. bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6348. }
  6349. if (bestMatch == nullptr) {
  6350. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6351. return nullptr;
  6352. }
  6353. // For built-ins, we can convert across the arguments. This will happen in several steps:
  6354. // Step 1: If there's an exact match, use it.
  6355. // Step 2a: Otherwise, get the operator from the best match and promote arguments:
  6356. // Step 2b: reconstruct the TFunction based on the new arg types
  6357. // Step 3: Re-select after type promotion is applied, to find proper candidate.
  6358. if (builtIn) {
  6359. // Step 1: If there's an exact match, use it.
  6360. if (call.getMangledName() == bestMatch->getMangledName())
  6361. return bestMatch;
  6362. // Step 2a: Otherwise, get the operator from the best match and promote arguments as if we
  6363. // are that kind of operator.
  6364. if (args != nullptr) {
  6365. // The arg list can be a unary node, or an aggregate. We have to handle both.
  6366. // We will use the normal promote() facilities, which require an interm node.
  6367. TIntermOperator* promote = nullptr;
  6368. if (call.getParamCount() == 1) {
  6369. promote = new TIntermUnary(bestMatch->getBuiltInOp());
  6370. promote->getAsUnaryNode()->setOperand(args->getAsTyped());
  6371. } else {
  6372. promote = new TIntermAggregate(bestMatch->getBuiltInOp());
  6373. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6374. }
  6375. if (! intermediate.promote(promote))
  6376. return nullptr;
  6377. // Obtain the promoted arg list.
  6378. if (call.getParamCount() == 1) {
  6379. args = promote->getAsUnaryNode()->getOperand();
  6380. } else {
  6381. promote->getAsAggregate()->getSequence().swap(args->getAsAggregate()->getSequence());
  6382. }
  6383. }
  6384. // Step 2b: reconstruct the TFunction based on the new arg types
  6385. TFunction convertedCall(&call.getName(), call.getType(), call.getBuiltInOp());
  6386. if (args->getAsAggregate()) {
  6387. // Handle aggregates: put all args into the new function call
  6388. for (int arg=0; arg<int(args->getAsAggregate()->getSequence().size()); ++arg) {
  6389. // TODO: But for constness, we could avoid the new & shallowCopy, and use the pointer directly.
  6390. TParameter param = { 0, new TType, nullptr };
  6391. param.type->shallowCopy(args->getAsAggregate()->getSequence()[arg]->getAsTyped()->getType());
  6392. convertedCall.addParameter(param);
  6393. }
  6394. } else if (args->getAsUnaryNode()) {
  6395. // Handle unaries: put all args into the new function call
  6396. TParameter param = { 0, new TType, nullptr };
  6397. param.type->shallowCopy(args->getAsUnaryNode()->getOperand()->getAsTyped()->getType());
  6398. convertedCall.addParameter(param);
  6399. } else if (args->getAsTyped()) {
  6400. // Handle bare e.g, floats, not in an aggregate.
  6401. TParameter param = { 0, new TType, nullptr };
  6402. param.type->shallowCopy(args->getAsTyped()->getType());
  6403. convertedCall.addParameter(param);
  6404. } else {
  6405. assert(0); // unknown argument list.
  6406. return nullptr;
  6407. }
  6408. // Step 3: Re-select after type promotion, to find proper candidate
  6409. // send to the generic selector
  6410. bestMatch = selectFunction(candidateList, convertedCall, convertible, better, tie);
  6411. // At this point, there should be no tie.
  6412. }
  6413. if (tie)
  6414. error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
  6415. // Append default parameter values if needed
  6416. if (!tie && bestMatch != nullptr) {
  6417. for (int defParam = call.getParamCount(); defParam < bestMatch->getParamCount(); ++defParam) {
  6418. handleFunctionArgument(&call, args, (*bestMatch)[defParam].defaultValue);
  6419. }
  6420. }
  6421. return bestMatch;
  6422. }
  6423. //
  6424. // Do everything necessary to handle a typedef declaration, for a single symbol.
  6425. //
  6426. // 'parseType' is the type part of the declaration (to the left)
  6427. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6428. //
  6429. void HlslParseContext::declareTypedef(const TSourceLoc& loc, const TString& identifier, const TType& parseType)
  6430. {
  6431. TVariable* typeSymbol = new TVariable(&identifier, parseType, true);
  6432. if (! symbolTable.insert(*typeSymbol))
  6433. error(loc, "name already defined", "typedef", identifier.c_str());
  6434. }
  6435. // Do everything necessary to handle a struct declaration, including
  6436. // making IO aliases because HLSL allows mixed IO in a struct that specializes
  6437. // based on the usage (input, output, uniform, none).
  6438. void HlslParseContext::declareStruct(const TSourceLoc& loc, TString& structName, TType& type)
  6439. {
  6440. // If it was named, which means the type can be reused later, add
  6441. // it to the symbol table. (Unless it's a block, in which
  6442. // case the name is not a type.)
  6443. if (type.getBasicType() == EbtBlock || structName.size() == 0)
  6444. return;
  6445. TVariable* userTypeDef = new TVariable(&structName, type, true);
  6446. if (! symbolTable.insert(*userTypeDef)) {
  6447. error(loc, "redefinition", structName.c_str(), "struct");
  6448. return;
  6449. }
  6450. // See if we need IO aliases for the structure typeList
  6451. const auto condAlloc = [](bool pred, TTypeList*& list) {
  6452. if (pred && list == nullptr)
  6453. list = new TTypeList;
  6454. };
  6455. tIoKinds newLists = { nullptr, nullptr, nullptr }; // allocate for each kind found
  6456. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6457. condAlloc(hasUniform(member->type->getQualifier()), newLists.uniform);
  6458. condAlloc( hasInput(member->type->getQualifier()), newLists.input);
  6459. condAlloc( hasOutput(member->type->getQualifier()), newLists.output);
  6460. if (member->type->isStruct()) {
  6461. auto it = ioTypeMap.find(member->type->getStruct());
  6462. if (it != ioTypeMap.end()) {
  6463. condAlloc(it->second.uniform != nullptr, newLists.uniform);
  6464. condAlloc(it->second.input != nullptr, newLists.input);
  6465. condAlloc(it->second.output != nullptr, newLists.output);
  6466. }
  6467. }
  6468. }
  6469. if (newLists.uniform == nullptr &&
  6470. newLists.input == nullptr &&
  6471. newLists.output == nullptr) {
  6472. // Won't do any IO caching, clear up the type and get out now.
  6473. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member)
  6474. clearUniformInputOutput(member->type->getQualifier());
  6475. return;
  6476. }
  6477. // We have IO involved.
  6478. // Make a pure typeList for the symbol table, and cache side copies of IO versions.
  6479. for (auto member = type.getStruct()->begin(); member != type.getStruct()->end(); ++member) {
  6480. const auto inheritStruct = [&](TTypeList* s, TTypeLoc& ioMember) {
  6481. if (s != nullptr) {
  6482. ioMember.type = new TType;
  6483. ioMember.type->shallowCopy(*member->type);
  6484. ioMember.type->setStruct(s);
  6485. }
  6486. };
  6487. const auto newMember = [&](TTypeLoc& m) {
  6488. if (m.type == nullptr) {
  6489. m.type = new TType;
  6490. m.type->shallowCopy(*member->type);
  6491. }
  6492. };
  6493. TTypeLoc newUniformMember = { nullptr, member->loc };
  6494. TTypeLoc newInputMember = { nullptr, member->loc };
  6495. TTypeLoc newOutputMember = { nullptr, member->loc };
  6496. if (member->type->isStruct()) {
  6497. // swap in an IO child if there is one
  6498. auto it = ioTypeMap.find(member->type->getStruct());
  6499. if (it != ioTypeMap.end()) {
  6500. inheritStruct(it->second.uniform, newUniformMember);
  6501. inheritStruct(it->second.input, newInputMember);
  6502. inheritStruct(it->second.output, newOutputMember);
  6503. }
  6504. }
  6505. if (newLists.uniform) {
  6506. newMember(newUniformMember);
  6507. // inherit default matrix layout (changeable via #pragma pack_matrix), if none given.
  6508. if (member->type->isMatrix() && member->type->getQualifier().layoutMatrix == ElmNone)
  6509. newUniformMember.type->getQualifier().layoutMatrix = globalUniformDefaults.layoutMatrix;
  6510. correctUniform(newUniformMember.type->getQualifier());
  6511. newLists.uniform->push_back(newUniformMember);
  6512. }
  6513. if (newLists.input) {
  6514. newMember(newInputMember);
  6515. correctInput(newInputMember.type->getQualifier());
  6516. newLists.input->push_back(newInputMember);
  6517. }
  6518. if (newLists.output) {
  6519. newMember(newOutputMember);
  6520. correctOutput(newOutputMember.type->getQualifier());
  6521. newLists.output->push_back(newOutputMember);
  6522. }
  6523. // make original pure
  6524. clearUniformInputOutput(member->type->getQualifier());
  6525. }
  6526. ioTypeMap[type.getStruct()] = newLists;
  6527. }
  6528. // Lookup a user-type by name.
  6529. // If found, fill in the type and return the defining symbol.
  6530. // If not found, return nullptr.
  6531. TSymbol* HlslParseContext::lookupUserType(const TString& typeName, TType& type)
  6532. {
  6533. TSymbol* symbol = symbolTable.find(typeName);
  6534. if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
  6535. type.shallowCopy(symbol->getType());
  6536. return symbol;
  6537. } else
  6538. return nullptr;
  6539. }
  6540. //
  6541. // Do everything necessary to handle a variable (non-block) declaration.
  6542. // Either redeclaring a variable, or making a new one, updating the symbol
  6543. // table, and all error checking.
  6544. //
  6545. // Returns a subtree node that computes an initializer, if needed.
  6546. // Returns nullptr if there is no code to execute for initialization.
  6547. //
  6548. // 'parseType' is the type part of the declaration (to the left)
  6549. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6550. //
  6551. TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, const TString& identifier, TType& type,
  6552. TIntermTyped* initializer)
  6553. {
  6554. if (voidErrorCheck(loc, identifier, type.getBasicType()))
  6555. return nullptr;
  6556. // Global consts with initializers that are non-const act like EvqGlobal in HLSL.
  6557. // This test is implicitly recursive, because initializers propagate constness
  6558. // up the aggregate node tree during creation. E.g, for:
  6559. // { { 1, 2 }, { 3, 4 } }
  6560. // the initializer list is marked EvqConst at the top node, and remains so here. However:
  6561. // { 1, { myvar, 2 }, 3 }
  6562. // is not a const intializer, and still becomes EvqGlobal here.
  6563. const bool nonConstInitializer = (initializer != nullptr && initializer->getQualifier().storage != EvqConst);
  6564. if (type.getQualifier().storage == EvqConst && symbolTable.atGlobalLevel() && nonConstInitializer) {
  6565. // Force to global
  6566. type.getQualifier().storage = EvqGlobal;
  6567. }
  6568. // make const and initialization consistent
  6569. fixConstInit(loc, identifier, type, initializer);
  6570. // Check for redeclaration of built-ins and/or attempting to declare a reserved name
  6571. TSymbol* symbol = nullptr;
  6572. inheritGlobalDefaults(type.getQualifier());
  6573. const bool flattenVar = shouldFlatten(type, type.getQualifier().storage, true);
  6574. // correct IO in the type
  6575. switch (type.getQualifier().storage) {
  6576. case EvqGlobal:
  6577. case EvqTemporary:
  6578. clearUniformInputOutput(type.getQualifier());
  6579. break;
  6580. case EvqUniform:
  6581. case EvqBuffer:
  6582. correctUniform(type.getQualifier());
  6583. if (type.isStruct()) {
  6584. auto it = ioTypeMap.find(type.getStruct());
  6585. if (it != ioTypeMap.end())
  6586. type.setStruct(it->second.uniform);
  6587. }
  6588. break;
  6589. default:
  6590. break;
  6591. }
  6592. // Declare the variable
  6593. if (type.isArray()) {
  6594. // array case
  6595. declareArray(loc, identifier, type, symbol, !flattenVar);
  6596. } else {
  6597. // non-array case
  6598. if (symbol == nullptr)
  6599. symbol = declareNonArray(loc, identifier, type, !flattenVar);
  6600. else if (type != symbol->getType())
  6601. error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
  6602. }
  6603. if (symbol == nullptr)
  6604. return nullptr;
  6605. if (flattenVar)
  6606. flatten(*symbol->getAsVariable(), symbolTable.atGlobalLevel());
  6607. if (initializer == nullptr)
  6608. return nullptr;
  6609. // Deal with initializer
  6610. TVariable* variable = symbol->getAsVariable();
  6611. if (variable == nullptr) {
  6612. error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
  6613. return nullptr;
  6614. }
  6615. return executeInitializer(loc, initializer, variable);
  6616. }
  6617. // Pick up global defaults from the provide global defaults into dst.
  6618. void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
  6619. {
  6620. if (dst.storage == EvqVaryingOut) {
  6621. if (! dst.hasStream() && language == EShLangGeometry)
  6622. dst.layoutStream = globalOutputDefaults.layoutStream;
  6623. if (! dst.hasXfbBuffer())
  6624. dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  6625. }
  6626. }
  6627. //
  6628. // Make an internal-only variable whose name is for debug purposes only
  6629. // and won't be searched for. Callers will only use the return value to use
  6630. // the variable, not the name to look it up. It is okay if the name
  6631. // is the same as other names; there won't be any conflict.
  6632. //
  6633. TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
  6634. {
  6635. TString* nameString = NewPoolTString(name);
  6636. TVariable* variable = new TVariable(nameString, type);
  6637. symbolTable.makeInternalVariable(*variable);
  6638. return variable;
  6639. }
  6640. // Make a symbol node holding a new internal temporary variable.
  6641. TIntermSymbol* HlslParseContext::makeInternalVariableNode(const TSourceLoc& loc, const char* name,
  6642. const TType& type) const
  6643. {
  6644. TVariable* tmpVar = makeInternalVariable(name, type);
  6645. tmpVar->getWritableType().getQualifier().makeTemporary();
  6646. return intermediate.addSymbol(*tmpVar, loc);
  6647. }
  6648. //
  6649. // Declare a non-array variable, the main point being there is no redeclaration
  6650. // for resizing allowed.
  6651. //
  6652. // Return the successfully declared variable.
  6653. //
  6654. TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type,
  6655. bool track)
  6656. {
  6657. // make a new variable
  6658. TVariable* variable = new TVariable(&identifier, type);
  6659. // add variable to symbol table
  6660. if (symbolTable.insert(*variable)) {
  6661. if (track && symbolTable.atGlobalLevel())
  6662. trackLinkage(*variable);
  6663. return variable;
  6664. }
  6665. error(loc, "redefinition", variable->getName().c_str(), "");
  6666. return nullptr;
  6667. }
  6668. //
  6669. // Handle all types of initializers from the grammar.
  6670. //
  6671. // Returning nullptr just means there is no code to execute to handle the
  6672. // initializer, which will, for example, be the case for constant initializers.
  6673. //
  6674. // Returns a subtree that accomplished the initialization.
  6675. //
  6676. TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
  6677. {
  6678. //
  6679. // Identifier must be of type constant, a global, or a temporary, and
  6680. // starting at version 120, desktop allows uniforms to have initializers.
  6681. //
  6682. TStorageQualifier qualifier = variable->getType().getQualifier().storage;
  6683. //
  6684. // If the initializer was from braces { ... }, we convert the whole subtree to a
  6685. // constructor-style subtree, allowing the rest of the code to operate
  6686. // identically for both kinds of initializers.
  6687. //
  6688. //
  6689. // Type can't be deduced from the initializer list, so a skeletal type to
  6690. // follow has to be passed in. Constness and specialization-constness
  6691. // should be deduced bottom up, not dictated by the skeletal type.
  6692. //
  6693. TType skeletalType;
  6694. skeletalType.shallowCopy(variable->getType());
  6695. skeletalType.getQualifier().makeTemporary();
  6696. if (initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull)
  6697. initializer = convertInitializerList(loc, skeletalType, initializer, nullptr);
  6698. if (initializer == nullptr) {
  6699. // error recovery; don't leave const without constant values
  6700. if (qualifier == EvqConst)
  6701. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6702. return nullptr;
  6703. }
  6704. // Fix outer arrayness if variable is unsized, getting size from the initializer
  6705. if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
  6706. variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
  6707. // Inner arrayness can also get set by an initializer
  6708. if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
  6709. initializer->getType().getArraySizes()->getNumDims() ==
  6710. variable->getType().getArraySizes()->getNumDims()) {
  6711. // adopt unsized sizes from the initializer's sizes
  6712. for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
  6713. if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
  6714. variable->getWritableType().getArraySizes()->setDimSize(d,
  6715. initializer->getType().getArraySizes()->getDimSize(d));
  6716. }
  6717. }
  6718. }
  6719. // Uniform and global consts require a constant initializer
  6720. if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
  6721. error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
  6722. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6723. return nullptr;
  6724. }
  6725. // Const variables require a constant initializer
  6726. if (qualifier == EvqConst) {
  6727. if (initializer->getType().getQualifier().storage != EvqConst) {
  6728. variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
  6729. qualifier = EvqConstReadOnly;
  6730. }
  6731. }
  6732. if (qualifier == EvqConst || qualifier == EvqUniform) {
  6733. // Compile-time tagging of the variable with its constant value...
  6734. initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
  6735. if (initializer != nullptr && variable->getType() != initializer->getType())
  6736. initializer = intermediate.addUniShapeConversion(EOpAssign, variable->getType(), initializer);
  6737. if (initializer == nullptr || !initializer->getAsConstantUnion() ||
  6738. variable->getType() != initializer->getType()) {
  6739. error(loc, "non-matching or non-convertible constant type for const initializer",
  6740. variable->getType().getStorageQualifierString(), "");
  6741. variable->getWritableType().getQualifier().storage = EvqTemporary;
  6742. return nullptr;
  6743. }
  6744. variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
  6745. } else {
  6746. // normal assigning of a value to a variable...
  6747. specializationCheck(loc, initializer->getType(), "initializer");
  6748. TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
  6749. TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
  6750. if (initNode == nullptr)
  6751. assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
  6752. return initNode;
  6753. }
  6754. return nullptr;
  6755. }
  6756. //
  6757. // Reprocess any initializer-list { ... } parts of the initializer.
  6758. // Need to hierarchically assign correct types and implicit
  6759. // conversions. Will do this mimicking the same process used for
  6760. // creating a constructor-style initializer, ensuring we get the
  6761. // same form.
  6762. //
  6763. // Returns a node representing an expression for the initializer list expressed
  6764. // as the correct type.
  6765. //
  6766. // Returns nullptr if there is an error.
  6767. //
  6768. TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type,
  6769. TIntermTyped* initializer, TIntermTyped* scalarInit)
  6770. {
  6771. // Will operate recursively. Once a subtree is found that is constructor style,
  6772. // everything below it is already good: Only the "top part" of the initializer
  6773. // can be an initializer list, where "top part" can extend for several (or all) levels.
  6774. // see if we have bottomed out in the tree within the initializer-list part
  6775. TIntermAggregate* initList = initializer->getAsAggregate();
  6776. if (initList == nullptr || initList->getOp() != EOpNull) {
  6777. // We don't have a list, but if it's a scalar and the 'type' is a
  6778. // composite, we need to lengthen below to make it useful.
  6779. // Otherwise, this is an already formed object to initialize with.
  6780. if (type.isScalar() || !initializer->getType().isScalar())
  6781. return initializer;
  6782. else
  6783. initList = intermediate.makeAggregate(initializer);
  6784. }
  6785. // Of the initializer-list set of nodes, need to process bottom up,
  6786. // so recurse deep, then process on the way up.
  6787. // Go down the tree here...
  6788. if (type.isArray()) {
  6789. // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
  6790. // Later on, initializer execution code will deal with array size logic.
  6791. TType arrayType;
  6792. arrayType.shallowCopy(type); // sharing struct stuff is fine
  6793. arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
  6794. // edit array sizes to fill in unsized dimensions
  6795. if (type.isUnsizedArray())
  6796. arrayType.changeOuterArraySize((int)initList->getSequence().size());
  6797. // set unsized array dimensions that can be derived from the initializer's first element
  6798. if (arrayType.isArrayOfArrays() && initList->getSequence().size() > 0) {
  6799. TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
  6800. if (firstInit->getType().isArray() &&
  6801. arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
  6802. for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
  6803. if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
  6804. arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
  6805. }
  6806. }
  6807. }
  6808. // lengthen list to be long enough
  6809. lengthenList(loc, initList->getSequence(), arrayType.getOuterArraySize(), scalarInit);
  6810. // recursively process each element
  6811. TType elementType(arrayType, 0); // dereferenced type
  6812. for (int i = 0; i < arrayType.getOuterArraySize(); ++i) {
  6813. initList->getSequence()[i] = convertInitializerList(loc, elementType,
  6814. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6815. if (initList->getSequence()[i] == nullptr)
  6816. return nullptr;
  6817. }
  6818. return addConstructor(loc, initList, arrayType);
  6819. } else if (type.isStruct()) {
  6820. // do we have implicit assignments to opaques?
  6821. for (size_t i = initList->getSequence().size(); i < type.getStruct()->size(); ++i) {
  6822. if ((*type.getStruct())[i].type->containsOpaque()) {
  6823. error(loc, "cannot implicitly initialize opaque members", "initializer list", "");
  6824. return nullptr;
  6825. }
  6826. }
  6827. // lengthen list to be long enough
  6828. lengthenList(loc, initList->getSequence(), static_cast<int>(type.getStruct()->size()), scalarInit);
  6829. if (type.getStruct()->size() != initList->getSequence().size()) {
  6830. error(loc, "wrong number of structure members", "initializer list", "");
  6831. return nullptr;
  6832. }
  6833. for (size_t i = 0; i < type.getStruct()->size(); ++i) {
  6834. initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type,
  6835. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6836. if (initList->getSequence()[i] == nullptr)
  6837. return nullptr;
  6838. }
  6839. } else if (type.isMatrix()) {
  6840. if (type.computeNumComponents() == (int)initList->getSequence().size()) {
  6841. // This means the matrix is initialized component-wise, rather than as
  6842. // a series of rows and columns. We can just use the list directly as
  6843. // a constructor; no further processing needed.
  6844. } else {
  6845. // lengthen list to be long enough
  6846. lengthenList(loc, initList->getSequence(), type.getMatrixCols(), scalarInit);
  6847. if (type.getMatrixCols() != (int)initList->getSequence().size()) {
  6848. error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
  6849. return nullptr;
  6850. }
  6851. TType vectorType(type, 0); // dereferenced type
  6852. for (int i = 0; i < type.getMatrixCols(); ++i) {
  6853. initList->getSequence()[i] = convertInitializerList(loc, vectorType,
  6854. initList->getSequence()[i]->getAsTyped(), scalarInit);
  6855. if (initList->getSequence()[i] == nullptr)
  6856. return nullptr;
  6857. }
  6858. }
  6859. } else if (type.isVector()) {
  6860. // lengthen list to be long enough
  6861. lengthenList(loc, initList->getSequence(), type.getVectorSize(), scalarInit);
  6862. // error check; we're at bottom, so work is finished below
  6863. if (type.getVectorSize() != (int)initList->getSequence().size()) {
  6864. error(loc, "wrong vector size (or rows in a matrix column):", "initializer list",
  6865. type.getCompleteString().c_str());
  6866. return nullptr;
  6867. }
  6868. } else if (type.isScalar()) {
  6869. // lengthen list to be long enough
  6870. lengthenList(loc, initList->getSequence(), 1, scalarInit);
  6871. if ((int)initList->getSequence().size() != 1) {
  6872. error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
  6873. return nullptr;
  6874. }
  6875. } else {
  6876. error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
  6877. return nullptr;
  6878. }
  6879. // Now that the subtree is processed, process this node as if the
  6880. // initializer list is a set of arguments to a constructor.
  6881. TIntermTyped* emulatedConstructorArguments;
  6882. if (initList->getSequence().size() == 1)
  6883. emulatedConstructorArguments = initList->getSequence()[0]->getAsTyped();
  6884. else
  6885. emulatedConstructorArguments = initList;
  6886. return addConstructor(loc, emulatedConstructorArguments, type);
  6887. }
  6888. // Lengthen list to be long enough to cover any gap from the current list size
  6889. // to 'size'. If the list is longer, do nothing.
  6890. // The value to lengthen with is the default for short lists.
  6891. //
  6892. // By default, lists that are too short due to lack of initializers initialize to zero.
  6893. // Alternatively, it could be a scalar initializer for a structure. Both cases are handled,
  6894. // based on whether something is passed in as 'scalarInit'.
  6895. //
  6896. // 'scalarInit' must be safe to use each time this is called (no side effects replication).
  6897. //
  6898. void HlslParseContext::lengthenList(const TSourceLoc& loc, TIntermSequence& list, int size, TIntermTyped* scalarInit)
  6899. {
  6900. for (int c = (int)list.size(); c < size; ++c) {
  6901. if (scalarInit == nullptr)
  6902. list.push_back(intermediate.addConstantUnion(0, loc));
  6903. else
  6904. list.push_back(scalarInit);
  6905. }
  6906. }
  6907. //
  6908. // Test for the correctness of the parameters passed to various constructor functions
  6909. // and also convert them to the right data type, if allowed and required.
  6910. //
  6911. // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
  6912. //
  6913. TIntermTyped* HlslParseContext::handleConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6914. {
  6915. if (node == nullptr)
  6916. return nullptr;
  6917. // Construct identical type
  6918. if (type == node->getType())
  6919. return node;
  6920. // Handle the idiom "(struct type)<scalar value>"
  6921. if (type.isStruct() && isScalarConstructor(node)) {
  6922. // 'node' will almost always get used multiple times, so should not be used directly,
  6923. // it would create a DAG instead of a tree, which might be okay (would
  6924. // like to formalize that for constants and symbols), but if it has
  6925. // side effects, they would get executed multiple times, which is not okay.
  6926. if (node->getAsConstantUnion() == nullptr && node->getAsSymbolNode() == nullptr) {
  6927. TIntermAggregate* seq = intermediate.makeAggregate(loc);
  6928. TIntermSymbol* copy = makeInternalVariableNode(loc, "scalarCopy", node->getType());
  6929. seq = intermediate.growAggregate(seq, intermediate.addBinaryNode(EOpAssign, copy, node, loc));
  6930. seq = intermediate.growAggregate(seq, convertInitializerList(loc, type, intermediate.makeAggregate(loc), copy));
  6931. seq->setOp(EOpComma);
  6932. seq->setType(type);
  6933. return seq;
  6934. } else
  6935. return convertInitializerList(loc, type, intermediate.makeAggregate(loc), node);
  6936. }
  6937. return addConstructor(loc, node, type);
  6938. }
  6939. // Add a constructor, either from the grammar, or other programmatic reasons.
  6940. //
  6941. // 'node' is what to construct from.
  6942. // 'type' is what type to construct.
  6943. //
  6944. // Returns the constructed object.
  6945. // Return nullptr if it can't be done.
  6946. //
  6947. TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermTyped* node, const TType& type)
  6948. {
  6949. TIntermAggregate* aggrNode = node->getAsAggregate();
  6950. TOperator op = intermediate.mapTypeToConstructorOp(type);
  6951. if (op == EOpConstructTextureSampler)
  6952. return intermediate.setAggregateOperator(aggrNode, op, type, loc);
  6953. TTypeList::const_iterator memberTypes;
  6954. if (op == EOpConstructStruct)
  6955. memberTypes = type.getStruct()->begin();
  6956. TType elementType;
  6957. if (type.isArray()) {
  6958. TType dereferenced(type, 0);
  6959. elementType.shallowCopy(dereferenced);
  6960. } else
  6961. elementType.shallowCopy(type);
  6962. bool singleArg;
  6963. if (aggrNode != nullptr) {
  6964. if (aggrNode->getOp() != EOpNull)
  6965. singleArg = true;
  6966. else
  6967. singleArg = false;
  6968. } else
  6969. singleArg = true;
  6970. TIntermTyped *newNode;
  6971. if (singleArg) {
  6972. // Handle array -> array conversion
  6973. // Constructing an array of one type from an array of another type is allowed,
  6974. // assuming there are enough components available (semantic-checked earlier).
  6975. if (type.isArray() && node->isArray())
  6976. newNode = convertArray(node, type);
  6977. // If structure constructor or array constructor is being called
  6978. // for only one parameter inside the aggregate, we need to call constructAggregate function once.
  6979. else if (type.isArray())
  6980. newNode = constructAggregate(node, elementType, 1, node->getLoc());
  6981. else if (op == EOpConstructStruct)
  6982. newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
  6983. else {
  6984. // shape conversion for matrix constructor from scalar. HLSL semantics are: scalar
  6985. // is replicated into every element of the matrix (not just the diagnonal), so
  6986. // that is handled specially here.
  6987. if (type.isMatrix() && node->getType().isScalarOrVec1())
  6988. node = intermediate.addShapeConversion(type, node);
  6989. newNode = constructBuiltIn(type, op, node, node->getLoc(), false);
  6990. }
  6991. if (newNode && (type.isArray() || op == EOpConstructStruct))
  6992. newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
  6993. return newNode;
  6994. }
  6995. //
  6996. // Handle list of arguments.
  6997. //
  6998. TIntermSequence& sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
  6999. // if the structure constructor contains more than one parameter, then construct
  7000. // each parameter
  7001. int paramCount = 0; // keeps a track of the constructor parameter number being checked
  7002. // for each parameter to the constructor call, check to see if the right type is passed or convert them
  7003. // to the right type if possible (and allowed).
  7004. // for structure constructors, just check if the right type is passed, no conversion is allowed.
  7005. for (TIntermSequence::iterator p = sequenceVector.begin();
  7006. p != sequenceVector.end(); p++, paramCount++) {
  7007. if (type.isArray())
  7008. newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
  7009. else if (op == EOpConstructStruct)
  7010. newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
  7011. else
  7012. newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
  7013. if (newNode)
  7014. *p = newNode;
  7015. else
  7016. return nullptr;
  7017. }
  7018. TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
  7019. return constructor;
  7020. }
  7021. // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
  7022. // for the parameter to the constructor (passed to this function). Essentially, it converts
  7023. // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
  7024. // float, then float is converted to int.
  7025. //
  7026. // Returns nullptr for an error or the constructed node.
  7027. //
  7028. TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node,
  7029. const TSourceLoc& loc, bool subset)
  7030. {
  7031. TIntermTyped* newNode;
  7032. TOperator basicOp;
  7033. //
  7034. // First, convert types as needed.
  7035. //
  7036. switch (op) {
  7037. case EOpConstructF16Vec2:
  7038. case EOpConstructF16Vec3:
  7039. case EOpConstructF16Vec4:
  7040. case EOpConstructF16Mat2x2:
  7041. case EOpConstructF16Mat2x3:
  7042. case EOpConstructF16Mat2x4:
  7043. case EOpConstructF16Mat3x2:
  7044. case EOpConstructF16Mat3x3:
  7045. case EOpConstructF16Mat3x4:
  7046. case EOpConstructF16Mat4x2:
  7047. case EOpConstructF16Mat4x3:
  7048. case EOpConstructF16Mat4x4:
  7049. case EOpConstructFloat16:
  7050. basicOp = EOpConstructFloat16;
  7051. break;
  7052. case EOpConstructVec2:
  7053. case EOpConstructVec3:
  7054. case EOpConstructVec4:
  7055. case EOpConstructMat2x2:
  7056. case EOpConstructMat2x3:
  7057. case EOpConstructMat2x4:
  7058. case EOpConstructMat3x2:
  7059. case EOpConstructMat3x3:
  7060. case EOpConstructMat3x4:
  7061. case EOpConstructMat4x2:
  7062. case EOpConstructMat4x3:
  7063. case EOpConstructMat4x4:
  7064. case EOpConstructFloat:
  7065. basicOp = EOpConstructFloat;
  7066. break;
  7067. case EOpConstructDVec2:
  7068. case EOpConstructDVec3:
  7069. case EOpConstructDVec4:
  7070. case EOpConstructDMat2x2:
  7071. case EOpConstructDMat2x3:
  7072. case EOpConstructDMat2x4:
  7073. case EOpConstructDMat3x2:
  7074. case EOpConstructDMat3x3:
  7075. case EOpConstructDMat3x4:
  7076. case EOpConstructDMat4x2:
  7077. case EOpConstructDMat4x3:
  7078. case EOpConstructDMat4x4:
  7079. case EOpConstructDouble:
  7080. basicOp = EOpConstructDouble;
  7081. break;
  7082. case EOpConstructI16Vec2:
  7083. case EOpConstructI16Vec3:
  7084. case EOpConstructI16Vec4:
  7085. case EOpConstructInt16:
  7086. basicOp = EOpConstructInt16;
  7087. break;
  7088. case EOpConstructIVec2:
  7089. case EOpConstructIVec3:
  7090. case EOpConstructIVec4:
  7091. case EOpConstructIMat2x2:
  7092. case EOpConstructIMat2x3:
  7093. case EOpConstructIMat2x4:
  7094. case EOpConstructIMat3x2:
  7095. case EOpConstructIMat3x3:
  7096. case EOpConstructIMat3x4:
  7097. case EOpConstructIMat4x2:
  7098. case EOpConstructIMat4x3:
  7099. case EOpConstructIMat4x4:
  7100. case EOpConstructInt:
  7101. basicOp = EOpConstructInt;
  7102. break;
  7103. case EOpConstructU16Vec2:
  7104. case EOpConstructU16Vec3:
  7105. case EOpConstructU16Vec4:
  7106. case EOpConstructUint16:
  7107. basicOp = EOpConstructUint16;
  7108. break;
  7109. case EOpConstructUVec2:
  7110. case EOpConstructUVec3:
  7111. case EOpConstructUVec4:
  7112. case EOpConstructUMat2x2:
  7113. case EOpConstructUMat2x3:
  7114. case EOpConstructUMat2x4:
  7115. case EOpConstructUMat3x2:
  7116. case EOpConstructUMat3x3:
  7117. case EOpConstructUMat3x4:
  7118. case EOpConstructUMat4x2:
  7119. case EOpConstructUMat4x3:
  7120. case EOpConstructUMat4x4:
  7121. case EOpConstructUint:
  7122. basicOp = EOpConstructUint;
  7123. break;
  7124. case EOpConstructBVec2:
  7125. case EOpConstructBVec3:
  7126. case EOpConstructBVec4:
  7127. case EOpConstructBMat2x2:
  7128. case EOpConstructBMat2x3:
  7129. case EOpConstructBMat2x4:
  7130. case EOpConstructBMat3x2:
  7131. case EOpConstructBMat3x3:
  7132. case EOpConstructBMat3x4:
  7133. case EOpConstructBMat4x2:
  7134. case EOpConstructBMat4x3:
  7135. case EOpConstructBMat4x4:
  7136. case EOpConstructBool:
  7137. basicOp = EOpConstructBool;
  7138. break;
  7139. default:
  7140. error(loc, "unsupported construction", "", "");
  7141. return nullptr;
  7142. }
  7143. newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
  7144. if (newNode == nullptr) {
  7145. error(loc, "can't convert", "constructor", "");
  7146. return nullptr;
  7147. }
  7148. //
  7149. // Now, if there still isn't an operation to do the construction, and we need one, add one.
  7150. //
  7151. // Otherwise, skip out early.
  7152. if (subset || (newNode != node && newNode->getType() == type))
  7153. return newNode;
  7154. // setAggregateOperator will insert a new node for the constructor, as needed.
  7155. return intermediate.setAggregateOperator(newNode, op, type, loc);
  7156. }
  7157. // Convert the array in node to the requested type, which is also an array.
  7158. // Returns nullptr on failure, otherwise returns aggregate holding the list of
  7159. // elements needed to construct the array.
  7160. TIntermTyped* HlslParseContext::convertArray(TIntermTyped* node, const TType& type)
  7161. {
  7162. assert(node->isArray() && type.isArray());
  7163. if (node->getType().computeNumComponents() < type.computeNumComponents())
  7164. return nullptr;
  7165. // TODO: write an argument replicator, for the case the argument should not be
  7166. // executed multiple times, yet multiple copies are needed.
  7167. TIntermTyped* constructee = node->getAsTyped();
  7168. // track where we are in consuming the argument
  7169. int constructeeElement = 0;
  7170. int constructeeComponent = 0;
  7171. // bump up to the next component to consume
  7172. const auto getNextComponent = [&]() {
  7173. TIntermTyped* component;
  7174. component = handleBracketDereference(node->getLoc(), constructee,
  7175. intermediate.addConstantUnion(constructeeElement, node->getLoc()));
  7176. if (component->isVector())
  7177. component = handleBracketDereference(node->getLoc(), component,
  7178. intermediate.addConstantUnion(constructeeComponent, node->getLoc()));
  7179. // bump component pointer up
  7180. ++constructeeComponent;
  7181. if (constructeeComponent == constructee->getVectorSize()) {
  7182. constructeeComponent = 0;
  7183. ++constructeeElement;
  7184. }
  7185. return component;
  7186. };
  7187. // make one subnode per constructed array element
  7188. TIntermAggregate* constructor = nullptr;
  7189. TType derefType(type, 0);
  7190. TType speculativeComponentType(derefType, 0);
  7191. TType* componentType = derefType.isVector() ? &speculativeComponentType : &derefType;
  7192. TOperator componentOp = intermediate.mapTypeToConstructorOp(*componentType);
  7193. TType crossType(node->getBasicType(), EvqTemporary, type.getVectorSize());
  7194. for (int e = 0; e < type.getOuterArraySize(); ++e) {
  7195. // construct an element
  7196. TIntermTyped* elementArg;
  7197. if (type.getVectorSize() == constructee->getVectorSize()) {
  7198. // same element shape
  7199. elementArg = handleBracketDereference(node->getLoc(), constructee,
  7200. intermediate.addConstantUnion(e, node->getLoc()));
  7201. } else {
  7202. // mismatched element shapes
  7203. if (type.getVectorSize() == 1)
  7204. elementArg = getNextComponent();
  7205. else {
  7206. // make a vector
  7207. TIntermAggregate* elementConstructee = nullptr;
  7208. for (int c = 0; c < type.getVectorSize(); ++c)
  7209. elementConstructee = intermediate.growAggregate(elementConstructee, getNextComponent());
  7210. elementArg = addConstructor(node->getLoc(), elementConstructee, crossType);
  7211. }
  7212. }
  7213. // convert basic types
  7214. elementArg = intermediate.addConversion(componentOp, derefType, elementArg);
  7215. if (elementArg == nullptr)
  7216. return nullptr;
  7217. // combine with top-level constructor
  7218. constructor = intermediate.growAggregate(constructor, elementArg);
  7219. }
  7220. return constructor;
  7221. }
  7222. // This function tests for the type of the parameters to the structure or array constructor. Raises
  7223. // an error message if the expected type does not match the parameter passed to the constructor.
  7224. //
  7225. // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
  7226. //
  7227. TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount,
  7228. const TSourceLoc& loc)
  7229. {
  7230. // Handle cases that map more 1:1 between constructor arguments and constructed.
  7231. TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
  7232. if (converted == nullptr || converted->getType() != type) {
  7233. error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
  7234. node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
  7235. return nullptr;
  7236. }
  7237. return converted;
  7238. }
  7239. //
  7240. // Do everything needed to add an interface block.
  7241. //
  7242. void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName)
  7243. {
  7244. assert(type.getWritableStruct() != nullptr);
  7245. // Clean up top-level decorations that don't belong.
  7246. switch (type.getQualifier().storage) {
  7247. case EvqUniform:
  7248. case EvqBuffer:
  7249. correctUniform(type.getQualifier());
  7250. break;
  7251. case EvqVaryingIn:
  7252. correctInput(type.getQualifier());
  7253. break;
  7254. case EvqVaryingOut:
  7255. correctOutput(type.getQualifier());
  7256. break;
  7257. default:
  7258. break;
  7259. }
  7260. TTypeList& typeList = *type.getWritableStruct();
  7261. // fix and check for member storage qualifiers and types that don't belong within a block
  7262. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7263. TType& memberType = *typeList[member].type;
  7264. TQualifier& memberQualifier = memberType.getQualifier();
  7265. const TSourceLoc& memberLoc = typeList[member].loc;
  7266. globalQualifierFix(memberLoc, memberQualifier);
  7267. memberQualifier.storage = type.getQualifier().storage;
  7268. if (memberType.isStruct()) {
  7269. // clean up and pick up the right set of decorations
  7270. auto it = ioTypeMap.find(memberType.getStruct());
  7271. switch (type.getQualifier().storage) {
  7272. case EvqUniform:
  7273. case EvqBuffer:
  7274. correctUniform(type.getQualifier());
  7275. if (it != ioTypeMap.end() && it->second.uniform)
  7276. memberType.setStruct(it->second.uniform);
  7277. break;
  7278. case EvqVaryingIn:
  7279. correctInput(type.getQualifier());
  7280. if (it != ioTypeMap.end() && it->second.input)
  7281. memberType.setStruct(it->second.input);
  7282. break;
  7283. case EvqVaryingOut:
  7284. correctOutput(type.getQualifier());
  7285. if (it != ioTypeMap.end() && it->second.output)
  7286. memberType.setStruct(it->second.output);
  7287. break;
  7288. default:
  7289. break;
  7290. }
  7291. }
  7292. }
  7293. // Make default block qualification, and adjust the member qualifications
  7294. TQualifier defaultQualification;
  7295. switch (type.getQualifier().storage) {
  7296. case EvqUniform: defaultQualification = globalUniformDefaults; break;
  7297. case EvqBuffer: defaultQualification = globalBufferDefaults; break;
  7298. case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
  7299. case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
  7300. default: defaultQualification.clear(); break;
  7301. }
  7302. // Special case for "push_constant uniform", which has a default of std430,
  7303. // contrary to normal uniform defaults, and can't have a default tracked for it.
  7304. if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
  7305. type.getQualifier().layoutPacking = ElpStd430;
  7306. // fix and check for member layout qualifiers
  7307. mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
  7308. bool memberWithLocation = false;
  7309. bool memberWithoutLocation = false;
  7310. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7311. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7312. const TSourceLoc& memberLoc = typeList[member].loc;
  7313. if (memberQualifier.hasStream()) {
  7314. if (defaultQualification.layoutStream != memberQualifier.layoutStream)
  7315. error(memberLoc, "member cannot contradict block", "stream", "");
  7316. }
  7317. // "This includes a block's inheritance of the
  7318. // current global default buffer, a block member's inheritance of the block's
  7319. // buffer, and the requirement that any *xfb_buffer* declared on a block
  7320. // member must match the buffer inherited from the block."
  7321. if (memberQualifier.hasXfbBuffer()) {
  7322. if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
  7323. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
  7324. }
  7325. if (memberQualifier.hasLocation()) {
  7326. switch (type.getQualifier().storage) {
  7327. case EvqVaryingIn:
  7328. case EvqVaryingOut:
  7329. memberWithLocation = true;
  7330. break;
  7331. default:
  7332. break;
  7333. }
  7334. } else
  7335. memberWithoutLocation = true;
  7336. TQualifier newMemberQualification = defaultQualification;
  7337. mergeQualifiers(newMemberQualification, memberQualifier);
  7338. memberQualifier = newMemberQualification;
  7339. }
  7340. // Process the members
  7341. fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
  7342. fixXfbOffsets(type.getQualifier(), typeList);
  7343. fixBlockUniformOffsets(type.getQualifier(), typeList);
  7344. // reverse merge, so that currentBlockQualifier now has all layout information
  7345. // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
  7346. mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
  7347. //
  7348. // Build and add the interface block as a new type named 'blockName'
  7349. //
  7350. // Use the instance name as the interface name if one exists, else the block name.
  7351. const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
  7352. TType blockType(&typeList, interfaceName, type.getQualifier());
  7353. if (type.isArray())
  7354. blockType.transferArraySizes(type.getArraySizes());
  7355. // Add the variable, as anonymous or named instanceName.
  7356. // Make an anonymous variable if no name was provided.
  7357. if (instanceName == nullptr)
  7358. instanceName = NewPoolTString("");
  7359. TVariable& variable = *new TVariable(instanceName, blockType);
  7360. if (! symbolTable.insert(variable)) {
  7361. if (*instanceName == "")
  7362. error(loc, "nameless block contains a member that already has a name at global scope",
  7363. "" /* blockName->c_str() */, "");
  7364. else
  7365. error(loc, "block instance name redefinition", variable.getName().c_str(), "");
  7366. return;
  7367. }
  7368. // Save it in the AST for linker use.
  7369. if (symbolTable.atGlobalLevel())
  7370. trackLinkage(variable);
  7371. }
  7372. //
  7373. // "For a block, this process applies to the entire block, or until the first member
  7374. // is reached that has a location layout qualifier. When a block member is declared with a location
  7375. // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
  7376. // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
  7377. // until the next member declared with a location qualifier. The values used for locations do not have to be
  7378. // declared in increasing order."
  7379. void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
  7380. {
  7381. // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
  7382. // have a location layout qualifier, or a compile-time error results."
  7383. if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
  7384. error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
  7385. else {
  7386. if (memberWithLocation) {
  7387. // remove any block-level location and make it per *every* member
  7388. int nextLocation = 0; // by the rule above, initial value is not relevant
  7389. if (qualifier.hasAnyLocation()) {
  7390. nextLocation = qualifier.layoutLocation;
  7391. qualifier.layoutLocation = TQualifier::layoutLocationEnd;
  7392. if (qualifier.hasComponent()) {
  7393. // "It is a compile-time error to apply the *component* qualifier to a ... block"
  7394. error(loc, "cannot apply to a block", "component", "");
  7395. }
  7396. if (qualifier.hasIndex()) {
  7397. error(loc, "cannot apply to a block", "index", "");
  7398. }
  7399. }
  7400. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7401. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7402. const TSourceLoc& memberLoc = typeList[member].loc;
  7403. if (! memberQualifier.hasLocation()) {
  7404. if (nextLocation >= (int)TQualifier::layoutLocationEnd)
  7405. error(memberLoc, "location is too large", "location", "");
  7406. memberQualifier.layoutLocation = nextLocation;
  7407. memberQualifier.layoutComponent = 0;
  7408. }
  7409. nextLocation = memberQualifier.layoutLocation +
  7410. intermediate.computeTypeLocationSize(*typeList[member].type, language);
  7411. }
  7412. }
  7413. }
  7414. }
  7415. void HlslParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
  7416. {
  7417. // "If a block is qualified with xfb_offset, all its
  7418. // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
  7419. // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
  7420. // offsets."
  7421. if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
  7422. return;
  7423. int nextOffset = qualifier.layoutXfbOffset;
  7424. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7425. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7426. bool contains64BitType = false;
  7427. #ifdef AMD_EXTENSIONS
  7428. bool contains32BitType = false;
  7429. bool contains16BitType = false;
  7430. int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
  7431. #else
  7432. int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType);
  7433. #endif
  7434. // see if we need to auto-assign an offset to this member
  7435. if (! memberQualifier.hasXfbOffset()) {
  7436. // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
  7437. if (contains64BitType)
  7438. RoundToPow2(nextOffset, 8);
  7439. #ifdef AMD_EXTENSIONS
  7440. else if (contains32BitType)
  7441. RoundToPow2(nextOffset, 4);
  7442. // "if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2"
  7443. else if (contains16BitType)
  7444. RoundToPow2(nextOffset, 2);
  7445. #endif
  7446. memberQualifier.layoutXfbOffset = nextOffset;
  7447. } else
  7448. nextOffset = memberQualifier.layoutXfbOffset;
  7449. nextOffset += memberSize;
  7450. }
  7451. // The above gave all block members an offset, so we can take it off the block now,
  7452. // which will avoid double counting the offset usage.
  7453. qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
  7454. }
  7455. // Calculate and save the offset of each block member, using the recursively
  7456. // defined block offset rules and the user-provided offset and align.
  7457. //
  7458. // Also, compute and save the total size of the block. For the block's size, arrayness
  7459. // is not taken into account, as each element is backed by a separate buffer.
  7460. //
  7461. void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
  7462. {
  7463. if (! qualifier.isUniformOrBuffer())
  7464. return;
  7465. if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
  7466. return;
  7467. int offset = 0;
  7468. int memberSize;
  7469. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7470. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7471. const TSourceLoc& memberLoc = typeList[member].loc;
  7472. // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
  7473. // modify just the children's view of matrix layout, if there is one for this member
  7474. TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
  7475. int dummyStride;
  7476. int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride,
  7477. qualifier.layoutPacking,
  7478. subMatrixLayout != ElmNone
  7479. ? subMatrixLayout == ElmRowMajor
  7480. : qualifier.layoutMatrix == ElmRowMajor);
  7481. if (memberQualifier.hasOffset()) {
  7482. // "The specified offset must be a multiple
  7483. // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
  7484. if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
  7485. error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
  7486. // "The offset qualifier forces the qualified member to start at or after the specified
  7487. // integral-constant expression, which will be its byte offset from the beginning of the buffer.
  7488. // "The actual offset of a member is computed as
  7489. // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
  7490. offset = std::max(offset, memberQualifier.layoutOffset);
  7491. }
  7492. // "The actual alignment of a member will be the greater of the specified align alignment and the standard
  7493. // (e.g., std140) base alignment for the member's type."
  7494. if (memberQualifier.hasAlign())
  7495. memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
  7496. // "If the resulting offset is not a multiple of the actual alignment,
  7497. // increase it to the first offset that is a multiple of
  7498. // the actual alignment."
  7499. RoundToPow2(offset, memberAlignment);
  7500. typeList[member].type->getQualifier().layoutOffset = offset;
  7501. offset += memberSize;
  7502. }
  7503. }
  7504. // For an identifier that is already declared, add more qualification to it.
  7505. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
  7506. {
  7507. TSymbol* symbol = symbolTable.find(identifier);
  7508. if (symbol == nullptr) {
  7509. error(loc, "identifier not previously declared", identifier.c_str(), "");
  7510. return;
  7511. }
  7512. if (symbol->getAsFunction()) {
  7513. error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
  7514. return;
  7515. }
  7516. if (qualifier.isAuxiliary() ||
  7517. qualifier.isMemory() ||
  7518. qualifier.isInterpolation() ||
  7519. qualifier.hasLayout() ||
  7520. qualifier.storage != EvqTemporary ||
  7521. qualifier.precision != EpqNone) {
  7522. error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
  7523. return;
  7524. }
  7525. // For read-only built-ins, add a new symbol for holding the modified qualifier.
  7526. // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
  7527. if (symbol->isReadOnly())
  7528. symbol = symbolTable.copyUp(symbol);
  7529. if (qualifier.invariant) {
  7530. if (intermediate.inIoAccessed(identifier))
  7531. error(loc, "cannot change qualification after use", "invariant", "");
  7532. symbol->getWritableType().getQualifier().invariant = true;
  7533. } else if (qualifier.noContraction) {
  7534. if (intermediate.inIoAccessed(identifier))
  7535. error(loc, "cannot change qualification after use", "precise", "");
  7536. symbol->getWritableType().getQualifier().noContraction = true;
  7537. } else if (qualifier.specConstant) {
  7538. symbol->getWritableType().getQualifier().makeSpecConstant();
  7539. if (qualifier.hasSpecConstantId())
  7540. symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
  7541. } else
  7542. warn(loc, "unknown requalification", "", "");
  7543. }
  7544. void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
  7545. {
  7546. for (unsigned int i = 0; i < identifiers.size(); ++i)
  7547. addQualifierToExisting(loc, qualifier, *identifiers[i]);
  7548. }
  7549. //
  7550. // Update the intermediate for the given input geometry
  7551. //
  7552. bool HlslParseContext::handleInputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7553. {
  7554. switch (geometry) {
  7555. case ElgPoints: // fall through
  7556. case ElgLines: // ...
  7557. case ElgTriangles: // ...
  7558. case ElgLinesAdjacency: // ...
  7559. case ElgTrianglesAdjacency: // ...
  7560. if (! intermediate.setInputPrimitive(geometry)) {
  7561. error(loc, "input primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7562. return false;
  7563. }
  7564. break;
  7565. default:
  7566. error(loc, "cannot apply to 'in'", TQualifier::getGeometryString(geometry), "");
  7567. return false;
  7568. }
  7569. return true;
  7570. }
  7571. //
  7572. // Update the intermediate for the given output geometry
  7573. //
  7574. bool HlslParseContext::handleOutputGeometry(const TSourceLoc& loc, const TLayoutGeometry& geometry)
  7575. {
  7576. // If this is not a geometry shader, ignore. It might be a mixed shader including several stages.
  7577. // Since that's an OK situation, return true for success.
  7578. if (language != EShLangGeometry)
  7579. return true;
  7580. switch (geometry) {
  7581. case ElgPoints:
  7582. case ElgLineStrip:
  7583. case ElgTriangleStrip:
  7584. if (! intermediate.setOutputPrimitive(geometry)) {
  7585. error(loc, "output primitive geometry redefinition", TQualifier::getGeometryString(geometry), "");
  7586. return false;
  7587. }
  7588. break;
  7589. default:
  7590. error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(geometry), "");
  7591. return false;
  7592. }
  7593. return true;
  7594. }
  7595. //
  7596. // Selection attributes
  7597. //
  7598. void HlslParseContext::handleSelectionAttributes(const TSourceLoc& loc, TIntermSelection* selection,
  7599. const TAttributes& attributes)
  7600. {
  7601. if (selection == nullptr)
  7602. return;
  7603. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7604. switch (it->name) {
  7605. case EatFlatten:
  7606. selection->setFlatten();
  7607. break;
  7608. case EatBranch:
  7609. selection->setDontFlatten();
  7610. break;
  7611. default:
  7612. warn(loc, "attribute does not apply to a selection", "", "");
  7613. break;
  7614. }
  7615. }
  7616. }
  7617. //
  7618. // Switch attributes
  7619. //
  7620. void HlslParseContext::handleSwitchAttributes(const TSourceLoc& loc, TIntermSwitch* selection,
  7621. const TAttributes& attributes)
  7622. {
  7623. if (selection == nullptr)
  7624. return;
  7625. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7626. switch (it->name) {
  7627. case EatFlatten:
  7628. selection->setFlatten();
  7629. break;
  7630. case EatBranch:
  7631. selection->setDontFlatten();
  7632. break;
  7633. default:
  7634. warn(loc, "attribute does not apply to a switch", "", "");
  7635. break;
  7636. }
  7637. }
  7638. }
  7639. //
  7640. // Loop attributes
  7641. //
  7642. void HlslParseContext::handleLoopAttributes(const TSourceLoc& loc, TIntermLoop* loop,
  7643. const TAttributes& attributes)
  7644. {
  7645. if (loop == nullptr)
  7646. return;
  7647. for (auto it = attributes.begin(); it != attributes.end(); ++it) {
  7648. switch (it->name) {
  7649. case EatUnroll:
  7650. loop->setUnroll();
  7651. break;
  7652. case EatLoop:
  7653. loop->setDontUnroll();
  7654. break;
  7655. default:
  7656. warn(loc, "attribute does not apply to a loop", "", "");
  7657. break;
  7658. }
  7659. }
  7660. }
  7661. //
  7662. // Updating default qualifier for the case of a declaration with just a qualifier,
  7663. // no type, block, or identifier.
  7664. //
  7665. void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
  7666. {
  7667. if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
  7668. assert(language == EShLangTessControl || language == EShLangGeometry);
  7669. // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
  7670. }
  7671. if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
  7672. if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
  7673. error(loc, "cannot change previously set layout value", "invocations", "");
  7674. }
  7675. if (publicType.shaderQualifiers.geometry != ElgNone) {
  7676. if (publicType.qualifier.storage == EvqVaryingIn) {
  7677. switch (publicType.shaderQualifiers.geometry) {
  7678. case ElgPoints:
  7679. case ElgLines:
  7680. case ElgLinesAdjacency:
  7681. case ElgTriangles:
  7682. case ElgTrianglesAdjacency:
  7683. case ElgQuads:
  7684. case ElgIsolines:
  7685. break;
  7686. default:
  7687. error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7688. "");
  7689. }
  7690. } else if (publicType.qualifier.storage == EvqVaryingOut) {
  7691. handleOutputGeometry(loc, publicType.shaderQualifiers.geometry);
  7692. } else
  7693. error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry),
  7694. GetStorageQualifierString(publicType.qualifier.storage));
  7695. }
  7696. if (publicType.shaderQualifiers.spacing != EvsNone)
  7697. intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
  7698. if (publicType.shaderQualifiers.order != EvoNone)
  7699. intermediate.setVertexOrder(publicType.shaderQualifiers.order);
  7700. if (publicType.shaderQualifiers.pointMode)
  7701. intermediate.setPointMode();
  7702. for (int i = 0; i < 3; ++i) {
  7703. if (publicType.shaderQualifiers.localSize[i] > 1) {
  7704. int max = 0;
  7705. switch (i) {
  7706. case 0: max = resources.maxComputeWorkGroupSizeX; break;
  7707. case 1: max = resources.maxComputeWorkGroupSizeY; break;
  7708. case 2: max = resources.maxComputeWorkGroupSizeZ; break;
  7709. default: break;
  7710. }
  7711. if (intermediate.getLocalSize(i) > (unsigned int)max)
  7712. error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
  7713. // Fix the existing constant gl_WorkGroupSize with this new information.
  7714. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7715. workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
  7716. }
  7717. if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
  7718. intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
  7719. // Set the workgroup built-in variable as a specialization constant
  7720. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  7721. workGroupSize->getWritableType().getQualifier().specConstant = true;
  7722. }
  7723. }
  7724. if (publicType.shaderQualifiers.earlyFragmentTests)
  7725. intermediate.setEarlyFragmentTests();
  7726. const TQualifier& qualifier = publicType.qualifier;
  7727. switch (qualifier.storage) {
  7728. case EvqUniform:
  7729. if (qualifier.hasMatrix())
  7730. globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
  7731. if (qualifier.hasPacking())
  7732. globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
  7733. break;
  7734. case EvqBuffer:
  7735. if (qualifier.hasMatrix())
  7736. globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
  7737. if (qualifier.hasPacking())
  7738. globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
  7739. break;
  7740. case EvqVaryingIn:
  7741. break;
  7742. case EvqVaryingOut:
  7743. if (qualifier.hasStream())
  7744. globalOutputDefaults.layoutStream = qualifier.layoutStream;
  7745. if (qualifier.hasXfbBuffer())
  7746. globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
  7747. if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
  7748. if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
  7749. error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d",
  7750. qualifier.layoutXfbBuffer);
  7751. }
  7752. break;
  7753. default:
  7754. error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
  7755. return;
  7756. }
  7757. }
  7758. //
  7759. // Take the sequence of statements that has been built up since the last case/default,
  7760. // put it on the list of top-level nodes for the current (inner-most) switch statement,
  7761. // and follow that by the case/default we are on now. (See switch topology comment on
  7762. // TIntermSwitch.)
  7763. //
  7764. void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
  7765. {
  7766. TIntermSequence* switchSequence = switchSequenceStack.back();
  7767. if (statements) {
  7768. statements->setOperator(EOpSequence);
  7769. switchSequence->push_back(statements);
  7770. }
  7771. if (branchNode) {
  7772. // check all previous cases for the same label (or both are 'default')
  7773. for (unsigned int s = 0; s < switchSequence->size(); ++s) {
  7774. TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
  7775. if (prevBranch) {
  7776. TIntermTyped* prevExpression = prevBranch->getExpression();
  7777. TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
  7778. if (prevExpression == nullptr && newExpression == nullptr)
  7779. error(branchNode->getLoc(), "duplicate label", "default", "");
  7780. else if (prevExpression != nullptr &&
  7781. newExpression != nullptr &&
  7782. prevExpression->getAsConstantUnion() &&
  7783. newExpression->getAsConstantUnion() &&
  7784. prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
  7785. newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
  7786. error(branchNode->getLoc(), "duplicated value", "case", "");
  7787. }
  7788. }
  7789. switchSequence->push_back(branchNode);
  7790. }
  7791. }
  7792. //
  7793. // Turn the top-level node sequence built up of wrapupSwitchSubsequence
  7794. // into a switch node.
  7795. //
  7796. TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression,
  7797. TIntermAggregate* lastStatements, const TAttributes& attributes)
  7798. {
  7799. wrapupSwitchSubsequence(lastStatements, nullptr);
  7800. if (expression == nullptr ||
  7801. (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
  7802. expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
  7803. error(loc, "condition must be a scalar integer expression", "switch", "");
  7804. // If there is nothing to do, drop the switch but still execute the expression
  7805. TIntermSequence* switchSequence = switchSequenceStack.back();
  7806. if (switchSequence->size() == 0)
  7807. return expression;
  7808. if (lastStatements == nullptr) {
  7809. // emulate a break for error recovery
  7810. lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
  7811. lastStatements->setOperator(EOpSequence);
  7812. switchSequence->push_back(lastStatements);
  7813. }
  7814. TIntermAggregate* body = new TIntermAggregate(EOpSequence);
  7815. body->getSequence() = *switchSequenceStack.back();
  7816. body->setLoc(loc);
  7817. TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
  7818. switchNode->setLoc(loc);
  7819. handleSwitchAttributes(loc, switchNode, attributes);
  7820. return switchNode;
  7821. }
  7822. // Make a new symbol-table level that is made out of the members of a structure.
  7823. // This should be done as an anonymous struct (name is "") so that the symbol table
  7824. // finds the members with no explicit reference to a 'this' variable.
  7825. void HlslParseContext::pushThisScope(const TType& thisStruct, const TVector<TFunctionDeclarator>& functionDeclarators)
  7826. {
  7827. // member variables
  7828. TVariable& thisVariable = *new TVariable(NewPoolTString(""), thisStruct);
  7829. symbolTable.pushThis(thisVariable);
  7830. // member functions
  7831. for (auto it = functionDeclarators.begin(); it != functionDeclarators.end(); ++it) {
  7832. // member should have a prefix matching currentTypePrefix.back()
  7833. // but, symbol lookup within the class scope will just use the
  7834. // unprefixed name. Hence, there are two: one fully prefixed and
  7835. // one with no prefix.
  7836. TFunction& member = *it->function->clone();
  7837. member.removePrefix(currentTypePrefix.back());
  7838. symbolTable.insert(member);
  7839. }
  7840. }
  7841. // Track levels of class/struct/namespace nesting with a prefix string using
  7842. // the type names separated by the scoping operator. E.g., two levels
  7843. // would look like:
  7844. //
  7845. // outer::inner
  7846. //
  7847. // The string is empty when at normal global level.
  7848. //
  7849. void HlslParseContext::pushNamespace(const TString& typeName)
  7850. {
  7851. // make new type prefix
  7852. TString newPrefix;
  7853. if (currentTypePrefix.size() > 0)
  7854. newPrefix = currentTypePrefix.back();
  7855. newPrefix.append(typeName);
  7856. newPrefix.append(scopeMangler);
  7857. currentTypePrefix.push_back(newPrefix);
  7858. }
  7859. // Opposite of pushNamespace(), see above
  7860. void HlslParseContext::popNamespace()
  7861. {
  7862. currentTypePrefix.pop_back();
  7863. }
  7864. // Use the class/struct nesting string to create a global name for
  7865. // a member of a class/struct.
  7866. void HlslParseContext::getFullNamespaceName(TString*& name) const
  7867. {
  7868. if (currentTypePrefix.size() == 0)
  7869. return;
  7870. TString* fullName = NewPoolTString(currentTypePrefix.back().c_str());
  7871. fullName->append(*name);
  7872. name = fullName;
  7873. }
  7874. // Helper function to add the namespace scope mangling syntax to a string.
  7875. void HlslParseContext::addScopeMangler(TString& name)
  7876. {
  7877. name.append(scopeMangler);
  7878. }
  7879. // Return true if this has uniform-interface like decorations.
  7880. bool HlslParseContext::hasUniform(const TQualifier& qualifier) const
  7881. {
  7882. return qualifier.hasUniformLayout() ||
  7883. qualifier.layoutPushConstant;
  7884. }
  7885. // Potentially not the opposite of hasUniform(), as if some characteristic is
  7886. // ever used for more than one thing (e.g., uniform or input), hasUniform() should
  7887. // say it exists, but clearUniform() should leave it in place.
  7888. void HlslParseContext::clearUniform(TQualifier& qualifier)
  7889. {
  7890. qualifier.clearUniformLayout();
  7891. qualifier.layoutPushConstant = false;
  7892. }
  7893. // Return false if builtIn by itself doesn't force this qualifier to be an input qualifier.
  7894. bool HlslParseContext::isInputBuiltIn(const TQualifier& qualifier) const
  7895. {
  7896. switch (qualifier.builtIn) {
  7897. case EbvPosition:
  7898. case EbvPointSize:
  7899. return language != EShLangVertex && language != EShLangCompute && language != EShLangFragment;
  7900. case EbvClipDistance:
  7901. case EbvCullDistance:
  7902. return language != EShLangVertex && language != EShLangCompute;
  7903. case EbvFragCoord:
  7904. case EbvFace:
  7905. case EbvHelperInvocation:
  7906. case EbvLayer:
  7907. case EbvPointCoord:
  7908. case EbvSampleId:
  7909. case EbvSampleMask:
  7910. case EbvSamplePosition:
  7911. case EbvViewportIndex:
  7912. return language == EShLangFragment;
  7913. case EbvGlobalInvocationId:
  7914. case EbvLocalInvocationIndex:
  7915. case EbvLocalInvocationId:
  7916. case EbvNumWorkGroups:
  7917. case EbvWorkGroupId:
  7918. case EbvWorkGroupSize:
  7919. return language == EShLangCompute;
  7920. case EbvInvocationId:
  7921. return language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry;
  7922. case EbvPatchVertices:
  7923. return language == EShLangTessControl || language == EShLangTessEvaluation;
  7924. case EbvInstanceId:
  7925. case EbvInstanceIndex:
  7926. case EbvVertexId:
  7927. case EbvVertexIndex:
  7928. return language == EShLangVertex;
  7929. case EbvPrimitiveId:
  7930. return language == EShLangGeometry || language == EShLangFragment || language == EShLangTessControl;
  7931. case EbvTessLevelInner:
  7932. case EbvTessLevelOuter:
  7933. return language == EShLangTessEvaluation;
  7934. case EbvTessCoord:
  7935. return language == EShLangTessEvaluation;
  7936. default:
  7937. return false;
  7938. }
  7939. }
  7940. // Return true if there are decorations to preserve for input-like storage.
  7941. bool HlslParseContext::hasInput(const TQualifier& qualifier) const
  7942. {
  7943. if (qualifier.hasAnyLocation())
  7944. return true;
  7945. if (language == EShLangFragment && (qualifier.isInterpolation() || qualifier.centroid || qualifier.sample))
  7946. return true;
  7947. if (language == EShLangTessEvaluation && qualifier.patch)
  7948. return true;
  7949. if (isInputBuiltIn(qualifier))
  7950. return true;
  7951. return false;
  7952. }
  7953. // Return false if builtIn by itself doesn't force this qualifier to be an output qualifier.
  7954. bool HlslParseContext::isOutputBuiltIn(const TQualifier& qualifier) const
  7955. {
  7956. switch (qualifier.builtIn) {
  7957. case EbvPosition:
  7958. case EbvPointSize:
  7959. case EbvClipVertex:
  7960. case EbvClipDistance:
  7961. case EbvCullDistance:
  7962. return language != EShLangFragment && language != EShLangCompute;
  7963. case EbvFragDepth:
  7964. case EbvFragDepthGreater:
  7965. case EbvFragDepthLesser:
  7966. case EbvSampleMask:
  7967. return language == EShLangFragment;
  7968. case EbvLayer:
  7969. case EbvViewportIndex:
  7970. return language == EShLangGeometry || language == EShLangVertex;
  7971. case EbvPrimitiveId:
  7972. return language == EShLangGeometry;
  7973. case EbvTessLevelInner:
  7974. case EbvTessLevelOuter:
  7975. return language == EShLangTessControl;
  7976. default:
  7977. return false;
  7978. }
  7979. }
  7980. // Return true if there are decorations to preserve for output-like storage.
  7981. bool HlslParseContext::hasOutput(const TQualifier& qualifier) const
  7982. {
  7983. if (qualifier.hasAnyLocation())
  7984. return true;
  7985. if (language != EShLangFragment && language != EShLangCompute && qualifier.hasXfb())
  7986. return true;
  7987. if (language == EShLangTessControl && qualifier.patch)
  7988. return true;
  7989. if (language == EShLangGeometry && qualifier.hasStream())
  7990. return true;
  7991. if (isOutputBuiltIn(qualifier))
  7992. return true;
  7993. return false;
  7994. }
  7995. // Make the IO decorations etc. be appropriate only for an input interface.
  7996. void HlslParseContext::correctInput(TQualifier& qualifier)
  7997. {
  7998. clearUniform(qualifier);
  7999. if (language == EShLangVertex)
  8000. qualifier.clearInterstage();
  8001. if (language != EShLangTessEvaluation)
  8002. qualifier.patch = false;
  8003. if (language != EShLangFragment) {
  8004. qualifier.clearInterpolation();
  8005. qualifier.sample = false;
  8006. }
  8007. qualifier.clearStreamLayout();
  8008. qualifier.clearXfbLayout();
  8009. if (! isInputBuiltIn(qualifier))
  8010. qualifier.builtIn = EbvNone;
  8011. }
  8012. // Make the IO decorations etc. be appropriate only for an output interface.
  8013. void HlslParseContext::correctOutput(TQualifier& qualifier)
  8014. {
  8015. clearUniform(qualifier);
  8016. if (language == EShLangFragment)
  8017. qualifier.clearInterstage();
  8018. if (language != EShLangGeometry)
  8019. qualifier.clearStreamLayout();
  8020. if (language == EShLangFragment)
  8021. qualifier.clearXfbLayout();
  8022. if (language != EShLangTessControl)
  8023. qualifier.patch = false;
  8024. switch (qualifier.builtIn) {
  8025. case EbvFragDepth:
  8026. intermediate.setDepthReplacing();
  8027. intermediate.setDepth(EldAny);
  8028. break;
  8029. case EbvFragDepthGreater:
  8030. intermediate.setDepthReplacing();
  8031. intermediate.setDepth(EldGreater);
  8032. qualifier.builtIn = EbvFragDepth;
  8033. break;
  8034. case EbvFragDepthLesser:
  8035. intermediate.setDepthReplacing();
  8036. intermediate.setDepth(EldLess);
  8037. qualifier.builtIn = EbvFragDepth;
  8038. break;
  8039. default:
  8040. break;
  8041. }
  8042. if (! isOutputBuiltIn(qualifier))
  8043. qualifier.builtIn = EbvNone;
  8044. }
  8045. // Make the IO decorations etc. be appropriate only for uniform type interfaces.
  8046. void HlslParseContext::correctUniform(TQualifier& qualifier)
  8047. {
  8048. if (qualifier.declaredBuiltIn == EbvNone)
  8049. qualifier.declaredBuiltIn = qualifier.builtIn;
  8050. qualifier.builtIn = EbvNone;
  8051. qualifier.clearInterstage();
  8052. qualifier.clearInterstageLayout();
  8053. }
  8054. // Clear out all IO/Uniform stuff, so this has nothing to do with being an IO interface.
  8055. void HlslParseContext::clearUniformInputOutput(TQualifier& qualifier)
  8056. {
  8057. clearUniform(qualifier);
  8058. correctUniform(qualifier);
  8059. }
  8060. // Set texture return type. Returns success (not all types are valid).
  8061. bool HlslParseContext::setTextureReturnType(TSampler& sampler, const TType& retType, const TSourceLoc& loc)
  8062. {
  8063. // Seed the output with an invalid index. We will set it to a valid one if we can.
  8064. sampler.structReturnIndex = TSampler::noReturnStruct;
  8065. // Arrays aren't supported.
  8066. if (retType.isArray()) {
  8067. error(loc, "Arrays not supported in texture template types", "", "");
  8068. return false;
  8069. }
  8070. // If return type is a vector, remember the vector size in the sampler, and return.
  8071. if (retType.isVector() || retType.isScalar()) {
  8072. sampler.vectorSize = retType.getVectorSize();
  8073. return true;
  8074. }
  8075. // If it wasn't a vector, it must be a struct meeting certain requirements. The requirements
  8076. // are checked below: just check for struct-ness here.
  8077. if (!retType.isStruct()) {
  8078. error(loc, "Invalid texture template type", "", "");
  8079. return false;
  8080. }
  8081. // TODO: Subpass doesn't handle struct returns, due to some oddities with fn overloading.
  8082. if (sampler.isSubpass()) {
  8083. error(loc, "Unimplemented: structure template type in subpass input", "", "");
  8084. return false;
  8085. }
  8086. TTypeList* members = retType.getWritableStruct();
  8087. // Check for too many or not enough structure members.
  8088. if (members->size() > 4 || members->size() == 0) {
  8089. error(loc, "Invalid member count in texture template structure", "", "");
  8090. return false;
  8091. }
  8092. // Error checking: We must have <= 4 total components, all of the same basic type.
  8093. unsigned totalComponents = 0;
  8094. for (unsigned m = 0; m < members->size(); ++m) {
  8095. // Check for bad member types
  8096. if (!(*members)[m].type->isScalar() && !(*members)[m].type->isVector()) {
  8097. error(loc, "Invalid texture template struct member type", "", "");
  8098. return false;
  8099. }
  8100. const unsigned memberVectorSize = (*members)[m].type->getVectorSize();
  8101. totalComponents += memberVectorSize;
  8102. // too many total member components
  8103. if (totalComponents > 4) {
  8104. error(loc, "Too many components in texture template structure type", "", "");
  8105. return false;
  8106. }
  8107. // All members must be of a common basic type
  8108. if ((*members)[m].type->getBasicType() != (*members)[0].type->getBasicType()) {
  8109. error(loc, "Texture template structure members must same basic type", "", "");
  8110. return false;
  8111. }
  8112. }
  8113. // If the structure in the return type already exists in the table, we'll use it. Otherwise, we'll make
  8114. // a new entry. This is a linear search, but it hardly ever happens, and the list cannot be very large.
  8115. for (unsigned int idx = 0; idx < textureReturnStruct.size(); ++idx) {
  8116. if (textureReturnStruct[idx] == members) {
  8117. sampler.structReturnIndex = idx;
  8118. return true;
  8119. }
  8120. }
  8121. // It wasn't found as an existing entry. See if we have room for a new one.
  8122. if (textureReturnStruct.size() >= TSampler::structReturnSlots) {
  8123. error(loc, "Texture template struct return slots exceeded", "", "");
  8124. return false;
  8125. }
  8126. // Insert it in the vector that tracks struct return types.
  8127. sampler.structReturnIndex = unsigned(textureReturnStruct.size());
  8128. textureReturnStruct.push_back(members);
  8129. // Success!
  8130. return true;
  8131. }
  8132. // Return the sampler return type in retType.
  8133. void HlslParseContext::getTextureReturnType(const TSampler& sampler, TType& retType) const
  8134. {
  8135. if (sampler.hasReturnStruct()) {
  8136. assert(textureReturnStruct.size() >= sampler.structReturnIndex);
  8137. // We land here if the texture return is a structure.
  8138. TTypeList* blockStruct = textureReturnStruct[sampler.structReturnIndex];
  8139. const TType resultType(blockStruct, "");
  8140. retType.shallowCopy(resultType);
  8141. } else {
  8142. // We land here if the texture return is a vector or scalar.
  8143. const TType resultType(sampler.type, EvqTemporary, sampler.getVectorSize());
  8144. retType.shallowCopy(resultType);
  8145. }
  8146. }
  8147. // Return a symbol for the tessellation linkage variable of the given TBuiltInVariable type
  8148. TIntermSymbol* HlslParseContext::findTessLinkageSymbol(TBuiltInVariable biType) const
  8149. {
  8150. const auto it = builtInTessLinkageSymbols.find(biType);
  8151. if (it == builtInTessLinkageSymbols.end()) // if it wasn't declared by the user, return nullptr
  8152. return nullptr;
  8153. return intermediate.addSymbol(*it->second->getAsVariable());
  8154. }
  8155. // Find the patch constant function (issues error, returns nullptr if not found)
  8156. const TFunction* HlslParseContext::findPatchConstantFunction(const TSourceLoc& loc)
  8157. {
  8158. if (symbolTable.isFunctionNameVariable(patchConstantFunctionName)) {
  8159. error(loc, "can't use variable in patch constant function", patchConstantFunctionName.c_str(), "");
  8160. return nullptr;
  8161. }
  8162. const TString mangledName = patchConstantFunctionName + "(";
  8163. // create list of PCF candidates
  8164. TVector<const TFunction*> candidateList;
  8165. bool builtIn;
  8166. symbolTable.findFunctionNameList(mangledName, candidateList, builtIn);
  8167. // We have to have one and only one, or we don't know which to pick: the patchconstantfunc does not
  8168. // allow any disambiguation of overloads.
  8169. if (candidateList.empty()) {
  8170. error(loc, "patch constant function not found", patchConstantFunctionName.c_str(), "");
  8171. return nullptr;
  8172. }
  8173. // Based on directed experiments, it appears that if there are overloaded patchconstantfunctions,
  8174. // HLSL picks the last one in shader source order. Since that isn't yet implemented here, error
  8175. // out if there is more than one candidate.
  8176. if (candidateList.size() > 1) {
  8177. error(loc, "ambiguous patch constant function", patchConstantFunctionName.c_str(), "");
  8178. return nullptr;
  8179. }
  8180. return candidateList[0];
  8181. }
  8182. // Finalization step: Add patch constant function invocation
  8183. void HlslParseContext::addPatchConstantInvocation()
  8184. {
  8185. TSourceLoc loc;
  8186. loc.init();
  8187. // If there's no patch constant function, or we're not a HS, do nothing.
  8188. if (patchConstantFunctionName.empty() || language != EShLangTessControl)
  8189. return;
  8190. // Look for built-in variables in a function's parameter list.
  8191. const auto findBuiltIns = [&](const TFunction& function, std::set<tInterstageIoData>& builtIns) {
  8192. for (int p=0; p<function.getParamCount(); ++p) {
  8193. TStorageQualifier storage = function[p].type->getQualifier().storage;
  8194. if (storage == EvqConstReadOnly) // treated identically to input
  8195. storage = EvqIn;
  8196. if (function[p].getDeclaredBuiltIn() != EbvNone)
  8197. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].getDeclaredBuiltIn(), storage));
  8198. else
  8199. builtIns.insert(HlslParseContext::tInterstageIoData(function[p].type->getQualifier().builtIn, storage));
  8200. }
  8201. };
  8202. // If we synthesize a built-in interface variable, we must add it to the linkage.
  8203. const auto addToLinkage = [&](const TType& type, const TString* name, TIntermSymbol** symbolNode) {
  8204. if (name == nullptr) {
  8205. error(loc, "unable to locate patch function parameter name", "", "");
  8206. return;
  8207. } else {
  8208. TVariable& variable = *new TVariable(name, type);
  8209. if (! symbolTable.insert(variable)) {
  8210. error(loc, "unable to declare patch constant function interface variable", name->c_str(), "");
  8211. return;
  8212. }
  8213. globalQualifierFix(loc, variable.getWritableType().getQualifier());
  8214. if (symbolNode != nullptr)
  8215. *symbolNode = intermediate.addSymbol(variable);
  8216. trackLinkage(variable);
  8217. }
  8218. };
  8219. const auto isOutputPatch = [](TFunction& patchConstantFunction, int param) {
  8220. const TType& type = *patchConstantFunction[param].type;
  8221. const TBuiltInVariable biType = patchConstantFunction[param].getDeclaredBuiltIn();
  8222. return type.isSizedArray() && biType == EbvOutputPatch;
  8223. };
  8224. // We will perform these steps. Each is in a scoped block for separation: they could
  8225. // become separate functions to make addPatchConstantInvocation shorter.
  8226. //
  8227. // 1. Union the interfaces, and create built-ins for anything present in the PCF and
  8228. // declared as a built-in variable that isn't present in the entry point's signature.
  8229. //
  8230. // 2. Synthesizes a call to the patchconstfunction using built-in variables from either main,
  8231. // or the ones we created. Matching is based on built-in type. We may use synthesized
  8232. // variables from (1) above.
  8233. //
  8234. // 2B: Synthesize per control point invocations of wrapped entry point if the PCF requires them.
  8235. //
  8236. // 3. Create a return sequence: copy the return value (if any) from the PCF to a
  8237. // (non-sanitized) output variable. In case this may involve multiple copies, such as for
  8238. // an arrayed variable, a temporary copy of the PCF output is created to avoid multiple
  8239. // indirections into a complex R-value coming from the call to the PCF.
  8240. //
  8241. // 4. Create a barrier.
  8242. //
  8243. // 5/5B. Call the PCF inside an if test for (invocation id == 0).
  8244. TFunction* patchConstantFunctionPtr = const_cast<TFunction*>(findPatchConstantFunction(loc));
  8245. if (patchConstantFunctionPtr == nullptr)
  8246. return;
  8247. TFunction& patchConstantFunction = *patchConstantFunctionPtr;
  8248. const int pcfParamCount = patchConstantFunction.getParamCount();
  8249. TIntermSymbol* invocationIdSym = findTessLinkageSymbol(EbvInvocationId);
  8250. TIntermSequence& epBodySeq = entryPointFunctionBody->getAsAggregate()->getSequence();
  8251. int outPatchParam = -1; // -1 means there isn't one.
  8252. // ================ Step 1A: Union Interfaces ================
  8253. // Our patch constant function.
  8254. {
  8255. std::set<tInterstageIoData> pcfBuiltIns; // patch constant function built-ins
  8256. std::set<tInterstageIoData> epfBuiltIns; // entry point function built-ins
  8257. assert(entryPointFunction);
  8258. assert(entryPointFunctionBody);
  8259. findBuiltIns(patchConstantFunction, pcfBuiltIns);
  8260. findBuiltIns(*entryPointFunction, epfBuiltIns);
  8261. // Find the set of built-ins in the PCF that are not present in the entry point.
  8262. std::set<tInterstageIoData> notInEntryPoint;
  8263. notInEntryPoint = pcfBuiltIns;
  8264. // std::set_difference not usable on unordered containers
  8265. for (auto bi = epfBuiltIns.begin(); bi != epfBuiltIns.end(); ++bi)
  8266. notInEntryPoint.erase(*bi);
  8267. // Now we'll add those to the entry and to the linkage.
  8268. for (int p=0; p<pcfParamCount; ++p) {
  8269. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8270. TStorageQualifier storage = patchConstantFunction[p].type->getQualifier().storage;
  8271. // Track whether there is an output patch param
  8272. if (isOutputPatch(patchConstantFunction, p)) {
  8273. if (outPatchParam >= 0) {
  8274. // Presently we only support one per ctrl pt input.
  8275. error(loc, "unimplemented: multiple output patches in patch constant function", "", "");
  8276. return;
  8277. }
  8278. outPatchParam = p;
  8279. }
  8280. if (biType != EbvNone) {
  8281. TType* paramType = patchConstantFunction[p].type->clone();
  8282. if (storage == EvqConstReadOnly) // treated identically to input
  8283. storage = EvqIn;
  8284. // Presently, the only non-built-in we support is InputPatch, which is treated as
  8285. // a pseudo-built-in.
  8286. if (biType == EbvInputPatch) {
  8287. builtInTessLinkageSymbols[biType] = inputPatch;
  8288. } else if (biType == EbvOutputPatch) {
  8289. // Nothing...
  8290. } else {
  8291. // Use the original declaration type for the linkage
  8292. paramType->getQualifier().builtIn = biType;
  8293. if (notInEntryPoint.count(tInterstageIoData(biType, storage)) == 1)
  8294. addToLinkage(*paramType, patchConstantFunction[p].name, nullptr);
  8295. }
  8296. }
  8297. }
  8298. // If we didn't find it because the shader made one, add our own.
  8299. if (invocationIdSym == nullptr) {
  8300. TType invocationIdType(EbtUint, EvqIn, 1);
  8301. TString* invocationIdName = NewPoolTString("InvocationId");
  8302. invocationIdType.getQualifier().builtIn = EbvInvocationId;
  8303. addToLinkage(invocationIdType, invocationIdName, &invocationIdSym);
  8304. }
  8305. assert(invocationIdSym);
  8306. }
  8307. TIntermTyped* pcfArguments = nullptr;
  8308. TVariable* perCtrlPtVar = nullptr;
  8309. // ================ Step 1B: Argument synthesis ================
  8310. // Create pcfArguments for synthesis of patchconstantfunction invocation
  8311. {
  8312. for (int p=0; p<pcfParamCount; ++p) {
  8313. TIntermTyped* inputArg = nullptr;
  8314. if (p == outPatchParam) {
  8315. if (perCtrlPtVar == nullptr) {
  8316. perCtrlPtVar = makeInternalVariable(*patchConstantFunction[outPatchParam].name,
  8317. *patchConstantFunction[outPatchParam].type);
  8318. perCtrlPtVar->getWritableType().getQualifier().makeTemporary();
  8319. }
  8320. inputArg = intermediate.addSymbol(*perCtrlPtVar, loc);
  8321. } else {
  8322. // find which built-in it is
  8323. const TBuiltInVariable biType = patchConstantFunction[p].getDeclaredBuiltIn();
  8324. if (biType == EbvInputPatch && inputPatch == nullptr) {
  8325. error(loc, "unimplemented: PCF input patch without entry point input patch parameter", "", "");
  8326. return;
  8327. }
  8328. inputArg = findTessLinkageSymbol(biType);
  8329. if (inputArg == nullptr) {
  8330. error(loc, "unable to find patch constant function built-in variable", "", "");
  8331. return;
  8332. }
  8333. }
  8334. if (pcfParamCount == 1)
  8335. pcfArguments = inputArg;
  8336. else
  8337. pcfArguments = intermediate.growAggregate(pcfArguments, inputArg);
  8338. }
  8339. }
  8340. // ================ Step 2: Synthesize call to PCF ================
  8341. TIntermAggregate* pcfCallSequence = nullptr;
  8342. TIntermTyped* pcfCall = nullptr;
  8343. {
  8344. // Create a function call to the patchconstantfunction
  8345. if (pcfArguments)
  8346. addInputArgumentConversions(patchConstantFunction, pcfArguments);
  8347. // Synthetic call.
  8348. pcfCall = intermediate.setAggregateOperator(pcfArguments, EOpFunctionCall, patchConstantFunction.getType(), loc);
  8349. pcfCall->getAsAggregate()->setUserDefined();
  8350. pcfCall->getAsAggregate()->setName(patchConstantFunction.getMangledName());
  8351. intermediate.addToCallGraph(infoSink, intermediate.getEntryPointMangledName().c_str(),
  8352. patchConstantFunction.getMangledName());
  8353. if (pcfCall->getAsAggregate()) {
  8354. TQualifierList& qualifierList = pcfCall->getAsAggregate()->getQualifierList();
  8355. for (int i = 0; i < patchConstantFunction.getParamCount(); ++i) {
  8356. TStorageQualifier qual = patchConstantFunction[i].type->getQualifier().storage;
  8357. qualifierList.push_back(qual);
  8358. }
  8359. pcfCall = addOutputArgumentConversions(patchConstantFunction, *pcfCall->getAsOperator());
  8360. }
  8361. }
  8362. // ================ Step 2B: Per Control Point synthesis ================
  8363. // If there is per control point data, we must either emulate that with multiple
  8364. // invocations of the entry point to build up an array, or (TODO:) use a yet
  8365. // unavailable extension to look across the SIMD lanes. This is the former
  8366. // as a placeholder for the latter.
  8367. if (outPatchParam >= 0) {
  8368. // We must introduce a local temp variable of the type wanted by the PCF input.
  8369. const int arraySize = patchConstantFunction[outPatchParam].type->getOuterArraySize();
  8370. if (entryPointFunction->getType().getBasicType() == EbtVoid) {
  8371. error(loc, "entry point must return a value for use with patch constant function", "", "");
  8372. return;
  8373. }
  8374. // Create calls to wrapped main to fill in the array. We will substitute fixed values
  8375. // of invocation ID when calling the wrapped main.
  8376. // This is the type of the each member of the per ctrl point array.
  8377. const TType derefType(perCtrlPtVar->getType(), 0);
  8378. for (int cpt = 0; cpt < arraySize; ++cpt) {
  8379. // TODO: improve. substr(1) here is to avoid the '@' that was grafted on but isn't in the symtab
  8380. // for this function.
  8381. const TString origName = entryPointFunction->getName().substr(1);
  8382. TFunction callee(&origName, TType(EbtVoid));
  8383. TIntermTyped* callingArgs = nullptr;
  8384. for (int i = 0; i < entryPointFunction->getParamCount(); i++) {
  8385. TParameter& param = (*entryPointFunction)[i];
  8386. TType& paramType = *param.type;
  8387. if (paramType.getQualifier().isParamOutput()) {
  8388. error(loc, "unimplemented: entry point outputs in patch constant function invocation", "", "");
  8389. return;
  8390. }
  8391. if (paramType.getQualifier().isParamInput()) {
  8392. TIntermTyped* arg = nullptr;
  8393. if ((*entryPointFunction)[i].getDeclaredBuiltIn() == EbvInvocationId) {
  8394. // substitute invocation ID with the array element ID
  8395. arg = intermediate.addConstantUnion(cpt, loc);
  8396. } else {
  8397. TVariable* argVar = makeInternalVariable(*param.name, *param.type);
  8398. argVar->getWritableType().getQualifier().makeTemporary();
  8399. arg = intermediate.addSymbol(*argVar);
  8400. }
  8401. handleFunctionArgument(&callee, callingArgs, arg);
  8402. }
  8403. }
  8404. // Call and assign to per ctrl point variable
  8405. currentCaller = intermediate.getEntryPointMangledName().c_str();
  8406. TIntermTyped* callReturn = handleFunctionCall(loc, &callee, callingArgs);
  8407. TIntermTyped* index = intermediate.addConstantUnion(cpt, loc);
  8408. TIntermSymbol* perCtrlPtSym = intermediate.addSymbol(*perCtrlPtVar, loc);
  8409. TIntermTyped* element = intermediate.addIndex(EOpIndexDirect, perCtrlPtSym, index, loc);
  8410. element->setType(derefType);
  8411. element->setLoc(loc);
  8412. pcfCallSequence = intermediate.growAggregate(pcfCallSequence,
  8413. handleAssign(loc, EOpAssign, element, callReturn));
  8414. }
  8415. }
  8416. // ================ Step 3: Create return Sequence ================
  8417. // Return sequence: copy PCF result to a temporary, then to shader output variable.
  8418. if (pcfCall->getBasicType() != EbtVoid) {
  8419. const TType* retType = &patchConstantFunction.getType(); // return type from the PCF
  8420. TType outType; // output type that goes with the return type.
  8421. outType.shallowCopy(*retType);
  8422. // substitute the output type
  8423. const auto newLists = ioTypeMap.find(retType->getStruct());
  8424. if (newLists != ioTypeMap.end())
  8425. outType.setStruct(newLists->second.output);
  8426. // Substitute the top level type's built-in type
  8427. if (patchConstantFunction.getDeclaredBuiltInType() != EbvNone)
  8428. outType.getQualifier().builtIn = patchConstantFunction.getDeclaredBuiltInType();
  8429. outType.getQualifier().patch = true; // make it a per-patch variable
  8430. TVariable* pcfOutput = makeInternalVariable("@patchConstantOutput", outType);
  8431. pcfOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
  8432. if (pcfOutput->getType().containsBuiltIn())
  8433. split(*pcfOutput);
  8434. assignToInterface(*pcfOutput);
  8435. TIntermSymbol* pcfOutputSym = intermediate.addSymbol(*pcfOutput, loc);
  8436. // The call to the PCF is a complex R-value: we want to store it in a temp to avoid
  8437. // repeated calls to the PCF:
  8438. TVariable* pcfCallResult = makeInternalVariable("@patchConstantResult", *retType);
  8439. pcfCallResult->getWritableType().getQualifier().makeTemporary();
  8440. TIntermSymbol* pcfResultVar = intermediate.addSymbol(*pcfCallResult, loc);
  8441. TIntermNode* pcfResultAssign = handleAssign(loc, EOpAssign, pcfResultVar, pcfCall);
  8442. TIntermNode* pcfResultToOut = handleAssign(loc, EOpAssign, pcfOutputSym,
  8443. intermediate.addSymbol(*pcfCallResult, loc));
  8444. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultAssign);
  8445. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfResultToOut);
  8446. } else {
  8447. pcfCallSequence = intermediate.growAggregate(pcfCallSequence, pcfCall);
  8448. }
  8449. // ================ Step 4: Barrier ================
  8450. TIntermTyped* barrier = new TIntermAggregate(EOpBarrier);
  8451. barrier->setLoc(loc);
  8452. barrier->setType(TType(EbtVoid));
  8453. epBodySeq.insert(epBodySeq.end(), barrier);
  8454. // ================ Step 5: Test on invocation ID ================
  8455. TIntermTyped* zero = intermediate.addConstantUnion(0, loc, true);
  8456. TIntermTyped* cmp = intermediate.addBinaryNode(EOpEqual, invocationIdSym, zero, loc, TType(EbtBool));
  8457. // ================ Step 5B: Create if statement on Invocation ID == 0 ================
  8458. intermediate.setAggregateOperator(pcfCallSequence, EOpSequence, TType(EbtVoid), loc);
  8459. TIntermTyped* invocationIdTest = new TIntermSelection(cmp, pcfCallSequence, nullptr);
  8460. invocationIdTest->setLoc(loc);
  8461. // add our test sequence before the return.
  8462. epBodySeq.insert(epBodySeq.end(), invocationIdTest);
  8463. }
  8464. // Finalization step: remove unused buffer blocks from linkage (we don't know until the
  8465. // shader is entirely compiled).
  8466. // Preserve order of remaining symbols.
  8467. void HlslParseContext::removeUnusedStructBufferCounters()
  8468. {
  8469. const auto endIt = std::remove_if(linkageSymbols.begin(), linkageSymbols.end(),
  8470. [this](const TSymbol* sym) {
  8471. const auto sbcIt = structBufferCounter.find(sym->getName());
  8472. return sbcIt != structBufferCounter.end() && !sbcIt->second;
  8473. });
  8474. linkageSymbols.erase(endIt, linkageSymbols.end());
  8475. }
  8476. // Finalization step: patch texture shadow modes to match samplers they were combined with
  8477. void HlslParseContext::fixTextureShadowModes()
  8478. {
  8479. for (auto symbol = linkageSymbols.begin(); symbol != linkageSymbols.end(); ++symbol) {
  8480. TSampler& sampler = (*symbol)->getWritableType().getSampler();
  8481. if (sampler.isTexture()) {
  8482. const auto shadowMode = textureShadowVariant.find((*symbol)->getUniqueId());
  8483. if (shadowMode != textureShadowVariant.end()) {
  8484. if (shadowMode->second->overloaded())
  8485. // Texture needs legalization if it's been seen with both shadow and non-shadow modes.
  8486. intermediate.setNeedsLegalization();
  8487. sampler.shadow = shadowMode->second->isShadowId((*symbol)->getUniqueId());
  8488. }
  8489. }
  8490. }
  8491. }
  8492. // Finalization step: patch append methods to use proper stream output, which isn't known until
  8493. // main is parsed, which could happen after the append method is parsed.
  8494. void HlslParseContext::finalizeAppendMethods()
  8495. {
  8496. TSourceLoc loc;
  8497. loc.init();
  8498. // Nothing to do: bypass test for valid stream output.
  8499. if (gsAppends.empty())
  8500. return;
  8501. if (gsStreamOutput == nullptr) {
  8502. error(loc, "unable to find output symbol for Append()", "", "");
  8503. return;
  8504. }
  8505. // Patch append sequences, now that we know the stream output symbol.
  8506. for (auto append = gsAppends.begin(); append != gsAppends.end(); ++append) {
  8507. append->node->getSequence()[0] =
  8508. handleAssign(append->loc, EOpAssign,
  8509. intermediate.addSymbol(*gsStreamOutput, append->loc),
  8510. append->node->getSequence()[0]->getAsTyped());
  8511. }
  8512. }
  8513. // post-processing
  8514. void HlslParseContext::finish()
  8515. {
  8516. // Error check: There was a dangling .mips operator. These are not nested constructs in the grammar, so
  8517. // cannot be detected there. This is not strictly needed in a non-validating parser; it's just helpful.
  8518. if (! mipsOperatorMipArg.empty()) {
  8519. error(mipsOperatorMipArg.back().loc, "unterminated mips operator:", "", "");
  8520. }
  8521. removeUnusedStructBufferCounters();
  8522. addPatchConstantInvocation();
  8523. fixTextureShadowModes();
  8524. finalizeAppendMethods();
  8525. // Communicate out (esp. for command line) that we formed AST that will make
  8526. // illegal AST SPIR-V and it needs transforms to legalize it.
  8527. if (intermediate.needsLegalization() && (messages & EShMsgHlslLegalization))
  8528. infoSink.info << "WARNING: AST will form illegal SPIR-V; need to transform to legalize";
  8529. TParseContextBase::finish();
  8530. }
  8531. } // end namespace glslang