ParseHelper.cpp 430 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475
  1. //
  2. // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
  3. // Copyright (C) 2012-2015 LunarG, Inc.
  4. // Copyright (C) 2015-2018 Google, Inc.
  5. // Copyright (C) 2017, 2019 ARM Limited.
  6. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
  7. //
  8. // All rights reserved.
  9. //
  10. // Redistribution and use in source and binary forms, with or without
  11. // modification, are permitted provided that the following conditions
  12. // are met:
  13. //
  14. // Redistributions of source code must retain the above copyright
  15. // notice, this list of conditions and the following disclaimer.
  16. //
  17. // Redistributions in binary form must reproduce the above
  18. // copyright notice, this list of conditions and the following
  19. // disclaimer in the documentation and/or other materials provided
  20. // with the distribution.
  21. //
  22. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  23. // contributors may be used to endorse or promote products derived
  24. // from this software without specific prior written permission.
  25. //
  26. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  27. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  28. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  29. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  30. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  31. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  32. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  33. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  34. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  35. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  36. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  37. // POSSIBILITY OF SUCH DAMAGE.
  38. //
  39. #include "ParseHelper.h"
  40. #include "Scan.h"
  41. #include "../OSDependent/osinclude.h"
  42. #include <algorithm>
  43. #include "preprocessor/PpContext.h"
  44. extern int yyparse(glslang::TParseContext*);
  45. namespace glslang {
  46. TParseContext::TParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool parsingBuiltins,
  47. int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
  48. TInfoSink& infoSink, bool forwardCompatible, EShMessages messages,
  49. const TString* entryPoint) :
  50. TParseContextBase(symbolTable, interm, parsingBuiltins, version, profile, spvVersion, language,
  51. infoSink, forwardCompatible, messages, entryPoint),
  52. inMain(false),
  53. blockName(nullptr),
  54. limits(resources.limits)
  55. #ifndef GLSLANG_WEB
  56. ,
  57. atomicUintOffsets(nullptr), anyIndexLimits(false)
  58. #endif
  59. {
  60. // decide whether precision qualifiers should be ignored or respected
  61. if (isEsProfile() || spvVersion.vulkan > 0) {
  62. precisionManager.respectPrecisionQualifiers();
  63. if (! parsingBuiltins && language == EShLangFragment && !isEsProfile() && spvVersion.vulkan > 0)
  64. precisionManager.warnAboutDefaults();
  65. }
  66. setPrecisionDefaults();
  67. globalUniformDefaults.clear();
  68. globalUniformDefaults.layoutMatrix = ElmColumnMajor;
  69. globalUniformDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd140 : ElpShared;
  70. globalBufferDefaults.clear();
  71. globalBufferDefaults.layoutMatrix = ElmColumnMajor;
  72. globalBufferDefaults.layoutPacking = spvVersion.spv != 0 ? ElpStd430 : ElpShared;
  73. // use storage buffer on SPIR-V 1.3 and up
  74. if (spvVersion.spv >= EShTargetSpv_1_3)
  75. intermediate.setUseStorageBuffer();
  76. globalInputDefaults.clear();
  77. globalOutputDefaults.clear();
  78. globalSharedDefaults.clear();
  79. globalSharedDefaults.layoutMatrix = ElmColumnMajor;
  80. globalSharedDefaults.layoutPacking = ElpStd430;
  81. #ifndef GLSLANG_WEB
  82. // "Shaders in the transform
  83. // feedback capturing mode have an initial global default of
  84. // layout(xfb_buffer = 0) out;"
  85. if (language == EShLangVertex ||
  86. language == EShLangTessControl ||
  87. language == EShLangTessEvaluation ||
  88. language == EShLangGeometry)
  89. globalOutputDefaults.layoutXfbBuffer = 0;
  90. if (language == EShLangGeometry)
  91. globalOutputDefaults.layoutStream = 0;
  92. #endif
  93. if (entryPoint != nullptr && entryPoint->size() > 0 && *entryPoint != "main")
  94. infoSink.info.message(EPrefixError, "Source entry point must be \"main\"");
  95. }
  96. TParseContext::~TParseContext()
  97. {
  98. #ifndef GLSLANG_WEB
  99. delete [] atomicUintOffsets;
  100. #endif
  101. }
  102. // Set up all default precisions as needed by the current environment.
  103. // Intended just as a TParseContext constructor helper.
  104. void TParseContext::setPrecisionDefaults()
  105. {
  106. // Set all precision defaults to EpqNone, which is correct for all types
  107. // when not obeying precision qualifiers, and correct for types that don't
  108. // have defaults (thus getting an error on use) when obeying precision
  109. // qualifiers.
  110. for (int type = 0; type < EbtNumTypes; ++type)
  111. defaultPrecision[type] = EpqNone;
  112. for (int type = 0; type < maxSamplerIndex; ++type)
  113. defaultSamplerPrecision[type] = EpqNone;
  114. // replace with real precision defaults for those that have them
  115. if (obeyPrecisionQualifiers()) {
  116. if (isEsProfile()) {
  117. // Most don't have defaults, a few default to lowp.
  118. TSampler sampler;
  119. sampler.set(EbtFloat, Esd2D);
  120. defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
  121. sampler.set(EbtFloat, EsdCube);
  122. defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
  123. sampler.set(EbtFloat, Esd2D);
  124. sampler.setExternal(true);
  125. defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
  126. }
  127. // If we are parsing built-in computational variables/functions, it is meaningful to record
  128. // whether the built-in has no precision qualifier, as that ambiguity
  129. // is used to resolve the precision from the supplied arguments/operands instead.
  130. // So, we don't actually want to replace EpqNone with a default precision for built-ins.
  131. if (! parsingBuiltins) {
  132. if (isEsProfile() && language == EShLangFragment) {
  133. defaultPrecision[EbtInt] = EpqMedium;
  134. defaultPrecision[EbtUint] = EpqMedium;
  135. } else {
  136. defaultPrecision[EbtInt] = EpqHigh;
  137. defaultPrecision[EbtUint] = EpqHigh;
  138. defaultPrecision[EbtFloat] = EpqHigh;
  139. }
  140. if (!isEsProfile()) {
  141. // Non-ES profile
  142. // All sampler precisions default to highp.
  143. for (int type = 0; type < maxSamplerIndex; ++type)
  144. defaultSamplerPrecision[type] = EpqHigh;
  145. }
  146. }
  147. defaultPrecision[EbtSampler] = EpqLow;
  148. defaultPrecision[EbtAtomicUint] = EpqHigh;
  149. }
  150. }
  151. void TParseContext::setLimits(const TBuiltInResource& r)
  152. {
  153. resources = r;
  154. intermediate.setLimits(r);
  155. #ifndef GLSLANG_WEB
  156. anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
  157. ! limits.generalConstantMatrixVectorIndexing ||
  158. ! limits.generalSamplerIndexing ||
  159. ! limits.generalUniformIndexing ||
  160. ! limits.generalVariableIndexing ||
  161. ! limits.generalVaryingIndexing;
  162. // "Each binding point tracks its own current default offset for
  163. // inheritance of subsequent variables using the same binding. The initial state of compilation is that all
  164. // binding points have an offset of 0."
  165. atomicUintOffsets = new int[resources.maxAtomicCounterBindings];
  166. for (int b = 0; b < resources.maxAtomicCounterBindings; ++b)
  167. atomicUintOffsets[b] = 0;
  168. #endif
  169. }
  170. //
  171. // Parse an array of strings using yyparse, going through the
  172. // preprocessor to tokenize the shader strings, then through
  173. // the GLSL scanner.
  174. //
  175. // Returns true for successful acceptance of the shader, false if any errors.
  176. //
  177. bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
  178. {
  179. currentScanner = &input;
  180. ppContext.setInput(input, versionWillBeError);
  181. yyparse(this);
  182. finish();
  183. return numErrors == 0;
  184. }
  185. // This is called from bison when it has a parse (syntax) error
  186. // Note though that to stop cascading errors, we set EOF, which
  187. // will usually cause a syntax error, so be more accurate that
  188. // compilation is terminating.
  189. void TParseContext::parserError(const char* s)
  190. {
  191. if (! getScanner()->atEndOfInput() || numErrors == 0)
  192. error(getCurrentLoc(), "", "", s, "");
  193. else
  194. error(getCurrentLoc(), "compilation terminated", "", "");
  195. }
  196. void TParseContext::growGlobalUniformBlock(const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
  197. {
  198. bool createBlock = globalUniformBlock == nullptr;
  199. if (createBlock) {
  200. globalUniformBinding = intermediate.getGlobalUniformBinding();
  201. globalUniformSet = intermediate.getGlobalUniformSet();
  202. }
  203. // use base class function to create/expand block
  204. TParseContextBase::growGlobalUniformBlock(loc, memberType, memberName, typeList);
  205. if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
  206. // check for a block storage override
  207. TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getGlobalUniformBlockName());
  208. TQualifier& qualifier = globalUniformBlock->getWritableType().getQualifier();
  209. qualifier.defaultBlock = true;
  210. if (storageOverride != EbsNone) {
  211. if (createBlock) {
  212. // Remap block storage
  213. qualifier.setBlockStorage(storageOverride);
  214. // check that the change didn't create errors
  215. blockQualifierCheck(loc, qualifier, false);
  216. }
  217. // remap meber storage as well
  218. memberType.getQualifier().setBlockStorage(storageOverride);
  219. }
  220. }
  221. }
  222. void TParseContext::growAtomicCounterBlock(int binding, const TSourceLoc& loc, TType& memberType, const TString& memberName, TTypeList* typeList)
  223. {
  224. bool createBlock = atomicCounterBuffers.find(binding) == atomicCounterBuffers.end();
  225. if (createBlock) {
  226. atomicCounterBlockSet = intermediate.getAtomicCounterBlockSet();
  227. }
  228. // use base class function to create/expand block
  229. TParseContextBase::growAtomicCounterBlock(binding, loc, memberType, memberName, typeList);
  230. TQualifier& qualifier = atomicCounterBuffers[binding]->getWritableType().getQualifier();
  231. qualifier.defaultBlock = true;
  232. if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
  233. // check for a Block storage override
  234. TBlockStorageClass storageOverride = intermediate.getBlockStorageOverride(getAtomicCounterBlockName());
  235. if (storageOverride != EbsNone) {
  236. if (createBlock) {
  237. // Remap block storage
  238. qualifier.setBlockStorage(storageOverride);
  239. // check that the change didn't create errors
  240. blockQualifierCheck(loc, qualifier, false);
  241. }
  242. // remap meber storage as well
  243. memberType.getQualifier().setBlockStorage(storageOverride);
  244. }
  245. }
  246. }
  247. const char* TParseContext::getGlobalUniformBlockName() const
  248. {
  249. const char* name = intermediate.getGlobalUniformBlockName();
  250. if (std::string(name) == "")
  251. return "gl_DefaultUniformBlock";
  252. else
  253. return name;
  254. }
  255. void TParseContext::finalizeGlobalUniformBlockLayout(TVariable&)
  256. {
  257. }
  258. void TParseContext::setUniformBlockDefaults(TType& block) const
  259. {
  260. block.getQualifier().layoutPacking = ElpStd140;
  261. block.getQualifier().layoutMatrix = ElmColumnMajor;
  262. }
  263. const char* TParseContext::getAtomicCounterBlockName() const
  264. {
  265. const char* name = intermediate.getAtomicCounterBlockName();
  266. if (std::string(name) == "")
  267. return "gl_AtomicCounterBlock";
  268. else
  269. return name;
  270. }
  271. void TParseContext::finalizeAtomicCounterBlockLayout(TVariable&)
  272. {
  273. }
  274. void TParseContext::setAtomicCounterBlockDefaults(TType& block) const
  275. {
  276. block.getQualifier().layoutPacking = ElpStd430;
  277. block.getQualifier().layoutMatrix = ElmRowMajor;
  278. }
  279. void TParseContext::setInvariant(const TSourceLoc& loc, const char* builtin) {
  280. TSymbol* symbol = symbolTable.find(builtin);
  281. if (symbol && symbol->getType().getQualifier().isPipeOutput()) {
  282. if (intermediate.inIoAccessed(builtin))
  283. warn(loc, "changing qualification after use", "invariant", builtin);
  284. TSymbol* csymbol = symbolTable.copyUp(symbol);
  285. csymbol->getWritableType().getQualifier().invariant = true;
  286. }
  287. }
  288. void TParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
  289. {
  290. #ifndef GLSLANG_WEB
  291. if (pragmaCallback)
  292. pragmaCallback(loc.line, tokens);
  293. if (tokens.size() == 0)
  294. return;
  295. if (tokens[0].compare("optimize") == 0) {
  296. if (tokens.size() != 4) {
  297. error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
  298. return;
  299. }
  300. if (tokens[1].compare("(") != 0) {
  301. error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
  302. return;
  303. }
  304. if (tokens[2].compare("on") == 0)
  305. contextPragma.optimize = true;
  306. else if (tokens[2].compare("off") == 0)
  307. contextPragma.optimize = false;
  308. else {
  309. if(relaxedErrors())
  310. // If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
  311. warn(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
  312. return;
  313. }
  314. if (tokens[3].compare(")") != 0) {
  315. error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
  316. return;
  317. }
  318. } else if (tokens[0].compare("debug") == 0) {
  319. if (tokens.size() != 4) {
  320. error(loc, "debug pragma syntax is incorrect", "#pragma", "");
  321. return;
  322. }
  323. if (tokens[1].compare("(") != 0) {
  324. error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
  325. return;
  326. }
  327. if (tokens[2].compare("on") == 0)
  328. contextPragma.debug = true;
  329. else if (tokens[2].compare("off") == 0)
  330. contextPragma.debug = false;
  331. else {
  332. if(relaxedErrors())
  333. // If an implementation does not recognize the tokens following #pragma, then it will ignore that pragma.
  334. warn(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
  335. return;
  336. }
  337. if (tokens[3].compare(")") != 0) {
  338. error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
  339. return;
  340. }
  341. } else if (spvVersion.spv > 0 && tokens[0].compare("use_storage_buffer") == 0) {
  342. if (tokens.size() != 1)
  343. error(loc, "extra tokens", "#pragma", "");
  344. intermediate.setUseStorageBuffer();
  345. } else if (spvVersion.spv > 0 && tokens[0].compare("use_vulkan_memory_model") == 0) {
  346. if (tokens.size() != 1)
  347. error(loc, "extra tokens", "#pragma", "");
  348. intermediate.setUseVulkanMemoryModel();
  349. } else if (spvVersion.spv > 0 && tokens[0].compare("use_variable_pointers") == 0) {
  350. if (tokens.size() != 1)
  351. error(loc, "extra tokens", "#pragma", "");
  352. if (spvVersion.spv < glslang::EShTargetSpv_1_3)
  353. error(loc, "requires SPIR-V 1.3", "#pragma use_variable_pointers", "");
  354. intermediate.setUseVariablePointers();
  355. } else if (tokens[0].compare("once") == 0) {
  356. warn(loc, "not implemented", "#pragma once", "");
  357. } else if (tokens[0].compare("glslang_binary_double_output") == 0) {
  358. intermediate.setBinaryDoubleOutput();
  359. } else if (spvVersion.spv > 0 && tokens[0].compare("STDGL") == 0 &&
  360. tokens[1].compare("invariant") == 0 && tokens[3].compare("all") == 0) {
  361. intermediate.setInvariantAll();
  362. // Set all builtin out variables invariant if declared
  363. setInvariant(loc, "gl_Position");
  364. setInvariant(loc, "gl_PointSize");
  365. setInvariant(loc, "gl_ClipDistance");
  366. setInvariant(loc, "gl_CullDistance");
  367. setInvariant(loc, "gl_TessLevelOuter");
  368. setInvariant(loc, "gl_TessLevelInner");
  369. setInvariant(loc, "gl_PrimitiveID");
  370. setInvariant(loc, "gl_Layer");
  371. setInvariant(loc, "gl_ViewportIndex");
  372. setInvariant(loc, "gl_FragDepth");
  373. setInvariant(loc, "gl_SampleMask");
  374. setInvariant(loc, "gl_ClipVertex");
  375. setInvariant(loc, "gl_FrontColor");
  376. setInvariant(loc, "gl_BackColor");
  377. setInvariant(loc, "gl_FrontSecondaryColor");
  378. setInvariant(loc, "gl_BackSecondaryColor");
  379. setInvariant(loc, "gl_TexCoord");
  380. setInvariant(loc, "gl_FogFragCoord");
  381. setInvariant(loc, "gl_FragColor");
  382. setInvariant(loc, "gl_FragData");
  383. }
  384. #endif
  385. }
  386. //
  387. // Handle seeing a variable identifier in the grammar.
  388. //
  389. TIntermTyped* TParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
  390. {
  391. TIntermTyped* node = nullptr;
  392. // Error check for requiring specific extensions present.
  393. if (symbol && symbol->getNumExtensions())
  394. requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
  395. #ifndef GLSLANG_WEB
  396. if (symbol && symbol->isReadOnly()) {
  397. // All shared things containing an unsized array must be copied up
  398. // on first use, so that all future references will share its array structure,
  399. // so that editing the implicit size will effect all nodes consuming it,
  400. // and so that editing the implicit size won't change the shared one.
  401. //
  402. // If this is a variable or a block, check it and all it contains, but if this
  403. // is a member of an anonymous block, check the whole block, as the whole block
  404. // will need to be copied up if it contains an unsized array.
  405. //
  406. // This check is being done before the block-name check further down, so guard
  407. // for that too.
  408. if (!symbol->getType().isUnusableName()) {
  409. if (symbol->getType().containsUnsizedArray() ||
  410. (symbol->getAsAnonMember() &&
  411. symbol->getAsAnonMember()->getAnonContainer().getType().containsUnsizedArray()))
  412. makeEditable(symbol);
  413. }
  414. }
  415. #endif
  416. const TVariable* variable;
  417. const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
  418. if (anon) {
  419. // It was a member of an anonymous container.
  420. // Create a subtree for its dereference.
  421. variable = anon->getAnonContainer().getAsVariable();
  422. TIntermTyped* container = intermediate.addSymbol(*variable, loc);
  423. TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
  424. node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
  425. node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
  426. if (node->getType().hiddenMember())
  427. error(loc, "member of nameless block was not redeclared", string->c_str(), "");
  428. } else {
  429. // Not a member of an anonymous container.
  430. // The symbol table search was done in the lexical phase.
  431. // See if it was a variable.
  432. variable = symbol ? symbol->getAsVariable() : nullptr;
  433. if (variable) {
  434. if (variable->getType().isUnusableName()) {
  435. error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
  436. variable = nullptr;
  437. }
  438. if (language == EShLangMesh && variable) {
  439. TLayoutGeometry primitiveType = intermediate.getOutputPrimitive();
  440. if ((variable->getMangledName() == "gl_PrimitiveTriangleIndicesEXT" && primitiveType != ElgTriangles) ||
  441. (variable->getMangledName() == "gl_PrimitiveLineIndicesEXT" && primitiveType != ElgLines) ||
  442. (variable->getMangledName() == "gl_PrimitivePointIndicesEXT" && primitiveType != ElgPoints)) {
  443. error(loc, "cannot be used (ouput primitive type mismatch)", string->c_str(), "");
  444. variable = nullptr;
  445. }
  446. }
  447. } else {
  448. if (symbol)
  449. error(loc, "variable name expected", string->c_str(), "");
  450. }
  451. // Recovery, if it wasn't found or was not a variable.
  452. if (! variable)
  453. variable = new TVariable(string, TType(EbtVoid));
  454. if (variable->getType().getQualifier().isFrontEndConstant())
  455. node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
  456. else
  457. node = intermediate.addSymbol(*variable, loc);
  458. }
  459. if (variable->getType().getQualifier().isIo())
  460. intermediate.addIoAccessed(*string);
  461. if (variable->getType().isReference() &&
  462. variable->getType().getQualifier().bufferReferenceNeedsVulkanMemoryModel()) {
  463. intermediate.setUseVulkanMemoryModel();
  464. }
  465. return node;
  466. }
  467. //
  468. // Handle seeing a base[index] dereference in the grammar.
  469. //
  470. TIntermTyped* TParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
  471. {
  472. int indexValue = 0;
  473. if (index->getQualifier().isFrontEndConstant())
  474. indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
  475. // basic type checks...
  476. variableCheck(base);
  477. if (! base->isArray() && ! base->isMatrix() && ! base->isVector() && ! base->getType().isCoopMat() &&
  478. ! base->isReference()) {
  479. if (base->getAsSymbolNode())
  480. error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
  481. else
  482. error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
  483. // Insert dummy error-recovery result
  484. return intermediate.addConstantUnion(0.0, EbtFloat, loc);
  485. }
  486. if (!base->isArray() && base->isVector()) {
  487. if (base->getType().contains16BitFloat())
  488. requireFloat16Arithmetic(loc, "[", "does not operate on types containing float16");
  489. if (base->getType().contains16BitInt())
  490. requireInt16Arithmetic(loc, "[", "does not operate on types containing (u)int16");
  491. if (base->getType().contains8BitInt())
  492. requireInt8Arithmetic(loc, "[", "does not operate on types containing (u)int8");
  493. }
  494. // check for constant folding
  495. if (base->getType().getQualifier().isFrontEndConstant() && index->getQualifier().isFrontEndConstant()) {
  496. // both base and index are front-end constants
  497. checkIndex(loc, base->getType(), indexValue);
  498. return intermediate.foldDereference(base, indexValue, loc);
  499. }
  500. // at least one of base and index is not a front-end constant variable...
  501. TIntermTyped* result = nullptr;
  502. #ifndef GLSLANG_WEB
  503. if (base->isReference() && ! base->isArray()) {
  504. requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference indexing");
  505. if (base->getType().getReferentType()->containsUnsizedArray()) {
  506. error(loc, "cannot index reference to buffer containing an unsized array", "", "");
  507. result = nullptr;
  508. } else {
  509. result = intermediate.addBinaryMath(EOpAdd, base, index, loc);
  510. if (result != nullptr)
  511. result->setType(base->getType());
  512. }
  513. if (result == nullptr) {
  514. error(loc, "cannot index buffer reference", "", "");
  515. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  516. }
  517. return result;
  518. }
  519. if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
  520. handleIoResizeArrayAccess(loc, base);
  521. #endif
  522. if (index->getQualifier().isFrontEndConstant())
  523. checkIndex(loc, base->getType(), indexValue);
  524. if (index->getQualifier().isFrontEndConstant()) {
  525. #ifndef GLSLANG_WEB
  526. if (base->getType().isUnsizedArray()) {
  527. base->getWritableType().updateImplicitArraySize(indexValue + 1);
  528. // For 2D per-view builtin arrays, update the inner dimension size in parent type
  529. if (base->getQualifier().isPerView() && base->getQualifier().builtIn != EbvNone) {
  530. TIntermBinary* binaryNode = base->getAsBinaryNode();
  531. if (binaryNode) {
  532. TType& leftType = binaryNode->getLeft()->getWritableType();
  533. TArraySizes& arraySizes = *leftType.getArraySizes();
  534. assert(arraySizes.getNumDims() == 2);
  535. arraySizes.setDimSize(1, std::max(arraySizes.getDimSize(1), indexValue + 1));
  536. }
  537. }
  538. } else
  539. #endif
  540. checkIndex(loc, base->getType(), indexValue);
  541. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  542. } else {
  543. #ifndef GLSLANG_WEB
  544. if (base->getType().isUnsizedArray()) {
  545. // we have a variable index into an unsized array, which is okay,
  546. // depending on the situation
  547. if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
  548. error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable");
  549. else {
  550. // it is okay for a run-time sized array
  551. checkRuntimeSizable(loc, *base);
  552. }
  553. base->getWritableType().setArrayVariablyIndexed();
  554. }
  555. #endif
  556. if (base->getBasicType() == EbtBlock) {
  557. if (base->getQualifier().storage == EvqBuffer)
  558. requireProfile(base->getLoc(), ~EEsProfile, "variable indexing buffer block array");
  559. else if (base->getQualifier().storage == EvqUniform)
  560. profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
  561. "variable indexing uniform block array");
  562. else {
  563. // input/output blocks either don't exist or can't be variably indexed
  564. }
  565. } else if (language == EShLangFragment && base->getQualifier().isPipeOutput())
  566. requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader output array");
  567. else if (base->getBasicType() == EbtSampler && version >= 130) {
  568. const char* explanation = "variable indexing sampler array";
  569. requireProfile(base->getLoc(), EEsProfile | ECoreProfile | ECompatibilityProfile, explanation);
  570. profileRequires(base->getLoc(), EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5, explanation);
  571. profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, nullptr, explanation);
  572. }
  573. result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
  574. }
  575. // Insert valid dereferenced result type
  576. TType newType(base->getType(), 0);
  577. if (base->getType().getQualifier().isConstant() && index->getQualifier().isConstant()) {
  578. newType.getQualifier().storage = EvqConst;
  579. // If base or index is a specialization constant, the result should also be a specialization constant.
  580. if (base->getType().getQualifier().isSpecConstant() || index->getQualifier().isSpecConstant()) {
  581. newType.getQualifier().makeSpecConstant();
  582. }
  583. } else {
  584. newType.getQualifier().storage = EvqTemporary;
  585. newType.getQualifier().specConstant = false;
  586. }
  587. result->setType(newType);
  588. #ifndef GLSLANG_WEB
  589. inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
  590. // Propagate nonuniform
  591. if (base->getQualifier().isNonUniform() || index->getQualifier().isNonUniform())
  592. result->getWritableType().getQualifier().nonUniform = true;
  593. if (anyIndexLimits)
  594. handleIndexLimits(loc, base, index);
  595. #endif
  596. return result;
  597. }
  598. #ifndef GLSLANG_WEB
  599. // for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms
  600. void TParseContext::handleIndexLimits(const TSourceLoc& /*loc*/, TIntermTyped* base, TIntermTyped* index)
  601. {
  602. if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) ||
  603. (! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) ||
  604. (! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) ||
  605. (! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) ||
  606. (! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() &&
  607. ! base->getType().getQualifier().isPipeInput() &&
  608. ! base->getType().getQualifier().isPipeOutput() &&
  609. ! base->getType().getQualifier().isConstant()) ||
  610. (! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() ||
  611. base->getType().getQualifier().isPipeOutput()))) {
  612. // it's too early to know what the inductive variables are, save it for post processing
  613. needsIndexLimitationChecking.push_back(index);
  614. }
  615. }
  616. // Make a shared symbol have a non-shared version that can be edited by the current
  617. // compile, such that editing its type will not change the shared version and will
  618. // effect all nodes sharing it.
  619. void TParseContext::makeEditable(TSymbol*& symbol)
  620. {
  621. TParseContextBase::makeEditable(symbol);
  622. // See if it's tied to IO resizing
  623. if (isIoResizeArray(symbol->getType()))
  624. ioArraySymbolResizeList.push_back(symbol);
  625. }
  626. // Return true if this is a geometry shader input array or tessellation control output array
  627. // or mesh shader output array.
  628. bool TParseContext::isIoResizeArray(const TType& type) const
  629. {
  630. return type.isArray() &&
  631. ((language == EShLangGeometry && type.getQualifier().storage == EvqVaryingIn) ||
  632. (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut &&
  633. ! type.getQualifier().patch) ||
  634. (language == EShLangFragment && type.getQualifier().storage == EvqVaryingIn &&
  635. (type.getQualifier().pervertexNV || type.getQualifier().pervertexEXT)) ||
  636. (language == EShLangMesh && type.getQualifier().storage == EvqVaryingOut &&
  637. !type.getQualifier().perTaskNV));
  638. }
  639. // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
  640. void TParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
  641. {
  642. if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
  643. return;
  644. assert(! isIoResizeArray(type));
  645. if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
  646. return;
  647. if (language == EShLangTessControl || language == EShLangTessEvaluation) {
  648. if (type.getOuterArraySize() != resources.maxPatchVertices) {
  649. if (type.isSizedArray())
  650. error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
  651. type.changeOuterArraySize(resources.maxPatchVertices);
  652. }
  653. }
  654. }
  655. // Issue any errors if the non-array object is missing arrayness WRT
  656. // shader I/O that has array requirements.
  657. // All arrayness checking is handled in array paths, this is for
  658. void TParseContext::ioArrayCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
  659. {
  660. if (! type.isArray() && ! symbolTable.atBuiltInLevel()) {
  661. if (type.getQualifier().isArrayedIo(language) && !type.getQualifier().layoutPassthrough)
  662. error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str());
  663. }
  664. }
  665. // Handle a dereference of a geometry shader input array or tessellation control output array.
  666. // See ioArraySymbolResizeList comment in ParseHelper.h.
  667. //
  668. void TParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
  669. {
  670. TIntermSymbol* symbolNode = base->getAsSymbolNode();
  671. assert(symbolNode);
  672. if (! symbolNode)
  673. return;
  674. // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
  675. if (symbolNode->getType().isUnsizedArray()) {
  676. int newSize = getIoArrayImplicitSize(symbolNode->getType().getQualifier());
  677. if (newSize > 0)
  678. symbolNode->getWritableType().changeOuterArraySize(newSize);
  679. }
  680. }
  681. // If there has been an input primitive declaration (geometry shader) or an output
  682. // number of vertices declaration(tessellation shader), make sure all input array types
  683. // match it in size. Types come either from nodes in the AST or symbols in the
  684. // symbol table.
  685. //
  686. // Types without an array size will be given one.
  687. // Types already having a size that is wrong will get an error.
  688. //
  689. void TParseContext::checkIoArraysConsistency(const TSourceLoc &loc, bool tailOnly)
  690. {
  691. int requiredSize = 0;
  692. TString featureString;
  693. size_t listSize = ioArraySymbolResizeList.size();
  694. size_t i = 0;
  695. // If tailOnly = true, only check the last array symbol in the list.
  696. if (tailOnly) {
  697. i = listSize - 1;
  698. }
  699. for (bool firstIteration = true; i < listSize; ++i) {
  700. TType &type = ioArraySymbolResizeList[i]->getWritableType();
  701. // As I/O array sizes don't change, fetch requiredSize only once,
  702. // except for mesh shaders which could have different I/O array sizes based on type qualifiers.
  703. if (firstIteration || (language == EShLangMesh)) {
  704. requiredSize = getIoArrayImplicitSize(type.getQualifier(), &featureString);
  705. if (requiredSize == 0)
  706. break;
  707. firstIteration = false;
  708. }
  709. checkIoArrayConsistency(loc, requiredSize, featureString.c_str(), type,
  710. ioArraySymbolResizeList[i]->getName());
  711. }
  712. }
  713. int TParseContext::getIoArrayImplicitSize(const TQualifier &qualifier, TString *featureString) const
  714. {
  715. int expectedSize = 0;
  716. TString str = "unknown";
  717. unsigned int maxVertices = intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
  718. if (language == EShLangGeometry) {
  719. expectedSize = TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
  720. str = TQualifier::getGeometryString(intermediate.getInputPrimitive());
  721. }
  722. else if (language == EShLangTessControl) {
  723. expectedSize = maxVertices;
  724. str = "vertices";
  725. } else if (language == EShLangFragment) {
  726. // Number of vertices for Fragment shader is always three.
  727. expectedSize = 3;
  728. str = "vertices";
  729. } else if (language == EShLangMesh) {
  730. unsigned int maxPrimitives =
  731. intermediate.getPrimitives() != TQualifier::layoutNotSet ? intermediate.getPrimitives() : 0;
  732. if (qualifier.builtIn == EbvPrimitiveIndicesNV) {
  733. expectedSize = maxPrimitives * TQualifier::mapGeometryToSize(intermediate.getOutputPrimitive());
  734. str = "max_primitives*";
  735. str += TQualifier::getGeometryString(intermediate.getOutputPrimitive());
  736. }
  737. else if (qualifier.builtIn == EbvPrimitiveTriangleIndicesEXT || qualifier.builtIn == EbvPrimitiveLineIndicesEXT ||
  738. qualifier.builtIn == EbvPrimitivePointIndicesEXT) {
  739. expectedSize = maxPrimitives;
  740. str = "max_primitives";
  741. }
  742. else if (qualifier.isPerPrimitive()) {
  743. expectedSize = maxPrimitives;
  744. str = "max_primitives";
  745. }
  746. else {
  747. expectedSize = maxVertices;
  748. str = "max_vertices";
  749. }
  750. }
  751. if (featureString)
  752. *featureString = str;
  753. return expectedSize;
  754. }
  755. void TParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name)
  756. {
  757. if (type.isUnsizedArray())
  758. type.changeOuterArraySize(requiredSize);
  759. else if (type.getOuterArraySize() != requiredSize) {
  760. if (language == EShLangGeometry)
  761. error(loc, "inconsistent input primitive for array size of", feature, name.c_str());
  762. else if (language == EShLangTessControl)
  763. error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str());
  764. else if (language == EShLangFragment) {
  765. if (type.getOuterArraySize() > requiredSize)
  766. error(loc, " cannot be greater than 3 for pervertexEXT", feature, name.c_str());
  767. }
  768. else if (language == EShLangMesh)
  769. error(loc, "inconsistent output array size of", feature, name.c_str());
  770. else
  771. assert(0);
  772. }
  773. }
  774. #endif // GLSLANG_WEB
  775. // Handle seeing a binary node with a math operation.
  776. // Returns nullptr if not semantically allowed.
  777. TIntermTyped* TParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
  778. {
  779. rValueErrorCheck(loc, str, left->getAsTyped());
  780. rValueErrorCheck(loc, str, right->getAsTyped());
  781. bool allowed = true;
  782. switch (op) {
  783. // TODO: Bring more source language-specific checks up from intermediate.cpp
  784. // to the specific parse helpers for that source language.
  785. case EOpLessThan:
  786. case EOpGreaterThan:
  787. case EOpLessThanEqual:
  788. case EOpGreaterThanEqual:
  789. if (! left->isScalar() || ! right->isScalar())
  790. allowed = false;
  791. break;
  792. default:
  793. break;
  794. }
  795. if (((left->getType().contains16BitFloat() || right->getType().contains16BitFloat()) && !float16Arithmetic()) ||
  796. ((left->getType().contains16BitInt() || right->getType().contains16BitInt()) && !int16Arithmetic()) ||
  797. ((left->getType().contains8BitInt() || right->getType().contains8BitInt()) && !int8Arithmetic())) {
  798. allowed = false;
  799. }
  800. TIntermTyped* result = nullptr;
  801. if (allowed) {
  802. if ((left->isReference() || right->isReference()))
  803. requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "buffer reference math");
  804. result = intermediate.addBinaryMath(op, left, right, loc);
  805. }
  806. if (result == nullptr) {
  807. bool enhanced = intermediate.getEnhancedMsgs();
  808. binaryOpError(loc, str, left->getCompleteString(enhanced), right->getCompleteString(enhanced));
  809. }
  810. return result;
  811. }
  812. // Handle seeing a unary node with a math operation.
  813. TIntermTyped* TParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
  814. {
  815. rValueErrorCheck(loc, str, childNode);
  816. bool allowed = true;
  817. if ((childNode->getType().contains16BitFloat() && !float16Arithmetic()) ||
  818. (childNode->getType().contains16BitInt() && !int16Arithmetic()) ||
  819. (childNode->getType().contains8BitInt() && !int8Arithmetic())) {
  820. allowed = false;
  821. }
  822. TIntermTyped* result = nullptr;
  823. if (allowed)
  824. result = intermediate.addUnaryMath(op, childNode, loc);
  825. if (result)
  826. return result;
  827. else {
  828. bool enhanced = intermediate.getEnhancedMsgs();
  829. unaryOpError(loc, str, childNode->getCompleteString(enhanced));
  830. }
  831. return childNode;
  832. }
  833. //
  834. // Handle seeing a base.field dereference in the grammar.
  835. //
  836. TIntermTyped* TParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
  837. {
  838. variableCheck(base);
  839. //
  840. // .length() can't be resolved until we later see the function-calling syntax.
  841. // Save away the name in the AST for now. Processing is completed in
  842. // handleLengthMethod().
  843. //
  844. if (field == "length") {
  845. if (base->isArray()) {
  846. profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, ".length");
  847. profileRequires(loc, EEsProfile, 300, nullptr, ".length");
  848. } else if (base->isVector() || base->isMatrix()) {
  849. const char* feature = ".length() on vectors and matrices";
  850. requireProfile(loc, ~EEsProfile, feature);
  851. profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, feature);
  852. } else if (!base->getType().isCoopMat()) {
  853. bool enhanced = intermediate.getEnhancedMsgs();
  854. error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString(enhanced).c_str());
  855. return base;
  856. }
  857. return intermediate.addMethod(base, TType(EbtInt), &field, loc);
  858. }
  859. // It's not .length() if we get to here.
  860. if (base->isArray()) {
  861. error(loc, "cannot apply to an array:", ".", field.c_str());
  862. return base;
  863. }
  864. if (base->getType().isCoopMat()) {
  865. error(loc, "cannot apply to a cooperative matrix type:", ".", field.c_str());
  866. return base;
  867. }
  868. // It's neither an array nor .length() if we get here,
  869. // leaving swizzles and struct/block dereferences.
  870. TIntermTyped* result = base;
  871. if ((base->isVector() || base->isScalar()) &&
  872. (base->isFloatingDomain() || base->isIntegerDomain() || base->getBasicType() == EbtBool)) {
  873. result = handleDotSwizzle(loc, base, field);
  874. } else if (base->isStruct() || base->isReference()) {
  875. const TTypeList* fields = base->isReference() ?
  876. base->getType().getReferentType()->getStruct() :
  877. base->getType().getStruct();
  878. bool fieldFound = false;
  879. int member;
  880. for (member = 0; member < (int)fields->size(); ++member) {
  881. if ((*fields)[member].type->getFieldName() == field) {
  882. fieldFound = true;
  883. break;
  884. }
  885. }
  886. if (fieldFound) {
  887. if (base->getType().getQualifier().isFrontEndConstant())
  888. result = intermediate.foldDereference(base, member, loc);
  889. else {
  890. blockMemberExtensionCheck(loc, base, member, field);
  891. TIntermTyped* index = intermediate.addConstantUnion(member, loc);
  892. result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
  893. result->setType(*(*fields)[member].type);
  894. if ((*fields)[member].type->getQualifier().isIo())
  895. intermediate.addIoAccessed(field);
  896. }
  897. inheritMemoryQualifiers(base->getQualifier(), result->getWritableType().getQualifier());
  898. } else {
  899. auto baseSymbol = base;
  900. while (baseSymbol->getAsSymbolNode() == nullptr)
  901. baseSymbol = baseSymbol->getAsBinaryNode()->getLeft();
  902. TString structName;
  903. structName.append("\'").append(baseSymbol->getAsSymbolNode()->getName().c_str()).append( "\'");
  904. error(loc, "no such field in structure", field.c_str(), structName.c_str());
  905. }
  906. } else
  907. error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
  908. // Propagate noContraction up the dereference chain
  909. if (base->getQualifier().isNoContraction())
  910. result->getWritableType().getQualifier().setNoContraction();
  911. // Propagate nonuniform
  912. if (base->getQualifier().isNonUniform())
  913. result->getWritableType().getQualifier().nonUniform = true;
  914. return result;
  915. }
  916. //
  917. // Handle seeing a base.swizzle, a subset of base.identifier in the grammar.
  918. //
  919. TIntermTyped* TParseContext::handleDotSwizzle(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
  920. {
  921. TIntermTyped* result = base;
  922. if (base->isScalar()) {
  923. const char* dotFeature = "scalar swizzle";
  924. requireProfile(loc, ~EEsProfile, dotFeature);
  925. profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, dotFeature);
  926. }
  927. TSwizzleSelectors<TVectorSelector> selectors;
  928. parseSwizzleSelector(loc, field, base->getVectorSize(), selectors);
  929. if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitFloat())
  930. requireFloat16Arithmetic(loc, ".", "can't swizzle types containing float16");
  931. if (base->isVector() && selectors.size() != 1 && base->getType().contains16BitInt())
  932. requireInt16Arithmetic(loc, ".", "can't swizzle types containing (u)int16");
  933. if (base->isVector() && selectors.size() != 1 && base->getType().contains8BitInt())
  934. requireInt8Arithmetic(loc, ".", "can't swizzle types containing (u)int8");
  935. if (base->isScalar()) {
  936. if (selectors.size() == 1)
  937. return result;
  938. else {
  939. TType type(base->getBasicType(), EvqTemporary, selectors.size());
  940. // Swizzle operations propagate specialization-constantness
  941. if (base->getQualifier().isSpecConstant())
  942. type.getQualifier().makeSpecConstant();
  943. return addConstructor(loc, base, type);
  944. }
  945. }
  946. if (base->getType().getQualifier().isFrontEndConstant())
  947. result = intermediate.foldSwizzle(base, selectors, loc);
  948. else {
  949. if (selectors.size() == 1) {
  950. TIntermTyped* index = intermediate.addConstantUnion(selectors[0], loc);
  951. result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
  952. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
  953. } else {
  954. TIntermTyped* index = intermediate.addSwizzle(selectors, loc);
  955. result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
  956. result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, selectors.size()));
  957. }
  958. // Swizzle operations propagate specialization-constantness
  959. if (base->getType().getQualifier().isSpecConstant())
  960. result->getWritableType().getQualifier().makeSpecConstant();
  961. }
  962. return result;
  963. }
  964. void TParseContext::blockMemberExtensionCheck(const TSourceLoc& loc, const TIntermTyped* base, int member, const TString& memberName)
  965. {
  966. // a block that needs extension checking is either 'base', or if arrayed,
  967. // one level removed to the left
  968. const TIntermSymbol* baseSymbol = nullptr;
  969. if (base->getAsBinaryNode() == nullptr)
  970. baseSymbol = base->getAsSymbolNode();
  971. else
  972. baseSymbol = base->getAsBinaryNode()->getLeft()->getAsSymbolNode();
  973. if (baseSymbol == nullptr)
  974. return;
  975. const TSymbol* symbol = symbolTable.find(baseSymbol->getName());
  976. if (symbol == nullptr)
  977. return;
  978. const TVariable* variable = symbol->getAsVariable();
  979. if (variable == nullptr)
  980. return;
  981. if (!variable->hasMemberExtensions())
  982. return;
  983. // We now have a variable that is the base of a dot reference
  984. // with members that need extension checking.
  985. if (variable->getNumMemberExtensions(member) > 0)
  986. requireExtensions(loc, variable->getNumMemberExtensions(member), variable->getMemberExtensions(member), memberName.c_str());
  987. }
  988. //
  989. // Handle seeing a function declarator in the grammar. This is the precursor
  990. // to recognizing a function prototype or function definition.
  991. //
  992. TFunction* TParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
  993. {
  994. // ES can't declare prototypes inside functions
  995. if (! symbolTable.atGlobalLevel())
  996. requireProfile(loc, ~EEsProfile, "local function declaration");
  997. //
  998. // Multiple declarations of the same function name are allowed.
  999. //
  1000. // If this is a definition, the definition production code will check for redefinitions
  1001. // (we don't know at this point if it's a definition or not).
  1002. //
  1003. // Redeclarations (full signature match) are allowed. But, return types and parameter qualifiers must also match.
  1004. // - except ES 100, which only allows a single prototype
  1005. //
  1006. // ES 100 does not allow redefining, but does allow overloading of built-in functions.
  1007. // ES 300 does not allow redefining or overloading of built-in functions.
  1008. //
  1009. bool builtIn;
  1010. TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
  1011. if (symbol && symbol->getAsFunction() && builtIn)
  1012. requireProfile(loc, ~EEsProfile, "redefinition of built-in function");
  1013. #ifndef GLSLANG_WEB
  1014. // Check the validity of using spirv_literal qualifier
  1015. for (int i = 0; i < function.getParamCount(); ++i) {
  1016. if (function[i].type->getQualifier().isSpirvLiteral() && function.getBuiltInOp() != EOpSpirvInst)
  1017. error(loc, "'spirv_literal' can only be used on functions defined with 'spirv_instruction' for argument",
  1018. function.getName().c_str(), "%d", i + 1);
  1019. }
  1020. // For function declaration with SPIR-V instruction qualifier, always ignore the built-in function and
  1021. // respect this redeclared one.
  1022. if (symbol && builtIn && function.getBuiltInOp() == EOpSpirvInst)
  1023. symbol = nullptr;
  1024. #endif
  1025. const TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
  1026. if (prevDec) {
  1027. if (prevDec->isPrototyped() && prototype)
  1028. profileRequires(loc, EEsProfile, 300, nullptr, "multiple prototypes for same function");
  1029. if (prevDec->getType() != function.getType())
  1030. error(loc, "overloaded functions must have the same return type", function.getName().c_str(), "");
  1031. #ifndef GLSLANG_WEB
  1032. if (prevDec->getSpirvInstruction() != function.getSpirvInstruction()) {
  1033. error(loc, "overloaded functions must have the same qualifiers", function.getName().c_str(),
  1034. "spirv_instruction");
  1035. }
  1036. #endif
  1037. for (int i = 0; i < prevDec->getParamCount(); ++i) {
  1038. if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage)
  1039. error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1);
  1040. if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision)
  1041. error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1);
  1042. }
  1043. }
  1044. arrayObjectCheck(loc, function.getType(), "array in function return type");
  1045. if (prototype) {
  1046. // All built-in functions are defined, even though they don't have a body.
  1047. // Count their prototype as a definition instead.
  1048. if (symbolTable.atBuiltInLevel())
  1049. function.setDefined();
  1050. else {
  1051. if (prevDec && ! builtIn)
  1052. symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
  1053. function.setPrototyped();
  1054. }
  1055. }
  1056. // This insert won't actually insert it if it's a duplicate signature, but it will still check for
  1057. // other forms of name collisions.
  1058. if (! symbolTable.insert(function))
  1059. error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
  1060. //
  1061. // If this is a redeclaration, it could also be a definition,
  1062. // in which case, we need to use the parameter names from this one, and not the one that's
  1063. // being redeclared. So, pass back this declaration, not the one in the symbol table.
  1064. //
  1065. return &function;
  1066. }
  1067. //
  1068. // Handle seeing the function prototype in front of a function definition in the grammar.
  1069. // The body is handled after this function returns.
  1070. //
  1071. TIntermAggregate* TParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
  1072. {
  1073. currentCaller = function.getMangledName();
  1074. TSymbol* symbol = symbolTable.find(function.getMangledName());
  1075. TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
  1076. if (! prevDec)
  1077. error(loc, "can't find function", function.getName().c_str(), "");
  1078. // Note: 'prevDec' could be 'function' if this is the first time we've seen function
  1079. // as it would have just been put in the symbol table. Otherwise, we're looking up
  1080. // an earlier occurrence.
  1081. if (prevDec && prevDec->isDefined()) {
  1082. // Then this function already has a body.
  1083. error(loc, "function already has a body", function.getName().c_str(), "");
  1084. }
  1085. if (prevDec && ! prevDec->isDefined()) {
  1086. prevDec->setDefined();
  1087. // Remember the return type for later checking for RETURN statements.
  1088. currentFunctionType = &(prevDec->getType());
  1089. } else
  1090. currentFunctionType = new TType(EbtVoid);
  1091. functionReturnsValue = false;
  1092. // Check for entry point
  1093. if (function.getName().compare(intermediate.getEntryPointName().c_str()) == 0) {
  1094. intermediate.setEntryPointMangledName(function.getMangledName().c_str());
  1095. intermediate.incrementEntryPointCount();
  1096. inMain = true;
  1097. } else
  1098. inMain = false;
  1099. //
  1100. // Raise error message if main function takes any parameters or returns anything other than void
  1101. //
  1102. if (inMain) {
  1103. if (function.getParamCount() > 0)
  1104. error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
  1105. if (function.getType().getBasicType() != EbtVoid)
  1106. error(loc, "", function.getType().getBasicTypeString().c_str(), "entry point cannot return a value");
  1107. }
  1108. //
  1109. // New symbol table scope for body of function plus its arguments
  1110. //
  1111. symbolTable.push();
  1112. //
  1113. // Insert parameters into the symbol table.
  1114. // If the parameter has no name, it's not an error, just don't insert it
  1115. // (could be used for unused args).
  1116. //
  1117. // Also, accumulate the list of parameters into the HIL, so lower level code
  1118. // knows where to find parameters.
  1119. //
  1120. TIntermAggregate* paramNodes = new TIntermAggregate;
  1121. for (int i = 0; i < function.getParamCount(); i++) {
  1122. TParameter& param = function[i];
  1123. if (param.name != nullptr) {
  1124. TVariable *variable = new TVariable(param.name, *param.type);
  1125. // Insert the parameters with name in the symbol table.
  1126. if (! symbolTable.insert(*variable))
  1127. error(loc, "redefinition", variable->getName().c_str(), "");
  1128. else {
  1129. // Transfer ownership of name pointer to symbol table.
  1130. param.name = nullptr;
  1131. // Add the parameter to the HIL
  1132. paramNodes = intermediate.growAggregate(paramNodes,
  1133. intermediate.addSymbol(*variable, loc),
  1134. loc);
  1135. }
  1136. } else
  1137. paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
  1138. }
  1139. intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
  1140. loopNestingLevel = 0;
  1141. statementNestingLevel = 0;
  1142. controlFlowNestingLevel = 0;
  1143. postEntryPointReturn = false;
  1144. return paramNodes;
  1145. }
  1146. //
  1147. // Handle seeing function call syntax in the grammar, which could be any of
  1148. // - .length() method
  1149. // - constructor
  1150. // - a call to a built-in function mapped to an operator
  1151. // - a call to a built-in function that will remain a function call (e.g., texturing)
  1152. // - user function
  1153. // - subroutine call (not implemented yet)
  1154. //
  1155. TIntermTyped* TParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
  1156. {
  1157. TIntermTyped* result = nullptr;
  1158. if (spvVersion.vulkan != 0 && spvVersion.vulkanRelaxed) {
  1159. // allow calls that are invalid in Vulkan Semantics to be invisibily
  1160. // remapped to equivalent valid functions
  1161. result = vkRelaxedRemapFunctionCall(loc, function, arguments);
  1162. if (result)
  1163. return result;
  1164. }
  1165. if (function->getBuiltInOp() == EOpArrayLength)
  1166. result = handleLengthMethod(loc, function, arguments);
  1167. else if (function->getBuiltInOp() != EOpNull) {
  1168. //
  1169. // Then this should be a constructor.
  1170. // Don't go through the symbol table for constructors.
  1171. // Their parameters will be verified algorithmically.
  1172. //
  1173. TType type(EbtVoid); // use this to get the type back
  1174. if (! constructorError(loc, arguments, *function, function->getBuiltInOp(), type)) {
  1175. //
  1176. // It's a constructor, of type 'type'.
  1177. //
  1178. result = addConstructor(loc, arguments, type);
  1179. if (result == nullptr)
  1180. error(loc, "cannot construct with these arguments", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str(), "");
  1181. }
  1182. } else {
  1183. //
  1184. // Find it in the symbol table.
  1185. //
  1186. const TFunction* fnCandidate;
  1187. bool builtIn {false};
  1188. fnCandidate = findFunction(loc, *function, builtIn);
  1189. if (fnCandidate) {
  1190. // This is a declared function that might map to
  1191. // - a built-in operator,
  1192. // - a built-in function not mapped to an operator, or
  1193. // - a user function.
  1194. // Error check for a function requiring specific extensions present.
  1195. if (builtIn && fnCandidate->getNumExtensions())
  1196. requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
  1197. if (builtIn && fnCandidate->getType().contains16BitFloat())
  1198. requireFloat16Arithmetic(loc, "built-in function", "float16 types can only be in uniform block or buffer storage");
  1199. if (builtIn && fnCandidate->getType().contains16BitInt())
  1200. requireInt16Arithmetic(loc, "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
  1201. if (builtIn && fnCandidate->getType().contains8BitInt())
  1202. requireInt8Arithmetic(loc, "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
  1203. if (arguments != nullptr) {
  1204. // Make sure qualifications work for these arguments.
  1205. TIntermAggregate* aggregate = arguments->getAsAggregate();
  1206. for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
  1207. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  1208. // is the single argument itself or its children are the arguments. Only one argument
  1209. // means take 'arguments' itself as the one argument.
  1210. TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
  1211. TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
  1212. if (formalQualifier.isParamOutput()) {
  1213. if (lValueErrorCheck(arguments->getLoc(), "assign", arg->getAsTyped()))
  1214. error(arguments->getLoc(), "Non-L-value cannot be passed for 'out' or 'inout' parameters.", "out", "");
  1215. }
  1216. #ifndef GLSLANG_WEB
  1217. if (formalQualifier.isSpirvLiteral()) {
  1218. if (!arg->getAsTyped()->getQualifier().isFrontEndConstant()) {
  1219. error(arguments->getLoc(),
  1220. "Non front-end constant expressions cannot be passed for 'spirv_literal' parameters.",
  1221. "spirv_literal", "");
  1222. }
  1223. }
  1224. #endif
  1225. const TType& argType = arg->getAsTyped()->getType();
  1226. const TQualifier& argQualifier = argType.getQualifier();
  1227. if (argQualifier.isMemory() && (argType.containsOpaque() || argType.isReference())) {
  1228. const char* message = "argument cannot drop memory qualifier when passed to formal parameter";
  1229. #ifndef GLSLANG_WEB
  1230. if (argQualifier.volatil && ! formalQualifier.volatil)
  1231. error(arguments->getLoc(), message, "volatile", "");
  1232. if (argQualifier.coherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
  1233. error(arguments->getLoc(), message, "coherent", "");
  1234. if (argQualifier.devicecoherent && ! (formalQualifier.devicecoherent || formalQualifier.coherent))
  1235. error(arguments->getLoc(), message, "devicecoherent", "");
  1236. if (argQualifier.queuefamilycoherent && ! (formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
  1237. error(arguments->getLoc(), message, "queuefamilycoherent", "");
  1238. if (argQualifier.workgroupcoherent && ! (formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
  1239. error(arguments->getLoc(), message, "workgroupcoherent", "");
  1240. if (argQualifier.subgroupcoherent && ! (formalQualifier.subgroupcoherent || formalQualifier.workgroupcoherent || formalQualifier.queuefamilycoherent || formalQualifier.devicecoherent || formalQualifier.coherent))
  1241. error(arguments->getLoc(), message, "subgroupcoherent", "");
  1242. if (argQualifier.readonly && ! formalQualifier.readonly)
  1243. error(arguments->getLoc(), message, "readonly", "");
  1244. if (argQualifier.writeonly && ! formalQualifier.writeonly)
  1245. error(arguments->getLoc(), message, "writeonly", "");
  1246. // Don't check 'restrict', it is different than the rest:
  1247. // "...but only restrict can be taken away from a calling argument, by a formal parameter that
  1248. // lacks the restrict qualifier..."
  1249. #endif
  1250. }
  1251. if (!builtIn && argQualifier.getFormat() != formalQualifier.getFormat()) {
  1252. // we have mismatched formats, which should only be allowed if writeonly
  1253. // and at least one format is unknown
  1254. if (!formalQualifier.isWriteOnly() || (formalQualifier.getFormat() != ElfNone &&
  1255. argQualifier.getFormat() != ElfNone))
  1256. error(arguments->getLoc(), "image formats must match", "format", "");
  1257. }
  1258. if (builtIn && arg->getAsTyped()->getType().contains16BitFloat())
  1259. requireFloat16Arithmetic(arguments->getLoc(), "built-in function", "float16 types can only be in uniform block or buffer storage");
  1260. if (builtIn && arg->getAsTyped()->getType().contains16BitInt())
  1261. requireInt16Arithmetic(arguments->getLoc(), "built-in function", "(u)int16 types can only be in uniform block or buffer storage");
  1262. if (builtIn && arg->getAsTyped()->getType().contains8BitInt())
  1263. requireInt8Arithmetic(arguments->getLoc(), "built-in function", "(u)int8 types can only be in uniform block or buffer storage");
  1264. // TODO 4.5 functionality: A shader will fail to compile
  1265. // if the value passed to the memargument of an atomic memory function does not correspond to a buffer or
  1266. // shared variable. It is acceptable to pass an element of an array or a single component of a vector to the
  1267. // memargument of an atomic memory function, as long as the underlying array or vector is a buffer or
  1268. // shared variable.
  1269. }
  1270. // Convert 'in' arguments
  1271. addInputArgumentConversions(*fnCandidate, arguments); // arguments may be modified if it's just a single argument node
  1272. }
  1273. if (builtIn && fnCandidate->getBuiltInOp() != EOpNull) {
  1274. // A function call mapped to a built-in operation.
  1275. result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
  1276. #ifndef GLSLANG_WEB
  1277. } else if (fnCandidate->getBuiltInOp() == EOpSpirvInst) {
  1278. // When SPIR-V instruction qualifier is specified, the function call is still mapped to a built-in operation.
  1279. result = handleBuiltInFunctionCall(loc, arguments, *fnCandidate);
  1280. #endif
  1281. } else {
  1282. // This is a function call not mapped to built-in operator.
  1283. // It could still be a built-in function, but only if PureOperatorBuiltins == false.
  1284. result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
  1285. TIntermAggregate* call = result->getAsAggregate();
  1286. call->setName(fnCandidate->getMangledName());
  1287. // this is how we know whether the given function is a built-in function or a user-defined function
  1288. // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
  1289. // if builtIn == true, it's definitely a built-in function with EOpNull
  1290. if (! builtIn) {
  1291. call->setUserDefined();
  1292. if (symbolTable.atGlobalLevel()) {
  1293. requireProfile(loc, ~EEsProfile, "calling user function from global scope");
  1294. intermediate.addToCallGraph(infoSink, "main(", fnCandidate->getMangledName());
  1295. } else
  1296. intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
  1297. }
  1298. #ifndef GLSLANG_WEB
  1299. if (builtIn)
  1300. nonOpBuiltInCheck(loc, *fnCandidate, *call);
  1301. else
  1302. #endif
  1303. userFunctionCallCheck(loc, *call);
  1304. }
  1305. // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
  1306. // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
  1307. // Also, build the qualifier list for user function calls, which are always called with an aggregate.
  1308. if (result->getAsAggregate()) {
  1309. TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
  1310. for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
  1311. TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
  1312. qualifierList.push_back(qual);
  1313. }
  1314. result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
  1315. }
  1316. if (result->getAsTyped()->getType().isCoopMat() &&
  1317. !result->getAsTyped()->getType().isParameterized()) {
  1318. assert(fnCandidate->getBuiltInOp() == EOpCooperativeMatrixMulAdd);
  1319. result->setType(result->getAsAggregate()->getSequence()[2]->getAsTyped()->getType());
  1320. }
  1321. }
  1322. }
  1323. // generic error recovery
  1324. // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
  1325. if (result == nullptr)
  1326. result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
  1327. return result;
  1328. }
  1329. TIntermTyped* TParseContext::handleBuiltInFunctionCall(TSourceLoc loc, TIntermNode* arguments,
  1330. const TFunction& function)
  1331. {
  1332. checkLocation(loc, function.getBuiltInOp());
  1333. TIntermTyped *result = intermediate.addBuiltInFunctionCall(loc, function.getBuiltInOp(),
  1334. function.getParamCount() == 1,
  1335. arguments, function.getType());
  1336. if (result != nullptr && obeyPrecisionQualifiers())
  1337. computeBuiltinPrecisions(*result, function);
  1338. if (result == nullptr) {
  1339. if (arguments == nullptr)
  1340. error(loc, " wrong operand type", "Internal Error",
  1341. "built in unary operator function. Type: %s", "");
  1342. else
  1343. error(arguments->getLoc(), " wrong operand type", "Internal Error",
  1344. "built in unary operator function. Type: %s",
  1345. static_cast<TIntermTyped*>(arguments)->getCompleteString(intermediate.getEnhancedMsgs()).c_str());
  1346. } else if (result->getAsOperator())
  1347. builtInOpCheck(loc, function, *result->getAsOperator());
  1348. #ifndef GLSLANG_WEB
  1349. // Special handling for function call with SPIR-V instruction qualifier specified
  1350. if (function.getBuiltInOp() == EOpSpirvInst) {
  1351. if (auto agg = result->getAsAggregate()) {
  1352. // Propogate spirv_by_reference/spirv_literal from parameters to arguments
  1353. auto& sequence = agg->getSequence();
  1354. for (unsigned i = 0; i < sequence.size(); ++i) {
  1355. if (function[i].type->getQualifier().isSpirvByReference())
  1356. sequence[i]->getAsTyped()->getQualifier().setSpirvByReference();
  1357. if (function[i].type->getQualifier().isSpirvLiteral())
  1358. sequence[i]->getAsTyped()->getQualifier().setSpirvLiteral();
  1359. }
  1360. // Attach the function call to SPIR-V intruction
  1361. agg->setSpirvInstruction(function.getSpirvInstruction());
  1362. } else if (auto unaryNode = result->getAsUnaryNode()) {
  1363. // Propogate spirv_by_reference/spirv_literal from parameters to arguments
  1364. if (function[0].type->getQualifier().isSpirvByReference())
  1365. unaryNode->getOperand()->getQualifier().setSpirvByReference();
  1366. if (function[0].type->getQualifier().isSpirvLiteral())
  1367. unaryNode->getOperand()->getQualifier().setSpirvLiteral();
  1368. // Attach the function call to SPIR-V intruction
  1369. unaryNode->setSpirvInstruction(function.getSpirvInstruction());
  1370. } else
  1371. assert(0);
  1372. }
  1373. #endif
  1374. return result;
  1375. }
  1376. // "The operation of a built-in function can have a different precision
  1377. // qualification than the precision qualification of the resulting value.
  1378. // These two precision qualifications are established as follows.
  1379. //
  1380. // The precision qualification of the operation of a built-in function is
  1381. // based on the precision qualification of its input arguments and formal
  1382. // parameters: When a formal parameter specifies a precision qualifier,
  1383. // that is used, otherwise, the precision qualification of the calling
  1384. // argument is used. The highest precision of these will be the precision
  1385. // qualification of the operation of the built-in function. Generally,
  1386. // this is applied across all arguments to a built-in function, with the
  1387. // exceptions being:
  1388. // - bitfieldExtract and bitfieldInsert ignore the 'offset' and 'bits'
  1389. // arguments.
  1390. // - interpolateAt* functions only look at the 'interpolant' argument.
  1391. //
  1392. // The precision qualification of the result of a built-in function is
  1393. // determined in one of the following ways:
  1394. //
  1395. // - For the texture sampling, image load, and image store functions,
  1396. // the precision of the return type matches the precision of the
  1397. // sampler type
  1398. //
  1399. // Otherwise:
  1400. //
  1401. // - For prototypes that do not specify a resulting precision qualifier,
  1402. // the precision will be the same as the precision of the operation.
  1403. //
  1404. // - For prototypes that do specify a resulting precision qualifier,
  1405. // the specified precision qualifier is the precision qualification of
  1406. // the result."
  1407. //
  1408. void TParseContext::computeBuiltinPrecisions(TIntermTyped& node, const TFunction& function)
  1409. {
  1410. TPrecisionQualifier operationPrecision = EpqNone;
  1411. TPrecisionQualifier resultPrecision = EpqNone;
  1412. TIntermOperator* opNode = node.getAsOperator();
  1413. if (opNode == nullptr)
  1414. return;
  1415. if (TIntermUnary* unaryNode = node.getAsUnaryNode()) {
  1416. operationPrecision = std::max(function[0].type->getQualifier().precision,
  1417. unaryNode->getOperand()->getType().getQualifier().precision);
  1418. if (function.getType().getBasicType() != EbtBool)
  1419. resultPrecision = function.getType().getQualifier().precision == EpqNone ?
  1420. operationPrecision :
  1421. function.getType().getQualifier().precision;
  1422. } else if (TIntermAggregate* agg = node.getAsAggregate()) {
  1423. TIntermSequence& sequence = agg->getSequence();
  1424. unsigned int numArgs = (unsigned int)sequence.size();
  1425. switch (agg->getOp()) {
  1426. case EOpBitfieldExtract:
  1427. numArgs = 1;
  1428. break;
  1429. case EOpBitfieldInsert:
  1430. numArgs = 2;
  1431. break;
  1432. case EOpInterpolateAtCentroid:
  1433. case EOpInterpolateAtOffset:
  1434. case EOpInterpolateAtSample:
  1435. numArgs = 1;
  1436. break;
  1437. case EOpDebugPrintf:
  1438. numArgs = 0;
  1439. break;
  1440. default:
  1441. break;
  1442. }
  1443. // find the maximum precision from the arguments and parameters
  1444. for (unsigned int arg = 0; arg < numArgs; ++arg) {
  1445. operationPrecision = std::max(operationPrecision, sequence[arg]->getAsTyped()->getQualifier().precision);
  1446. operationPrecision = std::max(operationPrecision, function[arg].type->getQualifier().precision);
  1447. }
  1448. // compute the result precision
  1449. if (agg->isSampling() ||
  1450. agg->getOp() == EOpImageLoad || agg->getOp() == EOpImageStore ||
  1451. agg->getOp() == EOpImageLoadLod || agg->getOp() == EOpImageStoreLod)
  1452. resultPrecision = sequence[0]->getAsTyped()->getQualifier().precision;
  1453. else if (function.getType().getBasicType() != EbtBool)
  1454. resultPrecision = function.getType().getQualifier().precision == EpqNone ?
  1455. operationPrecision :
  1456. function.getType().getQualifier().precision;
  1457. }
  1458. // Propagate precision through this node and its children. That algorithm stops
  1459. // when a precision is found, so start by clearing this subroot precision
  1460. opNode->getQualifier().precision = EpqNone;
  1461. if (operationPrecision != EpqNone) {
  1462. opNode->propagatePrecision(operationPrecision);
  1463. opNode->setOperationPrecision(operationPrecision);
  1464. }
  1465. // Now, set the result precision, which might not match
  1466. opNode->getQualifier().precision = resultPrecision;
  1467. }
  1468. TIntermNode* TParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
  1469. {
  1470. #ifndef GLSLANG_WEB
  1471. storage16BitAssignmentCheck(loc, value->getType(), "return");
  1472. #endif
  1473. functionReturnsValue = true;
  1474. TIntermBranch* branch = nullptr;
  1475. if (currentFunctionType->getBasicType() == EbtVoid) {
  1476. error(loc, "void function cannot return a value", "return", "");
  1477. branch = intermediate.addBranch(EOpReturn, loc);
  1478. } else if (*currentFunctionType != value->getType()) {
  1479. TIntermTyped* converted = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
  1480. if (converted) {
  1481. if (*currentFunctionType != converted->getType())
  1482. error(loc, "cannot convert return value to function return type", "return", "");
  1483. if (version < 420)
  1484. warn(loc, "type conversion on return values was not explicitly allowed until version 420",
  1485. "return", "");
  1486. branch = intermediate.addBranch(EOpReturn, converted, loc);
  1487. } else {
  1488. error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
  1489. branch = intermediate.addBranch(EOpReturn, value, loc);
  1490. }
  1491. } else
  1492. branch = intermediate.addBranch(EOpReturn, value, loc);
  1493. branch->updatePrecision(currentFunctionType->getQualifier().precision);
  1494. return branch;
  1495. }
  1496. // See if the operation is being done in an illegal location.
  1497. void TParseContext::checkLocation(const TSourceLoc& loc, TOperator op)
  1498. {
  1499. #ifndef GLSLANG_WEB
  1500. switch (op) {
  1501. case EOpBarrier:
  1502. if (language == EShLangTessControl) {
  1503. if (controlFlowNestingLevel > 0)
  1504. error(loc, "tessellation control barrier() cannot be placed within flow control", "", "");
  1505. if (! inMain)
  1506. error(loc, "tessellation control barrier() must be in main()", "", "");
  1507. else if (postEntryPointReturn)
  1508. error(loc, "tessellation control barrier() cannot be placed after a return from main()", "", "");
  1509. }
  1510. break;
  1511. case EOpBeginInvocationInterlock:
  1512. if (language != EShLangFragment)
  1513. error(loc, "beginInvocationInterlockARB() must be in a fragment shader", "", "");
  1514. if (! inMain)
  1515. error(loc, "beginInvocationInterlockARB() must be in main()", "", "");
  1516. else if (postEntryPointReturn)
  1517. error(loc, "beginInvocationInterlockARB() cannot be placed after a return from main()", "", "");
  1518. if (controlFlowNestingLevel > 0)
  1519. error(loc, "beginInvocationInterlockARB() cannot be placed within flow control", "", "");
  1520. if (beginInvocationInterlockCount > 0)
  1521. error(loc, "beginInvocationInterlockARB() must only be called once", "", "");
  1522. if (endInvocationInterlockCount > 0)
  1523. error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
  1524. beginInvocationInterlockCount++;
  1525. // default to pixel_interlock_ordered
  1526. if (intermediate.getInterlockOrdering() == EioNone)
  1527. intermediate.setInterlockOrdering(EioPixelInterlockOrdered);
  1528. break;
  1529. case EOpEndInvocationInterlock:
  1530. if (language != EShLangFragment)
  1531. error(loc, "endInvocationInterlockARB() must be in a fragment shader", "", "");
  1532. if (! inMain)
  1533. error(loc, "endInvocationInterlockARB() must be in main()", "", "");
  1534. else if (postEntryPointReturn)
  1535. error(loc, "endInvocationInterlockARB() cannot be placed after a return from main()", "", "");
  1536. if (controlFlowNestingLevel > 0)
  1537. error(loc, "endInvocationInterlockARB() cannot be placed within flow control", "", "");
  1538. if (endInvocationInterlockCount > 0)
  1539. error(loc, "endInvocationInterlockARB() must only be called once", "", "");
  1540. if (beginInvocationInterlockCount == 0)
  1541. error(loc, "beginInvocationInterlockARB() must be called before endInvocationInterlockARB()", "", "");
  1542. endInvocationInterlockCount++;
  1543. break;
  1544. default:
  1545. break;
  1546. }
  1547. #endif
  1548. }
  1549. // Finish processing object.length(). This started earlier in handleDotDereference(), where
  1550. // the ".length" part was recognized and semantically checked, and finished here where the
  1551. // function syntax "()" is recognized.
  1552. //
  1553. // Return resulting tree node.
  1554. TIntermTyped* TParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
  1555. {
  1556. int length = 0;
  1557. if (function->getParamCount() > 0)
  1558. error(loc, "method does not accept any arguments", function->getName().c_str(), "");
  1559. else {
  1560. const TType& type = intermNode->getAsTyped()->getType();
  1561. if (type.isArray()) {
  1562. if (type.isUnsizedArray()) {
  1563. #ifndef GLSLANG_WEB
  1564. if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
  1565. // We could be between a layout declaration that gives a built-in io array implicit size and
  1566. // a user redeclaration of that array, meaning we have to substitute its implicit size here
  1567. // without actually redeclaring the array. (It is an error to use a member before the
  1568. // redeclaration, but not an error to use the array name itself.)
  1569. const TString& name = intermNode->getAsSymbolNode()->getName();
  1570. if (name == "gl_in" || name == "gl_out" || name == "gl_MeshVerticesNV" ||
  1571. name == "gl_MeshPrimitivesNV") {
  1572. length = getIoArrayImplicitSize(type.getQualifier());
  1573. }
  1574. }
  1575. #endif
  1576. if (length == 0) {
  1577. #ifndef GLSLANG_WEB
  1578. if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
  1579. error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
  1580. else if (isRuntimeLength(*intermNode->getAsTyped())) {
  1581. // Create a unary op and let the back end handle it
  1582. return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
  1583. } else
  1584. #endif
  1585. error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
  1586. }
  1587. } else if (type.getOuterArrayNode()) {
  1588. // If the array's outer size is specified by an intermediate node, it means the array's length
  1589. // was specified by a specialization constant. In such a case, we should return the node of the
  1590. // specialization constants to represent the length.
  1591. return type.getOuterArrayNode();
  1592. } else
  1593. length = type.getOuterArraySize();
  1594. } else if (type.isMatrix())
  1595. length = type.getMatrixCols();
  1596. else if (type.isVector())
  1597. length = type.getVectorSize();
  1598. else if (type.isCoopMat())
  1599. return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
  1600. else {
  1601. // we should not get here, because earlier semantic checking should have prevented this path
  1602. error(loc, ".length()", "unexpected use of .length()", "");
  1603. }
  1604. }
  1605. if (length == 0)
  1606. length = 1;
  1607. return intermediate.addConstantUnion(length, loc);
  1608. }
  1609. //
  1610. // Add any needed implicit conversions for function-call arguments to input parameters.
  1611. //
  1612. void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
  1613. {
  1614. #ifndef GLSLANG_WEB
  1615. TIntermAggregate* aggregate = arguments->getAsAggregate();
  1616. // Process each argument's conversion
  1617. for (int i = 0; i < function.getParamCount(); ++i) {
  1618. // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
  1619. // is the single argument itself or its children are the arguments. Only one argument
  1620. // means take 'arguments' itself as the one argument.
  1621. TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
  1622. if (*function[i].type != arg->getType()) {
  1623. if (function[i].type->getQualifier().isParamInput() &&
  1624. !function[i].type->isCoopMat()) {
  1625. // In-qualified arguments just need an extra node added above the argument to
  1626. // convert to the correct type.
  1627. arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
  1628. if (arg) {
  1629. if (function.getParamCount() == 1)
  1630. arguments = arg;
  1631. else {
  1632. if (aggregate)
  1633. aggregate->getSequence()[i] = arg;
  1634. else
  1635. arguments = arg;
  1636. }
  1637. }
  1638. }
  1639. }
  1640. }
  1641. #endif
  1642. }
  1643. //
  1644. // Add any needed implicit output conversions for function-call arguments. This
  1645. // can require a new tree topology, complicated further by whether the function
  1646. // has a return value.
  1647. //
  1648. // Returns a node of a subtree that evaluates to the return value of the function.
  1649. //
  1650. TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
  1651. {
  1652. #ifdef GLSLANG_WEB
  1653. return &intermNode;
  1654. #else
  1655. TIntermSequence& arguments = intermNode.getSequence();
  1656. // Will there be any output conversions?
  1657. bool outputConversions = false;
  1658. for (int i = 0; i < function.getParamCount(); ++i) {
  1659. if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().isParamOutput()) {
  1660. outputConversions = true;
  1661. break;
  1662. }
  1663. }
  1664. if (! outputConversions)
  1665. return &intermNode;
  1666. // Setup for the new tree, if needed:
  1667. //
  1668. // Output conversions need a different tree topology.
  1669. // Out-qualified arguments need a temporary of the correct type, with the call
  1670. // followed by an assignment of the temporary to the original argument:
  1671. // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
  1672. // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
  1673. // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
  1674. TIntermTyped* conversionTree = nullptr;
  1675. TVariable* tempRet = nullptr;
  1676. if (intermNode.getBasicType() != EbtVoid) {
  1677. // do the "tempRet = function(...), " bit from above
  1678. tempRet = makeInternalVariable("tempReturn", intermNode.getType());
  1679. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
  1680. conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
  1681. } else
  1682. conversionTree = &intermNode;
  1683. conversionTree = intermediate.makeAggregate(conversionTree);
  1684. // Process each argument's conversion
  1685. for (int i = 0; i < function.getParamCount(); ++i) {
  1686. if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
  1687. if (function[i].type->getQualifier().isParamOutput()) {
  1688. // Out-qualified arguments need to use the topology set up above.
  1689. // do the " ...(tempArg, ...), arg = tempArg" bit from above
  1690. TType paramType;
  1691. paramType.shallowCopy(*function[i].type);
  1692. if (arguments[i]->getAsTyped()->getType().isParameterized() &&
  1693. !paramType.isParameterized()) {
  1694. paramType.shallowCopy(arguments[i]->getAsTyped()->getType());
  1695. paramType.copyTypeParameters(*arguments[i]->getAsTyped()->getType().getTypeParameters());
  1696. }
  1697. TVariable* tempArg = makeInternalVariable("tempArg", paramType);
  1698. tempArg->getWritableType().getQualifier().makeTemporary();
  1699. TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
  1700. TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
  1701. conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
  1702. // replace the argument with another node for the same tempArg variable
  1703. arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
  1704. }
  1705. }
  1706. }
  1707. // Finalize the tree topology (see bigger comment above).
  1708. if (tempRet) {
  1709. // do the "..., tempRet" bit from above
  1710. TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
  1711. conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
  1712. }
  1713. conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
  1714. return conversionTree;
  1715. #endif
  1716. }
  1717. TIntermTyped* TParseContext::addAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left, TIntermTyped* right)
  1718. {
  1719. if ((op == EOpAddAssign || op == EOpSubAssign) && left->isReference())
  1720. requireExtensions(loc, 1, &E_GL_EXT_buffer_reference2, "+= and -= on a buffer reference");
  1721. return intermediate.addAssign(op, left, right, loc);
  1722. }
  1723. void TParseContext::memorySemanticsCheck(const TSourceLoc& loc, const TFunction& fnCandidate, const TIntermOperator& callNode)
  1724. {
  1725. const TIntermSequence* argp = &callNode.getAsAggregate()->getSequence();
  1726. //const int gl_SemanticsRelaxed = 0x0;
  1727. const int gl_SemanticsAcquire = 0x2;
  1728. const int gl_SemanticsRelease = 0x4;
  1729. const int gl_SemanticsAcquireRelease = 0x8;
  1730. const int gl_SemanticsMakeAvailable = 0x2000;
  1731. const int gl_SemanticsMakeVisible = 0x4000;
  1732. const int gl_SemanticsVolatile = 0x8000;
  1733. //const int gl_StorageSemanticsNone = 0x0;
  1734. const int gl_StorageSemanticsBuffer = 0x40;
  1735. const int gl_StorageSemanticsShared = 0x100;
  1736. const int gl_StorageSemanticsImage = 0x800;
  1737. const int gl_StorageSemanticsOutput = 0x1000;
  1738. unsigned int semantics = 0, storageClassSemantics = 0;
  1739. unsigned int semantics2 = 0, storageClassSemantics2 = 0;
  1740. const TIntermTyped* arg0 = (*argp)[0]->getAsTyped();
  1741. const bool isMS = arg0->getBasicType() == EbtSampler && arg0->getType().getSampler().isMultiSample();
  1742. // Grab the semantics and storage class semantics from the operands, based on opcode
  1743. switch (callNode.getOp()) {
  1744. case EOpAtomicAdd:
  1745. case EOpAtomicSubtract:
  1746. case EOpAtomicMin:
  1747. case EOpAtomicMax:
  1748. case EOpAtomicAnd:
  1749. case EOpAtomicOr:
  1750. case EOpAtomicXor:
  1751. case EOpAtomicExchange:
  1752. case EOpAtomicStore:
  1753. storageClassSemantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1754. semantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1755. break;
  1756. case EOpAtomicLoad:
  1757. storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1758. semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1759. break;
  1760. case EOpAtomicCompSwap:
  1761. storageClassSemantics = (*argp)[4]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1762. semantics = (*argp)[5]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1763. storageClassSemantics2 = (*argp)[6]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1764. semantics2 = (*argp)[7]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1765. break;
  1766. case EOpImageAtomicAdd:
  1767. case EOpImageAtomicMin:
  1768. case EOpImageAtomicMax:
  1769. case EOpImageAtomicAnd:
  1770. case EOpImageAtomicOr:
  1771. case EOpImageAtomicXor:
  1772. case EOpImageAtomicExchange:
  1773. case EOpImageAtomicStore:
  1774. storageClassSemantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1775. semantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1776. break;
  1777. case EOpImageAtomicLoad:
  1778. storageClassSemantics = (*argp)[isMS ? 4 : 3]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1779. semantics = (*argp)[isMS ? 5 : 4]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1780. break;
  1781. case EOpImageAtomicCompSwap:
  1782. storageClassSemantics = (*argp)[isMS ? 6 : 5]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1783. semantics = (*argp)[isMS ? 7 : 6]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1784. storageClassSemantics2 = (*argp)[isMS ? 8 : 7]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1785. semantics2 = (*argp)[isMS ? 9 : 8]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1786. break;
  1787. case EOpBarrier:
  1788. storageClassSemantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1789. semantics = (*argp)[3]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1790. break;
  1791. case EOpMemoryBarrier:
  1792. storageClassSemantics = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1793. semantics = (*argp)[2]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1794. break;
  1795. default:
  1796. break;
  1797. }
  1798. if ((semantics & gl_SemanticsAcquire) &&
  1799. (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore)) {
  1800. error(loc, "gl_SemanticsAcquire must not be used with (image) atomic store",
  1801. fnCandidate.getName().c_str(), "");
  1802. }
  1803. if ((semantics & gl_SemanticsRelease) &&
  1804. (callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpImageAtomicLoad)) {
  1805. error(loc, "gl_SemanticsRelease must not be used with (image) atomic load",
  1806. fnCandidate.getName().c_str(), "");
  1807. }
  1808. if ((semantics & gl_SemanticsAcquireRelease) &&
  1809. (callNode.getOp() == EOpAtomicStore || callNode.getOp() == EOpImageAtomicStore ||
  1810. callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpImageAtomicLoad)) {
  1811. error(loc, "gl_SemanticsAcquireRelease must not be used with (image) atomic load/store",
  1812. fnCandidate.getName().c_str(), "");
  1813. }
  1814. if (((semantics | semantics2) & ~(gl_SemanticsAcquire |
  1815. gl_SemanticsRelease |
  1816. gl_SemanticsAcquireRelease |
  1817. gl_SemanticsMakeAvailable |
  1818. gl_SemanticsMakeVisible |
  1819. gl_SemanticsVolatile))) {
  1820. error(loc, "Invalid semantics value", fnCandidate.getName().c_str(), "");
  1821. }
  1822. if (((storageClassSemantics | storageClassSemantics2) & ~(gl_StorageSemanticsBuffer |
  1823. gl_StorageSemanticsShared |
  1824. gl_StorageSemanticsImage |
  1825. gl_StorageSemanticsOutput))) {
  1826. error(loc, "Invalid storage class semantics value", fnCandidate.getName().c_str(), "");
  1827. }
  1828. if (callNode.getOp() == EOpMemoryBarrier) {
  1829. if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
  1830. error(loc, "Semantics must include exactly one of gl_SemanticsRelease, gl_SemanticsAcquire, or "
  1831. "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
  1832. }
  1833. } else {
  1834. if (semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
  1835. if (!IsPow2(semantics & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
  1836. error(loc, "Semantics must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
  1837. "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
  1838. }
  1839. }
  1840. if (semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease)) {
  1841. if (!IsPow2(semantics2 & (gl_SemanticsAcquire | gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
  1842. error(loc, "semUnequal must not include multiple of gl_SemanticsRelease, gl_SemanticsAcquire, or "
  1843. "gl_SemanticsAcquireRelease", fnCandidate.getName().c_str(), "");
  1844. }
  1845. }
  1846. }
  1847. if (callNode.getOp() == EOpMemoryBarrier) {
  1848. if (storageClassSemantics == 0) {
  1849. error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
  1850. }
  1851. }
  1852. if (callNode.getOp() == EOpBarrier && semantics != 0 && storageClassSemantics == 0) {
  1853. error(loc, "Storage class semantics must not be zero", fnCandidate.getName().c_str(), "");
  1854. }
  1855. if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
  1856. (semantics2 & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
  1857. error(loc, "semUnequal must not be gl_SemanticsRelease or gl_SemanticsAcquireRelease",
  1858. fnCandidate.getName().c_str(), "");
  1859. }
  1860. if ((semantics & gl_SemanticsMakeAvailable) &&
  1861. !(semantics & (gl_SemanticsRelease | gl_SemanticsAcquireRelease))) {
  1862. error(loc, "gl_SemanticsMakeAvailable requires gl_SemanticsRelease or gl_SemanticsAcquireRelease",
  1863. fnCandidate.getName().c_str(), "");
  1864. }
  1865. if ((semantics & gl_SemanticsMakeVisible) &&
  1866. !(semantics & (gl_SemanticsAcquire | gl_SemanticsAcquireRelease))) {
  1867. error(loc, "gl_SemanticsMakeVisible requires gl_SemanticsAcquire or gl_SemanticsAcquireRelease",
  1868. fnCandidate.getName().c_str(), "");
  1869. }
  1870. if ((semantics & gl_SemanticsVolatile) &&
  1871. (callNode.getOp() == EOpMemoryBarrier || callNode.getOp() == EOpBarrier)) {
  1872. error(loc, "gl_SemanticsVolatile must not be used with memoryBarrier or controlBarrier",
  1873. fnCandidate.getName().c_str(), "");
  1874. }
  1875. if ((callNode.getOp() == EOpAtomicCompSwap || callNode.getOp() == EOpImageAtomicCompSwap) &&
  1876. ((semantics ^ semantics2) & gl_SemanticsVolatile)) {
  1877. error(loc, "semEqual and semUnequal must either both include gl_SemanticsVolatile or neither",
  1878. fnCandidate.getName().c_str(), "");
  1879. }
  1880. }
  1881. //
  1882. // Do additional checking of built-in function calls that is not caught
  1883. // by normal semantic checks on argument type, extension tagging, etc.
  1884. //
  1885. // Assumes there has been a semantically correct match to a built-in function prototype.
  1886. //
  1887. void TParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
  1888. {
  1889. // Set up convenience accessors to the argument(s). There is almost always
  1890. // multiple arguments for the cases below, but when there might be one,
  1891. // check the unaryArg first.
  1892. const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
  1893. const TIntermTyped* unaryArg = nullptr;
  1894. const TIntermTyped* arg0 = nullptr;
  1895. if (callNode.getAsAggregate()) {
  1896. argp = &callNode.getAsAggregate()->getSequence();
  1897. if (argp->size() > 0)
  1898. arg0 = (*argp)[0]->getAsTyped();
  1899. } else {
  1900. assert(callNode.getAsUnaryNode());
  1901. unaryArg = callNode.getAsUnaryNode()->getOperand();
  1902. arg0 = unaryArg;
  1903. }
  1904. TString featureString;
  1905. const char* feature = nullptr;
  1906. switch (callNode.getOp()) {
  1907. #ifndef GLSLANG_WEB
  1908. case EOpTextureGather:
  1909. case EOpTextureGatherOffset:
  1910. case EOpTextureGatherOffsets:
  1911. {
  1912. // Figure out which variants are allowed by what extensions,
  1913. // and what arguments must be constant for which situations.
  1914. featureString = fnCandidate.getName();
  1915. featureString += "(...)";
  1916. feature = featureString.c_str();
  1917. profileRequires(loc, EEsProfile, 310, nullptr, feature);
  1918. int compArg = -1; // track which argument, if any, is the constant component argument
  1919. switch (callNode.getOp()) {
  1920. case EOpTextureGather:
  1921. // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
  1922. // otherwise, need GL_ARB_texture_gather.
  1923. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
  1924. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
  1925. if (! fnCandidate[0].type->getSampler().shadow)
  1926. compArg = 2;
  1927. } else
  1928. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
  1929. break;
  1930. case EOpTextureGatherOffset:
  1931. // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
  1932. if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
  1933. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
  1934. else
  1935. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
  1936. if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
  1937. profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
  1938. "non-constant offset argument");
  1939. if (! fnCandidate[0].type->getSampler().shadow)
  1940. compArg = 3;
  1941. break;
  1942. case EOpTextureGatherOffsets:
  1943. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
  1944. if (! fnCandidate[0].type->getSampler().shadow)
  1945. compArg = 3;
  1946. // check for constant offsets
  1947. if (! (*argp)[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion())
  1948. error(loc, "must be a compile-time constant:", feature, "offsets argument");
  1949. break;
  1950. default:
  1951. break;
  1952. }
  1953. if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
  1954. if ((*argp)[compArg]->getAsConstantUnion()) {
  1955. int value = (*argp)[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
  1956. if (value < 0 || value > 3)
  1957. error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
  1958. } else
  1959. error(loc, "must be a compile-time constant:", feature, "component argument");
  1960. }
  1961. bool bias = false;
  1962. if (callNode.getOp() == EOpTextureGather)
  1963. bias = fnCandidate.getParamCount() > 3;
  1964. else if (callNode.getOp() == EOpTextureGatherOffset ||
  1965. callNode.getOp() == EOpTextureGatherOffsets)
  1966. bias = fnCandidate.getParamCount() > 4;
  1967. if (bias) {
  1968. featureString = fnCandidate.getName();
  1969. featureString += "with bias argument";
  1970. feature = featureString.c_str();
  1971. profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
  1972. requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
  1973. }
  1974. break;
  1975. }
  1976. case EOpSparseTextureGather:
  1977. case EOpSparseTextureGatherOffset:
  1978. case EOpSparseTextureGatherOffsets:
  1979. {
  1980. bool bias = false;
  1981. if (callNode.getOp() == EOpSparseTextureGather)
  1982. bias = fnCandidate.getParamCount() > 4;
  1983. else if (callNode.getOp() == EOpSparseTextureGatherOffset ||
  1984. callNode.getOp() == EOpSparseTextureGatherOffsets)
  1985. bias = fnCandidate.getParamCount() > 5;
  1986. if (bias) {
  1987. featureString = fnCandidate.getName();
  1988. featureString += "with bias argument";
  1989. feature = featureString.c_str();
  1990. profileRequires(loc, ~EEsProfile, 450, nullptr, feature);
  1991. requireExtensions(loc, 1, &E_GL_AMD_texture_gather_bias_lod, feature);
  1992. }
  1993. // As per GL_ARB_sparse_texture2 extension "Offsets" parameter must be constant integral expression
  1994. // for sparseTextureGatherOffsetsARB just as textureGatherOffsets
  1995. if (callNode.getOp() == EOpSparseTextureGatherOffsets) {
  1996. int offsetsArg = arg0->getType().getSampler().shadow ? 3 : 2;
  1997. if (!(*argp)[offsetsArg]->getAsConstantUnion())
  1998. error(loc, "argument must be compile-time constant", "offsets", "");
  1999. }
  2000. break;
  2001. }
  2002. case EOpSparseTextureGatherLod:
  2003. case EOpSparseTextureGatherLodOffset:
  2004. case EOpSparseTextureGatherLodOffsets:
  2005. {
  2006. requireExtensions(loc, 1, &E_GL_ARB_sparse_texture2, fnCandidate.getName().c_str());
  2007. break;
  2008. }
  2009. case EOpSwizzleInvocations:
  2010. {
  2011. if (! (*argp)[1]->getAsConstantUnion())
  2012. error(loc, "argument must be compile-time constant", "offset", "");
  2013. else {
  2014. unsigned offset[4] = {};
  2015. offset[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
  2016. offset[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
  2017. offset[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
  2018. offset[3] = (*argp)[1]->getAsConstantUnion()->getConstArray()[3].getUConst();
  2019. if (offset[0] > 3 || offset[1] > 3 || offset[2] > 3 || offset[3] > 3)
  2020. error(loc, "components must be in the range [0, 3]", "offset", "");
  2021. }
  2022. break;
  2023. }
  2024. case EOpSwizzleInvocationsMasked:
  2025. {
  2026. if (! (*argp)[1]->getAsConstantUnion())
  2027. error(loc, "argument must be compile-time constant", "mask", "");
  2028. else {
  2029. unsigned mask[3] = {};
  2030. mask[0] = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
  2031. mask[1] = (*argp)[1]->getAsConstantUnion()->getConstArray()[1].getUConst();
  2032. mask[2] = (*argp)[1]->getAsConstantUnion()->getConstArray()[2].getUConst();
  2033. if (mask[0] > 31 || mask[1] > 31 || mask[2] > 31)
  2034. error(loc, "components must be in the range [0, 31]", "mask", "");
  2035. }
  2036. break;
  2037. }
  2038. #endif
  2039. case EOpTextureOffset:
  2040. case EOpTextureFetchOffset:
  2041. case EOpTextureProjOffset:
  2042. case EOpTextureLodOffset:
  2043. case EOpTextureProjLodOffset:
  2044. case EOpTextureGradOffset:
  2045. case EOpTextureProjGradOffset:
  2046. {
  2047. // Handle texture-offset limits checking
  2048. // Pick which argument has to hold constant offsets
  2049. int arg = -1;
  2050. switch (callNode.getOp()) {
  2051. case EOpTextureOffset: arg = 2; break;
  2052. case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().isRect()) ? 2 : 3; break;
  2053. case EOpTextureProjOffset: arg = 2; break;
  2054. case EOpTextureLodOffset: arg = 3; break;
  2055. case EOpTextureProjLodOffset: arg = 3; break;
  2056. case EOpTextureGradOffset: arg = 4; break;
  2057. case EOpTextureProjGradOffset: arg = 4; break;
  2058. default:
  2059. assert(0);
  2060. break;
  2061. }
  2062. if (arg > 0) {
  2063. #ifndef GLSLANG_WEB
  2064. bool f16ShadowCompare = (*argp)[1]->getAsTyped()->getBasicType() == EbtFloat16 &&
  2065. arg0->getType().getSampler().shadow;
  2066. if (f16ShadowCompare)
  2067. ++arg;
  2068. #endif
  2069. if (! (*argp)[arg]->getAsTyped()->getQualifier().isConstant())
  2070. error(loc, "argument must be compile-time constant", "texel offset", "");
  2071. else if ((*argp)[arg]->getAsConstantUnion()) {
  2072. const TType& type = (*argp)[arg]->getAsTyped()->getType();
  2073. for (int c = 0; c < type.getVectorSize(); ++c) {
  2074. int offset = (*argp)[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
  2075. if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
  2076. error(loc, "value is out of range:", "texel offset",
  2077. "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
  2078. }
  2079. }
  2080. if (callNode.getOp() == EOpTextureOffset) {
  2081. TSampler s = arg0->getType().getSampler();
  2082. if (s.is2D() && s.isArrayed() && s.isShadow()) {
  2083. if (isEsProfile())
  2084. error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "ES Profile");
  2085. else if (version <= 420)
  2086. error(loc, "TextureOffset does not support sampler2DArrayShadow : ", "sampler", "version <= 420");
  2087. }
  2088. }
  2089. }
  2090. break;
  2091. }
  2092. #ifndef GLSLANG_WEB
  2093. case EOpTraceNV:
  2094. if (!(*argp)[10]->getAsConstantUnion())
  2095. error(loc, "argument must be compile-time constant", "payload number", "a");
  2096. break;
  2097. case EOpTraceRayMotionNV:
  2098. if (!(*argp)[11]->getAsConstantUnion())
  2099. error(loc, "argument must be compile-time constant", "payload number", "a");
  2100. break;
  2101. case EOpTraceKHR:
  2102. if (!(*argp)[10]->getAsConstantUnion())
  2103. error(loc, "argument must be compile-time constant", "payload number", "a");
  2104. else {
  2105. unsigned int location = (*argp)[10]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
  2106. if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(0, location) < 0)
  2107. error(loc, "with layout(location =", "no rayPayloadEXT/rayPayloadInEXT declared", "%d)", location);
  2108. }
  2109. break;
  2110. case EOpExecuteCallableNV:
  2111. if (!(*argp)[1]->getAsConstantUnion())
  2112. error(loc, "argument must be compile-time constant", "callable data number", "");
  2113. break;
  2114. case EOpExecuteCallableKHR:
  2115. if (!(*argp)[1]->getAsConstantUnion())
  2116. error(loc, "argument must be compile-time constant", "callable data number", "");
  2117. else {
  2118. unsigned int location = (*argp)[1]->getAsConstantUnion()->getAsConstantUnion()->getConstArray()[0].getUConst();
  2119. if (!extensionTurnedOn(E_GL_EXT_spirv_intrinsics) && intermediate.checkLocationRT(1, location) < 0)
  2120. error(loc, "with layout(location =", "no callableDataEXT/callableDataInEXT declared", "%d)", location);
  2121. }
  2122. break;
  2123. case EOpRayQueryGetIntersectionType:
  2124. case EOpRayQueryGetIntersectionT:
  2125. case EOpRayQueryGetIntersectionInstanceCustomIndex:
  2126. case EOpRayQueryGetIntersectionInstanceId:
  2127. case EOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffset:
  2128. case EOpRayQueryGetIntersectionGeometryIndex:
  2129. case EOpRayQueryGetIntersectionPrimitiveIndex:
  2130. case EOpRayQueryGetIntersectionBarycentrics:
  2131. case EOpRayQueryGetIntersectionFrontFace:
  2132. case EOpRayQueryGetIntersectionObjectRayDirection:
  2133. case EOpRayQueryGetIntersectionObjectRayOrigin:
  2134. case EOpRayQueryGetIntersectionObjectToWorld:
  2135. case EOpRayQueryGetIntersectionWorldToObject:
  2136. if (!(*argp)[1]->getAsConstantUnion())
  2137. error(loc, "argument must be compile-time constant", "committed", "");
  2138. break;
  2139. case EOpTextureQuerySamples:
  2140. case EOpImageQuerySamples:
  2141. // GL_ARB_shader_texture_image_samples
  2142. profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
  2143. break;
  2144. case EOpImageAtomicAdd:
  2145. case EOpImageAtomicMin:
  2146. case EOpImageAtomicMax:
  2147. case EOpImageAtomicAnd:
  2148. case EOpImageAtomicOr:
  2149. case EOpImageAtomicXor:
  2150. case EOpImageAtomicExchange:
  2151. case EOpImageAtomicCompSwap:
  2152. case EOpImageAtomicLoad:
  2153. case EOpImageAtomicStore:
  2154. {
  2155. // Make sure the image types have the correct layout() format and correct argument types
  2156. const TType& imageType = arg0->getType();
  2157. if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint ||
  2158. imageType.getSampler().type == EbtInt64 || imageType.getSampler().type == EbtUint64) {
  2159. if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui &&
  2160. imageType.getQualifier().getFormat() != ElfR64i && imageType.getQualifier().getFormat() != ElfR64ui)
  2161. error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
  2162. if (callNode.getType().getBasicType() == EbtInt64 && imageType.getQualifier().getFormat() != ElfR64i)
  2163. error(loc, "only supported on image with format r64i", fnCandidate.getName().c_str(), "");
  2164. else if (callNode.getType().getBasicType() == EbtUint64 && imageType.getQualifier().getFormat() != ElfR64ui)
  2165. error(loc, "only supported on image with format r64ui", fnCandidate.getName().c_str(), "");
  2166. } else if (imageType.getSampler().type == EbtFloat) {
  2167. if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") == 0) {
  2168. // imageAtomicExchange doesn't require an extension
  2169. } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicAdd") == 0) ||
  2170. (fnCandidate.getName().compare(0, 15, "imageAtomicLoad") == 0) ||
  2171. (fnCandidate.getName().compare(0, 16, "imageAtomicStore") == 0)) {
  2172. requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
  2173. } else if ((fnCandidate.getName().compare(0, 14, "imageAtomicMin") == 0) ||
  2174. (fnCandidate.getName().compare(0, 14, "imageAtomicMax") == 0)) {
  2175. requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
  2176. } else {
  2177. error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
  2178. }
  2179. if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
  2180. error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
  2181. } else {
  2182. error(loc, "not supported on this image type", fnCandidate.getName().c_str(), "");
  2183. }
  2184. const size_t maxArgs = imageType.getSampler().isMultiSample() ? 5 : 4;
  2185. if (argp->size() > maxArgs) {
  2186. requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
  2187. memorySemanticsCheck(loc, fnCandidate, callNode);
  2188. }
  2189. break;
  2190. }
  2191. case EOpAtomicAdd:
  2192. case EOpAtomicSubtract:
  2193. case EOpAtomicMin:
  2194. case EOpAtomicMax:
  2195. case EOpAtomicAnd:
  2196. case EOpAtomicOr:
  2197. case EOpAtomicXor:
  2198. case EOpAtomicExchange:
  2199. case EOpAtomicCompSwap:
  2200. case EOpAtomicLoad:
  2201. case EOpAtomicStore:
  2202. {
  2203. if (argp->size() > 3) {
  2204. requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
  2205. memorySemanticsCheck(loc, fnCandidate, callNode);
  2206. if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
  2207. callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore) &&
  2208. (arg0->getType().getBasicType() == EbtFloat ||
  2209. arg0->getType().getBasicType() == EbtDouble)) {
  2210. requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
  2211. } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
  2212. callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
  2213. callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
  2214. arg0->getType().isFloatingDomain()) {
  2215. requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
  2216. }
  2217. } else if (arg0->getType().getBasicType() == EbtInt64 || arg0->getType().getBasicType() == EbtUint64) {
  2218. const char* const extensions[2] = { E_GL_NV_shader_atomic_int64,
  2219. E_GL_EXT_shader_atomic_int64 };
  2220. requireExtensions(loc, 2, extensions, fnCandidate.getName().c_str());
  2221. } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange) &&
  2222. (arg0->getType().getBasicType() == EbtFloat ||
  2223. arg0->getType().getBasicType() == EbtDouble)) {
  2224. requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float, fnCandidate.getName().c_str());
  2225. } else if ((callNode.getOp() == EOpAtomicAdd || callNode.getOp() == EOpAtomicExchange ||
  2226. callNode.getOp() == EOpAtomicLoad || callNode.getOp() == EOpAtomicStore ||
  2227. callNode.getOp() == EOpAtomicMin || callNode.getOp() == EOpAtomicMax) &&
  2228. arg0->getType().isFloatingDomain()) {
  2229. requireExtensions(loc, 1, &E_GL_EXT_shader_atomic_float2, fnCandidate.getName().c_str());
  2230. }
  2231. const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true , true);
  2232. const TType* refType = (base->getType().isReference()) ? base->getType().getReferentType() : nullptr;
  2233. const TQualifier& qualifier = (refType != nullptr) ? refType->getQualifier() : base->getType().getQualifier();
  2234. if (qualifier.storage != EvqShared && qualifier.storage != EvqBuffer && qualifier.storage != EvqtaskPayloadSharedEXT)
  2235. error(loc,"Atomic memory function can only be used for shader storage block member or shared variable.",
  2236. fnCandidate.getName().c_str(), "");
  2237. break;
  2238. }
  2239. case EOpInterpolateAtCentroid:
  2240. case EOpInterpolateAtSample:
  2241. case EOpInterpolateAtOffset:
  2242. case EOpInterpolateAtVertex:
  2243. // Make sure the first argument is an interpolant, or an array element of an interpolant
  2244. if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
  2245. // It might still be an array element.
  2246. //
  2247. // We could check more, but the semantics of the first argument are already met; the
  2248. // only way to turn an array into a float/vec* is array dereference and swizzle.
  2249. //
  2250. // ES and desktop 4.3 and earlier: swizzles may not be used
  2251. // desktop 4.4 and later: swizzles may be used
  2252. bool swizzleOkay = (!isEsProfile()) && (version >= 440);
  2253. const TIntermTyped* base = TIntermediate::findLValueBase(arg0, swizzleOkay);
  2254. if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
  2255. error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
  2256. }
  2257. if (callNode.getOp() == EOpInterpolateAtVertex) {
  2258. if (!arg0->getType().getQualifier().isExplicitInterpolation())
  2259. error(loc, "argument must be qualified as __explicitInterpAMD in", "interpolant", "");
  2260. else {
  2261. if (! (*argp)[1]->getAsConstantUnion())
  2262. error(loc, "argument must be compile-time constant", "vertex index", "");
  2263. else {
  2264. unsigned vertexIdx = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getUConst();
  2265. if (vertexIdx > 2)
  2266. error(loc, "must be in the range [0, 2]", "vertex index", "");
  2267. }
  2268. }
  2269. }
  2270. break;
  2271. case EOpEmitStreamVertex:
  2272. case EOpEndStreamPrimitive:
  2273. if (version == 150)
  2274. requireExtensions(loc, 1, &E_GL_ARB_gpu_shader5, "if the verison is 150 , the EmitStreamVertex and EndStreamPrimitive only support at extension GL_ARB_gpu_shader5");
  2275. intermediate.setMultiStream();
  2276. break;
  2277. case EOpSubgroupClusteredAdd:
  2278. case EOpSubgroupClusteredMul:
  2279. case EOpSubgroupClusteredMin:
  2280. case EOpSubgroupClusteredMax:
  2281. case EOpSubgroupClusteredAnd:
  2282. case EOpSubgroupClusteredOr:
  2283. case EOpSubgroupClusteredXor:
  2284. // The <clusterSize> as used in the subgroupClustered<op>() operations must be:
  2285. // - An integral constant expression.
  2286. // - At least 1.
  2287. // - A power of 2.
  2288. if ((*argp)[1]->getAsConstantUnion() == nullptr)
  2289. error(loc, "argument must be compile-time constant", "cluster size", "");
  2290. else {
  2291. int size = (*argp)[1]->getAsConstantUnion()->getConstArray()[0].getIConst();
  2292. if (size < 1)
  2293. error(loc, "argument must be at least 1", "cluster size", "");
  2294. else if (!IsPow2(size))
  2295. error(loc, "argument must be a power of 2", "cluster size", "");
  2296. }
  2297. break;
  2298. case EOpSubgroupBroadcast:
  2299. case EOpSubgroupQuadBroadcast:
  2300. if (spvVersion.spv < EShTargetSpv_1_5) {
  2301. // <id> must be an integral constant expression.
  2302. if ((*argp)[1]->getAsConstantUnion() == nullptr)
  2303. error(loc, "argument must be compile-time constant", "id", "");
  2304. }
  2305. break;
  2306. case EOpBarrier:
  2307. case EOpMemoryBarrier:
  2308. if (argp->size() > 0) {
  2309. requireExtensions(loc, 1, &E_GL_KHR_memory_scope_semantics, fnCandidate.getName().c_str());
  2310. memorySemanticsCheck(loc, fnCandidate, callNode);
  2311. }
  2312. break;
  2313. case EOpMix:
  2314. if (profile == EEsProfile && version < 310) {
  2315. // Look for specific signatures
  2316. if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
  2317. (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
  2318. (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
  2319. requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, "specific signature of builtin mix");
  2320. }
  2321. }
  2322. if (profile != EEsProfile && version < 450) {
  2323. if ((*argp)[0]->getAsTyped()->getBasicType() != EbtFloat &&
  2324. (*argp)[0]->getAsTyped()->getBasicType() != EbtDouble &&
  2325. (*argp)[1]->getAsTyped()->getBasicType() != EbtFloat &&
  2326. (*argp)[1]->getAsTyped()->getBasicType() != EbtDouble &&
  2327. (*argp)[2]->getAsTyped()->getBasicType() == EbtBool) {
  2328. requireExtensions(loc, 1, &E_GL_EXT_shader_integer_mix, fnCandidate.getName().c_str());
  2329. }
  2330. }
  2331. break;
  2332. #endif
  2333. default:
  2334. break;
  2335. }
  2336. // Texture operations on texture objects (aside from texelFetch on a
  2337. // textureBuffer) require EXT_samplerless_texture_functions.
  2338. switch (callNode.getOp()) {
  2339. case EOpTextureQuerySize:
  2340. case EOpTextureQueryLevels:
  2341. case EOpTextureQuerySamples:
  2342. case EOpTextureFetch:
  2343. case EOpTextureFetchOffset:
  2344. {
  2345. const TSampler& sampler = fnCandidate[0].type->getSampler();
  2346. const bool isTexture = sampler.isTexture() && !sampler.isCombined();
  2347. const bool isBuffer = sampler.isBuffer();
  2348. const bool isFetch = callNode.getOp() == EOpTextureFetch || callNode.getOp() == EOpTextureFetchOffset;
  2349. if (isTexture && (!isBuffer || !isFetch))
  2350. requireExtensions(loc, 1, &E_GL_EXT_samplerless_texture_functions, fnCandidate.getName().c_str());
  2351. break;
  2352. }
  2353. default:
  2354. break;
  2355. }
  2356. if (callNode.isSubgroup()) {
  2357. // these require SPIR-V 1.3
  2358. if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_3)
  2359. error(loc, "requires SPIR-V 1.3", "subgroup op", "");
  2360. // Check that if extended types are being used that the correct extensions are enabled.
  2361. if (arg0 != nullptr) {
  2362. const TType& type = arg0->getType();
  2363. bool enhanced = intermediate.getEnhancedMsgs();
  2364. switch (type.getBasicType()) {
  2365. default:
  2366. break;
  2367. case EbtInt8:
  2368. case EbtUint8:
  2369. requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int8, type.getCompleteString(enhanced).c_str());
  2370. break;
  2371. case EbtInt16:
  2372. case EbtUint16:
  2373. requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int16, type.getCompleteString(enhanced).c_str());
  2374. break;
  2375. case EbtInt64:
  2376. case EbtUint64:
  2377. requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_int64, type.getCompleteString(enhanced).c_str());
  2378. break;
  2379. case EbtFloat16:
  2380. requireExtensions(loc, 1, &E_GL_EXT_shader_subgroup_extended_types_float16, type.getCompleteString(enhanced).c_str());
  2381. break;
  2382. }
  2383. }
  2384. }
  2385. }
  2386. #ifndef GLSLANG_WEB
  2387. extern bool PureOperatorBuiltins;
  2388. // Deprecated! Use PureOperatorBuiltins == true instead, in which case this
  2389. // functionality is handled in builtInOpCheck() instead of here.
  2390. //
  2391. // Do additional checking of built-in function calls that were not mapped
  2392. // to built-in operations (e.g., texturing functions).
  2393. //
  2394. // Assumes there has been a semantically correct match to a built-in function.
  2395. //
  2396. void TParseContext::nonOpBuiltInCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
  2397. {
  2398. // Further maintenance of this function is deprecated, because the "correct"
  2399. // future-oriented design is to not have to do string compares on function names.
  2400. // If PureOperatorBuiltins == true, then all built-ins should be mapped
  2401. // to a TOperator, and this function would then never get called.
  2402. assert(PureOperatorBuiltins == false);
  2403. // built-in texturing functions get their return value precision from the precision of the sampler
  2404. if (fnCandidate.getType().getQualifier().precision == EpqNone &&
  2405. fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
  2406. callNode.getQualifier().precision = callNode.getSequence()[0]->getAsTyped()->getQualifier().precision;
  2407. if (fnCandidate.getName().compare(0, 7, "texture") == 0) {
  2408. if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) {
  2409. TString featureString = fnCandidate.getName() + "(...)";
  2410. const char* feature = featureString.c_str();
  2411. profileRequires(loc, EEsProfile, 310, nullptr, feature);
  2412. int compArg = -1; // track which argument, if any, is the constant component argument
  2413. if (fnCandidate.getName().compare("textureGatherOffset") == 0) {
  2414. // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
  2415. if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
  2416. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
  2417. else
  2418. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
  2419. int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
  2420. if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
  2421. profileRequires(loc, EEsProfile, 320, Num_AEP_gpu_shader5, AEP_gpu_shader5,
  2422. "non-constant offset argument");
  2423. if (! fnCandidate[0].type->getSampler().shadow)
  2424. compArg = 3;
  2425. } else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) {
  2426. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
  2427. if (! fnCandidate[0].type->getSampler().shadow)
  2428. compArg = 3;
  2429. // check for constant offsets
  2430. int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
  2431. if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
  2432. error(loc, "must be a compile-time constant:", feature, "offsets argument");
  2433. } else if (fnCandidate.getName().compare("textureGather") == 0) {
  2434. // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
  2435. // otherwise, need GL_ARB_texture_gather.
  2436. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
  2437. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature);
  2438. if (! fnCandidate[0].type->getSampler().shadow)
  2439. compArg = 2;
  2440. } else
  2441. profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature);
  2442. }
  2443. if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
  2444. if (callNode.getSequence()[compArg]->getAsConstantUnion()) {
  2445. int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
  2446. if (value < 0 || value > 3)
  2447. error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
  2448. } else
  2449. error(loc, "must be a compile-time constant:", feature, "component argument");
  2450. }
  2451. } else {
  2452. // this is only for functions not starting "textureGather"...
  2453. if (fnCandidate.getName().find("Offset") != TString::npos) {
  2454. // Handle texture-offset limits checking
  2455. int arg = -1;
  2456. if (fnCandidate.getName().compare("textureOffset") == 0)
  2457. arg = 2;
  2458. else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
  2459. arg = 3;
  2460. else if (fnCandidate.getName().compare("textureProjOffset") == 0)
  2461. arg = 2;
  2462. else if (fnCandidate.getName().compare("textureLodOffset") == 0)
  2463. arg = 3;
  2464. else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
  2465. arg = 3;
  2466. else if (fnCandidate.getName().compare("textureGradOffset") == 0)
  2467. arg = 4;
  2468. else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
  2469. arg = 4;
  2470. if (arg > 0) {
  2471. if (! callNode.getSequence()[arg]->getAsConstantUnion())
  2472. error(loc, "argument must be compile-time constant", "texel offset", "");
  2473. else {
  2474. const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType();
  2475. for (int c = 0; c < type.getVectorSize(); ++c) {
  2476. int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
  2477. if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
  2478. error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
  2479. }
  2480. }
  2481. }
  2482. }
  2483. }
  2484. }
  2485. // GL_ARB_shader_texture_image_samples
  2486. if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0)
  2487. profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
  2488. if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) {
  2489. const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType();
  2490. if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
  2491. if (imageType.getQualifier().getFormat() != ElfR32i && imageType.getQualifier().getFormat() != ElfR32ui)
  2492. error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
  2493. } else {
  2494. if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0)
  2495. error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
  2496. else if (imageType.getQualifier().getFormat() != ElfR32f && isEsProfile())
  2497. error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), "");
  2498. }
  2499. }
  2500. }
  2501. #endif
  2502. //
  2503. // Do any extra checking for a user function call.
  2504. //
  2505. void TParseContext::userFunctionCallCheck(const TSourceLoc& loc, TIntermAggregate& callNode)
  2506. {
  2507. TIntermSequence& arguments = callNode.getSequence();
  2508. for (int i = 0; i < (int)arguments.size(); ++i)
  2509. samplerConstructorLocationCheck(loc, "call argument", arguments[i]);
  2510. }
  2511. //
  2512. // Emit an error if this is a sampler constructor
  2513. //
  2514. void TParseContext::samplerConstructorLocationCheck(const TSourceLoc& loc, const char* token, TIntermNode* node)
  2515. {
  2516. if (node->getAsOperator() && node->getAsOperator()->getOp() == EOpConstructTextureSampler)
  2517. error(loc, "sampler constructor must appear at point of use", token, "");
  2518. }
  2519. //
  2520. // Handle seeing a built-in constructor in a grammar production.
  2521. //
  2522. TFunction* TParseContext::handleConstructorCall(const TSourceLoc& loc, const TPublicType& publicType)
  2523. {
  2524. TType type(publicType);
  2525. type.getQualifier().precision = EpqNone;
  2526. if (type.isArray()) {
  2527. profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed constructor");
  2528. profileRequires(loc, EEsProfile, 300, nullptr, "arrayed constructor");
  2529. }
  2530. TOperator op = intermediate.mapTypeToConstructorOp(type);
  2531. if (op == EOpNull) {
  2532. if (intermediate.getEnhancedMsgs() && type.getBasicType() == EbtSampler)
  2533. error(loc, "function not supported in this version; use texture() instead", "texture*D*", "");
  2534. else
  2535. error(loc, "cannot construct this type", type.getBasicString(), "");
  2536. op = EOpConstructFloat;
  2537. TType errorType(EbtFloat);
  2538. type.shallowCopy(errorType);
  2539. }
  2540. TString empty("");
  2541. return new TFunction(&empty, type, op);
  2542. }
  2543. // Handle seeing a precision qualifier in the grammar.
  2544. void TParseContext::handlePrecisionQualifier(const TSourceLoc& /*loc*/, TQualifier& qualifier, TPrecisionQualifier precision)
  2545. {
  2546. if (obeyPrecisionQualifiers())
  2547. qualifier.precision = precision;
  2548. }
  2549. // Check for messages to give on seeing a precision qualifier used in a
  2550. // declaration in the grammar.
  2551. void TParseContext::checkPrecisionQualifier(const TSourceLoc& loc, TPrecisionQualifier)
  2552. {
  2553. if (precisionManager.shouldWarnAboutDefaults()) {
  2554. warn(loc, "all default precisions are highp; use precision statements to quiet warning, e.g.:\n"
  2555. " \"precision mediump int; precision highp float;\"", "", "");
  2556. precisionManager.defaultWarningGiven();
  2557. }
  2558. }
  2559. //
  2560. // Same error message for all places assignments don't work.
  2561. //
  2562. void TParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
  2563. {
  2564. error(loc, "", op, "cannot convert from '%s' to '%s'",
  2565. right.c_str(), left.c_str());
  2566. }
  2567. //
  2568. // Same error message for all places unary operations don't work.
  2569. //
  2570. void TParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
  2571. {
  2572. error(loc, " wrong operand type", op,
  2573. "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
  2574. op, operand.c_str());
  2575. }
  2576. //
  2577. // Same error message for all binary operations don't work.
  2578. //
  2579. void TParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
  2580. {
  2581. error(loc, " wrong operand types:", op,
  2582. "no operation '%s' exists that takes a left-hand operand of type '%s' and "
  2583. "a right operand of type '%s' (or there is no acceptable conversion)",
  2584. op, left.c_str(), right.c_str());
  2585. }
  2586. //
  2587. // A basic type of EbtVoid is a key that the name string was seen in the source, but
  2588. // it was not found as a variable in the symbol table. If so, give the error
  2589. // message and insert a dummy variable in the symbol table to prevent future errors.
  2590. //
  2591. void TParseContext::variableCheck(TIntermTyped*& nodePtr)
  2592. {
  2593. TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
  2594. if (! symbol)
  2595. return;
  2596. if (symbol->getType().getBasicType() == EbtVoid) {
  2597. const char *extraInfoFormat = "";
  2598. if (spvVersion.vulkan != 0 && symbol->getName() == "gl_VertexID") {
  2599. extraInfoFormat = "(Did you mean gl_VertexIndex?)";
  2600. } else if (spvVersion.vulkan != 0 && symbol->getName() == "gl_InstanceID") {
  2601. extraInfoFormat = "(Did you mean gl_InstanceIndex?)";
  2602. }
  2603. error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), extraInfoFormat);
  2604. // Add to symbol table to prevent future error messages on the same name
  2605. if (symbol->getName().size() > 0) {
  2606. TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
  2607. symbolTable.insert(*fakeVariable);
  2608. // substitute a symbol node for this new variable
  2609. nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
  2610. }
  2611. } else {
  2612. switch (symbol->getQualifier().storage) {
  2613. case EvqPointCoord:
  2614. profileRequires(symbol->getLoc(), ENoProfile, 120, nullptr, "gl_PointCoord");
  2615. break;
  2616. default: break; // some compilers want this
  2617. }
  2618. }
  2619. }
  2620. //
  2621. // Both test and if necessary, spit out an error, to see if the node is really
  2622. // an l-value that can be operated on this way.
  2623. //
  2624. // Returns true if there was an error.
  2625. //
  2626. bool TParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
  2627. {
  2628. TIntermBinary* binaryNode = node->getAsBinaryNode();
  2629. if (binaryNode) {
  2630. bool errorReturn = false;
  2631. switch(binaryNode->getOp()) {
  2632. #ifndef GLSLANG_WEB
  2633. case EOpIndexDirect:
  2634. case EOpIndexIndirect:
  2635. // ... tessellation control shader ...
  2636. // If a per-vertex output variable is used as an l-value, it is a
  2637. // compile-time or link-time error if the expression indicating the
  2638. // vertex index is not the identifier gl_InvocationID.
  2639. if (language == EShLangTessControl) {
  2640. const TType& leftType = binaryNode->getLeft()->getType();
  2641. if (leftType.getQualifier().storage == EvqVaryingOut && ! leftType.getQualifier().patch && binaryNode->getLeft()->getAsSymbolNode()) {
  2642. // we have a per-vertex output
  2643. const TIntermSymbol* rightSymbol = binaryNode->getRight()->getAsSymbolNode();
  2644. if (! rightSymbol || rightSymbol->getQualifier().builtIn != EbvInvocationId)
  2645. error(loc, "tessellation-control per-vertex output l-value must be indexed with gl_InvocationID", "[]", "");
  2646. }
  2647. }
  2648. break; // left node is checked by base class
  2649. #endif
  2650. case EOpVectorSwizzle:
  2651. errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft());
  2652. if (!errorReturn) {
  2653. int offset[4] = {0,0,0,0};
  2654. TIntermTyped* rightNode = binaryNode->getRight();
  2655. TIntermAggregate *aggrNode = rightNode->getAsAggregate();
  2656. for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
  2657. p != aggrNode->getSequence().end(); p++) {
  2658. int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
  2659. offset[value]++;
  2660. if (offset[value] > 1) {
  2661. error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
  2662. return true;
  2663. }
  2664. }
  2665. }
  2666. return errorReturn;
  2667. default:
  2668. break;
  2669. }
  2670. if (errorReturn) {
  2671. error(loc, " l-value required", op, "", "");
  2672. return true;
  2673. }
  2674. }
  2675. if (binaryNode && binaryNode->getOp() == EOpIndexDirectStruct && binaryNode->getLeft()->isReference())
  2676. return false;
  2677. // Let the base class check errors
  2678. if (TParseContextBase::lValueErrorCheck(loc, op, node))
  2679. return true;
  2680. const char* symbol = nullptr;
  2681. TIntermSymbol* symNode = node->getAsSymbolNode();
  2682. if (symNode != nullptr)
  2683. symbol = symNode->getName().c_str();
  2684. const char* message = nullptr;
  2685. switch (node->getQualifier().storage) {
  2686. case EvqVaryingIn: message = "can't modify shader input"; break;
  2687. case EvqInstanceId: message = "can't modify gl_InstanceID"; break;
  2688. case EvqVertexId: message = "can't modify gl_VertexID"; break;
  2689. case EvqFace: message = "can't modify gl_FrontFace"; break;
  2690. case EvqFragCoord: message = "can't modify gl_FragCoord"; break;
  2691. case EvqPointCoord: message = "can't modify gl_PointCoord"; break;
  2692. case EvqFragDepth:
  2693. intermediate.setDepthReplacing();
  2694. // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
  2695. if (isEsProfile() && intermediate.getEarlyFragmentTests())
  2696. message = "can't modify gl_FragDepth if using early_fragment_tests";
  2697. break;
  2698. case EvqFragStencil:
  2699. intermediate.setStencilReplacing();
  2700. // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
  2701. if (isEsProfile() && intermediate.getEarlyFragmentTests())
  2702. message = "can't modify EvqFragStencil if using early_fragment_tests";
  2703. break;
  2704. case EvqtaskPayloadSharedEXT:
  2705. if (language == EShLangMesh)
  2706. message = "can't modify variable with storage qualifier taskPayloadSharedEXT in mesh shaders";
  2707. break;
  2708. default:
  2709. break;
  2710. }
  2711. if (message == nullptr && binaryNode == nullptr && symNode == nullptr) {
  2712. error(loc, " l-value required", op, "", "");
  2713. return true;
  2714. }
  2715. //
  2716. // Everything else is okay, no error.
  2717. //
  2718. if (message == nullptr)
  2719. return false;
  2720. //
  2721. // If we get here, we have an error and a message.
  2722. //
  2723. if (symNode)
  2724. error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
  2725. else
  2726. error(loc, " l-value required", op, "(%s)", message);
  2727. return true;
  2728. }
  2729. // Test for and give an error if the node can't be read from.
  2730. void TParseContext::rValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
  2731. {
  2732. // Let the base class check errors
  2733. TParseContextBase::rValueErrorCheck(loc, op, node);
  2734. TIntermSymbol* symNode = node->getAsSymbolNode();
  2735. if (!(symNode && symNode->getQualifier().isWriteOnly())) // base class checks
  2736. if (symNode && symNode->getQualifier().isExplicitInterpolation())
  2737. error(loc, "can't read from explicitly-interpolated object: ", op, symNode->getName().c_str());
  2738. // local_size_{xyz} must be assigned or specialized before gl_WorkGroupSize can be assigned.
  2739. if(node->getQualifier().builtIn == EbvWorkGroupSize &&
  2740. !(intermediate.isLocalSizeSet() || intermediate.isLocalSizeSpecialized()))
  2741. error(loc, "can't read from gl_WorkGroupSize before a fixed workgroup size has been declared", op, "");
  2742. }
  2743. //
  2744. // Both test, and if necessary spit out an error, to see if the node is really
  2745. // a constant.
  2746. //
  2747. void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
  2748. {
  2749. if (! node->getQualifier().isConstant())
  2750. error(node->getLoc(), "constant expression required", token, "");
  2751. }
  2752. //
  2753. // Both test, and if necessary spit out an error, to see if the node is really
  2754. // a 32-bit integer or can implicitly convert to one.
  2755. //
  2756. void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
  2757. {
  2758. auto from_type = node->getBasicType();
  2759. if ((from_type == EbtInt || from_type == EbtUint ||
  2760. intermediate.canImplicitlyPromote(from_type, EbtInt, EOpNull) ||
  2761. intermediate.canImplicitlyPromote(from_type, EbtUint, EOpNull)) && node->isScalar())
  2762. return;
  2763. error(node->getLoc(), "scalar integer expression required", token, "");
  2764. }
  2765. //
  2766. // Both test, and if necessary spit out an error, to see if we are currently
  2767. // globally scoped.
  2768. //
  2769. void TParseContext::globalCheck(const TSourceLoc& loc, const char* token)
  2770. {
  2771. if (! symbolTable.atGlobalLevel())
  2772. error(loc, "not allowed in nested scope", token, "");
  2773. }
  2774. //
  2775. // Reserved errors for GLSL.
  2776. //
  2777. void TParseContext::reservedErrorCheck(const TSourceLoc& loc, const TString& identifier)
  2778. {
  2779. // "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be
  2780. // declared in a shader; this results in a compile-time error."
  2781. if (! symbolTable.atBuiltInLevel()) {
  2782. if (builtInName(identifier) && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
  2783. // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "gl_".
  2784. error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), "");
  2785. // "__" are not supposed to be an error. ES 300 (and desktop) added the clarification:
  2786. // "In addition, all identifiers containing two consecutive underscores (__) are
  2787. // reserved; using such a name does not itself result in an error, but may result
  2788. // in undefined behavior."
  2789. // however, before that, ES tests required an error.
  2790. if (identifier.find("__") != TString::npos && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
  2791. // The extension GL_EXT_spirv_intrinsics allows us to declare identifiers starting with "__".
  2792. if (isEsProfile() && version < 300)
  2793. error(loc, "identifiers containing consecutive underscores (\"__\") are reserved, and an error if version < 300", identifier.c_str(), "");
  2794. else
  2795. warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), "");
  2796. }
  2797. }
  2798. }
  2799. //
  2800. // Reserved errors for the preprocessor.
  2801. //
  2802. void TParseContext::reservedPpErrorCheck(const TSourceLoc& loc, const char* identifier, const char* op)
  2803. {
  2804. // "__" are not supposed to be an error. ES 300 (and desktop) added the clarification:
  2805. // "All macro names containing two consecutive underscores ( __ ) are reserved;
  2806. // defining such a name does not itself result in an error, but may result in
  2807. // undefined behavior. All macro names prefixed with "GL_" ("GL" followed by a
  2808. // single underscore) are also reserved, and defining such a name results in a
  2809. // compile-time error."
  2810. // however, before that, ES tests required an error.
  2811. if (strncmp(identifier, "GL_", 3) == 0 && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
  2812. // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "GL_".
  2813. ppError(loc, "names beginning with \"GL_\" can't be (un)defined:", op, identifier);
  2814. else if (strncmp(identifier, "defined", 8) == 0)
  2815. if (relaxedErrors())
  2816. ppWarn(loc, "\"defined\" is (un)defined:", op, identifier);
  2817. else
  2818. ppError(loc, "\"defined\" can't be (un)defined:", op, identifier);
  2819. else if (strstr(identifier, "__") != nullptr && !extensionTurnedOn(E_GL_EXT_spirv_intrinsics)) {
  2820. // The extension GL_EXT_spirv_intrinsics allows us to declare macros prefixed with "__".
  2821. if (isEsProfile() && version >= 300 &&
  2822. (strcmp(identifier, "__LINE__") == 0 ||
  2823. strcmp(identifier, "__FILE__") == 0 ||
  2824. strcmp(identifier, "__VERSION__") == 0))
  2825. ppError(loc, "predefined names can't be (un)defined:", op, identifier);
  2826. else {
  2827. if (isEsProfile() && version < 300 && !relaxedErrors())
  2828. ppError(loc, "names containing consecutive underscores are reserved, and an error if version < 300:", op, identifier);
  2829. else
  2830. ppWarn(loc, "names containing consecutive underscores are reserved:", op, identifier);
  2831. }
  2832. }
  2833. }
  2834. //
  2835. // See if this version/profile allows use of the line-continuation character '\'.
  2836. //
  2837. // Returns true if a line continuation should be done.
  2838. //
  2839. bool TParseContext::lineContinuationCheck(const TSourceLoc& loc, bool endOfComment)
  2840. {
  2841. #ifdef GLSLANG_WEB
  2842. return true;
  2843. #endif
  2844. const char* message = "line continuation";
  2845. bool lineContinuationAllowed = (isEsProfile() && version >= 300) ||
  2846. (!isEsProfile() && (version >= 420 || extensionTurnedOn(E_GL_ARB_shading_language_420pack)));
  2847. if (endOfComment) {
  2848. if (lineContinuationAllowed)
  2849. warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
  2850. else
  2851. warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
  2852. return lineContinuationAllowed;
  2853. }
  2854. if (relaxedErrors()) {
  2855. if (! lineContinuationAllowed)
  2856. warn(loc, "not allowed in this version", message, "");
  2857. return true;
  2858. } else {
  2859. profileRequires(loc, EEsProfile, 300, nullptr, message);
  2860. profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, message);
  2861. }
  2862. return lineContinuationAllowed;
  2863. }
  2864. bool TParseContext::builtInName(const TString& identifier)
  2865. {
  2866. return identifier.compare(0, 3, "gl_") == 0;
  2867. }
  2868. //
  2869. // Make sure there is enough data and not too many arguments provided to the
  2870. // constructor to build something of the type of the constructor. Also returns
  2871. // the type of the constructor.
  2872. //
  2873. // Part of establishing type is establishing specialization-constness.
  2874. // We don't yet know "top down" whether type is a specialization constant,
  2875. // but a const constructor can becomes a specialization constant if any of
  2876. // its children are, subject to KHR_vulkan_glsl rules:
  2877. //
  2878. // - int(), uint(), and bool() constructors for type conversions
  2879. // from any of the following types to any of the following types:
  2880. // * int
  2881. // * uint
  2882. // * bool
  2883. // - vector versions of the above conversion constructors
  2884. //
  2885. // Returns true if there was an error in construction.
  2886. //
  2887. bool TParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
  2888. {
  2889. // See if the constructor does not establish the main type, only requalifies
  2890. // it, in which case the type comes from the argument instead of from the
  2891. // constructor function.
  2892. switch (op) {
  2893. #ifndef GLSLANG_WEB
  2894. case EOpConstructNonuniform:
  2895. if (node != nullptr && node->getAsTyped() != nullptr) {
  2896. type.shallowCopy(node->getAsTyped()->getType());
  2897. type.getQualifier().makeTemporary();
  2898. type.getQualifier().nonUniform = true;
  2899. }
  2900. break;
  2901. #endif
  2902. default:
  2903. type.shallowCopy(function.getType());
  2904. break;
  2905. }
  2906. TString constructorString;
  2907. if (intermediate.getEnhancedMsgs())
  2908. constructorString.append(type.getCompleteString(true, false, false, true)).append(" constructor");
  2909. else
  2910. constructorString.append("constructor");
  2911. // See if it's a matrix
  2912. bool constructingMatrix = false;
  2913. switch (op) {
  2914. case EOpConstructTextureSampler:
  2915. return constructorTextureSamplerError(loc, function);
  2916. case EOpConstructMat2x2:
  2917. case EOpConstructMat2x3:
  2918. case EOpConstructMat2x4:
  2919. case EOpConstructMat3x2:
  2920. case EOpConstructMat3x3:
  2921. case EOpConstructMat3x4:
  2922. case EOpConstructMat4x2:
  2923. case EOpConstructMat4x3:
  2924. case EOpConstructMat4x4:
  2925. #ifndef GLSLANG_WEB
  2926. case EOpConstructDMat2x2:
  2927. case EOpConstructDMat2x3:
  2928. case EOpConstructDMat2x4:
  2929. case EOpConstructDMat3x2:
  2930. case EOpConstructDMat3x3:
  2931. case EOpConstructDMat3x4:
  2932. case EOpConstructDMat4x2:
  2933. case EOpConstructDMat4x3:
  2934. case EOpConstructDMat4x4:
  2935. case EOpConstructF16Mat2x2:
  2936. case EOpConstructF16Mat2x3:
  2937. case EOpConstructF16Mat2x4:
  2938. case EOpConstructF16Mat3x2:
  2939. case EOpConstructF16Mat3x3:
  2940. case EOpConstructF16Mat3x4:
  2941. case EOpConstructF16Mat4x2:
  2942. case EOpConstructF16Mat4x3:
  2943. case EOpConstructF16Mat4x4:
  2944. #endif
  2945. constructingMatrix = true;
  2946. break;
  2947. default:
  2948. break;
  2949. }
  2950. //
  2951. // Walk the arguments for first-pass checks and collection of information.
  2952. //
  2953. int size = 0;
  2954. bool constType = true;
  2955. bool specConstType = false; // value is only valid if constType is true
  2956. bool full = false;
  2957. bool overFull = false;
  2958. bool matrixInMatrix = false;
  2959. bool arrayArg = false;
  2960. bool floatArgument = false;
  2961. bool intArgument = false;
  2962. for (int arg = 0; arg < function.getParamCount(); ++arg) {
  2963. if (function[arg].type->isArray()) {
  2964. if (function[arg].type->isUnsizedArray()) {
  2965. // Can't construct from an unsized array.
  2966. error(loc, "array argument must be sized", constructorString.c_str(), "");
  2967. return true;
  2968. }
  2969. arrayArg = true;
  2970. }
  2971. if (constructingMatrix && function[arg].type->isMatrix())
  2972. matrixInMatrix = true;
  2973. // 'full' will go to true when enough args have been seen. If we loop
  2974. // again, there is an extra argument.
  2975. if (full) {
  2976. // For vectors and matrices, it's okay to have too many components
  2977. // available, but not okay to have unused arguments.
  2978. overFull = true;
  2979. }
  2980. size += function[arg].type->computeNumComponents();
  2981. if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
  2982. full = true;
  2983. if (! function[arg].type->getQualifier().isConstant())
  2984. constType = false;
  2985. if (function[arg].type->getQualifier().isSpecConstant())
  2986. specConstType = true;
  2987. if (function[arg].type->isFloatingDomain())
  2988. floatArgument = true;
  2989. if (function[arg].type->isIntegerDomain())
  2990. intArgument = true;
  2991. if (type.isStruct()) {
  2992. if (function[arg].type->contains16BitFloat()) {
  2993. requireFloat16Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 16-bit type");
  2994. }
  2995. if (function[arg].type->contains16BitInt()) {
  2996. requireInt16Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 16-bit type");
  2997. }
  2998. if (function[arg].type->contains8BitInt()) {
  2999. requireInt8Arithmetic(loc, constructorString.c_str(), "can't construct structure containing 8-bit type");
  3000. }
  3001. }
  3002. }
  3003. if (op == EOpConstructNonuniform)
  3004. constType = false;
  3005. #ifndef GLSLANG_WEB
  3006. switch (op) {
  3007. case EOpConstructFloat16:
  3008. case EOpConstructF16Vec2:
  3009. case EOpConstructF16Vec3:
  3010. case EOpConstructF16Vec4:
  3011. if (type.isArray())
  3012. requireFloat16Arithmetic(loc, constructorString.c_str(), "16-bit arrays not supported");
  3013. if (type.isVector() && function.getParamCount() != 1)
  3014. requireFloat16Arithmetic(loc, constructorString.c_str(), "16-bit vectors only take vector types");
  3015. break;
  3016. case EOpConstructUint16:
  3017. case EOpConstructU16Vec2:
  3018. case EOpConstructU16Vec3:
  3019. case EOpConstructU16Vec4:
  3020. case EOpConstructInt16:
  3021. case EOpConstructI16Vec2:
  3022. case EOpConstructI16Vec3:
  3023. case EOpConstructI16Vec4:
  3024. if (type.isArray())
  3025. requireInt16Arithmetic(loc, constructorString.c_str(), "16-bit arrays not supported");
  3026. if (type.isVector() && function.getParamCount() != 1)
  3027. requireInt16Arithmetic(loc, constructorString.c_str(), "16-bit vectors only take vector types");
  3028. break;
  3029. case EOpConstructUint8:
  3030. case EOpConstructU8Vec2:
  3031. case EOpConstructU8Vec3:
  3032. case EOpConstructU8Vec4:
  3033. case EOpConstructInt8:
  3034. case EOpConstructI8Vec2:
  3035. case EOpConstructI8Vec3:
  3036. case EOpConstructI8Vec4:
  3037. if (type.isArray())
  3038. requireInt8Arithmetic(loc, constructorString.c_str(), "8-bit arrays not supported");
  3039. if (type.isVector() && function.getParamCount() != 1)
  3040. requireInt8Arithmetic(loc, constructorString.c_str(), "8-bit vectors only take vector types");
  3041. break;
  3042. default:
  3043. break;
  3044. }
  3045. #endif
  3046. // inherit constness from children
  3047. if (constType) {
  3048. bool makeSpecConst;
  3049. // Finish pinning down spec-const semantics
  3050. if (specConstType) {
  3051. switch (op) {
  3052. case EOpConstructInt8:
  3053. case EOpConstructInt:
  3054. case EOpConstructUint:
  3055. case EOpConstructBool:
  3056. case EOpConstructBVec2:
  3057. case EOpConstructBVec3:
  3058. case EOpConstructBVec4:
  3059. case EOpConstructIVec2:
  3060. case EOpConstructIVec3:
  3061. case EOpConstructIVec4:
  3062. case EOpConstructUVec2:
  3063. case EOpConstructUVec3:
  3064. case EOpConstructUVec4:
  3065. #ifndef GLSLANG_WEB
  3066. case EOpConstructUint8:
  3067. case EOpConstructInt16:
  3068. case EOpConstructUint16:
  3069. case EOpConstructInt64:
  3070. case EOpConstructUint64:
  3071. case EOpConstructI8Vec2:
  3072. case EOpConstructI8Vec3:
  3073. case EOpConstructI8Vec4:
  3074. case EOpConstructU8Vec2:
  3075. case EOpConstructU8Vec3:
  3076. case EOpConstructU8Vec4:
  3077. case EOpConstructI16Vec2:
  3078. case EOpConstructI16Vec3:
  3079. case EOpConstructI16Vec4:
  3080. case EOpConstructU16Vec2:
  3081. case EOpConstructU16Vec3:
  3082. case EOpConstructU16Vec4:
  3083. case EOpConstructI64Vec2:
  3084. case EOpConstructI64Vec3:
  3085. case EOpConstructI64Vec4:
  3086. case EOpConstructU64Vec2:
  3087. case EOpConstructU64Vec3:
  3088. case EOpConstructU64Vec4:
  3089. #endif
  3090. // This was the list of valid ones, if they aren't converting from float
  3091. // and aren't making an array.
  3092. makeSpecConst = ! floatArgument && ! type.isArray();
  3093. break;
  3094. case EOpConstructVec2:
  3095. case EOpConstructVec3:
  3096. case EOpConstructVec4:
  3097. // This was the list of valid ones, if they aren't converting from int
  3098. // and aren't making an array.
  3099. makeSpecConst = ! intArgument && !type.isArray();
  3100. break;
  3101. default:
  3102. // anything else wasn't white-listed in the spec as a conversion
  3103. makeSpecConst = false;
  3104. break;
  3105. }
  3106. } else
  3107. makeSpecConst = false;
  3108. if (makeSpecConst)
  3109. type.getQualifier().makeSpecConstant();
  3110. else if (specConstType)
  3111. type.getQualifier().makeTemporary();
  3112. else
  3113. type.getQualifier().storage = EvqConst;
  3114. }
  3115. if (type.isArray()) {
  3116. if (function.getParamCount() == 0) {
  3117. error(loc, "array constructor must have at least one argument", constructorString.c_str(), "");
  3118. return true;
  3119. }
  3120. if (type.isUnsizedArray()) {
  3121. // auto adapt the constructor type to the number of arguments
  3122. type.changeOuterArraySize(function.getParamCount());
  3123. } else if (type.getOuterArraySize() != function.getParamCount()) {
  3124. error(loc, "array constructor needs one argument per array element", constructorString.c_str(), "");
  3125. return true;
  3126. }
  3127. if (type.isArrayOfArrays()) {
  3128. // Types have to match, but we're still making the type.
  3129. // Finish making the type, and the comparison is done later
  3130. // when checking for conversion.
  3131. TArraySizes& arraySizes = *type.getArraySizes();
  3132. // At least the dimensionalities have to match.
  3133. if (! function[0].type->isArray() ||
  3134. arraySizes.getNumDims() != function[0].type->getArraySizes()->getNumDims() + 1) {
  3135. error(loc, "array constructor argument not correct type to construct array element", constructorString.c_str(), "");
  3136. return true;
  3137. }
  3138. if (arraySizes.isInnerUnsized()) {
  3139. // "Arrays of arrays ..., and the size for any dimension is optional"
  3140. // That means we need to adopt (from the first argument) the other array sizes into the type.
  3141. for (int d = 1; d < arraySizes.getNumDims(); ++d) {
  3142. if (arraySizes.getDimSize(d) == UnsizedArraySize) {
  3143. arraySizes.setDimSize(d, function[0].type->getArraySizes()->getDimSize(d - 1));
  3144. }
  3145. }
  3146. }
  3147. }
  3148. }
  3149. if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
  3150. error(loc, "constructing non-array constituent from array argument", constructorString.c_str(), "");
  3151. return true;
  3152. }
  3153. if (matrixInMatrix && ! type.isArray()) {
  3154. profileRequires(loc, ENoProfile, 120, nullptr, "constructing matrix from matrix");
  3155. // "If a matrix argument is given to a matrix constructor,
  3156. // it is a compile-time error to have any other arguments."
  3157. if (function.getParamCount() != 1)
  3158. error(loc, "matrix constructed from matrix can only have one argument", constructorString.c_str(), "");
  3159. return false;
  3160. }
  3161. if (overFull) {
  3162. error(loc, "too many arguments", constructorString.c_str(), "");
  3163. return true;
  3164. }
  3165. if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
  3166. error(loc, "Number of constructor parameters does not match the number of structure fields", constructorString.c_str(), "");
  3167. return true;
  3168. }
  3169. if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
  3170. (op == EOpConstructStruct && size < type.computeNumComponents())) {
  3171. error(loc, "not enough data provided for construction", constructorString.c_str(), "");
  3172. return true;
  3173. }
  3174. if (type.isCoopMat() && function.getParamCount() != 1) {
  3175. error(loc, "wrong number of arguments", constructorString.c_str(), "");
  3176. return true;
  3177. }
  3178. if (type.isCoopMat() &&
  3179. !(function[0].type->isScalar() || function[0].type->isCoopMat())) {
  3180. error(loc, "Cooperative matrix constructor argument must be scalar or cooperative matrix", constructorString.c_str(), "");
  3181. return true;
  3182. }
  3183. TIntermTyped* typed = node->getAsTyped();
  3184. if (typed == nullptr) {
  3185. error(loc, "constructor argument does not have a type", constructorString.c_str(), "");
  3186. return true;
  3187. }
  3188. if (op != EOpConstructStruct && op != EOpConstructNonuniform && typed->getBasicType() == EbtSampler) {
  3189. error(loc, "cannot convert a sampler", constructorString.c_str(), "");
  3190. return true;
  3191. }
  3192. if (op != EOpConstructStruct && typed->isAtomic()) {
  3193. error(loc, "cannot convert an atomic_uint", constructorString.c_str(), "");
  3194. return true;
  3195. }
  3196. if (typed->getBasicType() == EbtVoid) {
  3197. error(loc, "cannot convert a void", constructorString.c_str(), "");
  3198. return true;
  3199. }
  3200. return false;
  3201. }
  3202. // Verify all the correct semantics for constructing a combined texture/sampler.
  3203. // Return true if the semantics are incorrect.
  3204. bool TParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
  3205. {
  3206. TString constructorName = function.getType().getBasicTypeString(); // TODO: performance: should not be making copy; interface needs to change
  3207. const char* token = constructorName.c_str();
  3208. // exactly two arguments needed
  3209. if (function.getParamCount() != 2) {
  3210. error(loc, "sampler-constructor requires two arguments", token, "");
  3211. return true;
  3212. }
  3213. // For now, not allowing arrayed constructors, the rest of this function
  3214. // is set up to allow them, if this test is removed:
  3215. if (function.getType().isArray()) {
  3216. error(loc, "sampler-constructor cannot make an array of samplers", token, "");
  3217. return true;
  3218. }
  3219. // first argument
  3220. // * the constructor's first argument must be a texture type
  3221. // * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
  3222. // of the texture type must match that of the constructed sampler type
  3223. // (that is, the suffixes of the type of the first argument and the
  3224. // type of the constructor will be spelled the same way)
  3225. if (function[0].type->getBasicType() != EbtSampler ||
  3226. ! function[0].type->getSampler().isTexture() ||
  3227. function[0].type->isArray()) {
  3228. error(loc, "sampler-constructor first argument must be a scalar *texture* type", token, "");
  3229. return true;
  3230. }
  3231. // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
  3232. TSampler texture = function.getType().getSampler();
  3233. texture.setCombined(false);
  3234. texture.shadow = false;
  3235. if (texture != function[0].type->getSampler()) {
  3236. error(loc, "sampler-constructor first argument must be a *texture* type"
  3237. " matching the dimensionality and sampled type of the constructor", token, "");
  3238. return true;
  3239. }
  3240. // second argument
  3241. // * the constructor's second argument must be a scalar of type
  3242. // *sampler* or *samplerShadow*
  3243. if ( function[1].type->getBasicType() != EbtSampler ||
  3244. ! function[1].type->getSampler().isPureSampler() ||
  3245. function[1].type->isArray()) {
  3246. error(loc, "sampler-constructor second argument must be a scalar sampler or samplerShadow", token, "");
  3247. return true;
  3248. }
  3249. return false;
  3250. }
  3251. // Checks to see if a void variable has been declared and raise an error message for such a case
  3252. //
  3253. // returns true in case of an error
  3254. //
  3255. bool TParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
  3256. {
  3257. if (basicType == EbtVoid) {
  3258. error(loc, "illegal use of type 'void'", identifier.c_str(), "");
  3259. return true;
  3260. }
  3261. return false;
  3262. }
  3263. // Checks to see if the node (for the expression) contains a scalar boolean expression or not
  3264. void TParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
  3265. {
  3266. if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
  3267. error(loc, "boolean expression expected", "", "");
  3268. }
  3269. // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
  3270. void TParseContext::boolCheck(const TSourceLoc& loc, const TPublicType& pType)
  3271. {
  3272. if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
  3273. error(loc, "boolean expression expected", "", "");
  3274. }
  3275. void TParseContext::samplerCheck(const TSourceLoc& loc, const TType& type, const TString& identifier, TIntermTyped* /*initializer*/)
  3276. {
  3277. // Check that the appropriate extension is enabled if external sampler is used.
  3278. // There are two extensions. The correct one must be used based on GLSL version.
  3279. if (type.getBasicType() == EbtSampler && type.getSampler().isExternal()) {
  3280. if (version < 300) {
  3281. requireExtensions(loc, 1, &E_GL_OES_EGL_image_external, "samplerExternalOES");
  3282. } else {
  3283. requireExtensions(loc, 1, &E_GL_OES_EGL_image_external_essl3, "samplerExternalOES");
  3284. }
  3285. }
  3286. if (type.getSampler().isYuv()) {
  3287. requireExtensions(loc, 1, &E_GL_EXT_YUV_target, "__samplerExternal2DY2YEXT");
  3288. }
  3289. if (type.getQualifier().storage == EvqUniform)
  3290. return;
  3291. if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler))
  3292. error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str());
  3293. else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform) {
  3294. // non-uniform sampler
  3295. // not yet: okay if it has an initializer
  3296. // if (! initializer)
  3297. error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
  3298. }
  3299. }
  3300. #ifndef GLSLANG_WEB
  3301. void TParseContext::atomicUintCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
  3302. {
  3303. if (type.getQualifier().storage == EvqUniform)
  3304. return;
  3305. if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint))
  3306. error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str());
  3307. else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform)
  3308. error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
  3309. }
  3310. void TParseContext::accStructCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
  3311. {
  3312. if (type.getQualifier().storage == EvqUniform)
  3313. return;
  3314. if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAccStruct))
  3315. error(loc, "non-uniform struct contains an accelerationStructureNV:", type.getBasicTypeString().c_str(), identifier.c_str());
  3316. else if (type.getBasicType() == EbtAccStruct && type.getQualifier().storage != EvqUniform)
  3317. error(loc, "accelerationStructureNV can only be used in uniform variables or function parameters:",
  3318. type.getBasicTypeString().c_str(), identifier.c_str());
  3319. }
  3320. #endif // GLSLANG_WEB
  3321. void TParseContext::transparentOpaqueCheck(const TSourceLoc& loc, const TType& type, const TString& identifier)
  3322. {
  3323. if (parsingBuiltins)
  3324. return;
  3325. if (type.getQualifier().storage != EvqUniform)
  3326. return;
  3327. if (type.containsNonOpaque()) {
  3328. // Vulkan doesn't allow transparent uniforms outside of blocks
  3329. if (spvVersion.vulkan > 0 && !spvVersion.vulkanRelaxed)
  3330. vulkanRemoved(loc, "non-opaque uniforms outside a block");
  3331. // OpenGL wants locations on these (unless they are getting automapped)
  3332. if (spvVersion.openGl > 0 && !type.getQualifier().hasLocation() && !intermediate.getAutoMapLocations())
  3333. error(loc, "non-opaque uniform variables need a layout(location=L)", identifier.c_str(), "");
  3334. }
  3335. }
  3336. //
  3337. // Qualifier checks knowing the qualifier and that it is a member of a struct/block.
  3338. //
  3339. void TParseContext::memberQualifierCheck(glslang::TPublicType& publicType)
  3340. {
  3341. globalQualifierFixCheck(publicType.loc, publicType.qualifier, true);
  3342. checkNoShaderLayouts(publicType.loc, publicType.shaderQualifiers);
  3343. if (publicType.qualifier.isNonUniform()) {
  3344. error(publicType.loc, "not allowed on block or structure members", "nonuniformEXT", "");
  3345. publicType.qualifier.nonUniform = false;
  3346. }
  3347. }
  3348. //
  3349. // Check/fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
  3350. //
  3351. void TParseContext::globalQualifierFixCheck(const TSourceLoc& loc, TQualifier& qualifier, bool isMemberCheck)
  3352. {
  3353. bool nonuniformOkay = false;
  3354. // move from parameter/unknown qualifiers to pipeline in/out qualifiers
  3355. switch (qualifier.storage) {
  3356. case EvqIn:
  3357. profileRequires(loc, ENoProfile, 130, nullptr, "in for stage inputs");
  3358. profileRequires(loc, EEsProfile, 300, nullptr, "in for stage inputs");
  3359. qualifier.storage = EvqVaryingIn;
  3360. nonuniformOkay = true;
  3361. break;
  3362. case EvqOut:
  3363. profileRequires(loc, ENoProfile, 130, nullptr, "out for stage outputs");
  3364. profileRequires(loc, EEsProfile, 300, nullptr, "out for stage outputs");
  3365. qualifier.storage = EvqVaryingOut;
  3366. if (intermediate.isInvariantAll())
  3367. qualifier.invariant = true;
  3368. break;
  3369. case EvqInOut:
  3370. qualifier.storage = EvqVaryingIn;
  3371. error(loc, "cannot use 'inout' at global scope", "", "");
  3372. break;
  3373. case EvqGlobal:
  3374. case EvqTemporary:
  3375. nonuniformOkay = true;
  3376. break;
  3377. case EvqUniform:
  3378. // According to GLSL spec: The std430 qualifier is supported only for shader storage blocks; a shader using
  3379. // the std430 qualifier on a uniform block will fail to compile.
  3380. // Only check the global declaration: layout(std430) uniform;
  3381. if (blockName == nullptr &&
  3382. qualifier.layoutPacking == ElpStd430)
  3383. {
  3384. requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "default std430 layout for uniform");
  3385. }
  3386. break;
  3387. default:
  3388. break;
  3389. }
  3390. if (!nonuniformOkay && qualifier.isNonUniform())
  3391. error(loc, "for non-parameter, can only apply to 'in' or no storage qualifier", "nonuniformEXT", "");
  3392. #ifndef GLSLANG_WEB
  3393. if (qualifier.isSpirvByReference())
  3394. error(loc, "can only apply to parameter", "spirv_by_reference", "");
  3395. if (qualifier.isSpirvLiteral())
  3396. error(loc, "can only apply to parameter", "spirv_literal", "");
  3397. #endif
  3398. // Storage qualifier isn't ready for memberQualifierCheck, we should skip invariantCheck for it.
  3399. if (!isMemberCheck || structNestingLevel > 0)
  3400. invariantCheck(loc, qualifier);
  3401. }
  3402. //
  3403. // Check a full qualifier and type (no variable yet) at global level.
  3404. //
  3405. void TParseContext::globalQualifierTypeCheck(const TSourceLoc& loc, const TQualifier& qualifier, const TPublicType& publicType)
  3406. {
  3407. if (! symbolTable.atGlobalLevel())
  3408. return;
  3409. if (!(publicType.userDef && publicType.userDef->isReference()) && !parsingBuiltins) {
  3410. if (qualifier.isMemoryQualifierImageAndSSBOOnly() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer) {
  3411. error(loc, "memory qualifiers cannot be used on this type", "", "");
  3412. } else if (qualifier.isMemory() && (publicType.basicType != EbtSampler) && !publicType.qualifier.isUniformOrBuffer()) {
  3413. error(loc, "memory qualifiers cannot be used on this type", "", "");
  3414. }
  3415. }
  3416. if (qualifier.storage == EvqBuffer &&
  3417. publicType.basicType != EbtBlock &&
  3418. !qualifier.hasBufferReference())
  3419. error(loc, "buffers can be declared only as blocks", "buffer", "");
  3420. if (qualifier.storage != EvqVaryingIn && publicType.basicType == EbtDouble &&
  3421. extensionTurnedOn(E_GL_ARB_vertex_attrib_64bit) && language == EShLangVertex &&
  3422. version < 400) {
  3423. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 410, E_GL_ARB_gpu_shader_fp64, "vertex-shader `double` type");
  3424. }
  3425. if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
  3426. return;
  3427. if (publicType.shaderQualifiers.hasBlendEquation())
  3428. error(loc, "can only be applied to a standalone 'out'", "blend equation", "");
  3429. // now, knowing it is a shader in/out, do all the in/out semantic checks
  3430. if (publicType.basicType == EbtBool && !parsingBuiltins) {
  3431. error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
  3432. return;
  3433. }
  3434. if (isTypeInt(publicType.basicType) || publicType.basicType == EbtDouble)
  3435. profileRequires(loc, EEsProfile, 300, nullptr, "shader input/output");
  3436. if (!qualifier.flat && !qualifier.isExplicitInterpolation() && !qualifier.isPervertexNV() && !qualifier.isPervertexEXT()) {
  3437. if (isTypeInt(publicType.basicType) ||
  3438. publicType.basicType == EbtDouble ||
  3439. (publicType.userDef && ( publicType.userDef->containsBasicType(EbtInt)
  3440. || publicType.userDef->containsBasicType(EbtUint)
  3441. || publicType.userDef->contains16BitInt()
  3442. || publicType.userDef->contains8BitInt()
  3443. || publicType.userDef->contains64BitInt()
  3444. || publicType.userDef->containsDouble()))) {
  3445. if (qualifier.storage == EvqVaryingIn && language == EShLangFragment)
  3446. error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
  3447. else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300)
  3448. error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
  3449. }
  3450. }
  3451. if (qualifier.isPatch() && qualifier.isInterpolation())
  3452. error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
  3453. if (qualifier.isTaskPayload() && publicType.basicType == EbtBlock)
  3454. error(loc, "taskPayloadSharedEXT variables should not be declared as interface blocks", "taskPayloadSharedEXT", "");
  3455. if (qualifier.isTaskMemory() && publicType.basicType != EbtBlock)
  3456. error(loc, "taskNV variables can be declared only as blocks", "taskNV", "");
  3457. if (qualifier.storage == EvqVaryingIn) {
  3458. switch (language) {
  3459. case EShLangVertex:
  3460. if (publicType.basicType == EbtStruct) {
  3461. error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), "");
  3462. return;
  3463. }
  3464. if (publicType.arraySizes) {
  3465. requireProfile(loc, ~EEsProfile, "vertex input arrays");
  3466. profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
  3467. }
  3468. if (publicType.basicType == EbtDouble)
  3469. profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_vertex_attrib_64bit, "vertex-shader `double` type input");
  3470. if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
  3471. error(loc, "vertex input cannot be further qualified", "", "");
  3472. break;
  3473. case EShLangFragment:
  3474. if (publicType.userDef) {
  3475. profileRequires(loc, EEsProfile, 300, nullptr, "fragment-shader struct input");
  3476. profileRequires(loc, ~EEsProfile, 150, nullptr, "fragment-shader struct input");
  3477. if (publicType.userDef->containsStructure())
  3478. requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing structure");
  3479. if (publicType.userDef->containsArray())
  3480. requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing an array");
  3481. }
  3482. break;
  3483. case EShLangCompute:
  3484. if (! symbolTable.atBuiltInLevel())
  3485. error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
  3486. break;
  3487. #ifndef GLSLANG_WEB
  3488. case EShLangTessControl:
  3489. if (qualifier.patch)
  3490. error(loc, "can only use on output in tessellation-control shader", "patch", "");
  3491. break;
  3492. #endif
  3493. default:
  3494. break;
  3495. }
  3496. } else {
  3497. // qualifier.storage == EvqVaryingOut
  3498. switch (language) {
  3499. case EShLangVertex:
  3500. if (publicType.userDef) {
  3501. profileRequires(loc, EEsProfile, 300, nullptr, "vertex-shader struct output");
  3502. profileRequires(loc, ~EEsProfile, 150, nullptr, "vertex-shader struct output");
  3503. if (publicType.userDef->containsStructure())
  3504. requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing structure");
  3505. if (publicType.userDef->containsArray())
  3506. requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing an array");
  3507. }
  3508. break;
  3509. case EShLangFragment:
  3510. profileRequires(loc, EEsProfile, 300, nullptr, "fragment shader output");
  3511. if (publicType.basicType == EbtStruct) {
  3512. error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
  3513. return;
  3514. }
  3515. if (publicType.matrixRows > 0) {
  3516. error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
  3517. return;
  3518. }
  3519. if (qualifier.isAuxiliary())
  3520. error(loc, "can't use auxiliary qualifier on a fragment output", "centroid/sample/patch", "");
  3521. if (qualifier.isInterpolation())
  3522. error(loc, "can't use interpolation qualifier on a fragment output", "flat/smooth/noperspective", "");
  3523. if (publicType.basicType == EbtDouble || publicType.basicType == EbtInt64 || publicType.basicType == EbtUint64)
  3524. error(loc, "cannot contain a double, int64, or uint64", GetStorageQualifierString(qualifier.storage), "");
  3525. break;
  3526. case EShLangCompute:
  3527. error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
  3528. break;
  3529. #ifndef GLSLANG_WEB
  3530. case EShLangTessEvaluation:
  3531. if (qualifier.patch)
  3532. error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
  3533. break;
  3534. #endif
  3535. default:
  3536. break;
  3537. }
  3538. }
  3539. }
  3540. //
  3541. // Merge characteristics of the 'src' qualifier into the 'dst'.
  3542. // If there is duplication, issue error messages, unless 'force'
  3543. // is specified, which means to just override default settings.
  3544. //
  3545. // Also, when force is false, it will be assumed that 'src' follows
  3546. // 'dst', for the purpose of error checking order for versions
  3547. // that require specific orderings of qualifiers.
  3548. //
  3549. void TParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force)
  3550. {
  3551. // Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers')
  3552. if (src.isAuxiliary() && dst.isAuxiliary())
  3553. error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", "");
  3554. // Multiple interpolation qualifiers (mostly done later by 'individual qualifiers')
  3555. if (src.isInterpolation() && dst.isInterpolation())
  3556. error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective, __explicitInterpAMD)", "", "");
  3557. // Ordering
  3558. if (! force && ((!isEsProfile() && version < 420) ||
  3559. (isEsProfile() && version < 310))
  3560. && ! extensionTurnedOn(E_GL_ARB_shading_language_420pack)) {
  3561. // non-function parameters
  3562. if (src.isNoContraction() && (dst.invariant || dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
  3563. error(loc, "precise qualifier must appear first", "", "");
  3564. if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
  3565. error(loc, "invariant qualifier must appear before interpolation, storage, and precision qualifiers ", "", "");
  3566. else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
  3567. error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", "");
  3568. else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone))
  3569. error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", "");
  3570. else if (src.storage != EvqTemporary && (dst.precision != EpqNone))
  3571. error(loc, "precision qualifier must appear as last qualifier", "", "");
  3572. // function parameters
  3573. if (src.isNoContraction() && (dst.storage == EvqConst || dst.storage == EvqIn || dst.storage == EvqOut))
  3574. error(loc, "precise qualifier must appear first", "", "");
  3575. if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
  3576. error(loc, "in/out must appear before const", "", "");
  3577. }
  3578. // Storage qualification
  3579. if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
  3580. dst.storage = src.storage;
  3581. else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
  3582. (dst.storage == EvqOut && src.storage == EvqIn))
  3583. dst.storage = EvqInOut;
  3584. else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
  3585. (dst.storage == EvqConst && src.storage == EvqIn))
  3586. dst.storage = EvqConstReadOnly;
  3587. else if (src.storage != EvqTemporary &&
  3588. src.storage != EvqGlobal)
  3589. error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
  3590. // Precision qualifiers
  3591. if (! force && src.precision != EpqNone && dst.precision != EpqNone)
  3592. error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), "");
  3593. if (dst.precision == EpqNone || (force && src.precision != EpqNone))
  3594. dst.precision = src.precision;
  3595. #ifndef GLSLANG_WEB
  3596. if (!force && ((src.coherent && (dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
  3597. (src.devicecoherent && (dst.coherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
  3598. (src.queuefamilycoherent && (dst.coherent || dst.devicecoherent || dst.workgroupcoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
  3599. (src.workgroupcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.subgroupcoherent || dst.shadercallcoherent)) ||
  3600. (src.subgroupcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.shadercallcoherent)) ||
  3601. (src.shadercallcoherent && (dst.coherent || dst.devicecoherent || dst.queuefamilycoherent || dst.workgroupcoherent || dst.subgroupcoherent)))) {
  3602. error(loc, "only one coherent/devicecoherent/queuefamilycoherent/workgroupcoherent/subgroupcoherent/shadercallcoherent qualifier allowed",
  3603. GetPrecisionQualifierString(src.precision), "");
  3604. }
  3605. #endif
  3606. // Layout qualifiers
  3607. mergeObjectLayoutQualifiers(dst, src, false);
  3608. // individual qualifiers
  3609. bool repeated = false;
  3610. #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
  3611. MERGE_SINGLETON(invariant);
  3612. MERGE_SINGLETON(centroid);
  3613. MERGE_SINGLETON(smooth);
  3614. MERGE_SINGLETON(flat);
  3615. MERGE_SINGLETON(specConstant);
  3616. #ifndef GLSLANG_WEB
  3617. MERGE_SINGLETON(noContraction);
  3618. MERGE_SINGLETON(nopersp);
  3619. MERGE_SINGLETON(explicitInterp);
  3620. MERGE_SINGLETON(perPrimitiveNV);
  3621. MERGE_SINGLETON(perViewNV);
  3622. MERGE_SINGLETON(perTaskNV);
  3623. MERGE_SINGLETON(patch);
  3624. MERGE_SINGLETON(sample);
  3625. MERGE_SINGLETON(coherent);
  3626. MERGE_SINGLETON(devicecoherent);
  3627. MERGE_SINGLETON(queuefamilycoherent);
  3628. MERGE_SINGLETON(workgroupcoherent);
  3629. MERGE_SINGLETON(subgroupcoherent);
  3630. MERGE_SINGLETON(shadercallcoherent);
  3631. MERGE_SINGLETON(nonprivate);
  3632. MERGE_SINGLETON(volatil);
  3633. MERGE_SINGLETON(restrict);
  3634. MERGE_SINGLETON(readonly);
  3635. MERGE_SINGLETON(writeonly);
  3636. MERGE_SINGLETON(nonUniform);
  3637. #endif
  3638. #ifndef GLSLANG_WEB
  3639. // SPIR-V storage class qualifier (GL_EXT_spirv_intrinsics)
  3640. dst.spirvStorageClass = src.spirvStorageClass;
  3641. // SPIR-V decorate qualifiers (GL_EXT_spirv_intrinsics)
  3642. if (src.hasSprivDecorate()) {
  3643. if (dst.hasSprivDecorate()) {
  3644. const TSpirvDecorate& srcSpirvDecorate = src.getSpirvDecorate();
  3645. TSpirvDecorate& dstSpirvDecorate = dst.getSpirvDecorate();
  3646. for (auto& decorate : srcSpirvDecorate.decorates) {
  3647. if (dstSpirvDecorate.decorates.find(decorate.first) != dstSpirvDecorate.decorates.end())
  3648. error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate", "(decoration=%u)", decorate.first);
  3649. else
  3650. dstSpirvDecorate.decorates.insert(decorate);
  3651. }
  3652. for (auto& decorateId : srcSpirvDecorate.decorateIds) {
  3653. if (dstSpirvDecorate.decorateIds.find(decorateId.first) != dstSpirvDecorate.decorateIds.end())
  3654. error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_id", "(decoration=%u)", decorateId.first);
  3655. else
  3656. dstSpirvDecorate.decorateIds.insert(decorateId);
  3657. }
  3658. for (auto& decorateString : srcSpirvDecorate.decorateStrings) {
  3659. if (dstSpirvDecorate.decorates.find(decorateString.first) != dstSpirvDecorate.decorates.end())
  3660. error(loc, "too many SPIR-V decorate qualifiers", "spirv_decorate_string", "(decoration=%u)", decorateString.first);
  3661. else
  3662. dstSpirvDecorate.decorates.insert(decorateString);
  3663. }
  3664. } else {
  3665. dst.spirvDecorate = src.spirvDecorate;
  3666. }
  3667. }
  3668. #endif
  3669. if (repeated)
  3670. error(loc, "replicated qualifiers", "", "");
  3671. }
  3672. void TParseContext::setDefaultPrecision(const TSourceLoc& loc, TPublicType& publicType, TPrecisionQualifier qualifier)
  3673. {
  3674. TBasicType basicType = publicType.basicType;
  3675. if (basicType == EbtSampler) {
  3676. defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
  3677. return; // all is well
  3678. }
  3679. if (basicType == EbtInt || basicType == EbtFloat) {
  3680. if (publicType.isScalar()) {
  3681. defaultPrecision[basicType] = qualifier;
  3682. if (basicType == EbtInt) {
  3683. defaultPrecision[EbtUint] = qualifier;
  3684. precisionManager.explicitIntDefaultSeen();
  3685. } else
  3686. precisionManager.explicitFloatDefaultSeen();
  3687. return; // all is well
  3688. }
  3689. }
  3690. if (basicType == EbtAtomicUint) {
  3691. if (qualifier != EpqHigh)
  3692. error(loc, "can only apply highp to atomic_uint", "precision", "");
  3693. return;
  3694. }
  3695. error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
  3696. }
  3697. // used to flatten the sampler type space into a single dimension
  3698. // correlates with the declaration of defaultSamplerPrecision[]
  3699. int TParseContext::computeSamplerTypeIndex(TSampler& sampler)
  3700. {
  3701. int arrayIndex = sampler.arrayed ? 1 : 0;
  3702. int shadowIndex = sampler.shadow ? 1 : 0;
  3703. int externalIndex = sampler.isExternal() ? 1 : 0;
  3704. int imageIndex = sampler.isImageClass() ? 1 : 0;
  3705. int msIndex = sampler.isMultiSample() ? 1 : 0;
  3706. int flattened = EsdNumDims * (EbtNumTypes * (2 * (2 * (2 * (2 * arrayIndex + msIndex) + imageIndex) + shadowIndex) +
  3707. externalIndex) + sampler.type) + sampler.dim;
  3708. assert(flattened < maxSamplerIndex);
  3709. return flattened;
  3710. }
  3711. TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
  3712. {
  3713. if (publicType.basicType == EbtSampler)
  3714. return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
  3715. else
  3716. return defaultPrecision[publicType.basicType];
  3717. }
  3718. void TParseContext::precisionQualifierCheck(const TSourceLoc& loc, TBasicType baseType, TQualifier& qualifier)
  3719. {
  3720. // Built-in symbols are allowed some ambiguous precisions, to be pinned down
  3721. // later by context.
  3722. if (! obeyPrecisionQualifiers() || parsingBuiltins)
  3723. return;
  3724. #ifndef GLSLANG_WEB
  3725. if (baseType == EbtAtomicUint && qualifier.precision != EpqNone && qualifier.precision != EpqHigh)
  3726. error(loc, "atomic counters can only be highp", "atomic_uint", "");
  3727. #endif
  3728. if (baseType == EbtFloat || baseType == EbtUint || baseType == EbtInt || baseType == EbtSampler || baseType == EbtAtomicUint) {
  3729. if (qualifier.precision == EpqNone) {
  3730. if (relaxedErrors())
  3731. warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "substituting 'mediump'");
  3732. else
  3733. error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "");
  3734. qualifier.precision = EpqMedium;
  3735. defaultPrecision[baseType] = EpqMedium;
  3736. }
  3737. } else if (qualifier.precision != EpqNone)
  3738. error(loc, "type cannot have precision qualifier", TType::getBasicString(baseType), "");
  3739. }
  3740. void TParseContext::parameterTypeCheck(const TSourceLoc& loc, TStorageQualifier qualifier, const TType& type)
  3741. {
  3742. if ((qualifier == EvqOut || qualifier == EvqInOut) && type.isOpaque())
  3743. error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), "");
  3744. if (!parsingBuiltins && type.contains16BitFloat())
  3745. requireFloat16Arithmetic(loc, type.getBasicTypeString().c_str(), "float16 types can only be in uniform block or buffer storage");
  3746. if (!parsingBuiltins && type.contains16BitInt())
  3747. requireInt16Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int16 types can only be in uniform block or buffer storage");
  3748. if (!parsingBuiltins && type.contains8BitInt())
  3749. requireInt8Arithmetic(loc, type.getBasicTypeString().c_str(), "(u)int8 types can only be in uniform block or buffer storage");
  3750. }
  3751. bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
  3752. {
  3753. if (type.getBasicType() == basicType)
  3754. return true;
  3755. if (type.getBasicType() == EbtStruct) {
  3756. const TTypeList& structure = *type.getStruct();
  3757. for (unsigned int i = 0; i < structure.size(); ++i) {
  3758. if (containsFieldWithBasicType(*structure[i].type, basicType))
  3759. return true;
  3760. }
  3761. }
  3762. return false;
  3763. }
  3764. //
  3765. // Do size checking for an array type's size.
  3766. //
  3767. void TParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair, const char *sizeType)
  3768. {
  3769. bool isConst = false;
  3770. sizePair.node = nullptr;
  3771. int size = 1;
  3772. TIntermConstantUnion* constant = expr->getAsConstantUnion();
  3773. if (constant) {
  3774. // handle true (non-specialization) constant
  3775. size = constant->getConstArray()[0].getIConst();
  3776. isConst = true;
  3777. } else {
  3778. // see if it's a specialization constant instead
  3779. if (expr->getQualifier().isSpecConstant()) {
  3780. isConst = true;
  3781. sizePair.node = expr;
  3782. TIntermSymbol* symbol = expr->getAsSymbolNode();
  3783. if (symbol && symbol->getConstArray().size() > 0)
  3784. size = symbol->getConstArray()[0].getIConst();
  3785. } else if (expr->getAsUnaryNode() &&
  3786. expr->getAsUnaryNode()->getOp() == glslang::EOpArrayLength &&
  3787. expr->getAsUnaryNode()->getOperand()->getType().isCoopMat()) {
  3788. isConst = true;
  3789. size = 1;
  3790. sizePair.node = expr->getAsUnaryNode();
  3791. }
  3792. }
  3793. sizePair.size = size;
  3794. if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
  3795. error(loc, sizeType, "", "must be a constant integer expression");
  3796. return;
  3797. }
  3798. if (size <= 0) {
  3799. error(loc, sizeType, "", "must be a positive integer");
  3800. return;
  3801. }
  3802. }
  3803. //
  3804. // See if this qualifier can be an array.
  3805. //
  3806. // Returns true if there is an error.
  3807. //
  3808. bool TParseContext::arrayQualifierError(const TSourceLoc& loc, const TQualifier& qualifier)
  3809. {
  3810. if (qualifier.storage == EvqConst) {
  3811. profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "const array");
  3812. profileRequires(loc, EEsProfile, 300, nullptr, "const array");
  3813. }
  3814. if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
  3815. requireProfile(loc, ~EEsProfile, "vertex input arrays");
  3816. profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
  3817. }
  3818. return false;
  3819. }
  3820. //
  3821. // See if this qualifier and type combination can be an array.
  3822. // Assumes arrayQualifierError() was also called to catch the type-invariant tests.
  3823. //
  3824. // Returns true if there is an error.
  3825. //
  3826. bool TParseContext::arrayError(const TSourceLoc& loc, const TType& type)
  3827. {
  3828. if (type.getQualifier().storage == EvqVaryingOut && language == EShLangVertex) {
  3829. if (type.isArrayOfArrays())
  3830. requireProfile(loc, ~EEsProfile, "vertex-shader array-of-array output");
  3831. else if (type.isStruct())
  3832. requireProfile(loc, ~EEsProfile, "vertex-shader array-of-struct output");
  3833. }
  3834. if (type.getQualifier().storage == EvqVaryingIn && language == EShLangFragment) {
  3835. if (type.isArrayOfArrays())
  3836. requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array input");
  3837. else if (type.isStruct())
  3838. requireProfile(loc, ~EEsProfile, "fragment-shader array-of-struct input");
  3839. }
  3840. if (type.getQualifier().storage == EvqVaryingOut && language == EShLangFragment) {
  3841. if (type.isArrayOfArrays())
  3842. requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array output");
  3843. }
  3844. return false;
  3845. }
  3846. //
  3847. // Require array to be completely sized
  3848. //
  3849. void TParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
  3850. {
  3851. if (!parsingBuiltins && arraySizes.hasUnsized())
  3852. error(loc, "array size required", "", "");
  3853. }
  3854. void TParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
  3855. {
  3856. const TTypeList& structure = *type.getStruct();
  3857. for (int m = 0; m < (int)structure.size(); ++m) {
  3858. const TType& member = *structure[m].type;
  3859. if (member.isArray())
  3860. arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
  3861. }
  3862. }
  3863. void TParseContext::arraySizesCheck(const TSourceLoc& loc, const TQualifier& qualifier, TArraySizes* arraySizes,
  3864. const TIntermTyped* initializer, bool lastMember)
  3865. {
  3866. assert(arraySizes);
  3867. // always allow special built-in ins/outs sized to topologies
  3868. if (parsingBuiltins)
  3869. return;
  3870. // initializer must be a sized array, in which case
  3871. // allow the initializer to set any unknown array sizes
  3872. if (initializer != nullptr) {
  3873. if (initializer->getType().isUnsizedArray())
  3874. error(loc, "array initializer must be sized", "[]", "");
  3875. return;
  3876. }
  3877. // No environment allows any non-outer-dimension to be implicitly sized
  3878. if (arraySizes->isInnerUnsized()) {
  3879. error(loc, "only outermost dimension of an array of arrays can be implicitly sized", "[]", "");
  3880. arraySizes->clearInnerUnsized();
  3881. }
  3882. if (arraySizes->isInnerSpecialization() &&
  3883. (qualifier.storage != EvqTemporary && qualifier.storage != EvqGlobal && qualifier.storage != EvqShared && qualifier.storage != EvqConst))
  3884. error(loc, "only outermost dimension of an array of arrays can be a specialization constant", "[]", "");
  3885. #ifndef GLSLANG_WEB
  3886. // desktop always allows outer-dimension-unsized variable arrays,
  3887. if (!isEsProfile())
  3888. return;
  3889. // for ES, if size isn't coming from an initializer, it has to be explicitly declared now,
  3890. // with very few exceptions
  3891. // implicitly-sized io exceptions:
  3892. switch (language) {
  3893. case EShLangGeometry:
  3894. if (qualifier.storage == EvqVaryingIn)
  3895. if ((isEsProfile() && version >= 320) ||
  3896. extensionsTurnedOn(Num_AEP_geometry_shader, AEP_geometry_shader))
  3897. return;
  3898. break;
  3899. case EShLangTessControl:
  3900. if ( qualifier.storage == EvqVaryingIn ||
  3901. (qualifier.storage == EvqVaryingOut && ! qualifier.isPatch()))
  3902. if ((isEsProfile() && version >= 320) ||
  3903. extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
  3904. return;
  3905. break;
  3906. case EShLangTessEvaluation:
  3907. if ((qualifier.storage == EvqVaryingIn && ! qualifier.isPatch()) ||
  3908. qualifier.storage == EvqVaryingOut)
  3909. if ((isEsProfile() && version >= 320) ||
  3910. extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
  3911. return;
  3912. break;
  3913. case EShLangMesh:
  3914. if (qualifier.storage == EvqVaryingOut)
  3915. if ((isEsProfile() && version >= 320) ||
  3916. extensionsTurnedOn(Num_AEP_mesh_shader, AEP_mesh_shader))
  3917. return;
  3918. break;
  3919. default:
  3920. break;
  3921. }
  3922. #endif
  3923. // last member of ssbo block exception:
  3924. if (qualifier.storage == EvqBuffer && lastMember)
  3925. return;
  3926. arraySizeRequiredCheck(loc, *arraySizes);
  3927. }
  3928. void TParseContext::arrayOfArrayVersionCheck(const TSourceLoc& loc, const TArraySizes* sizes)
  3929. {
  3930. if (sizes == nullptr || sizes->getNumDims() == 1)
  3931. return;
  3932. const char* feature = "arrays of arrays";
  3933. requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
  3934. profileRequires(loc, EEsProfile, 310, nullptr, feature);
  3935. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature);
  3936. }
  3937. //
  3938. // Do all the semantic checking for declaring or redeclaring an array, with and
  3939. // without a size, and make the right changes to the symbol table.
  3940. //
  3941. void TParseContext::declareArray(const TSourceLoc& loc, const TString& identifier, const TType& type, TSymbol*& symbol)
  3942. {
  3943. if (symbol == nullptr) {
  3944. bool currentScope;
  3945. symbol = symbolTable.find(identifier, nullptr, &currentScope);
  3946. if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
  3947. // bad shader (errors already reported) trying to redeclare a built-in name as an array
  3948. symbol = nullptr;
  3949. return;
  3950. }
  3951. if (symbol == nullptr || ! currentScope) {
  3952. //
  3953. // Successfully process a new definition.
  3954. // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
  3955. //
  3956. symbol = new TVariable(&identifier, type);
  3957. symbolTable.insert(*symbol);
  3958. if (symbolTable.atGlobalLevel())
  3959. trackLinkage(*symbol);
  3960. #ifndef GLSLANG_WEB
  3961. if (! symbolTable.atBuiltInLevel()) {
  3962. if (isIoResizeArray(type)) {
  3963. ioArraySymbolResizeList.push_back(symbol);
  3964. checkIoArraysConsistency(loc, true);
  3965. } else
  3966. fixIoArraySize(loc, symbol->getWritableType());
  3967. }
  3968. #endif
  3969. return;
  3970. }
  3971. if (symbol->getAsAnonMember()) {
  3972. error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
  3973. symbol = nullptr;
  3974. return;
  3975. }
  3976. }
  3977. //
  3978. // Process a redeclaration.
  3979. //
  3980. if (symbol == nullptr) {
  3981. error(loc, "array variable name expected", identifier.c_str(), "");
  3982. return;
  3983. }
  3984. // redeclareBuiltinVariable() should have already done the copyUp()
  3985. TType& existingType = symbol->getWritableType();
  3986. if (! existingType.isArray()) {
  3987. error(loc, "redeclaring non-array as array", identifier.c_str(), "");
  3988. return;
  3989. }
  3990. if (! existingType.sameElementType(type)) {
  3991. error(loc, "redeclaration of array with a different element type", identifier.c_str(), "");
  3992. return;
  3993. }
  3994. if (! existingType.sameInnerArrayness(type)) {
  3995. error(loc, "redeclaration of array with a different array dimensions or sizes", identifier.c_str(), "");
  3996. return;
  3997. }
  3998. #ifndef GLSLANG_WEB
  3999. if (existingType.isSizedArray()) {
  4000. // be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
  4001. if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize()))
  4002. error(loc, "redeclaration of array with size", identifier.c_str(), "");
  4003. return;
  4004. }
  4005. arrayLimitCheck(loc, identifier, type.getOuterArraySize());
  4006. existingType.updateArraySizes(type);
  4007. if (isIoResizeArray(type))
  4008. checkIoArraysConsistency(loc);
  4009. #endif
  4010. }
  4011. #ifndef GLSLANG_WEB
  4012. // Policy and error check for needing a runtime sized array.
  4013. void TParseContext::checkRuntimeSizable(const TSourceLoc& loc, const TIntermTyped& base)
  4014. {
  4015. // runtime length implies runtime sizeable, so no problem
  4016. if (isRuntimeLength(base))
  4017. return;
  4018. if (base.getType().getQualifier().builtIn == EbvSampleMask)
  4019. return;
  4020. // Check for last member of a bufferreference type, which is runtime sizeable
  4021. // but doesn't support runtime length
  4022. if (base.getType().getQualifier().storage == EvqBuffer) {
  4023. const TIntermBinary* binary = base.getAsBinaryNode();
  4024. if (binary != nullptr &&
  4025. binary->getOp() == EOpIndexDirectStruct &&
  4026. binary->getLeft()->isReference()) {
  4027. const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
  4028. const int memberCount = (int)binary->getLeft()->getType().getReferentType()->getStruct()->size();
  4029. if (index == memberCount - 1)
  4030. return;
  4031. }
  4032. }
  4033. // check for additional things allowed by GL_EXT_nonuniform_qualifier
  4034. if (base.getBasicType() == EbtSampler || base.getBasicType() == EbtAccStruct || base.getBasicType() == EbtRayQuery ||
  4035. (base.getBasicType() == EbtBlock && base.getType().getQualifier().isUniformOrBuffer()))
  4036. requireExtensions(loc, 1, &E_GL_EXT_nonuniform_qualifier, "variable index");
  4037. else
  4038. error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
  4039. }
  4040. // Policy decision for whether a run-time .length() is allowed.
  4041. bool TParseContext::isRuntimeLength(const TIntermTyped& base) const
  4042. {
  4043. if (base.getType().getQualifier().storage == EvqBuffer) {
  4044. // in a buffer block
  4045. const TIntermBinary* binary = base.getAsBinaryNode();
  4046. if (binary != nullptr && binary->getOp() == EOpIndexDirectStruct) {
  4047. // is it the last member?
  4048. const int index = binary->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
  4049. if (binary->getLeft()->isReference())
  4050. return false;
  4051. const int memberCount = (int)binary->getLeft()->getType().getStruct()->size();
  4052. if (index == memberCount - 1)
  4053. return true;
  4054. }
  4055. }
  4056. return false;
  4057. }
  4058. // Check if mesh perviewNV attributes have a view dimension
  4059. // and resize it to gl_MaxMeshViewCountNV when implicitly sized.
  4060. void TParseContext::checkAndResizeMeshViewDim(const TSourceLoc& loc, TType& type, bool isBlockMember)
  4061. {
  4062. // see if member is a per-view attribute
  4063. if (!type.getQualifier().isPerView())
  4064. return;
  4065. if ((isBlockMember && type.isArray()) || (!isBlockMember && type.isArrayOfArrays())) {
  4066. // since we don't have the maxMeshViewCountNV set during parsing builtins, we hardcode the value.
  4067. int maxViewCount = parsingBuiltins ? 4 : resources.maxMeshViewCountNV;
  4068. // For block members, outermost array dimension is the view dimension.
  4069. // For non-block members, outermost array dimension is the vertex/primitive dimension
  4070. // and 2nd outermost is the view dimension.
  4071. int viewDim = isBlockMember ? 0 : 1;
  4072. int viewDimSize = type.getArraySizes()->getDimSize(viewDim);
  4073. if (viewDimSize != UnsizedArraySize && viewDimSize != maxViewCount)
  4074. error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
  4075. else if (viewDimSize == UnsizedArraySize)
  4076. type.getArraySizes()->setDimSize(viewDim, maxViewCount);
  4077. }
  4078. else {
  4079. error(loc, "requires a view array dimension", "perviewNV", "");
  4080. }
  4081. }
  4082. #endif // GLSLANG_WEB
  4083. // Returns true if the first argument to the #line directive is the line number for the next line.
  4084. //
  4085. // Desktop, pre-version 3.30: "After processing this directive
  4086. // (including its new-line), the implementation will behave as if it is compiling at line number line+1 and
  4087. // source string number source-string-number."
  4088. //
  4089. // Desktop, version 3.30 and later, and ES: "After processing this directive
  4090. // (including its new-line), the implementation will behave as if it is compiling at line number line and
  4091. // source string number source-string-number.
  4092. bool TParseContext::lineDirectiveShouldSetNextLine() const
  4093. {
  4094. return isEsProfile() || version >= 330;
  4095. }
  4096. //
  4097. // Enforce non-initializer type/qualifier rules.
  4098. //
  4099. void TParseContext::nonInitConstCheck(const TSourceLoc& loc, TString& identifier, TType& type)
  4100. {
  4101. //
  4102. // Make the qualifier make sense, given that there is not an initializer.
  4103. //
  4104. if (type.getQualifier().storage == EvqConst ||
  4105. type.getQualifier().storage == EvqConstReadOnly) {
  4106. type.getQualifier().makeTemporary();
  4107. error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), "");
  4108. }
  4109. }
  4110. //
  4111. // See if the identifier is a built-in symbol that can be redeclared, and if so,
  4112. // copy the symbol table's read-only built-in variable to the current
  4113. // global level, where it can be modified based on the passed in type.
  4114. //
  4115. // Returns nullptr if no redeclaration took place; meaning a normal declaration still
  4116. // needs to occur for it, not necessarily an error.
  4117. //
  4118. // Returns a redeclared and type-modified variable if a redeclarated occurred.
  4119. //
  4120. TSymbol* TParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier,
  4121. const TQualifier& qualifier, const TShaderQualifiers& publicType)
  4122. {
  4123. #ifndef GLSLANG_WEB
  4124. if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
  4125. return nullptr;
  4126. bool nonEsRedecls = (!isEsProfile() && (version >= 130 || identifier == "gl_TexCoord"));
  4127. bool esRedecls = (isEsProfile() &&
  4128. (version >= 320 || extensionsTurnedOn(Num_AEP_shader_io_blocks, AEP_shader_io_blocks)));
  4129. if (! esRedecls && ! nonEsRedecls)
  4130. return nullptr;
  4131. // Special case when using GL_ARB_separate_shader_objects
  4132. bool ssoPre150 = false; // means the only reason this variable is redeclared is due to this combination
  4133. if (!isEsProfile() && version <= 140 && extensionTurnedOn(E_GL_ARB_separate_shader_objects)) {
  4134. if (identifier == "gl_Position" ||
  4135. identifier == "gl_PointSize" ||
  4136. identifier == "gl_ClipVertex" ||
  4137. identifier == "gl_FogFragCoord")
  4138. ssoPre150 = true;
  4139. }
  4140. // Potentially redeclaring a built-in variable...
  4141. if (ssoPre150 ||
  4142. (identifier == "gl_FragDepth" && ((nonEsRedecls && version >= 420) || esRedecls)) ||
  4143. (identifier == "gl_FragCoord" && ((nonEsRedecls && version >= 140) || esRedecls)) ||
  4144. identifier == "gl_ClipDistance" ||
  4145. identifier == "gl_CullDistance" ||
  4146. identifier == "gl_ShadingRateEXT" ||
  4147. identifier == "gl_PrimitiveShadingRateEXT" ||
  4148. identifier == "gl_FrontColor" ||
  4149. identifier == "gl_BackColor" ||
  4150. identifier == "gl_FrontSecondaryColor" ||
  4151. identifier == "gl_BackSecondaryColor" ||
  4152. identifier == "gl_SecondaryColor" ||
  4153. (identifier == "gl_Color" && language == EShLangFragment) ||
  4154. (identifier == "gl_FragStencilRefARB" && (nonEsRedecls && version >= 140)
  4155. && language == EShLangFragment) ||
  4156. identifier == "gl_SampleMask" ||
  4157. identifier == "gl_Layer" ||
  4158. identifier == "gl_PrimitiveIndicesNV" ||
  4159. identifier == "gl_PrimitivePointIndicesEXT" ||
  4160. identifier == "gl_PrimitiveLineIndicesEXT" ||
  4161. identifier == "gl_PrimitiveTriangleIndicesEXT" ||
  4162. identifier == "gl_TexCoord") {
  4163. // Find the existing symbol, if any.
  4164. bool builtIn;
  4165. TSymbol* symbol = symbolTable.find(identifier, &builtIn);
  4166. // If the symbol was not found, this must be a version/profile/stage
  4167. // that doesn't have it.
  4168. if (! symbol)
  4169. return nullptr;
  4170. // If it wasn't at a built-in level, then it's already been redeclared;
  4171. // that is, this is a redeclaration of a redeclaration; reuse that initial
  4172. // redeclaration. Otherwise, make the new one.
  4173. if (builtIn) {
  4174. makeEditable(symbol);
  4175. symbolTable.amendSymbolIdLevel(*symbol);
  4176. }
  4177. // Now, modify the type of the copy, as per the type of the current redeclaration.
  4178. TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
  4179. if (ssoPre150) {
  4180. if (intermediate.inIoAccessed(identifier))
  4181. error(loc, "cannot redeclare after use", identifier.c_str(), "");
  4182. if (qualifier.hasLayout())
  4183. error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
  4184. if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex && qualifier.storage != EvqVaryingOut) ||
  4185. (language == EShLangFragment && qualifier.storage != EvqVaryingIn))
  4186. error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
  4187. if (! qualifier.smooth)
  4188. error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str());
  4189. } else if (identifier == "gl_FrontColor" ||
  4190. identifier == "gl_BackColor" ||
  4191. identifier == "gl_FrontSecondaryColor" ||
  4192. identifier == "gl_BackSecondaryColor" ||
  4193. identifier == "gl_SecondaryColor" ||
  4194. identifier == "gl_Color") {
  4195. symbolQualifier.flat = qualifier.flat;
  4196. symbolQualifier.smooth = qualifier.smooth;
  4197. symbolQualifier.nopersp = qualifier.nopersp;
  4198. if (qualifier.hasLayout())
  4199. error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
  4200. if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage)
  4201. error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
  4202. } else if (identifier == "gl_TexCoord" ||
  4203. identifier == "gl_ClipDistance" ||
  4204. identifier == "gl_CullDistance") {
  4205. if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() ||
  4206. qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
  4207. symbolQualifier.storage != qualifier.storage)
  4208. error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str());
  4209. } else if (identifier == "gl_FragCoord") {
  4210. if (!intermediate.getTexCoordRedeclared() && intermediate.inIoAccessed("gl_FragCoord"))
  4211. error(loc, "cannot redeclare after use", "gl_FragCoord", "");
  4212. if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
  4213. qualifier.isMemory() || qualifier.isAuxiliary())
  4214. error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
  4215. if (qualifier.storage != EvqVaryingIn)
  4216. error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str());
  4217. if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() ||
  4218. publicType.originUpperLeft != intermediate.getOriginUpperLeft()))
  4219. error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str());
  4220. intermediate.setTexCoordRedeclared();
  4221. if (publicType.pixelCenterInteger)
  4222. intermediate.setPixelCenterInteger();
  4223. if (publicType.originUpperLeft)
  4224. intermediate.setOriginUpperLeft();
  4225. } else if (identifier == "gl_FragDepth") {
  4226. if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
  4227. qualifier.isMemory() || qualifier.isAuxiliary())
  4228. error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
  4229. if (qualifier.storage != EvqVaryingOut)
  4230. error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
  4231. if (publicType.layoutDepth != EldNone) {
  4232. if (intermediate.inIoAccessed("gl_FragDepth"))
  4233. error(loc, "cannot redeclare after use", "gl_FragDepth", "");
  4234. if (! intermediate.setDepth(publicType.layoutDepth))
  4235. error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str());
  4236. }
  4237. } else if (identifier == "gl_FragStencilRefARB") {
  4238. if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
  4239. qualifier.isMemory() || qualifier.isAuxiliary())
  4240. error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
  4241. if (qualifier.storage != EvqVaryingOut)
  4242. error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
  4243. if (publicType.layoutStencil != ElsNone) {
  4244. if (intermediate.inIoAccessed("gl_FragStencilRefARB"))
  4245. error(loc, "cannot redeclare after use", "gl_FragStencilRefARB", "");
  4246. if (!intermediate.setStencil(publicType.layoutStencil))
  4247. error(loc, "all redeclarations must use the same stencil layout on", "redeclaration",
  4248. symbol->getName().c_str());
  4249. }
  4250. }
  4251. else if (
  4252. identifier == "gl_PrimitiveIndicesNV") {
  4253. if (qualifier.hasLayout())
  4254. error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
  4255. if (qualifier.storage != EvqVaryingOut)
  4256. error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
  4257. }
  4258. else if (identifier == "gl_SampleMask") {
  4259. if (!publicType.layoutOverrideCoverage) {
  4260. error(loc, "redeclaration only allowed for override_coverage layout", "redeclaration", symbol->getName().c_str());
  4261. }
  4262. intermediate.setLayoutOverrideCoverage();
  4263. }
  4264. else if (identifier == "gl_Layer") {
  4265. if (!qualifier.layoutViewportRelative && qualifier.layoutSecondaryViewportRelativeOffset == -2048)
  4266. error(loc, "redeclaration only allowed for viewport_relative or secondary_view_offset layout", "redeclaration", symbol->getName().c_str());
  4267. symbolQualifier.layoutViewportRelative = qualifier.layoutViewportRelative;
  4268. symbolQualifier.layoutSecondaryViewportRelativeOffset = qualifier.layoutSecondaryViewportRelativeOffset;
  4269. }
  4270. // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
  4271. return symbol;
  4272. }
  4273. #endif
  4274. return nullptr;
  4275. }
  4276. //
  4277. // Either redeclare the requested block, or give an error message why it can't be done.
  4278. //
  4279. // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
  4280. void TParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName,
  4281. const TString* instanceName, TArraySizes* arraySizes)
  4282. {
  4283. #ifndef GLSLANG_WEB
  4284. const char* feature = "built-in block redeclaration";
  4285. profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
  4286. profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
  4287. if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment" &&
  4288. blockName != "gl_MeshPerVertexNV" && blockName != "gl_MeshPerPrimitiveNV" &&
  4289. blockName != "gl_MeshPerVertexEXT" && blockName != "gl_MeshPerPrimitiveEXT") {
  4290. error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
  4291. return;
  4292. }
  4293. // Redeclaring a built-in block...
  4294. if (instanceName && ! builtInName(*instanceName)) {
  4295. error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
  4296. return;
  4297. }
  4298. // Blocks with instance names are easy to find, lookup the instance name,
  4299. // Anonymous blocks need to be found via a member.
  4300. bool builtIn;
  4301. TSymbol* block;
  4302. if (instanceName)
  4303. block = symbolTable.find(*instanceName, &builtIn);
  4304. else
  4305. block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
  4306. // If the block was not found, this must be a version/profile/stage
  4307. // that doesn't have it, or the instance name is wrong.
  4308. const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
  4309. if (! block) {
  4310. error(loc, "no declaration found for redeclaration", errorName, "");
  4311. return;
  4312. }
  4313. // Built-in blocks cannot be redeclared more than once, which if happened,
  4314. // we'd be finding the already redeclared one here, rather than the built in.
  4315. if (! builtIn) {
  4316. error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
  4317. return;
  4318. }
  4319. // Copy the block to make a writable version, to insert into the block table after editing.
  4320. block = symbolTable.copyUpDeferredInsert(block);
  4321. if (block->getType().getBasicType() != EbtBlock) {
  4322. error(loc, "cannot redeclare a non block as a block", errorName, "");
  4323. return;
  4324. }
  4325. // Fix XFB stuff up, it applies to the order of the redeclaration, not
  4326. // the order of the original members.
  4327. if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
  4328. if (!currentBlockQualifier.hasXfbBuffer())
  4329. currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  4330. if (!currentBlockQualifier.hasStream())
  4331. currentBlockQualifier.layoutStream = globalOutputDefaults.layoutStream;
  4332. fixXfbOffsets(currentBlockQualifier, newTypeList);
  4333. }
  4334. // Edit and error check the container against the redeclaration
  4335. // - remove unused members
  4336. // - ensure remaining qualifiers/types match
  4337. TType& type = block->getWritableType();
  4338. // if gl_PerVertex is redeclared for the purpose of passing through "gl_Position"
  4339. // for passthrough purpose, the redeclared block should have the same qualifers as
  4340. // the current one
  4341. if (currentBlockQualifier.layoutPassthrough) {
  4342. type.getQualifier().layoutPassthrough = currentBlockQualifier.layoutPassthrough;
  4343. type.getQualifier().storage = currentBlockQualifier.storage;
  4344. type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
  4345. type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
  4346. }
  4347. TTypeList::iterator member = type.getWritableStruct()->begin();
  4348. size_t numOriginalMembersFound = 0;
  4349. while (member != type.getStruct()->end()) {
  4350. // look for match
  4351. bool found = false;
  4352. TTypeList::const_iterator newMember;
  4353. TSourceLoc memberLoc;
  4354. memberLoc.init();
  4355. for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
  4356. if (member->type->getFieldName() == newMember->type->getFieldName()) {
  4357. found = true;
  4358. memberLoc = newMember->loc;
  4359. break;
  4360. }
  4361. }
  4362. if (found) {
  4363. ++numOriginalMembersFound;
  4364. // - ensure match between redeclared members' types
  4365. // - check for things that can't be changed
  4366. // - update things that can be changed
  4367. TType& oldType = *member->type;
  4368. const TType& newType = *newMember->type;
  4369. if (! newType.sameElementType(oldType))
  4370. error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
  4371. if (oldType.isArray() != newType.isArray())
  4372. error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
  4373. else if (! oldType.getQualifier().isPerView() && ! oldType.sameArrayness(newType) && oldType.isSizedArray())
  4374. error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
  4375. else if (! oldType.getQualifier().isPerView() && newType.isArray())
  4376. arrayLimitCheck(loc, member->type->getFieldName(), newType.getOuterArraySize());
  4377. if (oldType.getQualifier().isPerView() && ! newType.getQualifier().isPerView())
  4378. error(memberLoc, "missing perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
  4379. else if (! oldType.getQualifier().isPerView() && newType.getQualifier().isPerView())
  4380. error(memberLoc, "cannot add perviewNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
  4381. else if (newType.getQualifier().isPerView()) {
  4382. if (oldType.getArraySizes()->getNumDims() != newType.getArraySizes()->getNumDims())
  4383. error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
  4384. else if (! newType.isUnsizedArray() && newType.getOuterArraySize() != resources.maxMeshViewCountNV)
  4385. error(loc, "mesh view output array size must be gl_MaxMeshViewCountNV or implicitly sized", "[]", "");
  4386. else if (newType.getArraySizes()->getNumDims() == 2) {
  4387. int innerDimSize = newType.getArraySizes()->getDimSize(1);
  4388. arrayLimitCheck(memberLoc, member->type->getFieldName(), innerDimSize);
  4389. oldType.getArraySizes()->setDimSize(1, innerDimSize);
  4390. }
  4391. }
  4392. if (oldType.getQualifier().isPerPrimitive() && ! newType.getQualifier().isPerPrimitive())
  4393. error(memberLoc, "missing perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
  4394. else if (! oldType.getQualifier().isPerPrimitive() && newType.getQualifier().isPerPrimitive())
  4395. error(memberLoc, "cannot add perprimitiveNV qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
  4396. if (newType.getQualifier().isMemory())
  4397. error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
  4398. if (newType.getQualifier().hasNonXfbLayout())
  4399. error(memberLoc, "cannot add non-XFB layout to redeclared block member", member->type->getFieldName().c_str(), "");
  4400. if (newType.getQualifier().patch)
  4401. error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
  4402. if (newType.getQualifier().hasXfbBuffer() &&
  4403. newType.getQualifier().layoutXfbBuffer != currentBlockQualifier.layoutXfbBuffer)
  4404. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
  4405. if (newType.getQualifier().hasStream() &&
  4406. newType.getQualifier().layoutStream != currentBlockQualifier.layoutStream)
  4407. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_stream", "");
  4408. oldType.getQualifier().centroid = newType.getQualifier().centroid;
  4409. oldType.getQualifier().sample = newType.getQualifier().sample;
  4410. oldType.getQualifier().invariant = newType.getQualifier().invariant;
  4411. oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
  4412. oldType.getQualifier().smooth = newType.getQualifier().smooth;
  4413. oldType.getQualifier().flat = newType.getQualifier().flat;
  4414. oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
  4415. oldType.getQualifier().layoutXfbOffset = newType.getQualifier().layoutXfbOffset;
  4416. oldType.getQualifier().layoutXfbBuffer = newType.getQualifier().layoutXfbBuffer;
  4417. oldType.getQualifier().layoutXfbStride = newType.getQualifier().layoutXfbStride;
  4418. if (oldType.getQualifier().layoutXfbOffset != TQualifier::layoutXfbBufferEnd) {
  4419. // If any member has an xfb_offset, then the block's xfb_buffer inherents current xfb_buffer,
  4420. // and for xfb processing, the member needs it as well, along with xfb_stride.
  4421. type.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
  4422. oldType.getQualifier().layoutXfbBuffer = currentBlockQualifier.layoutXfbBuffer;
  4423. }
  4424. if (oldType.isUnsizedArray() && newType.isSizedArray())
  4425. oldType.changeOuterArraySize(newType.getOuterArraySize());
  4426. // check and process the member's type, which will include managing xfb information
  4427. layoutTypeCheck(loc, oldType);
  4428. // go to next member
  4429. ++member;
  4430. } else {
  4431. // For missing members of anonymous blocks that have been redeclared,
  4432. // hide the original (shared) declaration.
  4433. // Instance-named blocks can just have the member removed.
  4434. if (instanceName)
  4435. member = type.getWritableStruct()->erase(member);
  4436. else {
  4437. member->type->hideMember();
  4438. ++member;
  4439. }
  4440. }
  4441. }
  4442. if (spvVersion.vulkan > 0) {
  4443. // ...then streams apply to built-in blocks, instead of them being only on stream 0
  4444. type.getQualifier().layoutStream = currentBlockQualifier.layoutStream;
  4445. }
  4446. if (numOriginalMembersFound < newTypeList.size())
  4447. error(loc, "block redeclaration has extra members", blockName.c_str(), "");
  4448. if (type.isArray() != (arraySizes != nullptr) ||
  4449. (type.isArray() && arraySizes != nullptr && type.getArraySizes()->getNumDims() != arraySizes->getNumDims()))
  4450. error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
  4451. else if (type.isArray()) {
  4452. // At this point, we know both are arrays and both have the same number of dimensions.
  4453. // It is okay for a built-in block redeclaration to be unsized, and keep the size of the
  4454. // original block declaration.
  4455. if (!arraySizes->isSized() && type.isSizedArray())
  4456. arraySizes->changeOuterSize(type.getOuterArraySize());
  4457. // And, okay to be giving a size to the array, by the redeclaration
  4458. if (!type.isSizedArray() && arraySizes->isSized())
  4459. type.changeOuterArraySize(arraySizes->getOuterSize());
  4460. // Now, they must match in all dimensions.
  4461. if (type.isSizedArray() && *type.getArraySizes() != *arraySizes)
  4462. error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
  4463. }
  4464. symbolTable.insert(*block);
  4465. // Check for general layout qualifier errors
  4466. layoutObjectCheck(loc, *block);
  4467. // Tracking for implicit sizing of array
  4468. if (isIoResizeArray(block->getType())) {
  4469. ioArraySymbolResizeList.push_back(block);
  4470. checkIoArraysConsistency(loc, true);
  4471. } else if (block->getType().isArray())
  4472. fixIoArraySize(loc, block->getWritableType());
  4473. // Save it in the AST for linker use.
  4474. trackLinkage(*block);
  4475. #endif // GLSLANG_WEB
  4476. }
  4477. void TParseContext::paramCheckFixStorage(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type)
  4478. {
  4479. switch (qualifier) {
  4480. case EvqConst:
  4481. case EvqConstReadOnly:
  4482. type.getQualifier().storage = EvqConstReadOnly;
  4483. break;
  4484. case EvqIn:
  4485. case EvqOut:
  4486. case EvqInOut:
  4487. type.getQualifier().storage = qualifier;
  4488. break;
  4489. case EvqGlobal:
  4490. case EvqTemporary:
  4491. type.getQualifier().storage = EvqIn;
  4492. break;
  4493. default:
  4494. type.getQualifier().storage = EvqIn;
  4495. error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
  4496. break;
  4497. }
  4498. }
  4499. void TParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type)
  4500. {
  4501. #ifndef GLSLANG_WEB
  4502. if (qualifier.isMemory()) {
  4503. type.getQualifier().volatil = qualifier.volatil;
  4504. type.getQualifier().coherent = qualifier.coherent;
  4505. type.getQualifier().devicecoherent = qualifier.devicecoherent ;
  4506. type.getQualifier().queuefamilycoherent = qualifier.queuefamilycoherent;
  4507. type.getQualifier().workgroupcoherent = qualifier.workgroupcoherent;
  4508. type.getQualifier().subgroupcoherent = qualifier.subgroupcoherent;
  4509. type.getQualifier().shadercallcoherent = qualifier.shadercallcoherent;
  4510. type.getQualifier().nonprivate = qualifier.nonprivate;
  4511. type.getQualifier().readonly = qualifier.readonly;
  4512. type.getQualifier().writeonly = qualifier.writeonly;
  4513. type.getQualifier().restrict = qualifier.restrict;
  4514. }
  4515. #endif
  4516. if (qualifier.isAuxiliary() ||
  4517. qualifier.isInterpolation())
  4518. error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", "");
  4519. if (qualifier.hasLayout())
  4520. error(loc, "cannot use layout qualifiers on a function parameter", "", "");
  4521. if (qualifier.invariant)
  4522. error(loc, "cannot use invariant qualifier on a function parameter", "", "");
  4523. if (qualifier.isNoContraction()) {
  4524. if (qualifier.isParamOutput())
  4525. type.getQualifier().setNoContraction();
  4526. else
  4527. warn(loc, "qualifier has no effect on non-output parameters", "precise", "");
  4528. }
  4529. if (qualifier.isNonUniform())
  4530. type.getQualifier().nonUniform = qualifier.nonUniform;
  4531. #ifndef GLSLANG_WEB
  4532. if (qualifier.isSpirvByReference())
  4533. type.getQualifier().setSpirvByReference();
  4534. if (qualifier.isSpirvLiteral()) {
  4535. if (type.getBasicType() == EbtFloat || type.getBasicType() == EbtInt || type.getBasicType() == EbtUint ||
  4536. type.getBasicType() == EbtBool)
  4537. type.getQualifier().setSpirvLiteral();
  4538. else
  4539. error(loc, "cannot use spirv_literal qualifier", type.getBasicTypeString().c_str(), "");
  4540. #endif
  4541. }
  4542. paramCheckFixStorage(loc, qualifier.storage, type);
  4543. }
  4544. void TParseContext::nestedBlockCheck(const TSourceLoc& loc)
  4545. {
  4546. if (structNestingLevel > 0 || blockNestingLevel > 0)
  4547. error(loc, "cannot nest a block definition inside a structure or block", "", "");
  4548. ++blockNestingLevel;
  4549. }
  4550. void TParseContext::nestedStructCheck(const TSourceLoc& loc)
  4551. {
  4552. if (structNestingLevel > 0 || blockNestingLevel > 0)
  4553. error(loc, "cannot nest a structure definition inside a structure or block", "", "");
  4554. ++structNestingLevel;
  4555. }
  4556. void TParseContext::arrayObjectCheck(const TSourceLoc& loc, const TType& type, const char* op)
  4557. {
  4558. // Some versions don't allow comparing arrays or structures containing arrays
  4559. if (type.containsArray()) {
  4560. profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, op);
  4561. profileRequires(loc, EEsProfile, 300, nullptr, op);
  4562. }
  4563. }
  4564. void TParseContext::opaqueCheck(const TSourceLoc& loc, const TType& type, const char* op)
  4565. {
  4566. if (containsFieldWithBasicType(type, EbtSampler))
  4567. error(loc, "can't use with samplers or structs containing samplers", op, "");
  4568. }
  4569. void TParseContext::referenceCheck(const TSourceLoc& loc, const TType& type, const char* op)
  4570. {
  4571. #ifndef GLSLANG_WEB
  4572. if (containsFieldWithBasicType(type, EbtReference))
  4573. error(loc, "can't use with reference types", op, "");
  4574. #endif
  4575. }
  4576. void TParseContext::storage16BitAssignmentCheck(const TSourceLoc& loc, const TType& type, const char* op)
  4577. {
  4578. #ifndef GLSLANG_WEB
  4579. if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtFloat16))
  4580. requireFloat16Arithmetic(loc, op, "can't use with structs containing float16");
  4581. if (type.isArray() && type.getBasicType() == EbtFloat16)
  4582. requireFloat16Arithmetic(loc, op, "can't use with arrays containing float16");
  4583. if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt16))
  4584. requireInt16Arithmetic(loc, op, "can't use with structs containing int16");
  4585. if (type.isArray() && type.getBasicType() == EbtInt16)
  4586. requireInt16Arithmetic(loc, op, "can't use with arrays containing int16");
  4587. if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint16))
  4588. requireInt16Arithmetic(loc, op, "can't use with structs containing uint16");
  4589. if (type.isArray() && type.getBasicType() == EbtUint16)
  4590. requireInt16Arithmetic(loc, op, "can't use with arrays containing uint16");
  4591. if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtInt8))
  4592. requireInt8Arithmetic(loc, op, "can't use with structs containing int8");
  4593. if (type.isArray() && type.getBasicType() == EbtInt8)
  4594. requireInt8Arithmetic(loc, op, "can't use with arrays containing int8");
  4595. if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtUint8))
  4596. requireInt8Arithmetic(loc, op, "can't use with structs containing uint8");
  4597. if (type.isArray() && type.getBasicType() == EbtUint8)
  4598. requireInt8Arithmetic(loc, op, "can't use with arrays containing uint8");
  4599. #endif
  4600. }
  4601. void TParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
  4602. {
  4603. if (type.containsSpecializationSize())
  4604. error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
  4605. }
  4606. void TParseContext::structTypeCheck(const TSourceLoc& /*loc*/, TPublicType& publicType)
  4607. {
  4608. const TTypeList& typeList = *publicType.userDef->getStruct();
  4609. // fix and check for member storage qualifiers and types that don't belong within a structure
  4610. for (unsigned int member = 0; member < typeList.size(); ++member) {
  4611. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  4612. const TSourceLoc& memberLoc = typeList[member].loc;
  4613. if (memberQualifier.isAuxiliary() ||
  4614. memberQualifier.isInterpolation() ||
  4615. (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal))
  4616. error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
  4617. if (memberQualifier.isMemory())
  4618. error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
  4619. if (memberQualifier.hasLayout()) {
  4620. error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
  4621. memberQualifier.clearLayout();
  4622. }
  4623. if (memberQualifier.invariant)
  4624. error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
  4625. }
  4626. }
  4627. //
  4628. // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
  4629. //
  4630. // "The loop index has type int or float.
  4631. //
  4632. // "The for statement has the form:
  4633. // for ( init-declaration ; condition ; expression )
  4634. // init-declaration has the form: type-specifier identifier = constant-expression
  4635. // condition has the form: loop-index relational_operator constant-expression
  4636. // where relational_operator is one of: > >= < <= == or !=
  4637. // expression [sic] has one of the following forms:
  4638. // loop-index++
  4639. // loop-index--
  4640. // loop-index += constant-expression
  4641. // loop-index -= constant-expression
  4642. //
  4643. // The body is handled in an AST traversal.
  4644. //
  4645. void TParseContext::inductiveLoopCheck(const TSourceLoc& loc, TIntermNode* init, TIntermLoop* loop)
  4646. {
  4647. #ifndef GLSLANG_WEB
  4648. // loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration
  4649. bool badInit = false;
  4650. if (! init || ! init->getAsAggregate() || init->getAsAggregate()->getSequence().size() != 1)
  4651. badInit = true;
  4652. TIntermBinary* binaryInit = nullptr;
  4653. if (! badInit) {
  4654. // get the declaration assignment
  4655. binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
  4656. if (! binaryInit)
  4657. badInit = true;
  4658. }
  4659. if (badInit) {
  4660. error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
  4661. return;
  4662. }
  4663. // loop index must be type int or float
  4664. if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) {
  4665. error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", "");
  4666. return;
  4667. }
  4668. // init is the form "loop-index = constant"
  4669. if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) {
  4670. error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
  4671. return;
  4672. }
  4673. // get the unique id of the loop index
  4674. long long loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
  4675. inductiveLoopIds.insert(loopIndex);
  4676. // condition's form must be "loop-index relational-operator constant-expression"
  4677. bool badCond = ! loop->getTest();
  4678. if (! badCond) {
  4679. TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
  4680. badCond = ! binaryCond;
  4681. if (! badCond) {
  4682. switch (binaryCond->getOp()) {
  4683. case EOpGreaterThan:
  4684. case EOpGreaterThanEqual:
  4685. case EOpLessThan:
  4686. case EOpLessThanEqual:
  4687. case EOpEqual:
  4688. case EOpNotEqual:
  4689. break;
  4690. default:
  4691. badCond = true;
  4692. }
  4693. }
  4694. if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
  4695. binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
  4696. ! binaryCond->getRight()->getAsConstantUnion()))
  4697. badCond = true;
  4698. }
  4699. if (badCond) {
  4700. error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
  4701. return;
  4702. }
  4703. // loop-index++
  4704. // loop-index--
  4705. // loop-index += constant-expression
  4706. // loop-index -= constant-expression
  4707. bool badTerminal = ! loop->getTerminal();
  4708. if (! badTerminal) {
  4709. TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode();
  4710. TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode();
  4711. if (unaryTerminal || binaryTerminal) {
  4712. switch(loop->getTerminal()->getAsOperator()->getOp()) {
  4713. case EOpPostDecrement:
  4714. case EOpPostIncrement:
  4715. case EOpAddAssign:
  4716. case EOpSubAssign:
  4717. break;
  4718. default:
  4719. badTerminal = true;
  4720. }
  4721. } else
  4722. badTerminal = true;
  4723. if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
  4724. binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
  4725. ! binaryTerminal->getRight()->getAsConstantUnion()))
  4726. badTerminal = true;
  4727. if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
  4728. unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
  4729. badTerminal = true;
  4730. }
  4731. if (badTerminal) {
  4732. error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
  4733. return;
  4734. }
  4735. // the body
  4736. inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
  4737. #endif
  4738. }
  4739. #ifndef GLSLANG_WEB
  4740. // Do limit checks for built-in arrays.
  4741. void TParseContext::arrayLimitCheck(const TSourceLoc& loc, const TString& identifier, int size)
  4742. {
  4743. if (identifier.compare("gl_TexCoord") == 0)
  4744. limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size");
  4745. else if (identifier.compare("gl_ClipDistance") == 0)
  4746. limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size");
  4747. else if (identifier.compare("gl_CullDistance") == 0)
  4748. limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistance array size");
  4749. else if (identifier.compare("gl_ClipDistancePerViewNV") == 0)
  4750. limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistancePerViewNV array size");
  4751. else if (identifier.compare("gl_CullDistancePerViewNV") == 0)
  4752. limitCheck(loc, size, "gl_MaxCullDistances", "gl_CullDistancePerViewNV array size");
  4753. }
  4754. #endif // GLSLANG_WEB
  4755. // See if the provided value is less than or equal to the symbol indicated by limit,
  4756. // which should be a constant in the symbol table.
  4757. void TParseContext::limitCheck(const TSourceLoc& loc, int value, const char* limit, const char* feature)
  4758. {
  4759. TSymbol* symbol = symbolTable.find(limit);
  4760. assert(symbol->getAsVariable());
  4761. const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray();
  4762. assert(! constArray.empty());
  4763. if (value > constArray[0].getIConst())
  4764. error(loc, "must be less than or equal to", feature, "%s (%d)", limit, constArray[0].getIConst());
  4765. }
  4766. #ifndef GLSLANG_WEB
  4767. //
  4768. // Do any additional error checking, etc., once we know the parsing is done.
  4769. //
  4770. void TParseContext::finish()
  4771. {
  4772. TParseContextBase::finish();
  4773. if (parsingBuiltins)
  4774. return;
  4775. // Check on array indexes for ES 2.0 (version 100) limitations.
  4776. for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i)
  4777. constantIndexExpressionCheck(needsIndexLimitationChecking[i]);
  4778. // Check for stages that are enabled by extension.
  4779. // Can't do this at the beginning, it is chicken and egg to add a stage by
  4780. // extension.
  4781. // Stage-specific features were correctly tested for already, this is just
  4782. // about the stage itself.
  4783. switch (language) {
  4784. case EShLangGeometry:
  4785. if (isEsProfile() && version == 310)
  4786. requireExtensions(getCurrentLoc(), Num_AEP_geometry_shader, AEP_geometry_shader, "geometry shaders");
  4787. break;
  4788. case EShLangTessControl:
  4789. case EShLangTessEvaluation:
  4790. if (isEsProfile() && version == 310)
  4791. requireExtensions(getCurrentLoc(), Num_AEP_tessellation_shader, AEP_tessellation_shader, "tessellation shaders");
  4792. else if (!isEsProfile() && version < 400)
  4793. requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_tessellation_shader, "tessellation shaders");
  4794. break;
  4795. case EShLangCompute:
  4796. if (!isEsProfile() && version < 430)
  4797. requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_compute_shader, "compute shaders");
  4798. break;
  4799. case EShLangTask:
  4800. requireExtensions(getCurrentLoc(), Num_AEP_mesh_shader, AEP_mesh_shader, "task shaders");
  4801. break;
  4802. case EShLangMesh:
  4803. requireExtensions(getCurrentLoc(), Num_AEP_mesh_shader, AEP_mesh_shader, "mesh shaders");
  4804. break;
  4805. default:
  4806. break;
  4807. }
  4808. // Set default outputs for GL_NV_geometry_shader_passthrough
  4809. if (language == EShLangGeometry && extensionTurnedOn(E_SPV_NV_geometry_shader_passthrough)) {
  4810. if (intermediate.getOutputPrimitive() == ElgNone) {
  4811. switch (intermediate.getInputPrimitive()) {
  4812. case ElgPoints: intermediate.setOutputPrimitive(ElgPoints); break;
  4813. case ElgLines: intermediate.setOutputPrimitive(ElgLineStrip); break;
  4814. case ElgTriangles: intermediate.setOutputPrimitive(ElgTriangleStrip); break;
  4815. default: break;
  4816. }
  4817. }
  4818. if (intermediate.getVertices() == TQualifier::layoutNotSet) {
  4819. switch (intermediate.getInputPrimitive()) {
  4820. case ElgPoints: intermediate.setVertices(1); break;
  4821. case ElgLines: intermediate.setVertices(2); break;
  4822. case ElgTriangles: intermediate.setVertices(3); break;
  4823. default: break;
  4824. }
  4825. }
  4826. }
  4827. }
  4828. #endif // GLSLANG_WEB
  4829. //
  4830. // Layout qualifier stuff.
  4831. //
  4832. // Put the id's layout qualification into the public type, for qualifiers not having a number set.
  4833. // This is before we know any type information for error checking.
  4834. void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id)
  4835. {
  4836. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  4837. if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
  4838. publicType.qualifier.layoutMatrix = ElmColumnMajor;
  4839. return;
  4840. }
  4841. if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
  4842. publicType.qualifier.layoutMatrix = ElmRowMajor;
  4843. return;
  4844. }
  4845. if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
  4846. if (spvVersion.spv != 0) {
  4847. if (spvVersion.vulkanRelaxed)
  4848. return; // silently ignore qualifier
  4849. else
  4850. spvRemoved(loc, "packed");
  4851. }
  4852. publicType.qualifier.layoutPacking = ElpPacked;
  4853. return;
  4854. }
  4855. if (id == TQualifier::getLayoutPackingString(ElpShared)) {
  4856. if (spvVersion.spv != 0) {
  4857. if (spvVersion.vulkanRelaxed)
  4858. return; // silently ignore qualifier
  4859. else
  4860. spvRemoved(loc, "shared");
  4861. }
  4862. publicType.qualifier.layoutPacking = ElpShared;
  4863. return;
  4864. }
  4865. if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
  4866. publicType.qualifier.layoutPacking = ElpStd140;
  4867. return;
  4868. }
  4869. #ifndef GLSLANG_WEB
  4870. if (id == TQualifier::getLayoutPackingString(ElpStd430)) {
  4871. requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430");
  4872. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "std430");
  4873. profileRequires(loc, EEsProfile, 310, nullptr, "std430");
  4874. publicType.qualifier.layoutPacking = ElpStd430;
  4875. return;
  4876. }
  4877. if (id == TQualifier::getLayoutPackingString(ElpScalar)) {
  4878. requireVulkan(loc, "scalar");
  4879. requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "scalar block layout");
  4880. publicType.qualifier.layoutPacking = ElpScalar;
  4881. return;
  4882. }
  4883. // TODO: compile-time performance: may need to stop doing linear searches
  4884. for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) {
  4885. if (id == TQualifier::getLayoutFormatString(format)) {
  4886. if ((format > ElfEsFloatGuard && format < ElfFloatGuard) ||
  4887. (format > ElfEsIntGuard && format < ElfIntGuard) ||
  4888. (format > ElfEsUintGuard && format < ElfCount))
  4889. requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format");
  4890. profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "image load store");
  4891. profileRequires(loc, EEsProfile, 310, E_GL_ARB_shader_image_load_store, "image load store");
  4892. publicType.qualifier.layoutFormat = format;
  4893. return;
  4894. }
  4895. }
  4896. if (id == "push_constant") {
  4897. requireVulkan(loc, "push_constant");
  4898. publicType.qualifier.layoutPushConstant = true;
  4899. return;
  4900. }
  4901. if (id == "buffer_reference") {
  4902. requireVulkan(loc, "buffer_reference");
  4903. requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference");
  4904. publicType.qualifier.layoutBufferReference = true;
  4905. intermediate.setUseStorageBuffer();
  4906. intermediate.setUsePhysicalStorageBuffer();
  4907. return;
  4908. }
  4909. if (language == EShLangGeometry || language == EShLangTessEvaluation || language == EShLangMesh) {
  4910. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  4911. publicType.shaderQualifiers.geometry = ElgTriangles;
  4912. return;
  4913. }
  4914. if (language == EShLangGeometry || language == EShLangMesh) {
  4915. if (id == TQualifier::getGeometryString(ElgPoints)) {
  4916. publicType.shaderQualifiers.geometry = ElgPoints;
  4917. return;
  4918. }
  4919. if (id == TQualifier::getGeometryString(ElgLines)) {
  4920. publicType.shaderQualifiers.geometry = ElgLines;
  4921. return;
  4922. }
  4923. if (language == EShLangGeometry) {
  4924. if (id == TQualifier::getGeometryString(ElgLineStrip)) {
  4925. publicType.shaderQualifiers.geometry = ElgLineStrip;
  4926. return;
  4927. }
  4928. if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
  4929. publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
  4930. return;
  4931. }
  4932. if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
  4933. publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
  4934. return;
  4935. }
  4936. if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
  4937. publicType.shaderQualifiers.geometry = ElgTriangleStrip;
  4938. return;
  4939. }
  4940. if (id == "passthrough") {
  4941. requireExtensions(loc, 1, &E_SPV_NV_geometry_shader_passthrough, "geometry shader passthrough");
  4942. publicType.qualifier.layoutPassthrough = true;
  4943. intermediate.setGeoPassthroughEXT();
  4944. return;
  4945. }
  4946. }
  4947. } else {
  4948. assert(language == EShLangTessEvaluation);
  4949. // input primitive
  4950. if (id == TQualifier::getGeometryString(ElgTriangles)) {
  4951. publicType.shaderQualifiers.geometry = ElgTriangles;
  4952. return;
  4953. }
  4954. if (id == TQualifier::getGeometryString(ElgQuads)) {
  4955. publicType.shaderQualifiers.geometry = ElgQuads;
  4956. return;
  4957. }
  4958. if (id == TQualifier::getGeometryString(ElgIsolines)) {
  4959. publicType.shaderQualifiers.geometry = ElgIsolines;
  4960. return;
  4961. }
  4962. // vertex spacing
  4963. if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
  4964. publicType.shaderQualifiers.spacing = EvsEqual;
  4965. return;
  4966. }
  4967. if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
  4968. publicType.shaderQualifiers.spacing = EvsFractionalEven;
  4969. return;
  4970. }
  4971. if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
  4972. publicType.shaderQualifiers.spacing = EvsFractionalOdd;
  4973. return;
  4974. }
  4975. // triangle order
  4976. if (id == TQualifier::getVertexOrderString(EvoCw)) {
  4977. publicType.shaderQualifiers.order = EvoCw;
  4978. return;
  4979. }
  4980. if (id == TQualifier::getVertexOrderString(EvoCcw)) {
  4981. publicType.shaderQualifiers.order = EvoCcw;
  4982. return;
  4983. }
  4984. // point mode
  4985. if (id == "point_mode") {
  4986. publicType.shaderQualifiers.pointMode = true;
  4987. return;
  4988. }
  4989. }
  4990. }
  4991. if (language == EShLangFragment) {
  4992. if (id == "origin_upper_left") {
  4993. requireProfile(loc, ECoreProfile | ECompatibilityProfile | ENoProfile, "origin_upper_left");
  4994. if (profile == ENoProfile) {
  4995. profileRequires(loc,ECoreProfile | ECompatibilityProfile, 140, E_GL_ARB_fragment_coord_conventions, "origin_upper_left");
  4996. }
  4997. publicType.shaderQualifiers.originUpperLeft = true;
  4998. return;
  4999. }
  5000. if (id == "pixel_center_integer") {
  5001. requireProfile(loc, ECoreProfile | ECompatibilityProfile | ENoProfile, "pixel_center_integer");
  5002. if (profile == ENoProfile) {
  5003. profileRequires(loc,ECoreProfile | ECompatibilityProfile, 140, E_GL_ARB_fragment_coord_conventions, "pixel_center_integer");
  5004. }
  5005. publicType.shaderQualifiers.pixelCenterInteger = true;
  5006. return;
  5007. }
  5008. if (id == "early_fragment_tests") {
  5009. profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "early_fragment_tests");
  5010. profileRequires(loc, EEsProfile, 310, nullptr, "early_fragment_tests");
  5011. publicType.shaderQualifiers.earlyFragmentTests = true;
  5012. return;
  5013. }
  5014. if (id == "early_and_late_fragment_tests_amd") {
  5015. profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_AMD_shader_early_and_late_fragment_tests, "early_and_late_fragment_tests_amd");
  5016. profileRequires(loc, EEsProfile, 310, nullptr, "early_and_late_fragment_tests_amd");
  5017. publicType.shaderQualifiers.earlyAndLateFragmentTestsAMD = true;
  5018. return;
  5019. }
  5020. if (id == "post_depth_coverage") {
  5021. requireExtensions(loc, Num_post_depth_coverageEXTs, post_depth_coverageEXTs, "post depth coverage");
  5022. if (extensionTurnedOn(E_GL_ARB_post_depth_coverage)) {
  5023. publicType.shaderQualifiers.earlyFragmentTests = true;
  5024. }
  5025. publicType.shaderQualifiers.postDepthCoverage = true;
  5026. return;
  5027. }
  5028. for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) {
  5029. if (id == TQualifier::getLayoutDepthString(depth)) {
  5030. requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier");
  5031. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "depth layout qualifier");
  5032. publicType.shaderQualifiers.layoutDepth = depth;
  5033. return;
  5034. }
  5035. }
  5036. for (TLayoutStencil stencil = (TLayoutStencil)(ElsNone + 1); stencil < ElsCount; stencil = (TLayoutStencil)(stencil+1)) {
  5037. if (id == TQualifier::getLayoutStencilString(stencil)) {
  5038. requireProfile(loc, ECoreProfile | ECompatibilityProfile, "stencil layout qualifier");
  5039. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "stencil layout qualifier");
  5040. publicType.shaderQualifiers.layoutStencil = stencil;
  5041. return;
  5042. }
  5043. }
  5044. for (TInterlockOrdering order = (TInterlockOrdering)(EioNone + 1); order < EioCount; order = (TInterlockOrdering)(order+1)) {
  5045. if (id == TQualifier::getInterlockOrderingString(order)) {
  5046. requireProfile(loc, ECoreProfile | ECompatibilityProfile, "fragment shader interlock layout qualifier");
  5047. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 450, nullptr, "fragment shader interlock layout qualifier");
  5048. requireExtensions(loc, 1, &E_GL_ARB_fragment_shader_interlock, TQualifier::getInterlockOrderingString(order));
  5049. if (order == EioShadingRateInterlockOrdered || order == EioShadingRateInterlockUnordered)
  5050. requireExtensions(loc, 1, &E_GL_NV_shading_rate_image, TQualifier::getInterlockOrderingString(order));
  5051. publicType.shaderQualifiers.interlockOrdering = order;
  5052. return;
  5053. }
  5054. }
  5055. if (id.compare(0, 13, "blend_support") == 0) {
  5056. bool found = false;
  5057. for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
  5058. if (id == TQualifier::getBlendEquationString(be)) {
  5059. profileRequires(loc, EEsProfile, 320, E_GL_KHR_blend_equation_advanced, "blend equation");
  5060. profileRequires(loc, ~EEsProfile, 0, E_GL_KHR_blend_equation_advanced, "blend equation");
  5061. intermediate.addBlendEquation(be);
  5062. publicType.shaderQualifiers.blendEquation = true;
  5063. found = true;
  5064. break;
  5065. }
  5066. }
  5067. if (! found)
  5068. error(loc, "unknown blend equation", "blend_support", "");
  5069. return;
  5070. }
  5071. if (id == "override_coverage") {
  5072. requireExtensions(loc, 1, &E_GL_NV_sample_mask_override_coverage, "sample mask override coverage");
  5073. publicType.shaderQualifiers.layoutOverrideCoverage = true;
  5074. return;
  5075. }
  5076. }
  5077. if (language == EShLangVertex ||
  5078. language == EShLangTessControl ||
  5079. language == EShLangTessEvaluation ||
  5080. language == EShLangGeometry ) {
  5081. if (id == "viewport_relative") {
  5082. requireExtensions(loc, 1, &E_GL_NV_viewport_array2, "view port array2");
  5083. publicType.qualifier.layoutViewportRelative = true;
  5084. return;
  5085. }
  5086. } else {
  5087. if (language == EShLangRayGen || language == EShLangIntersect ||
  5088. language == EShLangAnyHit || language == EShLangClosestHit ||
  5089. language == EShLangMiss || language == EShLangCallable) {
  5090. if (id == "shaderrecordnv" || id == "shaderrecordext") {
  5091. if (id == "shaderrecordnv") {
  5092. requireExtensions(loc, 1, &E_GL_NV_ray_tracing, "shader record NV");
  5093. } else {
  5094. requireExtensions(loc, 1, &E_GL_EXT_ray_tracing, "shader record EXT");
  5095. }
  5096. publicType.qualifier.layoutShaderRecord = true;
  5097. return;
  5098. }
  5099. }
  5100. }
  5101. if (language == EShLangCompute) {
  5102. if (id.compare(0, 17, "derivative_group_") == 0) {
  5103. requireExtensions(loc, 1, &E_GL_NV_compute_shader_derivatives, "compute shader derivatives");
  5104. if (id == "derivative_group_quadsnv") {
  5105. publicType.shaderQualifiers.layoutDerivativeGroupQuads = true;
  5106. return;
  5107. } else if (id == "derivative_group_linearnv") {
  5108. publicType.shaderQualifiers.layoutDerivativeGroupLinear = true;
  5109. return;
  5110. }
  5111. }
  5112. }
  5113. if (id == "primitive_culling") {
  5114. requireExtensions(loc, 1, &E_GL_EXT_ray_flags_primitive_culling, "primitive culling");
  5115. publicType.shaderQualifiers.layoutPrimitiveCulling = true;
  5116. return;
  5117. }
  5118. #endif
  5119. error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
  5120. }
  5121. // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
  5122. // This is before we know any type information for error checking.
  5123. void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
  5124. {
  5125. const char* feature = "layout-id value";
  5126. const char* nonLiteralFeature = "non-literal layout-id value";
  5127. integerCheck(node, feature);
  5128. const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
  5129. int value;
  5130. bool nonLiteral = false;
  5131. if (constUnion) {
  5132. value = constUnion->getConstArray()[0].getIConst();
  5133. if (! constUnion->isLiteral()) {
  5134. requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature);
  5135. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, nonLiteralFeature);
  5136. }
  5137. } else {
  5138. // grammar should have give out the error message
  5139. value = 0;
  5140. nonLiteral = true;
  5141. }
  5142. if (value < 0) {
  5143. error(loc, "cannot be negative", feature, "");
  5144. return;
  5145. }
  5146. std::transform(id.begin(), id.end(), id.begin(), ::tolower);
  5147. if (id == "offset") {
  5148. // "offset" can be for either
  5149. // - uniform offsets
  5150. // - atomic_uint offsets
  5151. const char* feature = "offset";
  5152. if (spvVersion.spv == 0) {
  5153. requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
  5154. const char* exts[2] = { E_GL_ARB_enhanced_layouts, E_GL_ARB_shader_atomic_counters };
  5155. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature);
  5156. profileRequires(loc, EEsProfile, 310, nullptr, feature);
  5157. }
  5158. publicType.qualifier.layoutOffset = value;
  5159. publicType.qualifier.explicitOffset = true;
  5160. if (nonLiteral)
  5161. error(loc, "needs a literal integer", "offset", "");
  5162. return;
  5163. } else if (id == "align") {
  5164. const char* feature = "uniform buffer-member align";
  5165. if (spvVersion.spv == 0) {
  5166. requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
  5167. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
  5168. }
  5169. // "The specified alignment must be a power of 2, or a compile-time error results."
  5170. if (! IsPow2(value))
  5171. error(loc, "must be a power of 2", "align", "");
  5172. else
  5173. publicType.qualifier.layoutAlign = value;
  5174. if (nonLiteral)
  5175. error(loc, "needs a literal integer", "align", "");
  5176. return;
  5177. } else if (id == "location") {
  5178. profileRequires(loc, EEsProfile, 300, nullptr, "location");
  5179. const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
  5180. // GL_ARB_explicit_uniform_location requires 330 or GL_ARB_explicit_attrib_location we do not need to add it here
  5181. profileRequires(loc, ~EEsProfile, 330, 2, exts, "location");
  5182. if ((unsigned int)value >= TQualifier::layoutLocationEnd)
  5183. error(loc, "location is too large", id.c_str(), "");
  5184. else
  5185. publicType.qualifier.layoutLocation = value;
  5186. if (nonLiteral)
  5187. error(loc, "needs a literal integer", "location", "");
  5188. return;
  5189. } else if (id == "set") {
  5190. if ((unsigned int)value >= TQualifier::layoutSetEnd)
  5191. error(loc, "set is too large", id.c_str(), "");
  5192. else
  5193. publicType.qualifier.layoutSet = value;
  5194. if (value != 0)
  5195. requireVulkan(loc, "descriptor set");
  5196. if (nonLiteral)
  5197. error(loc, "needs a literal integer", "set", "");
  5198. return;
  5199. } else if (id == "binding") {
  5200. #ifndef GLSLANG_WEB
  5201. profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, "binding");
  5202. profileRequires(loc, EEsProfile, 310, nullptr, "binding");
  5203. #endif
  5204. if ((unsigned int)value >= TQualifier::layoutBindingEnd)
  5205. error(loc, "binding is too large", id.c_str(), "");
  5206. else
  5207. publicType.qualifier.layoutBinding = value;
  5208. if (nonLiteral)
  5209. error(loc, "needs a literal integer", "binding", "");
  5210. return;
  5211. }
  5212. if (id == "constant_id") {
  5213. requireSpv(loc, "constant_id");
  5214. if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
  5215. error(loc, "specialization-constant id is too large", id.c_str(), "");
  5216. } else {
  5217. publicType.qualifier.layoutSpecConstantId = value;
  5218. publicType.qualifier.specConstant = true;
  5219. if (! intermediate.addUsedConstantId(value))
  5220. error(loc, "specialization-constant id already used", id.c_str(), "");
  5221. }
  5222. if (nonLiteral)
  5223. error(loc, "needs a literal integer", "constant_id", "");
  5224. return;
  5225. }
  5226. #ifndef GLSLANG_WEB
  5227. if (id == "component") {
  5228. requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component");
  5229. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "component");
  5230. if ((unsigned)value >= TQualifier::layoutComponentEnd)
  5231. error(loc, "component is too large", id.c_str(), "");
  5232. else
  5233. publicType.qualifier.layoutComponent = value;
  5234. if (nonLiteral)
  5235. error(loc, "needs a literal integer", "component", "");
  5236. return;
  5237. }
  5238. if (id.compare(0, 4, "xfb_") == 0) {
  5239. // "Any shader making any static use (after preprocessing) of any of these
  5240. // *xfb_* qualifiers will cause the shader to be in a transform feedback
  5241. // capturing mode and hence responsible for describing the transform feedback
  5242. // setup."
  5243. intermediate.setXfbMode();
  5244. const char* feature = "transform feedback qualifier";
  5245. requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature);
  5246. requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
  5247. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
  5248. if (id == "xfb_buffer") {
  5249. // "It is a compile-time error to specify an *xfb_buffer* that is greater than
  5250. // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
  5251. if (value >= resources.maxTransformFeedbackBuffers)
  5252. error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
  5253. if (value >= (int)TQualifier::layoutXfbBufferEnd)
  5254. error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1);
  5255. else
  5256. publicType.qualifier.layoutXfbBuffer = value;
  5257. if (nonLiteral)
  5258. error(loc, "needs a literal integer", "xfb_buffer", "");
  5259. return;
  5260. } else if (id == "xfb_offset") {
  5261. if (value >= (int)TQualifier::layoutXfbOffsetEnd)
  5262. error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1);
  5263. else
  5264. publicType.qualifier.layoutXfbOffset = value;
  5265. if (nonLiteral)
  5266. error(loc, "needs a literal integer", "xfb_offset", "");
  5267. return;
  5268. } else if (id == "xfb_stride") {
  5269. // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
  5270. // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
  5271. if (value > 4 * resources.maxTransformFeedbackInterleavedComponents) {
  5272. error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d",
  5273. resources.maxTransformFeedbackInterleavedComponents);
  5274. }
  5275. if (value >= (int)TQualifier::layoutXfbStrideEnd)
  5276. error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1);
  5277. else
  5278. publicType.qualifier.layoutXfbStride = value;
  5279. if (nonLiteral)
  5280. error(loc, "needs a literal integer", "xfb_stride", "");
  5281. return;
  5282. }
  5283. }
  5284. if (id == "input_attachment_index") {
  5285. requireVulkan(loc, "input_attachment_index");
  5286. if (value >= (int)TQualifier::layoutAttachmentEnd)
  5287. error(loc, "attachment index is too large", id.c_str(), "");
  5288. else
  5289. publicType.qualifier.layoutAttachment = value;
  5290. if (nonLiteral)
  5291. error(loc, "needs a literal integer", "input_attachment_index", "");
  5292. return;
  5293. }
  5294. if (id == "num_views") {
  5295. requireExtensions(loc, Num_OVR_multiview_EXTs, OVR_multiview_EXTs, "num_views");
  5296. publicType.shaderQualifiers.numViews = value;
  5297. if (nonLiteral)
  5298. error(loc, "needs a literal integer", "num_views", "");
  5299. return;
  5300. }
  5301. if (language == EShLangVertex ||
  5302. language == EShLangTessControl ||
  5303. language == EShLangTessEvaluation ||
  5304. language == EShLangGeometry) {
  5305. if (id == "secondary_view_offset") {
  5306. requireExtensions(loc, 1, &E_GL_NV_stereo_view_rendering, "stereo view rendering");
  5307. publicType.qualifier.layoutSecondaryViewportRelativeOffset = value;
  5308. if (nonLiteral)
  5309. error(loc, "needs a literal integer", "secondary_view_offset", "");
  5310. return;
  5311. }
  5312. }
  5313. if (id == "buffer_reference_align") {
  5314. requireExtensions(loc, 1, &E_GL_EXT_buffer_reference, "buffer_reference_align");
  5315. if (! IsPow2(value))
  5316. error(loc, "must be a power of 2", "buffer_reference_align", "");
  5317. else
  5318. publicType.qualifier.layoutBufferReferenceAlign = IntLog2(value);
  5319. if (nonLiteral)
  5320. error(loc, "needs a literal integer", "buffer_reference_align", "");
  5321. return;
  5322. }
  5323. #endif
  5324. switch (language) {
  5325. #ifndef GLSLANG_WEB
  5326. case EShLangTessControl:
  5327. if (id == "vertices") {
  5328. if (value == 0)
  5329. error(loc, "must be greater than 0", "vertices", "");
  5330. else
  5331. publicType.shaderQualifiers.vertices = value;
  5332. if (nonLiteral)
  5333. error(loc, "needs a literal integer", "vertices", "");
  5334. return;
  5335. }
  5336. break;
  5337. case EShLangGeometry:
  5338. if (id == "invocations") {
  5339. profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, nullptr, "invocations");
  5340. if (value == 0)
  5341. error(loc, "must be at least 1", "invocations", "");
  5342. else
  5343. publicType.shaderQualifiers.invocations = value;
  5344. if (nonLiteral)
  5345. error(loc, "needs a literal integer", "invocations", "");
  5346. return;
  5347. }
  5348. if (id == "max_vertices") {
  5349. publicType.shaderQualifiers.vertices = value;
  5350. if (value > resources.maxGeometryOutputVertices)
  5351. error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
  5352. if (nonLiteral)
  5353. error(loc, "needs a literal integer", "max_vertices", "");
  5354. return;
  5355. }
  5356. if (id == "stream") {
  5357. requireProfile(loc, ~EEsProfile, "selecting output stream");
  5358. publicType.qualifier.layoutStream = value;
  5359. if (value > 0)
  5360. intermediate.setMultiStream();
  5361. if (nonLiteral)
  5362. error(loc, "needs a literal integer", "stream", "");
  5363. return;
  5364. }
  5365. break;
  5366. case EShLangFragment:
  5367. if (id == "index") {
  5368. requireProfile(loc, ECompatibilityProfile | ECoreProfile | EEsProfile, "index layout qualifier on fragment output");
  5369. const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
  5370. profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output");
  5371. profileRequires(loc, EEsProfile ,310, E_GL_EXT_blend_func_extended, "index layout qualifier on fragment output");
  5372. // "It is also a compile-time error if a fragment shader sets a layout index to less than 0 or greater than 1."
  5373. if (value < 0 || value > 1) {
  5374. value = 0;
  5375. error(loc, "value must be 0 or 1", "index", "");
  5376. }
  5377. publicType.qualifier.layoutIndex = value;
  5378. if (nonLiteral)
  5379. error(loc, "needs a literal integer", "index", "");
  5380. return;
  5381. }
  5382. break;
  5383. case EShLangMesh:
  5384. if (id == "max_vertices") {
  5385. requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "max_vertices");
  5386. publicType.shaderQualifiers.vertices = value;
  5387. int max = extensionTurnedOn(E_GL_EXT_mesh_shader) ? resources.maxMeshOutputVerticesEXT
  5388. : resources.maxMeshOutputVerticesNV;
  5389. if (value > max) {
  5390. TString maxsErrtring = "too large, must be less than ";
  5391. maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ? "gl_MaxMeshOutputVerticesEXT"
  5392. : "gl_MaxMeshOutputVerticesNV");
  5393. error(loc, maxsErrtring.c_str(), "max_vertices", "");
  5394. }
  5395. if (nonLiteral)
  5396. error(loc, "needs a literal integer", "max_vertices", "");
  5397. return;
  5398. }
  5399. if (id == "max_primitives") {
  5400. requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "max_primitives");
  5401. publicType.shaderQualifiers.primitives = value;
  5402. int max = extensionTurnedOn(E_GL_EXT_mesh_shader) ? resources.maxMeshOutputPrimitivesEXT
  5403. : resources.maxMeshOutputPrimitivesNV;
  5404. if (value > max) {
  5405. TString maxsErrtring = "too large, must be less than ";
  5406. maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ? "gl_MaxMeshOutputPrimitivesEXT"
  5407. : "gl_MaxMeshOutputPrimitivesNV");
  5408. error(loc, maxsErrtring.c_str(), "max_primitives", "");
  5409. }
  5410. if (nonLiteral)
  5411. error(loc, "needs a literal integer", "max_primitives", "");
  5412. return;
  5413. }
  5414. // Fall through
  5415. case EShLangTask:
  5416. // Fall through
  5417. #endif
  5418. case EShLangCompute:
  5419. if (id.compare(0, 11, "local_size_") == 0) {
  5420. #ifndef GLSLANG_WEB
  5421. if (language == EShLangMesh || language == EShLangTask) {
  5422. requireExtensions(loc, Num_AEP_mesh_shader, AEP_mesh_shader, "gl_WorkGroupSize");
  5423. } else {
  5424. profileRequires(loc, EEsProfile, 310, nullptr, "gl_WorkGroupSize");
  5425. profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_compute_shader, "gl_WorkGroupSize");
  5426. }
  5427. #endif
  5428. if (nonLiteral)
  5429. error(loc, "needs a literal integer", "local_size", "");
  5430. if (id.size() == 12 && value == 0) {
  5431. error(loc, "must be at least 1", id.c_str(), "");
  5432. return;
  5433. }
  5434. if (id == "local_size_x") {
  5435. publicType.shaderQualifiers.localSize[0] = value;
  5436. publicType.shaderQualifiers.localSizeNotDefault[0] = true;
  5437. return;
  5438. }
  5439. if (id == "local_size_y") {
  5440. publicType.shaderQualifiers.localSize[1] = value;
  5441. publicType.shaderQualifiers.localSizeNotDefault[1] = true;
  5442. return;
  5443. }
  5444. if (id == "local_size_z") {
  5445. publicType.shaderQualifiers.localSize[2] = value;
  5446. publicType.shaderQualifiers.localSizeNotDefault[2] = true;
  5447. return;
  5448. }
  5449. if (spvVersion.spv != 0) {
  5450. if (id == "local_size_x_id") {
  5451. publicType.shaderQualifiers.localSizeSpecId[0] = value;
  5452. return;
  5453. }
  5454. if (id == "local_size_y_id") {
  5455. publicType.shaderQualifiers.localSizeSpecId[1] = value;
  5456. return;
  5457. }
  5458. if (id == "local_size_z_id") {
  5459. publicType.shaderQualifiers.localSizeSpecId[2] = value;
  5460. return;
  5461. }
  5462. }
  5463. }
  5464. break;
  5465. default:
  5466. break;
  5467. }
  5468. error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
  5469. }
  5470. // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
  5471. //
  5472. // "More than one layout qualifier may appear in a single declaration.
  5473. // Additionally, the same layout-qualifier-name can occur multiple times
  5474. // within a layout qualifier or across multiple layout qualifiers in the
  5475. // same declaration. When the same layout-qualifier-name occurs
  5476. // multiple times, in a single declaration, the last occurrence overrides
  5477. // the former occurrence(s). Further, if such a layout-qualifier-name
  5478. // will effect subsequent declarations or other observable behavior, it
  5479. // is only the last occurrence that will have any effect, behaving as if
  5480. // the earlier occurrence(s) within the declaration are not present.
  5481. // This is also true for overriding layout-qualifier-names, where one
  5482. // overrides the other (e.g., row_major vs. column_major); only the last
  5483. // occurrence has any effect."
  5484. void TParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
  5485. {
  5486. if (src.hasMatrix())
  5487. dst.layoutMatrix = src.layoutMatrix;
  5488. if (src.hasPacking())
  5489. dst.layoutPacking = src.layoutPacking;
  5490. #ifndef GLSLANG_WEB
  5491. if (src.hasStream())
  5492. dst.layoutStream = src.layoutStream;
  5493. if (src.hasFormat())
  5494. dst.layoutFormat = src.layoutFormat;
  5495. if (src.hasXfbBuffer())
  5496. dst.layoutXfbBuffer = src.layoutXfbBuffer;
  5497. if (src.hasBufferReferenceAlign())
  5498. dst.layoutBufferReferenceAlign = src.layoutBufferReferenceAlign;
  5499. #endif
  5500. if (src.hasAlign())
  5501. dst.layoutAlign = src.layoutAlign;
  5502. if (! inheritOnly) {
  5503. if (src.hasLocation())
  5504. dst.layoutLocation = src.layoutLocation;
  5505. if (src.hasOffset())
  5506. dst.layoutOffset = src.layoutOffset;
  5507. if (src.hasSet())
  5508. dst.layoutSet = src.layoutSet;
  5509. if (src.layoutBinding != TQualifier::layoutBindingEnd)
  5510. dst.layoutBinding = src.layoutBinding;
  5511. if (src.hasSpecConstantId())
  5512. dst.layoutSpecConstantId = src.layoutSpecConstantId;
  5513. #ifndef GLSLANG_WEB
  5514. if (src.hasComponent())
  5515. dst.layoutComponent = src.layoutComponent;
  5516. if (src.hasIndex())
  5517. dst.layoutIndex = src.layoutIndex;
  5518. if (src.hasXfbStride())
  5519. dst.layoutXfbStride = src.layoutXfbStride;
  5520. if (src.hasXfbOffset())
  5521. dst.layoutXfbOffset = src.layoutXfbOffset;
  5522. if (src.hasAttachment())
  5523. dst.layoutAttachment = src.layoutAttachment;
  5524. if (src.layoutPushConstant)
  5525. dst.layoutPushConstant = true;
  5526. if (src.layoutBufferReference)
  5527. dst.layoutBufferReference = true;
  5528. if (src.layoutPassthrough)
  5529. dst.layoutPassthrough = true;
  5530. if (src.layoutViewportRelative)
  5531. dst.layoutViewportRelative = true;
  5532. if (src.layoutSecondaryViewportRelativeOffset != -2048)
  5533. dst.layoutSecondaryViewportRelativeOffset = src.layoutSecondaryViewportRelativeOffset;
  5534. if (src.layoutShaderRecord)
  5535. dst.layoutShaderRecord = true;
  5536. if (src.pervertexNV)
  5537. dst.pervertexNV = true;
  5538. if (src.pervertexEXT)
  5539. dst.pervertexEXT = true;
  5540. #endif
  5541. }
  5542. }
  5543. // Do error layout error checking given a full variable/block declaration.
  5544. void TParseContext::layoutObjectCheck(const TSourceLoc& loc, const TSymbol& symbol)
  5545. {
  5546. const TType& type = symbol.getType();
  5547. const TQualifier& qualifier = type.getQualifier();
  5548. // first, cross check WRT to just the type
  5549. layoutTypeCheck(loc, type);
  5550. // now, any remaining error checking based on the object itself
  5551. if (qualifier.hasAnyLocation()) {
  5552. switch (qualifier.storage) {
  5553. case EvqUniform:
  5554. case EvqBuffer:
  5555. if (symbol.getAsVariable() == nullptr)
  5556. error(loc, "can only be used on variable declaration", "location", "");
  5557. break;
  5558. default:
  5559. break;
  5560. }
  5561. }
  5562. // user-variable location check, which are required for SPIR-V in/out:
  5563. // - variables have it directly,
  5564. // - blocks have it on each member (already enforced), so check first one
  5565. if (spvVersion.spv > 0 && !parsingBuiltins && qualifier.builtIn == EbvNone &&
  5566. !qualifier.hasLocation() && !intermediate.getAutoMapLocations()) {
  5567. switch (qualifier.storage) {
  5568. case EvqVaryingIn:
  5569. case EvqVaryingOut:
  5570. if (!type.getQualifier().isTaskMemory() &&
  5571. #ifndef GLSLANG_WEB
  5572. !type.getQualifier().hasSprivDecorate() &&
  5573. #endif
  5574. (type.getBasicType() != EbtBlock ||
  5575. (!(*type.getStruct())[0].type->getQualifier().hasLocation() &&
  5576. (*type.getStruct())[0].type->getQualifier().builtIn == EbvNone)))
  5577. error(loc, "SPIR-V requires location for user input/output", "location", "");
  5578. break;
  5579. default:
  5580. break;
  5581. }
  5582. }
  5583. // Check packing and matrix
  5584. if (qualifier.hasUniformLayout()) {
  5585. switch (qualifier.storage) {
  5586. case EvqUniform:
  5587. case EvqBuffer:
  5588. if (type.getBasicType() != EbtBlock) {
  5589. if (qualifier.hasMatrix())
  5590. error(loc, "cannot specify matrix layout on a variable declaration", "layout", "");
  5591. if (qualifier.hasPacking())
  5592. error(loc, "cannot specify packing on a variable declaration", "layout", "");
  5593. // "The offset qualifier can only be used on block members of blocks..."
  5594. if (qualifier.hasOffset() && !type.isAtomic())
  5595. error(loc, "cannot specify on a variable declaration", "offset", "");
  5596. // "The align qualifier can only be used on blocks or block members..."
  5597. if (qualifier.hasAlign())
  5598. error(loc, "cannot specify on a variable declaration", "align", "");
  5599. if (qualifier.isPushConstant())
  5600. error(loc, "can only specify on a uniform block", "push_constant", "");
  5601. if (qualifier.isShaderRecord())
  5602. error(loc, "can only specify on a buffer block", "shaderRecordNV", "");
  5603. if (qualifier.hasLocation() && type.isAtomic())
  5604. error(loc, "cannot specify on atomic counter", "location", "");
  5605. }
  5606. break;
  5607. default:
  5608. // these were already filtered by layoutTypeCheck() (or its callees)
  5609. break;
  5610. }
  5611. }
  5612. }
  5613. // "For some blocks declared as arrays, the location can only be applied at the block level:
  5614. // When a block is declared as an array where additional locations are needed for each member
  5615. // for each block array element, it is a compile-time error to specify locations on the block
  5616. // members. That is, when locations would be under specified by applying them on block members,
  5617. // they are not allowed on block members. For arrayed interfaces (those generally having an
  5618. // extra level of arrayness due to interface expansion), the outer array is stripped before
  5619. // applying this rule."
  5620. void TParseContext::layoutMemberLocationArrayCheck(const TSourceLoc& loc, bool memberWithLocation,
  5621. TArraySizes* arraySizes)
  5622. {
  5623. if (memberWithLocation && arraySizes != nullptr) {
  5624. if (arraySizes->getNumDims() > (currentBlockQualifier.isArrayedIo(language) ? 1 : 0))
  5625. error(loc, "cannot use in a block array where new locations are needed for each block element",
  5626. "location", "");
  5627. }
  5628. }
  5629. // Do layout error checking with respect to a type.
  5630. void TParseContext::layoutTypeCheck(const TSourceLoc& loc, const TType& type)
  5631. {
  5632. #ifndef GLSLANG_WEB
  5633. if (extensionTurnedOn(E_GL_EXT_spirv_intrinsics))
  5634. return; // Skip any check if GL_EXT_spirv_intrinsics is turned on
  5635. #endif
  5636. const TQualifier& qualifier = type.getQualifier();
  5637. // first, intra-layout qualifier-only error checking
  5638. layoutQualifierCheck(loc, qualifier);
  5639. // now, error checking combining type and qualifier
  5640. if (qualifier.hasAnyLocation()) {
  5641. if (qualifier.hasLocation()) {
  5642. if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) {
  5643. if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers)
  5644. error(loc, "too large for fragment output", "location", "");
  5645. }
  5646. }
  5647. if (qualifier.hasComponent()) {
  5648. // "It is a compile-time error if this sequence of components gets larger than 3."
  5649. if (qualifier.layoutComponent + type.getVectorSize() * (type.getBasicType() == EbtDouble ? 2 : 1) > 4)
  5650. error(loc, "type overflows the available 4 components", "component", "");
  5651. // "It is a compile-time error to apply the component qualifier to a matrix, a structure, a block, or an array containing any of these."
  5652. if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct)
  5653. error(loc, "cannot apply to a matrix, structure, or block", "component", "");
  5654. // " It is a compile-time error to use component 1 or 3 as the beginning of a double or dvec2."
  5655. if (type.getBasicType() == EbtDouble)
  5656. if (qualifier.layoutComponent & 1)
  5657. error(loc, "doubles cannot start on an odd-numbered component", "component", "");
  5658. }
  5659. switch (qualifier.storage) {
  5660. case EvqVaryingIn:
  5661. case EvqVaryingOut:
  5662. if (type.getBasicType() == EbtBlock)
  5663. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "location qualifier on in/out block");
  5664. if (type.getQualifier().isTaskMemory())
  5665. error(loc, "cannot apply to taskNV in/out blocks", "location", "");
  5666. break;
  5667. case EvqUniform:
  5668. case EvqBuffer:
  5669. if (type.getBasicType() == EbtBlock)
  5670. error(loc, "cannot apply to uniform or buffer block", "location", "");
  5671. break;
  5672. case EvqtaskPayloadSharedEXT:
  5673. error(loc, "cannot apply to taskPayloadSharedEXT", "location", "");
  5674. break;
  5675. #ifndef GLSLANG_WEB
  5676. case EvqPayload:
  5677. case EvqPayloadIn:
  5678. case EvqHitAttr:
  5679. case EvqCallableData:
  5680. case EvqCallableDataIn:
  5681. break;
  5682. #endif
  5683. default:
  5684. error(loc, "can only apply to uniform, buffer, in, or out storage qualifiers", "location", "");
  5685. break;
  5686. }
  5687. bool typeCollision;
  5688. int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision);
  5689. if (repeated >= 0 && ! typeCollision)
  5690. error(loc, "overlapping use of location", "location", "%d", repeated);
  5691. // "fragment-shader outputs ... if two variables are placed within the same
  5692. // location, they must have the same underlying type (floating-point or integer)"
  5693. if (typeCollision && language == EShLangFragment && qualifier.isPipeOutput())
  5694. error(loc, "fragment outputs sharing the same location must be the same basic type", "location", "%d", repeated);
  5695. }
  5696. #ifndef GLSLANG_WEB
  5697. if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
  5698. if (type.isUnsizedArray()) {
  5699. error(loc, "unsized array", "xfb_offset", "in buffer %d", qualifier.layoutXfbBuffer);
  5700. } else {
  5701. int repeated = intermediate.addXfbBufferOffset(type);
  5702. if (repeated >= 0)
  5703. error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
  5704. }
  5705. // "The offset must be a multiple of the size of the first component of the first
  5706. // qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate
  5707. // containing a double or 64-bit integer, the offset must also be a multiple of 8..."
  5708. if ((type.containsBasicType(EbtDouble) || type.containsBasicType(EbtInt64) || type.containsBasicType(EbtUint64)) &&
  5709. ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8))
  5710. error(loc, "type contains double or 64-bit integer; xfb_offset must be a multiple of 8", "xfb_offset", "");
  5711. else if ((type.containsBasicType(EbtBool) || type.containsBasicType(EbtFloat) ||
  5712. type.containsBasicType(EbtInt) || type.containsBasicType(EbtUint)) &&
  5713. ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4))
  5714. error(loc, "must be a multiple of size of first component", "xfb_offset", "");
  5715. // ..., if applied to an aggregate containing a half float or 16-bit integer, the offset must also be a multiple of 2..."
  5716. else if ((type.contains16BitFloat() || type.containsBasicType(EbtInt16) || type.containsBasicType(EbtUint16)) &&
  5717. !IsMultipleOfPow2(qualifier.layoutXfbOffset, 2))
  5718. error(loc, "type contains half float or 16-bit integer; xfb_offset must be a multiple of 2", "xfb_offset", "");
  5719. }
  5720. if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) {
  5721. if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride))
  5722. error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
  5723. }
  5724. #endif
  5725. if (qualifier.hasBinding()) {
  5726. // Binding checking, from the spec:
  5727. //
  5728. // "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or
  5729. // equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time
  5730. // error will occur. When the binding identifier is used with a uniform or shader storage block instanced as
  5731. // an array of size N, all elements of the array from binding through binding + N - 1 must be within this
  5732. // range."
  5733. //
  5734. if (! type.isOpaque() && type.getBasicType() != EbtBlock)
  5735. error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", "");
  5736. if (type.getBasicType() == EbtSampler) {
  5737. int lastBinding = qualifier.layoutBinding;
  5738. if (type.isArray()) {
  5739. if (spvVersion.vulkan == 0) {
  5740. if (type.isSizedArray())
  5741. lastBinding += (type.getCumulativeArraySize() - 1);
  5742. else {
  5743. #ifndef GLSLANG_WEB
  5744. warn(loc, "assuming binding count of one for compile-time checking of binding numbers for unsized array", "[]", "");
  5745. #endif
  5746. }
  5747. }
  5748. }
  5749. #ifndef GLSLANG_WEB
  5750. if (spvVersion.vulkan == 0 && lastBinding >= resources.maxCombinedTextureImageUnits)
  5751. error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
  5752. #endif
  5753. }
  5754. if (type.isAtomic() && !spvVersion.vulkanRelaxed) {
  5755. if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
  5756. error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", "");
  5757. return;
  5758. }
  5759. }
  5760. } else if (!intermediate.getAutoMapBindings()) {
  5761. // some types require bindings
  5762. // atomic_uint
  5763. if (type.isAtomic())
  5764. error(loc, "layout(binding=X) is required", "atomic_uint", "");
  5765. // SPIR-V
  5766. if (spvVersion.spv > 0) {
  5767. if (qualifier.isUniformOrBuffer()) {
  5768. if (type.getBasicType() == EbtBlock && !qualifier.isPushConstant() &&
  5769. !qualifier.isShaderRecord() &&
  5770. !qualifier.hasAttachment() &&
  5771. !qualifier.hasBufferReference())
  5772. error(loc, "uniform/buffer blocks require layout(binding=X)", "binding", "");
  5773. else if (spvVersion.vulkan > 0 && type.getBasicType() == EbtSampler)
  5774. error(loc, "sampler/texture/image requires layout(binding=X)", "binding", "");
  5775. }
  5776. }
  5777. }
  5778. // some things can't have arrays of arrays
  5779. if (type.isArrayOfArrays()) {
  5780. if (spvVersion.vulkan > 0) {
  5781. if (type.isOpaque() || (type.getQualifier().isUniformOrBuffer() && type.getBasicType() == EbtBlock))
  5782. warn(loc, "Generating SPIR-V array-of-arrays, but Vulkan only supports single array level for this resource", "[][]", "");
  5783. }
  5784. }
  5785. // "The offset qualifier can only be used on block members of blocks..."
  5786. if (qualifier.hasOffset()) {
  5787. if (type.getBasicType() == EbtBlock)
  5788. error(loc, "only applies to block members, not blocks", "offset", "");
  5789. }
  5790. // Image format
  5791. if (qualifier.hasFormat()) {
  5792. if (! type.isImage())
  5793. error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
  5794. else {
  5795. if (type.getSampler().type == EbtFloat && qualifier.getFormat() > ElfFloatGuard)
  5796. error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
  5797. if (type.getSampler().type == EbtInt && (qualifier.getFormat() < ElfFloatGuard || qualifier.getFormat() > ElfIntGuard))
  5798. error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
  5799. if (type.getSampler().type == EbtUint && qualifier.getFormat() < ElfIntGuard)
  5800. error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
  5801. if (isEsProfile()) {
  5802. // "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must
  5803. // specify either memory qualifier readonly or the memory qualifier writeonly."
  5804. if (! (qualifier.getFormat() == ElfR32f || qualifier.getFormat() == ElfR32i || qualifier.getFormat() == ElfR32ui)) {
  5805. if (! qualifier.isReadOnly() && ! qualifier.isWriteOnly())
  5806. error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.getFormat()), "");
  5807. }
  5808. }
  5809. }
  5810. } else if (type.isImage() && ! qualifier.isWriteOnly()) {
  5811. const char *explanation = "image variables not declared 'writeonly' and without a format layout qualifier";
  5812. requireProfile(loc, ECoreProfile | ECompatibilityProfile, explanation);
  5813. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shader_image_load_formatted, explanation);
  5814. }
  5815. if (qualifier.isPushConstant()) {
  5816. if (type.getBasicType() != EbtBlock)
  5817. error(loc, "can only be used with a block", "push_constant", "");
  5818. if (type.isArray())
  5819. error(loc, "Push constants blocks can't be an array", "push_constant", "");
  5820. }
  5821. if (qualifier.hasBufferReference() && type.getBasicType() != EbtBlock)
  5822. error(loc, "can only be used with a block", "buffer_reference", "");
  5823. if (qualifier.isShaderRecord() && type.getBasicType() != EbtBlock)
  5824. error(loc, "can only be used with a block", "shaderRecordNV", "");
  5825. // input attachment
  5826. if (type.isSubpass()) {
  5827. if (! qualifier.hasAttachment())
  5828. error(loc, "requires an input_attachment_index layout qualifier", "subpass", "");
  5829. } else {
  5830. if (qualifier.hasAttachment())
  5831. error(loc, "can only be used with a subpass", "input_attachment_index", "");
  5832. }
  5833. // specialization-constant id
  5834. if (qualifier.hasSpecConstantId()) {
  5835. if (type.getQualifier().storage != EvqConst)
  5836. error(loc, "can only be applied to 'const'-qualified scalar", "constant_id", "");
  5837. if (! type.isScalar())
  5838. error(loc, "can only be applied to a scalar", "constant_id", "");
  5839. switch (type.getBasicType())
  5840. {
  5841. case EbtInt8:
  5842. case EbtUint8:
  5843. case EbtInt16:
  5844. case EbtUint16:
  5845. case EbtInt:
  5846. case EbtUint:
  5847. case EbtInt64:
  5848. case EbtUint64:
  5849. case EbtBool:
  5850. case EbtFloat:
  5851. case EbtDouble:
  5852. case EbtFloat16:
  5853. break;
  5854. default:
  5855. error(loc, "cannot be applied to this type", "constant_id", "");
  5856. break;
  5857. }
  5858. }
  5859. }
  5860. static bool storageCanHaveLayoutInBlock(const enum TStorageQualifier storage)
  5861. {
  5862. switch (storage) {
  5863. case EvqUniform:
  5864. case EvqBuffer:
  5865. case EvqShared:
  5866. return true;
  5867. default:
  5868. return false;
  5869. }
  5870. }
  5871. // Do layout error checking that can be done within a layout qualifier proper, not needing to know
  5872. // if there are blocks, atomic counters, variables, etc.
  5873. void TParseContext::layoutQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier)
  5874. {
  5875. if (qualifier.storage == EvqShared && qualifier.hasLayout()) {
  5876. if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
  5877. error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
  5878. }
  5879. profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
  5880. }
  5881. // "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)."
  5882. if (qualifier.hasComponent() && ! qualifier.hasLocation())
  5883. error(loc, "must specify 'location' to use 'component'", "component", "");
  5884. if (qualifier.hasAnyLocation()) {
  5885. // "As with input layout qualifiers, all shaders except compute shaders
  5886. // allow *location* layout qualifiers on output variable declarations,
  5887. // output block declarations, and output block member declarations."
  5888. switch (qualifier.storage) {
  5889. #ifndef GLSLANG_WEB
  5890. case EvqVaryingIn:
  5891. {
  5892. const char* feature = "location qualifier on input";
  5893. if (isEsProfile() && version < 310)
  5894. requireStage(loc, EShLangVertex, feature);
  5895. else
  5896. requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
  5897. if (language == EShLangVertex) {
  5898. const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
  5899. profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
  5900. profileRequires(loc, EEsProfile, 300, nullptr, feature);
  5901. } else {
  5902. profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
  5903. profileRequires(loc, EEsProfile, 310, nullptr, feature);
  5904. }
  5905. break;
  5906. }
  5907. case EvqVaryingOut:
  5908. {
  5909. const char* feature = "location qualifier on output";
  5910. if (isEsProfile() && version < 310)
  5911. requireStage(loc, EShLangFragment, feature);
  5912. else
  5913. requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
  5914. if (language == EShLangFragment) {
  5915. const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location };
  5916. profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
  5917. profileRequires(loc, EEsProfile, 300, nullptr, feature);
  5918. } else {
  5919. profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature);
  5920. profileRequires(loc, EEsProfile, 310, nullptr, feature);
  5921. }
  5922. break;
  5923. }
  5924. #endif
  5925. case EvqUniform:
  5926. case EvqBuffer:
  5927. {
  5928. const char* feature = "location qualifier on uniform or buffer";
  5929. requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile | ENoProfile, feature);
  5930. profileRequires(loc, ~EEsProfile, 330, E_GL_ARB_explicit_attrib_location, feature);
  5931. profileRequires(loc, ~EEsProfile, 430, E_GL_ARB_explicit_uniform_location, feature);
  5932. profileRequires(loc, EEsProfile, 310, nullptr, feature);
  5933. break;
  5934. }
  5935. default:
  5936. break;
  5937. }
  5938. if (qualifier.hasIndex()) {
  5939. if (qualifier.storage != EvqVaryingOut)
  5940. error(loc, "can only be used on an output", "index", "");
  5941. if (! qualifier.hasLocation())
  5942. error(loc, "can only be used with an explicit location", "index", "");
  5943. }
  5944. }
  5945. if (qualifier.hasBinding()) {
  5946. if (! qualifier.isUniformOrBuffer() && !qualifier.isTaskMemory())
  5947. error(loc, "requires uniform or buffer storage qualifier", "binding", "");
  5948. }
  5949. if (qualifier.hasStream()) {
  5950. if (!qualifier.isPipeOutput())
  5951. error(loc, "can only be used on an output", "stream", "");
  5952. }
  5953. if (qualifier.hasXfb()) {
  5954. if (!qualifier.isPipeOutput())
  5955. error(loc, "can only be used on an output", "xfb layout qualifier", "");
  5956. }
  5957. if (qualifier.hasUniformLayout()) {
  5958. if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory()) {
  5959. if (qualifier.hasMatrix() || qualifier.hasPacking())
  5960. error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", "");
  5961. if (qualifier.hasOffset() || qualifier.hasAlign())
  5962. error(loc, "offset/align can only be used on a uniform or buffer", "layout", "");
  5963. }
  5964. }
  5965. if (qualifier.isPushConstant()) {
  5966. if (qualifier.storage != EvqUniform)
  5967. error(loc, "can only be used with a uniform", "push_constant", "");
  5968. if (qualifier.hasSet())
  5969. error(loc, "cannot be used with push_constant", "set", "");
  5970. if (qualifier.hasBinding())
  5971. error(loc, "cannot be used with push_constant", "binding", "");
  5972. }
  5973. if (qualifier.hasBufferReference()) {
  5974. if (qualifier.storage != EvqBuffer)
  5975. error(loc, "can only be used with buffer", "buffer_reference", "");
  5976. }
  5977. if (qualifier.isShaderRecord()) {
  5978. if (qualifier.storage != EvqBuffer)
  5979. error(loc, "can only be used with a buffer", "shaderRecordNV", "");
  5980. if (qualifier.hasBinding())
  5981. error(loc, "cannot be used with shaderRecordNV", "binding", "");
  5982. if (qualifier.hasSet())
  5983. error(loc, "cannot be used with shaderRecordNV", "set", "");
  5984. }
  5985. if (qualifier.storage == EvqHitAttr && qualifier.hasLayout()) {
  5986. error(loc, "cannot apply layout qualifiers to hitAttributeNV variable", "hitAttributeNV", "");
  5987. }
  5988. }
  5989. // For places that can't have shader-level layout qualifiers
  5990. void TParseContext::checkNoShaderLayouts(const TSourceLoc& loc, const TShaderQualifiers& shaderQualifiers)
  5991. {
  5992. #ifndef GLSLANG_WEB
  5993. const char* message = "can only apply to a standalone qualifier";
  5994. if (shaderQualifiers.geometry != ElgNone)
  5995. error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), "");
  5996. if (shaderQualifiers.spacing != EvsNone)
  5997. error(loc, message, TQualifier::getVertexSpacingString(shaderQualifiers.spacing), "");
  5998. if (shaderQualifiers.order != EvoNone)
  5999. error(loc, message, TQualifier::getVertexOrderString(shaderQualifiers.order), "");
  6000. if (shaderQualifiers.pointMode)
  6001. error(loc, message, "point_mode", "");
  6002. if (shaderQualifiers.invocations != TQualifier::layoutNotSet)
  6003. error(loc, message, "invocations", "");
  6004. for (int i = 0; i < 3; ++i) {
  6005. if (shaderQualifiers.localSize[i] > 1)
  6006. error(loc, message, "local_size", "");
  6007. if (shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet)
  6008. error(loc, message, "local_size id", "");
  6009. }
  6010. if (shaderQualifiers.vertices != TQualifier::layoutNotSet) {
  6011. if (language == EShLangGeometry || language == EShLangMesh)
  6012. error(loc, message, "max_vertices", "");
  6013. else if (language == EShLangTessControl)
  6014. error(loc, message, "vertices", "");
  6015. else
  6016. assert(0);
  6017. }
  6018. if (shaderQualifiers.earlyFragmentTests)
  6019. error(loc, message, "early_fragment_tests", "");
  6020. if (shaderQualifiers.postDepthCoverage)
  6021. error(loc, message, "post_depth_coverage", "");
  6022. if (shaderQualifiers.primitives != TQualifier::layoutNotSet) {
  6023. if (language == EShLangMesh)
  6024. error(loc, message, "max_primitives", "");
  6025. else
  6026. assert(0);
  6027. }
  6028. if (shaderQualifiers.hasBlendEquation())
  6029. error(loc, message, "blend equation", "");
  6030. if (shaderQualifiers.numViews != TQualifier::layoutNotSet)
  6031. error(loc, message, "num_views", "");
  6032. if (shaderQualifiers.interlockOrdering != EioNone)
  6033. error(loc, message, TQualifier::getInterlockOrderingString(shaderQualifiers.interlockOrdering), "");
  6034. if (shaderQualifiers.layoutPrimitiveCulling)
  6035. error(loc, "can only be applied as standalone", "primitive_culling", "");
  6036. #endif
  6037. }
  6038. // Correct and/or advance an object's offset layout qualifier.
  6039. void TParseContext::fixOffset(const TSourceLoc& loc, TSymbol& symbol)
  6040. {
  6041. const TQualifier& qualifier = symbol.getType().getQualifier();
  6042. #ifndef GLSLANG_WEB
  6043. if (symbol.getType().isAtomic()) {
  6044. if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
  6045. // Set the offset
  6046. int offset;
  6047. if (qualifier.hasOffset())
  6048. offset = qualifier.layoutOffset;
  6049. else
  6050. offset = atomicUintOffsets[qualifier.layoutBinding];
  6051. if (offset % 4 != 0)
  6052. error(loc, "atomic counters offset should align based on 4:", "offset", "%d", offset);
  6053. symbol.getWritableType().getQualifier().layoutOffset = offset;
  6054. // Check for overlap
  6055. int numOffsets = 4;
  6056. if (symbol.getType().isArray()) {
  6057. if (symbol.getType().isSizedArray() && !symbol.getType().getArraySizes()->isInnerUnsized())
  6058. numOffsets *= symbol.getType().getCumulativeArraySize();
  6059. else {
  6060. // "It is a compile-time error to declare an unsized array of atomic_uint."
  6061. error(loc, "array must be explicitly sized", "atomic_uint", "");
  6062. }
  6063. }
  6064. int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
  6065. if (repeated >= 0)
  6066. error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
  6067. // Bump the default offset
  6068. atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
  6069. }
  6070. }
  6071. #endif
  6072. }
  6073. //
  6074. // Look up a function name in the symbol table, and make sure it is a function.
  6075. //
  6076. // Return the function symbol if found, otherwise nullptr.
  6077. //
  6078. const TFunction* TParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
  6079. {
  6080. if (symbolTable.isFunctionNameVariable(call.getName())) {
  6081. error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
  6082. return nullptr;
  6083. }
  6084. #ifdef GLSLANG_WEB
  6085. return findFunctionExact(loc, call, builtIn);
  6086. #endif
  6087. const TFunction* function = nullptr;
  6088. // debugPrintfEXT has var args and is in the symbol table as "debugPrintfEXT()",
  6089. // mangled to "debugPrintfEXT("
  6090. if (call.getName() == "debugPrintfEXT") {
  6091. TSymbol* symbol = symbolTable.find("debugPrintfEXT(", &builtIn);
  6092. if (symbol)
  6093. return symbol->getAsFunction();
  6094. }
  6095. bool explicitTypesEnabled = extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types) ||
  6096. extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int8) ||
  6097. extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int16) ||
  6098. extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int32) ||
  6099. extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_int64) ||
  6100. extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float16) ||
  6101. extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float32) ||
  6102. extensionTurnedOn(E_GL_EXT_shader_explicit_arithmetic_types_float64);
  6103. if (isEsProfile())
  6104. function = (explicitTypesEnabled && version >= 310)
  6105. ? findFunctionExplicitTypes(loc, call, builtIn)
  6106. : ((extensionTurnedOn(E_GL_EXT_shader_implicit_conversions) && version >= 310)
  6107. ? findFunction120(loc, call, builtIn)
  6108. : findFunctionExact(loc, call, builtIn));
  6109. else if (version < 120)
  6110. function = findFunctionExact(loc, call, builtIn);
  6111. else if (version < 400) {
  6112. bool needfindFunction400 = extensionTurnedOn(E_GL_ARB_gpu_shader_fp64) || extensionTurnedOn(E_GL_ARB_gpu_shader5);
  6113. function = needfindFunction400 ? findFunction400(loc, call, builtIn) : findFunction120(loc, call, builtIn);
  6114. }
  6115. else if (explicitTypesEnabled)
  6116. function = findFunctionExplicitTypes(loc, call, builtIn);
  6117. else
  6118. function = findFunction400(loc, call, builtIn);
  6119. return function;
  6120. }
  6121. // Function finding algorithm for ES and desktop 110.
  6122. const TFunction* TParseContext::findFunctionExact(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
  6123. {
  6124. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
  6125. if (symbol == nullptr) {
  6126. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6127. return nullptr;
  6128. }
  6129. return symbol->getAsFunction();
  6130. }
  6131. // Function finding algorithm for desktop versions 120 through 330.
  6132. const TFunction* TParseContext::findFunction120(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
  6133. {
  6134. // first, look for an exact match
  6135. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
  6136. if (symbol)
  6137. return symbol->getAsFunction();
  6138. // exact match not found, look through a list of overloaded functions of the same name
  6139. // "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types
  6140. // on input parameters (in or inout or default) must have a conversion from the calling argument type to the
  6141. // formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion
  6142. // from the formal parameter type to the calling argument type. When argument conversions are used to find
  6143. // a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match
  6144. // more than one function."
  6145. const TFunction* candidate = nullptr;
  6146. TVector<const TFunction*> candidateList;
  6147. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6148. for (auto it = candidateList.begin(); it != candidateList.end(); ++it) {
  6149. const TFunction& function = *(*it);
  6150. // to even be a potential match, number of arguments has to match
  6151. if (call.getParamCount() != function.getParamCount())
  6152. continue;
  6153. bool possibleMatch = true;
  6154. for (int i = 0; i < function.getParamCount(); ++i) {
  6155. // same types is easy
  6156. if (*function[i].type == *call[i].type)
  6157. continue;
  6158. // We have a mismatch in type, see if it is implicitly convertible
  6159. if (function[i].type->isArray() || call[i].type->isArray() ||
  6160. ! function[i].type->sameElementShape(*call[i].type))
  6161. possibleMatch = false;
  6162. else {
  6163. // do direction-specific checks for conversion of basic type
  6164. if (function[i].type->getQualifier().isParamInput()) {
  6165. if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
  6166. possibleMatch = false;
  6167. }
  6168. if (function[i].type->getQualifier().isParamOutput()) {
  6169. if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
  6170. possibleMatch = false;
  6171. }
  6172. }
  6173. if (! possibleMatch)
  6174. break;
  6175. }
  6176. if (possibleMatch) {
  6177. if (candidate) {
  6178. // our second match, meaning ambiguity
  6179. error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
  6180. } else
  6181. candidate = &function;
  6182. }
  6183. }
  6184. if (candidate == nullptr)
  6185. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6186. return candidate;
  6187. }
  6188. // Function finding algorithm for desktop version 400 and above.
  6189. //
  6190. // "When function calls are resolved, an exact type match for all the arguments
  6191. // is sought. If an exact match is found, all other functions are ignored, and
  6192. // the exact match is used. If no exact match is found, then the implicit
  6193. // conversions in section 4.1.10 Implicit Conversions will be applied to find
  6194. // a match. Mismatched types on input parameters (in or inout or default) must
  6195. // have a conversion from the calling argument type to the formal parameter type.
  6196. // Mismatched types on output parameters (out or inout) must have a conversion
  6197. // from the formal parameter type to the calling argument type.
  6198. //
  6199. // "If implicit conversions can be used to find more than one matching function,
  6200. // a single best-matching function is sought. To determine a best match, the
  6201. // conversions between calling argument and formal parameter types are compared
  6202. // for each function argument and pair of matching functions. After these
  6203. // comparisons are performed, each pair of matching functions are compared.
  6204. // A function declaration A is considered a better match than function
  6205. // declaration B if
  6206. //
  6207. // * for at least one function argument, the conversion for that argument in A
  6208. // is better than the corresponding conversion in B; and
  6209. // * there is no function argument for which the conversion in B is better than
  6210. // the corresponding conversion in A.
  6211. //
  6212. // "If a single function declaration is considered a better match than every
  6213. // other matching function declaration, it will be used. Otherwise, a
  6214. // compile-time semantic error for an ambiguous overloaded function call occurs.
  6215. //
  6216. // "To determine whether the conversion for a single argument in one match is
  6217. // better than that for another match, the following rules are applied, in order:
  6218. //
  6219. // 1. An exact match is better than a match involving any implicit conversion.
  6220. // 2. A match involving an implicit conversion from float to double is better
  6221. // than a match involving any other implicit conversion.
  6222. // 3. A match involving an implicit conversion from either int or uint to float
  6223. // is better than a match involving an implicit conversion from either int
  6224. // or uint to double.
  6225. //
  6226. // "If none of the rules above apply to a particular pair of conversions, neither
  6227. // conversion is considered better than the other."
  6228. //
  6229. const TFunction* TParseContext::findFunction400(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
  6230. {
  6231. // first, look for an exact match
  6232. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
  6233. if (symbol)
  6234. return symbol->getAsFunction();
  6235. // no exact match, use the generic selector, parameterized by the GLSL rules
  6236. // create list of candidates to send
  6237. TVector<const TFunction*> candidateList;
  6238. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6239. // can 'from' convert to 'to'?
  6240. const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
  6241. if (from == to)
  6242. return true;
  6243. if (from.coopMatParameterOK(to))
  6244. return true;
  6245. // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
  6246. if (builtIn && from.isArray() && to.isUnsizedArray()) {
  6247. TType fromElementType(from, 0);
  6248. TType toElementType(to, 0);
  6249. if (fromElementType == toElementType)
  6250. return true;
  6251. }
  6252. if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
  6253. return false;
  6254. if (from.isCoopMat() && to.isCoopMat())
  6255. return from.sameCoopMatBaseType(to);
  6256. return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
  6257. };
  6258. // Is 'to2' a better conversion than 'to1'?
  6259. // Ties should not be considered as better.
  6260. // Assumes 'convertible' already said true.
  6261. const auto better = [](const TType& from, const TType& to1, const TType& to2) -> bool {
  6262. // 1. exact match
  6263. if (from == to2)
  6264. return from != to1;
  6265. if (from == to1)
  6266. return false;
  6267. // 2. float -> double is better
  6268. if (from.getBasicType() == EbtFloat) {
  6269. if (to2.getBasicType() == EbtDouble && to1.getBasicType() != EbtDouble)
  6270. return true;
  6271. }
  6272. // 3. -> float is better than -> double
  6273. return to2.getBasicType() == EbtFloat && to1.getBasicType() == EbtDouble;
  6274. };
  6275. // for ambiguity reporting
  6276. bool tie = false;
  6277. // send to the generic selector
  6278. const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6279. if (bestMatch == nullptr)
  6280. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6281. else if (tie)
  6282. error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
  6283. return bestMatch;
  6284. }
  6285. // "To determine whether the conversion for a single argument in one match
  6286. // is better than that for another match, the conversion is assigned of the
  6287. // three ranks ordered from best to worst:
  6288. // 1. Exact match: no conversion.
  6289. // 2. Promotion: integral or floating-point promotion.
  6290. // 3. Conversion: integral conversion, floating-point conversion,
  6291. // floating-integral conversion.
  6292. // A conversion C1 is better than a conversion C2 if the rank of C1 is
  6293. // better than the rank of C2."
  6294. const TFunction* TParseContext::findFunctionExplicitTypes(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
  6295. {
  6296. // first, look for an exact match
  6297. TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
  6298. if (symbol)
  6299. return symbol->getAsFunction();
  6300. // no exact match, use the generic selector, parameterized by the GLSL rules
  6301. // create list of candidates to send
  6302. TVector<const TFunction*> candidateList;
  6303. symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
  6304. // can 'from' convert to 'to'?
  6305. const auto convertible = [this,builtIn](const TType& from, const TType& to, TOperator, int) -> bool {
  6306. if (from == to)
  6307. return true;
  6308. if (from.coopMatParameterOK(to))
  6309. return true;
  6310. // Allow a sized array to be passed through an unsized array parameter, for coopMatLoad/Store functions
  6311. if (builtIn && from.isArray() && to.isUnsizedArray()) {
  6312. TType fromElementType(from, 0);
  6313. TType toElementType(to, 0);
  6314. if (fromElementType == toElementType)
  6315. return true;
  6316. }
  6317. if (from.isArray() || to.isArray() || ! from.sameElementShape(to))
  6318. return false;
  6319. if (from.isCoopMat() && to.isCoopMat())
  6320. return from.sameCoopMatBaseType(to);
  6321. return intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType());
  6322. };
  6323. // Is 'to2' a better conversion than 'to1'?
  6324. // Ties should not be considered as better.
  6325. // Assumes 'convertible' already said true.
  6326. const auto better = [this](const TType& from, const TType& to1, const TType& to2) -> bool {
  6327. // 1. exact match
  6328. if (from == to2)
  6329. return from != to1;
  6330. if (from == to1)
  6331. return false;
  6332. // 2. Promotion (integral, floating-point) is better
  6333. TBasicType from_type = from.getBasicType();
  6334. TBasicType to1_type = to1.getBasicType();
  6335. TBasicType to2_type = to2.getBasicType();
  6336. bool isPromotion1 = (intermediate.isIntegralPromotion(from_type, to1_type) ||
  6337. intermediate.isFPPromotion(from_type, to1_type));
  6338. bool isPromotion2 = (intermediate.isIntegralPromotion(from_type, to2_type) ||
  6339. intermediate.isFPPromotion(from_type, to2_type));
  6340. if (isPromotion2)
  6341. return !isPromotion1;
  6342. if(isPromotion1)
  6343. return false;
  6344. // 3. Conversion (integral, floating-point , floating-integral)
  6345. bool isConversion1 = (intermediate.isIntegralConversion(from_type, to1_type) ||
  6346. intermediate.isFPConversion(from_type, to1_type) ||
  6347. intermediate.isFPIntegralConversion(from_type, to1_type));
  6348. bool isConversion2 = (intermediate.isIntegralConversion(from_type, to2_type) ||
  6349. intermediate.isFPConversion(from_type, to2_type) ||
  6350. intermediate.isFPIntegralConversion(from_type, to2_type));
  6351. return isConversion2 && !isConversion1;
  6352. };
  6353. // for ambiguity reporting
  6354. bool tie = false;
  6355. // send to the generic selector
  6356. const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
  6357. if (bestMatch == nullptr)
  6358. error(loc, "no matching overloaded function found", call.getName().c_str(), "");
  6359. else if (tie)
  6360. error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
  6361. return bestMatch;
  6362. }
  6363. //
  6364. // Adjust function calls that aren't declared in Vulkan to a
  6365. // calls with equivalent effects
  6366. //
  6367. TIntermTyped* TParseContext::vkRelaxedRemapFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
  6368. {
  6369. TIntermTyped* result = nullptr;
  6370. #ifndef GLSLANG_WEB
  6371. if (function->getBuiltInOp() != EOpNull) {
  6372. return nullptr;
  6373. }
  6374. if (function->getName() == "atomicCounterIncrement") {
  6375. // change atomicCounterIncrement into an atomicAdd of 1
  6376. TString name("atomicAdd");
  6377. TType uintType(EbtUint);
  6378. TFunction realFunc(&name, function->getType());
  6379. // Use copyParam to avoid shared ownership of the 'type' field
  6380. // of the parameter.
  6381. for (int i = 0; i < function->getParamCount(); ++i) {
  6382. realFunc.addParameter(TParameter().copyParam((*function)[i]));
  6383. }
  6384. TParameter tmpP = { nullptr, &uintType };
  6385. realFunc.addParameter(TParameter().copyParam(tmpP));
  6386. arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(1, loc, true));
  6387. result = handleFunctionCall(loc, &realFunc, arguments);
  6388. } else if (function->getName() == "atomicCounterDecrement") {
  6389. // change atomicCounterDecrement into an atomicAdd with -1
  6390. // and subtract 1 from result, to return post-decrement value
  6391. TString name("atomicAdd");
  6392. TType uintType(EbtUint);
  6393. TFunction realFunc(&name, function->getType());
  6394. for (int i = 0; i < function->getParamCount(); ++i) {
  6395. realFunc.addParameter(TParameter().copyParam((*function)[i]));
  6396. }
  6397. TParameter tmpP = { nullptr, &uintType };
  6398. realFunc.addParameter(TParameter().copyParam(tmpP));
  6399. arguments = intermediate.growAggregate(arguments, intermediate.addConstantUnion(-1, loc, true));
  6400. result = handleFunctionCall(loc, &realFunc, arguments);
  6401. // post decrement, so that it matches AtomicCounterDecrement semantics
  6402. if (result) {
  6403. result = handleBinaryMath(loc, "-", EOpSub, result, intermediate.addConstantUnion(1, loc, true));
  6404. }
  6405. } else if (function->getName() == "atomicCounter") {
  6406. // change atomicCounter into a direct read of the variable
  6407. if (arguments->getAsTyped()) {
  6408. result = arguments->getAsTyped();
  6409. }
  6410. }
  6411. #endif
  6412. return result;
  6413. }
  6414. // When a declaration includes a type, but not a variable name, it can be used
  6415. // to establish defaults.
  6416. void TParseContext::declareTypeDefaults(const TSourceLoc& loc, const TPublicType& publicType)
  6417. {
  6418. #ifndef GLSLANG_WEB
  6419. if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding()) {
  6420. if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
  6421. error(loc, "atomic_uint binding is too large", "binding", "");
  6422. return;
  6423. }
  6424. if (publicType.qualifier.hasOffset())
  6425. atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
  6426. return;
  6427. }
  6428. if (publicType.arraySizes) {
  6429. error(loc, "expect an array name", "", "");
  6430. }
  6431. if (publicType.qualifier.hasLayout() && !publicType.qualifier.hasBufferReference())
  6432. warn(loc, "useless application of layout qualifier", "layout", "");
  6433. #endif
  6434. }
  6435. bool TParseContext::vkRelaxedRemapUniformVariable(const TSourceLoc& loc, TString& identifier, const TPublicType&,
  6436. TArraySizes*, TIntermTyped* initializer, TType& type)
  6437. {
  6438. if (parsingBuiltins || symbolTable.atBuiltInLevel() || !symbolTable.atGlobalLevel() ||
  6439. type.getQualifier().storage != EvqUniform ||
  6440. !(type.containsNonOpaque()
  6441. #ifndef GLSLANG_WEB
  6442. || type.getBasicType() == EbtAtomicUint
  6443. #endif
  6444. )) {
  6445. return false;
  6446. }
  6447. if (type.getQualifier().hasLocation()) {
  6448. warn(loc, "ignoring layout qualifier for uniform", identifier.c_str(), "location");
  6449. type.getQualifier().layoutLocation = TQualifier::layoutLocationEnd;
  6450. }
  6451. if (initializer) {
  6452. warn(loc, "Ignoring initializer for uniform", identifier.c_str(), "");
  6453. initializer = nullptr;
  6454. }
  6455. if (type.isArray()) {
  6456. // do array size checks here
  6457. arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
  6458. if (arrayQualifierError(loc, type.getQualifier()) || arrayError(loc, type)) {
  6459. error(loc, "array param error", identifier.c_str(), "");
  6460. }
  6461. }
  6462. // do some checking on the type as it was declared
  6463. layoutTypeCheck(loc, type);
  6464. int bufferBinding = TQualifier::layoutBindingEnd;
  6465. TVariable* updatedBlock = nullptr;
  6466. #ifndef GLSLANG_WEB
  6467. // Convert atomic_uint into members of a buffer block
  6468. if (type.isAtomic()) {
  6469. type.setBasicType(EbtUint);
  6470. type.getQualifier().storage = EvqBuffer;
  6471. type.getQualifier().volatil = true;
  6472. type.getQualifier().coherent = true;
  6473. // xxTODO: use logic from fixOffset() to apply explicit member offset
  6474. bufferBinding = type.getQualifier().layoutBinding;
  6475. type.getQualifier().layoutBinding = TQualifier::layoutBindingEnd;
  6476. type.getQualifier().explicitOffset = false;
  6477. growAtomicCounterBlock(bufferBinding, loc, type, identifier, nullptr);
  6478. updatedBlock = atomicCounterBuffers[bufferBinding];
  6479. }
  6480. #endif
  6481. if (!updatedBlock) {
  6482. growGlobalUniformBlock(loc, type, identifier, nullptr);
  6483. updatedBlock = globalUniformBlock;
  6484. }
  6485. //
  6486. // don't assign explicit member offsets here
  6487. // if any are assigned, need to be updated here and in the merge/link step
  6488. // fixBlockUniformOffsets(updatedBlock->getWritableType().getQualifier(), *updatedBlock->getWritableType().getWritableStruct());
  6489. // checks on update buffer object
  6490. layoutObjectCheck(loc, *updatedBlock);
  6491. TSymbol* symbol = symbolTable.find(identifier);
  6492. if (!symbol) {
  6493. if (updatedBlock == globalUniformBlock)
  6494. error(loc, "error adding uniform to default uniform block", identifier.c_str(), "");
  6495. else
  6496. error(loc, "error adding atomic counter to atomic counter block", identifier.c_str(), "");
  6497. return false;
  6498. }
  6499. // merge qualifiers
  6500. mergeObjectLayoutQualifiers(updatedBlock->getWritableType().getQualifier(), type.getQualifier(), true);
  6501. return true;
  6502. }
  6503. //
  6504. // Do everything necessary to handle a variable (non-block) declaration.
  6505. // Either redeclaring a variable, or making a new one, updating the symbol
  6506. // table, and all error checking.
  6507. //
  6508. // Returns a subtree node that computes an initializer, if needed.
  6509. // Returns nullptr if there is no code to execute for initialization.
  6510. //
  6511. // 'publicType' is the type part of the declaration (to the left)
  6512. // 'arraySizes' is the arrayness tagged on the identifier (to the right)
  6513. //
  6514. TIntermNode* TParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TPublicType& publicType,
  6515. TArraySizes* arraySizes, TIntermTyped* initializer)
  6516. {
  6517. // Make a fresh type that combines the characteristics from the individual
  6518. // identifier syntax and the declaration-type syntax.
  6519. TType type(publicType);
  6520. type.transferArraySizes(arraySizes);
  6521. type.copyArrayInnerSizes(publicType.arraySizes);
  6522. arrayOfArrayVersionCheck(loc, type.getArraySizes());
  6523. if (initializer) {
  6524. if (type.getBasicType() == EbtRayQuery) {
  6525. error(loc, "ray queries can only be initialized by using the rayQueryInitializeEXT intrinsic:", "=", identifier.c_str());
  6526. }
  6527. }
  6528. if (type.isCoopMat()) {
  6529. intermediate.setUseVulkanMemoryModel();
  6530. intermediate.setUseStorageBuffer();
  6531. if (!publicType.typeParameters || publicType.typeParameters->getNumDims() != 4) {
  6532. error(loc, "expected four type parameters", identifier.c_str(), "");
  6533. }
  6534. if (publicType.typeParameters) {
  6535. if (isTypeFloat(publicType.basicType) &&
  6536. publicType.typeParameters->getDimSize(0) != 16 &&
  6537. publicType.typeParameters->getDimSize(0) != 32 &&
  6538. publicType.typeParameters->getDimSize(0) != 64) {
  6539. error(loc, "expected 16, 32, or 64 bits for first type parameter", identifier.c_str(), "");
  6540. }
  6541. if (isTypeInt(publicType.basicType) &&
  6542. publicType.typeParameters->getDimSize(0) != 8 &&
  6543. publicType.typeParameters->getDimSize(0) != 32) {
  6544. error(loc, "expected 8 or 32 bits for first type parameter", identifier.c_str(), "");
  6545. }
  6546. }
  6547. } else {
  6548. if (publicType.typeParameters && publicType.typeParameters->getNumDims() != 0) {
  6549. error(loc, "unexpected type parameters", identifier.c_str(), "");
  6550. }
  6551. }
  6552. if (voidErrorCheck(loc, identifier, type.getBasicType()))
  6553. return nullptr;
  6554. if (initializer)
  6555. rValueErrorCheck(loc, "initializer", initializer);
  6556. else
  6557. nonInitConstCheck(loc, identifier, type);
  6558. samplerCheck(loc, type, identifier, initializer);
  6559. transparentOpaqueCheck(loc, type, identifier);
  6560. #ifndef GLSLANG_WEB
  6561. atomicUintCheck(loc, type, identifier);
  6562. accStructCheck(loc, type, identifier);
  6563. checkAndResizeMeshViewDim(loc, type, /*isBlockMember*/ false);
  6564. #endif
  6565. if (type.getQualifier().storage == EvqConst && type.containsReference()) {
  6566. error(loc, "variables with reference type can't have qualifier 'const'", "qualifier", "");
  6567. }
  6568. if (type.getQualifier().storage != EvqUniform && type.getQualifier().storage != EvqBuffer) {
  6569. if (type.contains16BitFloat())
  6570. requireFloat16Arithmetic(loc, "qualifier", "float16 types can only be in uniform block or buffer storage");
  6571. if (type.contains16BitInt())
  6572. requireInt16Arithmetic(loc, "qualifier", "(u)int16 types can only be in uniform block or buffer storage");
  6573. if (type.contains8BitInt())
  6574. requireInt8Arithmetic(loc, "qualifier", "(u)int8 types can only be in uniform block or buffer storage");
  6575. }
  6576. if (type.getQualifier().storage == EvqtaskPayloadSharedEXT)
  6577. intermediate.addTaskPayloadEXTCount();
  6578. if (type.getQualifier().storage == EvqShared && type.containsCoopMat())
  6579. error(loc, "qualifier", "Cooperative matrix types must not be used in shared memory", "");
  6580. if (profile == EEsProfile) {
  6581. if (type.getQualifier().isPipeInput() && type.getBasicType() == EbtStruct) {
  6582. if (type.getQualifier().isArrayedIo(language)) {
  6583. TType perVertexType(type, 0);
  6584. if (perVertexType.containsArray() && perVertexType.containsBuiltIn() == false) {
  6585. error(loc, "A per vertex structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
  6586. }
  6587. }
  6588. else if (type.containsArray() && type.containsBuiltIn() == false) {
  6589. error(loc, "A structure containing an array is not allowed as input in ES", type.getTypeName().c_str(), "");
  6590. }
  6591. if (type.containsStructure())
  6592. error(loc, "A structure containing an struct is not allowed as input in ES", type.getTypeName().c_str(), "");
  6593. }
  6594. }
  6595. if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger))
  6596. error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", "");
  6597. if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.getDepth() != EldNone)
  6598. error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", "");
  6599. if (identifier != "gl_FragStencilRefARB" && publicType.shaderQualifiers.getStencil() != ElsNone)
  6600. error(loc, "can only apply depth layout to gl_FragStencilRefARB", "layout qualifier", "");
  6601. // Check for redeclaration of built-ins and/or attempting to declare a reserved name
  6602. TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers);
  6603. if (symbol == nullptr)
  6604. reservedErrorCheck(loc, identifier);
  6605. if (symbol == nullptr && spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed) {
  6606. bool remapped = vkRelaxedRemapUniformVariable(loc, identifier, publicType, arraySizes, initializer, type);
  6607. if (remapped) {
  6608. return nullptr;
  6609. }
  6610. }
  6611. inheritGlobalDefaults(type.getQualifier());
  6612. // Declare the variable
  6613. if (type.isArray()) {
  6614. // Check that implicit sizing is only where allowed.
  6615. arraySizesCheck(loc, type.getQualifier(), type.getArraySizes(), initializer, false);
  6616. if (! arrayQualifierError(loc, type.getQualifier()) && ! arrayError(loc, type))
  6617. declareArray(loc, identifier, type, symbol);
  6618. if (initializer) {
  6619. profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "initializer");
  6620. profileRequires(loc, EEsProfile, 300, nullptr, "initializer");
  6621. }
  6622. } else {
  6623. // non-array case
  6624. if (symbol == nullptr)
  6625. symbol = declareNonArray(loc, identifier, type);
  6626. else if (type != symbol->getType())
  6627. error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
  6628. }
  6629. if (symbol == nullptr)
  6630. return nullptr;
  6631. // Deal with initializer
  6632. TIntermNode* initNode = nullptr;
  6633. if (symbol != nullptr && initializer) {
  6634. TVariable* variable = symbol->getAsVariable();
  6635. if (! variable) {
  6636. error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
  6637. return nullptr;
  6638. }
  6639. initNode = executeInitializer(loc, initializer, variable);
  6640. }
  6641. // look for errors in layout qualifier use
  6642. layoutObjectCheck(loc, *symbol);
  6643. // fix up
  6644. fixOffset(loc, *symbol);
  6645. return initNode;
  6646. }
  6647. // Pick up global defaults from the provide global defaults into dst.
  6648. void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
  6649. {
  6650. #ifndef GLSLANG_WEB
  6651. if (dst.storage == EvqVaryingOut) {
  6652. if (! dst.hasStream() && language == EShLangGeometry)
  6653. dst.layoutStream = globalOutputDefaults.layoutStream;
  6654. if (! dst.hasXfbBuffer())
  6655. dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  6656. }
  6657. #endif
  6658. }
  6659. //
  6660. // Make an internal-only variable whose name is for debug purposes only
  6661. // and won't be searched for. Callers will only use the return value to use
  6662. // the variable, not the name to look it up. It is okay if the name
  6663. // is the same as other names; there won't be any conflict.
  6664. //
  6665. TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
  6666. {
  6667. TString* nameString = NewPoolTString(name);
  6668. TVariable* variable = new TVariable(nameString, type);
  6669. symbolTable.makeInternalVariable(*variable);
  6670. return variable;
  6671. }
  6672. //
  6673. // Declare a non-array variable, the main point being there is no redeclaration
  6674. // for resizing allowed.
  6675. //
  6676. // Return the successfully declared variable.
  6677. //
  6678. TVariable* TParseContext::declareNonArray(const TSourceLoc& loc, const TString& identifier, const TType& type)
  6679. {
  6680. // make a new variable
  6681. TVariable* variable = new TVariable(&identifier, type);
  6682. #ifndef GLSLANG_WEB
  6683. ioArrayCheck(loc, type, identifier);
  6684. #endif
  6685. // add variable to symbol table
  6686. if (symbolTable.insert(*variable)) {
  6687. if (symbolTable.atGlobalLevel())
  6688. trackLinkage(*variable);
  6689. return variable;
  6690. }
  6691. error(loc, "redefinition", variable->getName().c_str(), "");
  6692. return nullptr;
  6693. }
  6694. //
  6695. // Handle all types of initializers from the grammar.
  6696. //
  6697. // Returning nullptr just means there is no code to execute to handle the
  6698. // initializer, which will, for example, be the case for constant initializers.
  6699. //
  6700. TIntermNode* TParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
  6701. {
  6702. // A null initializer is an aggregate that hasn't had an op assigned yet
  6703. // (still EOpNull, no relation to nullInit), and has no children.
  6704. bool nullInit = initializer->getAsAggregate() && initializer->getAsAggregate()->getOp() == EOpNull &&
  6705. initializer->getAsAggregate()->getSequence().size() == 0;
  6706. //
  6707. // Identifier must be of type constant, a global, or a temporary, and
  6708. // starting at version 120, desktop allows uniforms to have initializers.
  6709. //
  6710. TStorageQualifier qualifier = variable->getType().getQualifier().storage;
  6711. if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst ||
  6712. (qualifier == EvqUniform && !isEsProfile() && version >= 120))) {
  6713. if (qualifier == EvqShared) {
  6714. // GL_EXT_null_initializer allows this for shared, if it's a null initializer
  6715. if (nullInit) {
  6716. const char* feature = "initialization with shared qualifier";
  6717. profileRequires(loc, EEsProfile, 0, E_GL_EXT_null_initializer, feature);
  6718. profileRequires(loc, ~EEsProfile, 0, E_GL_EXT_null_initializer, feature);
  6719. } else {
  6720. error(loc, "initializer can only be a null initializer ('{}')", "shared", "");
  6721. }
  6722. } else {
  6723. error(loc, " cannot initialize this type of qualifier ",
  6724. variable->getType().getStorageQualifierString(), "");
  6725. return nullptr;
  6726. }
  6727. }
  6728. if (nullInit) {
  6729. // only some types can be null initialized
  6730. if (variable->getType().containsUnsizedArray()) {
  6731. error(loc, "null initializers can't size unsized arrays", "{}", "");
  6732. return nullptr;
  6733. }
  6734. if (variable->getType().containsOpaque()) {
  6735. error(loc, "null initializers can't be used on opaque values", "{}", "");
  6736. return nullptr;
  6737. }
  6738. variable->getWritableType().getQualifier().setNullInit();
  6739. return nullptr;
  6740. }
  6741. arrayObjectCheck(loc, variable->getType(), "array initializer");
  6742. //
  6743. // If the initializer was from braces { ... }, we convert the whole subtree to a
  6744. // constructor-style subtree, allowing the rest of the code to operate
  6745. // identically for both kinds of initializers.
  6746. //
  6747. // Type can't be deduced from the initializer list, so a skeletal type to
  6748. // follow has to be passed in. Constness and specialization-constness
  6749. // should be deduced bottom up, not dictated by the skeletal type.
  6750. //
  6751. TType skeletalType;
  6752. skeletalType.shallowCopy(variable->getType());
  6753. skeletalType.getQualifier().makeTemporary();
  6754. #ifndef GLSLANG_WEB
  6755. initializer = convertInitializerList(loc, skeletalType, initializer);
  6756. #endif
  6757. if (! initializer) {
  6758. // error recovery; don't leave const without constant values
  6759. if (qualifier == EvqConst)
  6760. variable->getWritableType().getQualifier().makeTemporary();
  6761. return nullptr;
  6762. }
  6763. // Fix outer arrayness if variable is unsized, getting size from the initializer
  6764. if (initializer->getType().isSizedArray() && variable->getType().isUnsizedArray())
  6765. variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
  6766. // Inner arrayness can also get set by an initializer
  6767. if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
  6768. initializer->getType().getArraySizes()->getNumDims() ==
  6769. variable->getType().getArraySizes()->getNumDims()) {
  6770. // adopt unsized sizes from the initializer's sizes
  6771. for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
  6772. if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) {
  6773. variable->getWritableType().getArraySizes()->setDimSize(d,
  6774. initializer->getType().getArraySizes()->getDimSize(d));
  6775. }
  6776. }
  6777. }
  6778. // Uniforms require a compile-time constant initializer
  6779. if (qualifier == EvqUniform && ! initializer->getType().getQualifier().isFrontEndConstant()) {
  6780. error(loc, "uniform initializers must be constant", "=", "'%s'",
  6781. variable->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
  6782. variable->getWritableType().getQualifier().makeTemporary();
  6783. return nullptr;
  6784. }
  6785. // Global consts require a constant initializer (specialization constant is okay)
  6786. if (qualifier == EvqConst && symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
  6787. error(loc, "global const initializers must be constant", "=", "'%s'",
  6788. variable->getType().getCompleteString(intermediate.getEnhancedMsgs()).c_str());
  6789. variable->getWritableType().getQualifier().makeTemporary();
  6790. return nullptr;
  6791. }
  6792. // Const variables require a constant initializer, depending on version
  6793. if (qualifier == EvqConst) {
  6794. if (! initializer->getType().getQualifier().isConstant()) {
  6795. const char* initFeature = "non-constant initializer";
  6796. requireProfile(loc, ~EEsProfile, initFeature);
  6797. profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature);
  6798. variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
  6799. qualifier = EvqConstReadOnly;
  6800. }
  6801. } else {
  6802. // Non-const global variables in ES need a const initializer.
  6803. //
  6804. // "In declarations of global variables with no storage qualifier or with a const
  6805. // qualifier any initializer must be a constant expression."
  6806. if (symbolTable.atGlobalLevel() && ! initializer->getType().getQualifier().isConstant()) {
  6807. const char* initFeature =
  6808. "non-constant global initializer (needs GL_EXT_shader_non_constant_global_initializers)";
  6809. if (isEsProfile()) {
  6810. if (relaxedErrors() && ! extensionTurnedOn(E_GL_EXT_shader_non_constant_global_initializers))
  6811. warn(loc, "not allowed in this version", initFeature, "");
  6812. else
  6813. profileRequires(loc, EEsProfile, 0, E_GL_EXT_shader_non_constant_global_initializers, initFeature);
  6814. }
  6815. }
  6816. }
  6817. if (qualifier == EvqConst || qualifier == EvqUniform) {
  6818. // Compile-time tagging of the variable with its constant value...
  6819. initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
  6820. if (! initializer || ! initializer->getType().getQualifier().isConstant() ||
  6821. variable->getType() != initializer->getType()) {
  6822. error(loc, "non-matching or non-convertible constant type for const initializer",
  6823. variable->getType().getStorageQualifierString(), "");
  6824. variable->getWritableType().getQualifier().makeTemporary();
  6825. return nullptr;
  6826. }
  6827. // We either have a folded constant in getAsConstantUnion, or we have to use
  6828. // the initializer's subtree in the AST to represent the computation of a
  6829. // specialization constant.
  6830. assert(initializer->getAsConstantUnion() || initializer->getType().getQualifier().isSpecConstant());
  6831. if (initializer->getAsConstantUnion())
  6832. variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
  6833. else {
  6834. // It's a specialization constant.
  6835. variable->getWritableType().getQualifier().makeSpecConstant();
  6836. // Keep the subtree that computes the specialization constant with the variable.
  6837. // Later, a symbol node will adopt the subtree from the variable.
  6838. variable->setConstSubtree(initializer);
  6839. }
  6840. } else {
  6841. // normal assigning of a value to a variable...
  6842. specializationCheck(loc, initializer->getType(), "initializer");
  6843. TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
  6844. TIntermTyped* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
  6845. if (! initNode)
  6846. assignError(loc, "=", intermSymbol->getCompleteString(intermediate.getEnhancedMsgs()), initializer->getCompleteString(intermediate.getEnhancedMsgs()));
  6847. return initNode;
  6848. }
  6849. return nullptr;
  6850. }
  6851. //
  6852. // Reprocess any initializer-list (the "{ ... }" syntax) parts of the
  6853. // initializer.
  6854. //
  6855. // Need to hierarchically assign correct types and implicit
  6856. // conversions. Will do this mimicking the same process used for
  6857. // creating a constructor-style initializer, ensuring we get the
  6858. // same form. However, it has to in parallel walk the 'type'
  6859. // passed in, as type cannot be deduced from an initializer list.
  6860. //
  6861. TIntermTyped* TParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
  6862. {
  6863. // Will operate recursively. Once a subtree is found that is constructor style,
  6864. // everything below it is already good: Only the "top part" of the initializer
  6865. // can be an initializer list, where "top part" can extend for several (or all) levels.
  6866. // see if we have bottomed out in the tree within the initializer-list part
  6867. TIntermAggregate* initList = initializer->getAsAggregate();
  6868. if (! initList || initList->getOp() != EOpNull)
  6869. return initializer;
  6870. // Of the initializer-list set of nodes, need to process bottom up,
  6871. // so recurse deep, then process on the way up.
  6872. // Go down the tree here...
  6873. if (type.isArray()) {
  6874. // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
  6875. // Later on, initializer execution code will deal with array size logic.
  6876. TType arrayType;
  6877. arrayType.shallowCopy(type); // sharing struct stuff is fine
  6878. arrayType.copyArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
  6879. // edit array sizes to fill in unsized dimensions
  6880. arrayType.changeOuterArraySize((int)initList->getSequence().size());
  6881. TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
  6882. if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
  6883. arrayType.getArraySizes()->getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
  6884. for (int d = 1; d < arrayType.getArraySizes()->getNumDims(); ++d) {
  6885. if (arrayType.getArraySizes()->getDimSize(d) == UnsizedArraySize)
  6886. arrayType.getArraySizes()->setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
  6887. }
  6888. }
  6889. TType elementType(arrayType, 0); // dereferenced type
  6890. for (size_t i = 0; i < initList->getSequence().size(); ++i) {
  6891. initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
  6892. if (initList->getSequence()[i] == nullptr)
  6893. return nullptr;
  6894. }
  6895. return addConstructor(loc, initList, arrayType);
  6896. } else if (type.isStruct()) {
  6897. if (type.getStruct()->size() != initList->getSequence().size()) {
  6898. error(loc, "wrong number of structure members", "initializer list", "");
  6899. return nullptr;
  6900. }
  6901. for (size_t i = 0; i < type.getStruct()->size(); ++i) {
  6902. initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
  6903. if (initList->getSequence()[i] == nullptr)
  6904. return nullptr;
  6905. }
  6906. } else if (type.isMatrix()) {
  6907. if (type.getMatrixCols() != (int)initList->getSequence().size()) {
  6908. error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
  6909. return nullptr;
  6910. }
  6911. TType vectorType(type, 0); // dereferenced type
  6912. for (int i = 0; i < type.getMatrixCols(); ++i) {
  6913. initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
  6914. if (initList->getSequence()[i] == nullptr)
  6915. return nullptr;
  6916. }
  6917. } else if (type.isVector()) {
  6918. if (type.getVectorSize() != (int)initList->getSequence().size()) {
  6919. error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
  6920. return nullptr;
  6921. }
  6922. TBasicType destType = type.getBasicType();
  6923. for (int i = 0; i < type.getVectorSize(); ++i) {
  6924. TBasicType initType = initList->getSequence()[i]->getAsTyped()->getBasicType();
  6925. if (destType != initType && !intermediate.canImplicitlyPromote(initType, destType)) {
  6926. error(loc, "type mismatch in initializer list", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
  6927. return nullptr;
  6928. }
  6929. }
  6930. } else {
  6931. error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString(intermediate.getEnhancedMsgs()).c_str());
  6932. return nullptr;
  6933. }
  6934. // Now that the subtree is processed, process this node as if the
  6935. // initializer list is a set of arguments to a constructor.
  6936. TIntermNode* emulatedConstructorArguments;
  6937. if (initList->getSequence().size() == 1)
  6938. emulatedConstructorArguments = initList->getSequence()[0];
  6939. else
  6940. emulatedConstructorArguments = initList;
  6941. return addConstructor(loc, emulatedConstructorArguments, type);
  6942. }
  6943. //
  6944. // Test for the correctness of the parameters passed to various constructor functions
  6945. // and also convert them to the right data type, if allowed and required.
  6946. //
  6947. // 'node' is what to construct from.
  6948. // 'type' is what type to construct.
  6949. //
  6950. // Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
  6951. //
  6952. TIntermTyped* TParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type)
  6953. {
  6954. if (node == nullptr || node->getAsTyped() == nullptr)
  6955. return nullptr;
  6956. rValueErrorCheck(loc, "constructor", node->getAsTyped());
  6957. TIntermAggregate* aggrNode = node->getAsAggregate();
  6958. TOperator op = intermediate.mapTypeToConstructorOp(type);
  6959. // Combined texture-sampler constructors are completely semantic checked
  6960. // in constructorTextureSamplerError()
  6961. if (op == EOpConstructTextureSampler) {
  6962. if (aggrNode->getSequence()[1]->getAsTyped()->getType().getSampler().shadow) {
  6963. // Transfer depth into the texture (SPIR-V image) type, as a hint
  6964. // for tools to know this texture/image is a depth image.
  6965. aggrNode->getSequence()[0]->getAsTyped()->getWritableType().getSampler().shadow = true;
  6966. }
  6967. return intermediate.setAggregateOperator(aggrNode, op, type, loc);
  6968. }
  6969. TTypeList::const_iterator memberTypes;
  6970. if (op == EOpConstructStruct)
  6971. memberTypes = type.getStruct()->begin();
  6972. TType elementType;
  6973. if (type.isArray()) {
  6974. TType dereferenced(type, 0);
  6975. elementType.shallowCopy(dereferenced);
  6976. } else
  6977. elementType.shallowCopy(type);
  6978. bool singleArg;
  6979. if (aggrNode) {
  6980. if (aggrNode->getOp() != EOpNull)
  6981. singleArg = true;
  6982. else
  6983. singleArg = false;
  6984. } else
  6985. singleArg = true;
  6986. TIntermTyped *newNode;
  6987. if (singleArg) {
  6988. // If structure constructor or array constructor is being called
  6989. // for only one parameter inside the structure, we need to call constructAggregate function once.
  6990. if (type.isArray())
  6991. newNode = constructAggregate(node, elementType, 1, node->getLoc());
  6992. else if (op == EOpConstructStruct)
  6993. newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
  6994. else
  6995. newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
  6996. if (newNode && (type.isArray() || op == EOpConstructStruct))
  6997. newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
  6998. return newNode;
  6999. }
  7000. //
  7001. // Handle list of arguments.
  7002. //
  7003. TIntermSequence &sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
  7004. // if the structure constructor contains more than one parameter, then construct
  7005. // each parameter
  7006. int paramCount = 0; // keeps track of the constructor parameter number being checked
  7007. // for each parameter to the constructor call, check to see if the right type is passed or convert them
  7008. // to the right type if possible (and allowed).
  7009. // for structure constructors, just check if the right type is passed, no conversion is allowed.
  7010. for (TIntermSequence::iterator p = sequenceVector.begin();
  7011. p != sequenceVector.end(); p++, paramCount++) {
  7012. if (type.isArray())
  7013. newNode = constructAggregate(*p, elementType, paramCount+1, node->getLoc());
  7014. else if (op == EOpConstructStruct)
  7015. newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc());
  7016. else
  7017. newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
  7018. if (newNode)
  7019. *p = newNode;
  7020. else
  7021. return nullptr;
  7022. }
  7023. TIntermTyped *ret_node = intermediate.setAggregateOperator(aggrNode, op, type, loc);
  7024. TIntermAggregate *agg_node = ret_node->getAsAggregate();
  7025. if (agg_node && (agg_node->isVector() || agg_node->isArray() || agg_node->isMatrix()))
  7026. agg_node->updatePrecision();
  7027. return ret_node;
  7028. }
  7029. // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
  7030. // for the parameter to the constructor (passed to this function). Essentially, it converts
  7031. // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
  7032. // float, then float is converted to int.
  7033. //
  7034. // Returns nullptr for an error or the constructed node.
  7035. //
  7036. TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc,
  7037. bool subset)
  7038. {
  7039. // If we are changing a matrix in both domain of basic type and to a non matrix,
  7040. // do the shape change first (by default, below, basic type is changed before shape).
  7041. // This avoids requesting a matrix of a new type that is going to be discarded anyway.
  7042. // TODO: This could be generalized to more type combinations, but that would require
  7043. // more extensive testing and full algorithm rework. For now, the need to do two changes makes
  7044. // the recursive call work, and avoids the most egregious case of creating integer matrices.
  7045. if (node->getType().isMatrix() && (type.isScalar() || type.isVector()) &&
  7046. type.isFloatingDomain() != node->getType().isFloatingDomain()) {
  7047. TType transitionType(node->getBasicType(), glslang::EvqTemporary, type.getVectorSize(), 0, 0, node->isVector());
  7048. TOperator transitionOp = intermediate.mapTypeToConstructorOp(transitionType);
  7049. node = constructBuiltIn(transitionType, transitionOp, node, loc, false);
  7050. }
  7051. TIntermTyped* newNode;
  7052. TOperator basicOp;
  7053. //
  7054. // First, convert types as needed.
  7055. //
  7056. switch (op) {
  7057. case EOpConstructVec2:
  7058. case EOpConstructVec3:
  7059. case EOpConstructVec4:
  7060. case EOpConstructMat2x2:
  7061. case EOpConstructMat2x3:
  7062. case EOpConstructMat2x4:
  7063. case EOpConstructMat3x2:
  7064. case EOpConstructMat3x3:
  7065. case EOpConstructMat3x4:
  7066. case EOpConstructMat4x2:
  7067. case EOpConstructMat4x3:
  7068. case EOpConstructMat4x4:
  7069. case EOpConstructFloat:
  7070. basicOp = EOpConstructFloat;
  7071. break;
  7072. case EOpConstructIVec2:
  7073. case EOpConstructIVec3:
  7074. case EOpConstructIVec4:
  7075. case EOpConstructInt:
  7076. basicOp = EOpConstructInt;
  7077. break;
  7078. case EOpConstructUVec2:
  7079. if (node->getType().getBasicType() == EbtReference) {
  7080. requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "reference conversion to uvec2");
  7081. TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUvec2, true, node,
  7082. type);
  7083. return newNode;
  7084. }
  7085. case EOpConstructUVec3:
  7086. case EOpConstructUVec4:
  7087. case EOpConstructUint:
  7088. basicOp = EOpConstructUint;
  7089. break;
  7090. case EOpConstructBVec2:
  7091. case EOpConstructBVec3:
  7092. case EOpConstructBVec4:
  7093. case EOpConstructBool:
  7094. basicOp = EOpConstructBool;
  7095. break;
  7096. #ifndef GLSLANG_WEB
  7097. case EOpConstructDVec2:
  7098. case EOpConstructDVec3:
  7099. case EOpConstructDVec4:
  7100. case EOpConstructDMat2x2:
  7101. case EOpConstructDMat2x3:
  7102. case EOpConstructDMat2x4:
  7103. case EOpConstructDMat3x2:
  7104. case EOpConstructDMat3x3:
  7105. case EOpConstructDMat3x4:
  7106. case EOpConstructDMat4x2:
  7107. case EOpConstructDMat4x3:
  7108. case EOpConstructDMat4x4:
  7109. case EOpConstructDouble:
  7110. basicOp = EOpConstructDouble;
  7111. break;
  7112. case EOpConstructF16Vec2:
  7113. case EOpConstructF16Vec3:
  7114. case EOpConstructF16Vec4:
  7115. case EOpConstructF16Mat2x2:
  7116. case EOpConstructF16Mat2x3:
  7117. case EOpConstructF16Mat2x4:
  7118. case EOpConstructF16Mat3x2:
  7119. case EOpConstructF16Mat3x3:
  7120. case EOpConstructF16Mat3x4:
  7121. case EOpConstructF16Mat4x2:
  7122. case EOpConstructF16Mat4x3:
  7123. case EOpConstructF16Mat4x4:
  7124. case EOpConstructFloat16:
  7125. basicOp = EOpConstructFloat16;
  7126. // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
  7127. // so construct a 32-bit type and convert
  7128. if (!intermediate.getArithemeticFloat16Enabled()) {
  7129. TType tempType(EbtFloat, EvqTemporary, type.getVectorSize());
  7130. newNode = node;
  7131. if (tempType != newNode->getType()) {
  7132. TOperator aggregateOp;
  7133. if (op == EOpConstructFloat16)
  7134. aggregateOp = EOpConstructFloat;
  7135. else
  7136. aggregateOp = (TOperator)(EOpConstructVec2 + op - EOpConstructF16Vec2);
  7137. newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
  7138. }
  7139. newNode = intermediate.addConversion(EbtFloat16, newNode);
  7140. return newNode;
  7141. }
  7142. break;
  7143. case EOpConstructI8Vec2:
  7144. case EOpConstructI8Vec3:
  7145. case EOpConstructI8Vec4:
  7146. case EOpConstructInt8:
  7147. basicOp = EOpConstructInt8;
  7148. // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
  7149. // so construct a 32-bit type and convert
  7150. if (!intermediate.getArithemeticInt8Enabled()) {
  7151. TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
  7152. newNode = node;
  7153. if (tempType != newNode->getType()) {
  7154. TOperator aggregateOp;
  7155. if (op == EOpConstructInt8)
  7156. aggregateOp = EOpConstructInt;
  7157. else
  7158. aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI8Vec2);
  7159. newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
  7160. }
  7161. newNode = intermediate.addConversion(EbtInt8, newNode);
  7162. return newNode;
  7163. }
  7164. break;
  7165. case EOpConstructU8Vec2:
  7166. case EOpConstructU8Vec3:
  7167. case EOpConstructU8Vec4:
  7168. case EOpConstructUint8:
  7169. basicOp = EOpConstructUint8;
  7170. // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
  7171. // so construct a 32-bit type and convert
  7172. if (!intermediate.getArithemeticInt8Enabled()) {
  7173. TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
  7174. newNode = node;
  7175. if (tempType != newNode->getType()) {
  7176. TOperator aggregateOp;
  7177. if (op == EOpConstructUint8)
  7178. aggregateOp = EOpConstructUint;
  7179. else
  7180. aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU8Vec2);
  7181. newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
  7182. }
  7183. newNode = intermediate.addConversion(EbtUint8, newNode);
  7184. return newNode;
  7185. }
  7186. break;
  7187. case EOpConstructI16Vec2:
  7188. case EOpConstructI16Vec3:
  7189. case EOpConstructI16Vec4:
  7190. case EOpConstructInt16:
  7191. basicOp = EOpConstructInt16;
  7192. // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
  7193. // so construct a 32-bit type and convert
  7194. if (!intermediate.getArithemeticInt16Enabled()) {
  7195. TType tempType(EbtInt, EvqTemporary, type.getVectorSize());
  7196. newNode = node;
  7197. if (tempType != newNode->getType()) {
  7198. TOperator aggregateOp;
  7199. if (op == EOpConstructInt16)
  7200. aggregateOp = EOpConstructInt;
  7201. else
  7202. aggregateOp = (TOperator)(EOpConstructIVec2 + op - EOpConstructI16Vec2);
  7203. newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
  7204. }
  7205. newNode = intermediate.addConversion(EbtInt16, newNode);
  7206. return newNode;
  7207. }
  7208. break;
  7209. case EOpConstructU16Vec2:
  7210. case EOpConstructU16Vec3:
  7211. case EOpConstructU16Vec4:
  7212. case EOpConstructUint16:
  7213. basicOp = EOpConstructUint16;
  7214. // 8/16-bit storage extensions don't support constructing composites of 8/16-bit types,
  7215. // so construct a 32-bit type and convert
  7216. if (!intermediate.getArithemeticInt16Enabled()) {
  7217. TType tempType(EbtUint, EvqTemporary, type.getVectorSize());
  7218. newNode = node;
  7219. if (tempType != newNode->getType()) {
  7220. TOperator aggregateOp;
  7221. if (op == EOpConstructUint16)
  7222. aggregateOp = EOpConstructUint;
  7223. else
  7224. aggregateOp = (TOperator)(EOpConstructUVec2 + op - EOpConstructU16Vec2);
  7225. newNode = intermediate.setAggregateOperator(newNode, aggregateOp, tempType, node->getLoc());
  7226. }
  7227. newNode = intermediate.addConversion(EbtUint16, newNode);
  7228. return newNode;
  7229. }
  7230. break;
  7231. case EOpConstructI64Vec2:
  7232. case EOpConstructI64Vec3:
  7233. case EOpConstructI64Vec4:
  7234. case EOpConstructInt64:
  7235. basicOp = EOpConstructInt64;
  7236. break;
  7237. case EOpConstructUint64:
  7238. if (type.isScalar() && node->getType().isReference()) {
  7239. TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvPtrToUint64, true, node, type);
  7240. return newNode;
  7241. }
  7242. // fall through
  7243. case EOpConstructU64Vec2:
  7244. case EOpConstructU64Vec3:
  7245. case EOpConstructU64Vec4:
  7246. basicOp = EOpConstructUint64;
  7247. break;
  7248. case EOpConstructNonuniform:
  7249. // Make a nonuniform copy of node
  7250. newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpCopyObject, true, node, type);
  7251. return newNode;
  7252. case EOpConstructReference:
  7253. // construct reference from reference
  7254. if (node->getType().isReference()) {
  7255. newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConstructReference, true, node, type);
  7256. return newNode;
  7257. // construct reference from uint64
  7258. } else if (node->getType().isScalar() && node->getType().getBasicType() == EbtUint64) {
  7259. TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToPtr, true, node,
  7260. type);
  7261. return newNode;
  7262. // construct reference from uvec2
  7263. } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint &&
  7264. node->getVectorSize() == 2) {
  7265. requireExtensions(loc, 1, &E_GL_EXT_buffer_reference_uvec2, "uvec2 conversion to reference");
  7266. TIntermTyped* newNode = intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToPtr, true, node,
  7267. type);
  7268. return newNode;
  7269. } else {
  7270. return nullptr;
  7271. }
  7272. case EOpConstructCooperativeMatrix:
  7273. if (!node->getType().isCoopMat()) {
  7274. if (type.getBasicType() != node->getType().getBasicType()) {
  7275. node = intermediate.addConversion(type.getBasicType(), node);
  7276. if (node == nullptr)
  7277. return nullptr;
  7278. }
  7279. node = intermediate.setAggregateOperator(node, EOpConstructCooperativeMatrix, type, node->getLoc());
  7280. } else {
  7281. TOperator op = EOpNull;
  7282. switch (type.getBasicType()) {
  7283. default:
  7284. assert(0);
  7285. break;
  7286. case EbtInt:
  7287. switch (node->getType().getBasicType()) {
  7288. case EbtFloat: op = EOpConvFloatToInt; break;
  7289. case EbtFloat16: op = EOpConvFloat16ToInt; break;
  7290. case EbtUint8: op = EOpConvUint8ToInt; break;
  7291. case EbtInt8: op = EOpConvInt8ToInt; break;
  7292. case EbtUint: op = EOpConvUintToInt; break;
  7293. default: assert(0);
  7294. }
  7295. break;
  7296. case EbtUint:
  7297. switch (node->getType().getBasicType()) {
  7298. case EbtFloat: op = EOpConvFloatToUint; break;
  7299. case EbtFloat16: op = EOpConvFloat16ToUint; break;
  7300. case EbtUint8: op = EOpConvUint8ToUint; break;
  7301. case EbtInt8: op = EOpConvInt8ToUint; break;
  7302. case EbtInt: op = EOpConvIntToUint; break;
  7303. case EbtUint: op = EOpConvUintToInt8; break;
  7304. default: assert(0);
  7305. }
  7306. break;
  7307. case EbtInt8:
  7308. switch (node->getType().getBasicType()) {
  7309. case EbtFloat: op = EOpConvFloatToInt8; break;
  7310. case EbtFloat16: op = EOpConvFloat16ToInt8; break;
  7311. case EbtUint8: op = EOpConvUint8ToInt8; break;
  7312. case EbtInt: op = EOpConvIntToInt8; break;
  7313. case EbtUint: op = EOpConvUintToInt8; break;
  7314. default: assert(0);
  7315. }
  7316. break;
  7317. case EbtUint8:
  7318. switch (node->getType().getBasicType()) {
  7319. case EbtFloat: op = EOpConvFloatToUint8; break;
  7320. case EbtFloat16: op = EOpConvFloat16ToUint8; break;
  7321. case EbtInt8: op = EOpConvInt8ToUint8; break;
  7322. case EbtInt: op = EOpConvIntToUint8; break;
  7323. case EbtUint: op = EOpConvUintToUint8; break;
  7324. default: assert(0);
  7325. }
  7326. break;
  7327. case EbtFloat:
  7328. switch (node->getType().getBasicType()) {
  7329. case EbtFloat16: op = EOpConvFloat16ToFloat; break;
  7330. case EbtInt8: op = EOpConvInt8ToFloat; break;
  7331. case EbtUint8: op = EOpConvUint8ToFloat; break;
  7332. case EbtInt: op = EOpConvIntToFloat; break;
  7333. case EbtUint: op = EOpConvUintToFloat; break;
  7334. default: assert(0);
  7335. }
  7336. break;
  7337. case EbtFloat16:
  7338. switch (node->getType().getBasicType()) {
  7339. case EbtFloat: op = EOpConvFloatToFloat16; break;
  7340. case EbtInt8: op = EOpConvInt8ToFloat16; break;
  7341. case EbtUint8: op = EOpConvUint8ToFloat16; break;
  7342. case EbtInt: op = EOpConvIntToFloat16; break;
  7343. case EbtUint: op = EOpConvUintToFloat16; break;
  7344. default: assert(0);
  7345. }
  7346. break;
  7347. }
  7348. node = intermediate.addUnaryNode(op, node, node->getLoc(), type);
  7349. // If it's a (non-specialization) constant, it must be folded.
  7350. if (node->getAsUnaryNode()->getOperand()->getAsConstantUnion())
  7351. return node->getAsUnaryNode()->getOperand()->getAsConstantUnion()->fold(op, node->getType());
  7352. }
  7353. return node;
  7354. case EOpConstructAccStruct:
  7355. if ((node->getType().isScalar() && node->getType().getBasicType() == EbtUint64)) {
  7356. // construct acceleration structure from uint64
  7357. requireExtensions(loc, Num_ray_tracing_EXTs, ray_tracing_EXTs, "uint64_t conversion to acclerationStructureEXT");
  7358. return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUint64ToAccStruct, true, node,
  7359. type);
  7360. } else if (node->getType().isVector() && node->getType().getBasicType() == EbtUint && node->getVectorSize() == 2) {
  7361. // construct acceleration structure from uint64
  7362. requireExtensions(loc, Num_ray_tracing_EXTs, ray_tracing_EXTs, "uvec2 conversion to accelerationStructureEXT");
  7363. return intermediate.addBuiltInFunctionCall(node->getLoc(), EOpConvUvec2ToAccStruct, true, node,
  7364. type);
  7365. } else
  7366. return nullptr;
  7367. #endif // GLSLANG_WEB
  7368. default:
  7369. error(loc, "unsupported construction", "", "");
  7370. return nullptr;
  7371. }
  7372. newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
  7373. if (newNode == nullptr) {
  7374. error(loc, "can't convert", "constructor", "");
  7375. return nullptr;
  7376. }
  7377. //
  7378. // Now, if there still isn't an operation to do the construction, and we need one, add one.
  7379. //
  7380. // Otherwise, skip out early.
  7381. if (subset || (newNode != node && newNode->getType() == type))
  7382. return newNode;
  7383. // setAggregateOperator will insert a new node for the constructor, as needed.
  7384. return intermediate.setAggregateOperator(newNode, op, type, loc);
  7385. }
  7386. // This function tests for the type of the parameters to the structure or array constructor. Raises
  7387. // an error message if the expected type does not match the parameter passed to the constructor.
  7388. //
  7389. // Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
  7390. //
  7391. TIntermTyped* TParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
  7392. {
  7393. TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
  7394. if (! converted || converted->getType() != type) {
  7395. bool enhanced = intermediate.getEnhancedMsgs();
  7396. error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
  7397. node->getAsTyped()->getType().getCompleteString(enhanced).c_str(), type.getCompleteString(enhanced).c_str());
  7398. return nullptr;
  7399. }
  7400. return converted;
  7401. }
  7402. // If a memory qualifier is present in 'to', also make it present in 'from'.
  7403. void TParseContext::inheritMemoryQualifiers(const TQualifier& from, TQualifier& to)
  7404. {
  7405. #ifndef GLSLANG_WEB
  7406. if (from.isReadOnly())
  7407. to.readonly = from.readonly;
  7408. if (from.isWriteOnly())
  7409. to.writeonly = from.writeonly;
  7410. if (from.coherent)
  7411. to.coherent = from.coherent;
  7412. if (from.volatil)
  7413. to.volatil = from.volatil;
  7414. if (from.restrict)
  7415. to.restrict = from.restrict;
  7416. #endif
  7417. }
  7418. //
  7419. // Do everything needed to add an interface block.
  7420. //
  7421. void TParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName,
  7422. TArraySizes* arraySizes)
  7423. {
  7424. if (spvVersion.vulkan > 0 && spvVersion.vulkanRelaxed)
  7425. blockStorageRemap(loc, blockName, currentBlockQualifier);
  7426. blockStageIoCheck(loc, currentBlockQualifier);
  7427. blockQualifierCheck(loc, currentBlockQualifier, instanceName != nullptr);
  7428. if (arraySizes != nullptr) {
  7429. arraySizesCheck(loc, currentBlockQualifier, arraySizes, nullptr, false);
  7430. arrayOfArrayVersionCheck(loc, arraySizes);
  7431. if (arraySizes->getNumDims() > 1)
  7432. requireProfile(loc, ~EEsProfile, "array-of-array of block");
  7433. }
  7434. // Inherit and check member storage qualifiers WRT to the block-level qualifier.
  7435. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7436. TType& memberType = *typeList[member].type;
  7437. TQualifier& memberQualifier = memberType.getQualifier();
  7438. const TSourceLoc& memberLoc = typeList[member].loc;
  7439. if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage)
  7440. error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), "");
  7441. memberQualifier.storage = currentBlockQualifier.storage;
  7442. globalQualifierFixCheck(memberLoc, memberQualifier);
  7443. #ifndef GLSLANG_WEB
  7444. inheritMemoryQualifiers(currentBlockQualifier, memberQualifier);
  7445. if (currentBlockQualifier.perPrimitiveNV)
  7446. memberQualifier.perPrimitiveNV = currentBlockQualifier.perPrimitiveNV;
  7447. if (currentBlockQualifier.perViewNV)
  7448. memberQualifier.perViewNV = currentBlockQualifier.perViewNV;
  7449. if (currentBlockQualifier.perTaskNV)
  7450. memberQualifier.perTaskNV = currentBlockQualifier.perTaskNV;
  7451. if (currentBlockQualifier.storage == EvqtaskPayloadSharedEXT)
  7452. memberQualifier.storage = EvqtaskPayloadSharedEXT;
  7453. if (memberQualifier.storage == EvqSpirvStorageClass)
  7454. error(memberLoc, "member cannot have a spirv_storage_class qualifier", memberType.getFieldName().c_str(), "");
  7455. if (memberQualifier.hasSprivDecorate() && !memberQualifier.getSpirvDecorate().decorateIds.empty())
  7456. error(memberLoc, "member cannot have a spirv_decorate_id qualifier", memberType.getFieldName().c_str(), "");
  7457. #endif
  7458. if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary()))
  7459. error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), "");
  7460. if (memberType.isArray())
  7461. arraySizesCheck(memberLoc, currentBlockQualifier, memberType.getArraySizes(), nullptr, member == typeList.size() - 1);
  7462. if (memberQualifier.hasOffset()) {
  7463. if (spvVersion.spv == 0) {
  7464. profileRequires(memberLoc, ~EEsProfile, 440, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
  7465. profileRequires(memberLoc, EEsProfile, 300, E_GL_ARB_enhanced_layouts, "\"offset\" on block member");
  7466. }
  7467. }
  7468. if (memberType.containsOpaque())
  7469. error(memberLoc, "member of block cannot be or contain a sampler, image, or atomic_uint type", typeList[member].type->getFieldName().c_str(), "");
  7470. if (memberType.containsCoopMat())
  7471. error(memberLoc, "member of block cannot be or contain a cooperative matrix type", typeList[member].type->getFieldName().c_str(), "");
  7472. }
  7473. // This might be a redeclaration of a built-in block. If so, redeclareBuiltinBlock() will
  7474. // do all the rest.
  7475. if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
  7476. redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
  7477. return;
  7478. }
  7479. // Not a redeclaration of a built-in; check that all names are user names.
  7480. reservedErrorCheck(loc, *blockName);
  7481. if (instanceName)
  7482. reservedErrorCheck(loc, *instanceName);
  7483. for (unsigned int member = 0; member < typeList.size(); ++member)
  7484. reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
  7485. // Make default block qualification, and adjust the member qualifications
  7486. TQualifier defaultQualification;
  7487. switch (currentBlockQualifier.storage) {
  7488. case EvqUniform: defaultQualification = globalUniformDefaults; break;
  7489. case EvqBuffer: defaultQualification = globalBufferDefaults; break;
  7490. case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
  7491. case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
  7492. case EvqShared: defaultQualification = globalSharedDefaults; break;
  7493. default: defaultQualification.clear(); break;
  7494. }
  7495. // Special case for "push_constant uniform", which has a default of std430,
  7496. // contrary to normal uniform defaults, and can't have a default tracked for it.
  7497. if ((currentBlockQualifier.isPushConstant() && !currentBlockQualifier.hasPacking()) ||
  7498. (currentBlockQualifier.isShaderRecord() && !currentBlockQualifier.hasPacking()))
  7499. currentBlockQualifier.layoutPacking = ElpStd430;
  7500. // Special case for "taskNV in/out", which has a default of std430,
  7501. if (currentBlockQualifier.isTaskMemory() && !currentBlockQualifier.hasPacking())
  7502. currentBlockQualifier.layoutPacking = ElpStd430;
  7503. // fix and check for member layout qualifiers
  7504. mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
  7505. // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
  7506. if (currentBlockQualifier.hasAlign()) {
  7507. if (defaultQualification.layoutPacking != ElpStd140 &&
  7508. defaultQualification.layoutPacking != ElpStd430 &&
  7509. defaultQualification.layoutPacking != ElpScalar) {
  7510. error(loc, "can only be used with std140, std430, or scalar layout packing", "align", "");
  7511. defaultQualification.layoutAlign = -1;
  7512. }
  7513. }
  7514. bool memberWithLocation = false;
  7515. bool memberWithoutLocation = false;
  7516. bool memberWithPerViewQualifier = false;
  7517. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7518. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7519. const TSourceLoc& memberLoc = typeList[member].loc;
  7520. #ifndef GLSLANG_WEB
  7521. if (memberQualifier.hasStream()) {
  7522. if (defaultQualification.layoutStream != memberQualifier.layoutStream)
  7523. error(memberLoc, "member cannot contradict block", "stream", "");
  7524. }
  7525. // "This includes a block's inheritance of the
  7526. // current global default buffer, a block member's inheritance of the block's
  7527. // buffer, and the requirement that any *xfb_buffer* declared on a block
  7528. // member must match the buffer inherited from the block."
  7529. if (memberQualifier.hasXfbBuffer()) {
  7530. if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
  7531. error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
  7532. }
  7533. #endif
  7534. if (memberQualifier.hasPacking())
  7535. error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
  7536. if (memberQualifier.hasLocation()) {
  7537. const char* feature = "location on block member";
  7538. switch (currentBlockQualifier.storage) {
  7539. #ifndef GLSLANG_WEB
  7540. case EvqVaryingIn:
  7541. case EvqVaryingOut:
  7542. requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile | EEsProfile, feature);
  7543. profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature);
  7544. profileRequires(memberLoc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
  7545. memberWithLocation = true;
  7546. break;
  7547. #endif
  7548. default:
  7549. error(memberLoc, "can only use in an in/out block", feature, "");
  7550. break;
  7551. }
  7552. } else
  7553. memberWithoutLocation = true;
  7554. // "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts."
  7555. // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
  7556. if (memberQualifier.hasAlign() || memberQualifier.hasOffset()) {
  7557. if (defaultQualification.layoutPacking != ElpStd140 &&
  7558. defaultQualification.layoutPacking != ElpStd430 &&
  7559. defaultQualification.layoutPacking != ElpScalar)
  7560. error(memberLoc, "can only be used with std140, std430, or scalar layout packing", "offset/align", "");
  7561. }
  7562. if (memberQualifier.isPerView()) {
  7563. memberWithPerViewQualifier = true;
  7564. }
  7565. TQualifier newMemberQualification = defaultQualification;
  7566. mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
  7567. memberQualifier = newMemberQualification;
  7568. }
  7569. layoutMemberLocationArrayCheck(loc, memberWithLocation, arraySizes);
  7570. #ifndef GLSLANG_WEB
  7571. // Ensure that the block has an XfbBuffer assigned. This is needed
  7572. // because if the block has a XfbOffset assigned, then it is
  7573. // assumed that it has implicitly assigned the current global
  7574. // XfbBuffer, and because it's members need to be assigned a
  7575. // XfbOffset if they lack it.
  7576. if (currentBlockQualifier.storage == EvqVaryingOut && globalOutputDefaults.hasXfbBuffer()) {
  7577. if (!currentBlockQualifier.hasXfbBuffer() && currentBlockQualifier.hasXfbOffset())
  7578. currentBlockQualifier.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
  7579. }
  7580. #endif
  7581. // Process the members
  7582. fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
  7583. fixXfbOffsets(currentBlockQualifier, typeList);
  7584. fixBlockUniformOffsets(currentBlockQualifier, typeList);
  7585. fixBlockUniformLayoutMatrix(currentBlockQualifier, &typeList, nullptr);
  7586. fixBlockUniformLayoutPacking(currentBlockQualifier, &typeList, nullptr);
  7587. for (unsigned int member = 0; member < typeList.size(); ++member)
  7588. layoutTypeCheck(typeList[member].loc, *typeList[member].type);
  7589. #ifndef GLSLANG_WEB
  7590. if (memberWithPerViewQualifier) {
  7591. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7592. checkAndResizeMeshViewDim(typeList[member].loc, *typeList[member].type, /*isBlockMember*/ true);
  7593. }
  7594. }
  7595. #endif
  7596. // reverse merge, so that currentBlockQualifier now has all layout information
  7597. // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
  7598. mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
  7599. //
  7600. // Build and add the interface block as a new type named 'blockName'
  7601. //
  7602. TType blockType(&typeList, *blockName, currentBlockQualifier);
  7603. if (arraySizes != nullptr)
  7604. blockType.transferArraySizes(arraySizes);
  7605. #ifndef GLSLANG_WEB
  7606. if (arraySizes == nullptr)
  7607. ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
  7608. if (currentBlockQualifier.hasBufferReference()) {
  7609. if (currentBlockQualifier.storage != EvqBuffer)
  7610. error(loc, "can only be used with buffer", "buffer_reference", "");
  7611. // Create the block reference type. If it was forward-declared, detect that
  7612. // as a referent struct type with no members. Replace the referent type with
  7613. // blockType.
  7614. TType blockNameType(EbtReference, blockType, *blockName);
  7615. TVariable* blockNameVar = new TVariable(blockName, blockNameType, true);
  7616. if (! symbolTable.insert(*blockNameVar)) {
  7617. TSymbol* existingName = symbolTable.find(*blockName);
  7618. if (existingName->getType().isReference() &&
  7619. existingName->getType().getReferentType()->getStruct() &&
  7620. existingName->getType().getReferentType()->getStruct()->size() == 0 &&
  7621. existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
  7622. existingName->getType().getReferentType()->deepCopy(blockType);
  7623. } else {
  7624. error(loc, "block name cannot be redefined", blockName->c_str(), "");
  7625. }
  7626. }
  7627. if (!instanceName) {
  7628. return;
  7629. }
  7630. } else
  7631. #endif
  7632. {
  7633. //
  7634. // Don't make a user-defined type out of block name; that will cause an error
  7635. // if the same block name gets reused in a different interface.
  7636. //
  7637. // "Block names have no other use within a shader
  7638. // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
  7639. // other than as a block name (e.g., use of a block name for a global variable name or function name is
  7640. // currently reserved)."
  7641. //
  7642. // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
  7643. // whose type is EbtBlock, but without all the structure; that will come from the type
  7644. // the instances point to.
  7645. //
  7646. TType blockNameType(EbtBlock, blockType.getQualifier().storage);
  7647. TVariable* blockNameVar = new TVariable(blockName, blockNameType);
  7648. if (! symbolTable.insert(*blockNameVar)) {
  7649. TSymbol* existingName = symbolTable.find(*blockName);
  7650. if (existingName->getType().getBasicType() == EbtBlock) {
  7651. if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
  7652. error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
  7653. return;
  7654. }
  7655. } else {
  7656. error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
  7657. return;
  7658. }
  7659. }
  7660. }
  7661. // Add the variable, as anonymous or named instanceName.
  7662. // Make an anonymous variable if no name was provided.
  7663. if (! instanceName)
  7664. instanceName = NewPoolTString("");
  7665. TVariable& variable = *new TVariable(instanceName, blockType);
  7666. if (! symbolTable.insert(variable)) {
  7667. if (*instanceName == "")
  7668. error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
  7669. else
  7670. error(loc, "block instance name redefinition", variable.getName().c_str(), "");
  7671. return;
  7672. }
  7673. // Check for general layout qualifier errors
  7674. layoutObjectCheck(loc, variable);
  7675. #ifndef GLSLANG_WEB
  7676. // fix up
  7677. if (isIoResizeArray(blockType)) {
  7678. ioArraySymbolResizeList.push_back(&variable);
  7679. checkIoArraysConsistency(loc, true);
  7680. } else
  7681. fixIoArraySize(loc, variable.getWritableType());
  7682. #endif
  7683. // Save it in the AST for linker use.
  7684. trackLinkage(variable);
  7685. }
  7686. //
  7687. // allow storage type of block to be remapped at compile time
  7688. //
  7689. void TParseContext::blockStorageRemap(const TSourceLoc&, const TString* instanceName, TQualifier& qualifier)
  7690. {
  7691. TBlockStorageClass type = intermediate.getBlockStorageOverride(instanceName->c_str());
  7692. if (type != EbsNone) {
  7693. qualifier.setBlockStorage(type);
  7694. }
  7695. }
  7696. // Do all block-declaration checking regarding the combination of in/out/uniform/buffer
  7697. // with a particular stage.
  7698. void TParseContext::blockStageIoCheck(const TSourceLoc& loc, const TQualifier& qualifier)
  7699. {
  7700. const char *extsrt[2] = { E_GL_NV_ray_tracing, E_GL_EXT_ray_tracing };
  7701. switch (qualifier.storage) {
  7702. case EvqUniform:
  7703. profileRequires(loc, EEsProfile, 300, nullptr, "uniform block");
  7704. profileRequires(loc, ENoProfile, 140, E_GL_ARB_uniform_buffer_object, "uniform block");
  7705. if (currentBlockQualifier.layoutPacking == ElpStd430 && ! currentBlockQualifier.isPushConstant())
  7706. requireExtensions(loc, 1, &E_GL_EXT_scalar_block_layout, "std430 requires the buffer storage qualifier");
  7707. break;
  7708. case EvqBuffer:
  7709. requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block");
  7710. profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, E_GL_ARB_shader_storage_buffer_object, "buffer block");
  7711. profileRequires(loc, EEsProfile, 310, nullptr, "buffer block");
  7712. break;
  7713. case EvqVaryingIn:
  7714. profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "input block");
  7715. // It is a compile-time error to have an input block in a vertex shader or an output block in a fragment shader
  7716. // "Compute shaders do not permit user-defined input variables..."
  7717. requireStage(loc, (EShLanguageMask)(EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask|
  7718. EShLangFragmentMask|EShLangMeshMask), "input block");
  7719. if (language == EShLangFragment) {
  7720. profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "fragment input block");
  7721. } else if (language == EShLangMesh && ! qualifier.isTaskMemory()) {
  7722. error(loc, "input blocks cannot be used in a mesh shader", "out", "");
  7723. }
  7724. break;
  7725. case EvqVaryingOut:
  7726. profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "output block");
  7727. requireStage(loc, (EShLanguageMask)(EShLangVertexMask|EShLangTessControlMask|EShLangTessEvaluationMask|
  7728. EShLangGeometryMask|EShLangMeshMask|EShLangTaskMask), "output block");
  7729. // ES 310 can have a block before shader_io is turned on, so skip this test for built-ins
  7730. if (language == EShLangVertex && ! parsingBuiltins) {
  7731. profileRequires(loc, EEsProfile, 320, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "vertex output block");
  7732. } else if (language == EShLangMesh && qualifier.isTaskMemory()) {
  7733. error(loc, "can only use on input blocks in mesh shader", "taskNV", "");
  7734. } else if (language == EShLangTask && ! qualifier.isTaskMemory()) {
  7735. error(loc, "output blocks cannot be used in a task shader", "out", "");
  7736. }
  7737. break;
  7738. case EvqShared:
  7739. if (spvVersion.spv > 0 && spvVersion.spv < EShTargetSpv_1_4) {
  7740. error(loc, "shared block requires at least SPIR-V 1.4", "shared block", "");
  7741. }
  7742. profileRequires(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, 0, E_GL_EXT_shared_memory_block, "shared block");
  7743. break;
  7744. #ifndef GLSLANG_WEB
  7745. case EvqPayload:
  7746. profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadNV block");
  7747. requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
  7748. "rayPayloadNV block");
  7749. break;
  7750. case EvqPayloadIn:
  7751. profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "rayPayloadInNV block");
  7752. requireStage(loc, (EShLanguageMask)(EShLangAnyHitMask | EShLangClosestHitMask | EShLangMissMask),
  7753. "rayPayloadInNV block");
  7754. break;
  7755. case EvqHitAttr:
  7756. profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "hitAttributeNV block");
  7757. requireStage(loc, (EShLanguageMask)(EShLangIntersectMask | EShLangAnyHitMask | EShLangClosestHitMask), "hitAttributeNV block");
  7758. break;
  7759. case EvqCallableData:
  7760. profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataNV block");
  7761. requireStage(loc, (EShLanguageMask)(EShLangRayGenMask | EShLangClosestHitMask | EShLangMissMask | EShLangCallableMask),
  7762. "callableDataNV block");
  7763. break;
  7764. case EvqCallableDataIn:
  7765. profileRequires(loc, ~EEsProfile, 460, 2, extsrt, "callableDataInNV block");
  7766. requireStage(loc, (EShLanguageMask)(EShLangCallableMask), "callableDataInNV block");
  7767. break;
  7768. #endif
  7769. default:
  7770. error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
  7771. break;
  7772. }
  7773. }
  7774. // Do all block-declaration checking regarding its qualifiers.
  7775. void TParseContext::blockQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier, bool /*instanceName*/)
  7776. {
  7777. // The 4.5 specification says:
  7778. //
  7779. // interface-block :
  7780. // layout-qualifieropt interface-qualifier block-name { member-list } instance-nameopt ;
  7781. //
  7782. // interface-qualifier :
  7783. // in
  7784. // out
  7785. // patch in
  7786. // patch out
  7787. // uniform
  7788. // buffer
  7789. //
  7790. // Note however memory qualifiers aren't included, yet the specification also says
  7791. //
  7792. // "...memory qualifiers may also be used in the declaration of shader storage blocks..."
  7793. if (qualifier.isInterpolation())
  7794. error(loc, "cannot use interpolation qualifiers on an interface block", "flat/smooth/noperspective", "");
  7795. if (qualifier.centroid)
  7796. error(loc, "cannot use centroid qualifier on an interface block", "centroid", "");
  7797. if (qualifier.isSample())
  7798. error(loc, "cannot use sample qualifier on an interface block", "sample", "");
  7799. if (qualifier.invariant)
  7800. error(loc, "cannot use invariant qualifier on an interface block", "invariant", "");
  7801. if (qualifier.isPushConstant())
  7802. intermediate.addPushConstantCount();
  7803. if (qualifier.isShaderRecord())
  7804. intermediate.addShaderRecordCount();
  7805. if (qualifier.isTaskMemory())
  7806. intermediate.addTaskNVCount();
  7807. }
  7808. //
  7809. // "For a block, this process applies to the entire block, or until the first member
  7810. // is reached that has a location layout qualifier. When a block member is declared with a location
  7811. // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
  7812. // declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
  7813. // until the next member declared with a location qualifier. The values used for locations do not have to be
  7814. // declared in increasing order."
  7815. void TParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
  7816. {
  7817. // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
  7818. // have a location layout qualifier, or a compile-time error results."
  7819. if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
  7820. error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
  7821. else {
  7822. if (memberWithLocation) {
  7823. // remove any block-level location and make it per *every* member
  7824. int nextLocation = 0; // by the rule above, initial value is not relevant
  7825. if (qualifier.hasAnyLocation()) {
  7826. nextLocation = qualifier.layoutLocation;
  7827. qualifier.layoutLocation = TQualifier::layoutLocationEnd;
  7828. if (qualifier.hasComponent()) {
  7829. // "It is a compile-time error to apply the *component* qualifier to a ... block"
  7830. error(loc, "cannot apply to a block", "component", "");
  7831. }
  7832. if (qualifier.hasIndex()) {
  7833. error(loc, "cannot apply to a block", "index", "");
  7834. }
  7835. }
  7836. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7837. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7838. const TSourceLoc& memberLoc = typeList[member].loc;
  7839. if (! memberQualifier.hasLocation()) {
  7840. if (nextLocation >= (int)TQualifier::layoutLocationEnd)
  7841. error(memberLoc, "location is too large", "location", "");
  7842. memberQualifier.layoutLocation = nextLocation;
  7843. memberQualifier.layoutComponent = TQualifier::layoutComponentEnd;
  7844. }
  7845. nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(
  7846. *typeList[member].type, language);
  7847. }
  7848. }
  7849. }
  7850. }
  7851. void TParseContext::fixXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
  7852. {
  7853. #ifndef GLSLANG_WEB
  7854. // "If a block is qualified with xfb_offset, all its
  7855. // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
  7856. // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
  7857. // offsets."
  7858. if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
  7859. return;
  7860. int nextOffset = qualifier.layoutXfbOffset;
  7861. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7862. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7863. bool contains64BitType = false;
  7864. bool contains32BitType = false;
  7865. bool contains16BitType = false;
  7866. int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, contains64BitType, contains32BitType, contains16BitType);
  7867. // see if we need to auto-assign an offset to this member
  7868. if (! memberQualifier.hasXfbOffset()) {
  7869. // "if applied to an aggregate containing a double or 64-bit integer, the offset must also be a multiple of 8"
  7870. if (contains64BitType)
  7871. RoundToPow2(nextOffset, 8);
  7872. else if (contains32BitType)
  7873. RoundToPow2(nextOffset, 4);
  7874. else if (contains16BitType)
  7875. RoundToPow2(nextOffset, 2);
  7876. memberQualifier.layoutXfbOffset = nextOffset;
  7877. } else
  7878. nextOffset = memberQualifier.layoutXfbOffset;
  7879. nextOffset += memberSize;
  7880. }
  7881. // The above gave all block members an offset, so we can take it off the block now,
  7882. // which will avoid double counting the offset usage.
  7883. qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
  7884. #endif
  7885. }
  7886. // Calculate and save the offset of each block member, using the recursively
  7887. // defined block offset rules and the user-provided offset and align.
  7888. //
  7889. // Also, compute and save the total size of the block. For the block's size, arrayness
  7890. // is not taken into account, as each element is backed by a separate buffer.
  7891. //
  7892. void TParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
  7893. {
  7894. if (!storageCanHaveLayoutInBlock(qualifier.storage) && !qualifier.isTaskMemory())
  7895. return;
  7896. if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430 && qualifier.layoutPacking != ElpScalar)
  7897. return;
  7898. int offset = 0;
  7899. int memberSize;
  7900. for (unsigned int member = 0; member < typeList.size(); ++member) {
  7901. TQualifier& memberQualifier = typeList[member].type->getQualifier();
  7902. const TSourceLoc& memberLoc = typeList[member].loc;
  7903. // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
  7904. // modify just the children's view of matrix layout, if there is one for this member
  7905. TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
  7906. int dummyStride;
  7907. int memberAlignment = intermediate.getMemberAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking,
  7908. subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor);
  7909. if (memberQualifier.hasOffset()) {
  7910. // "The specified offset must be a multiple
  7911. // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
  7912. if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
  7913. error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
  7914. // GLSL: "It is a compile-time error to specify an offset that is smaller than the offset of the previous
  7915. // member in the block or that lies within the previous member of the block"
  7916. if (spvVersion.spv == 0) {
  7917. if (memberQualifier.layoutOffset < offset)
  7918. error(memberLoc, "cannot lie in previous members", "offset", "");
  7919. // "The offset qualifier forces the qualified member to start at or after the specified
  7920. // integral-constant expression, which will be its byte offset from the beginning of the buffer.
  7921. // "The actual offset of a member is computed as
  7922. // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
  7923. offset = std::max(offset, memberQualifier.layoutOffset);
  7924. } else {
  7925. // TODO: Vulkan: "It is a compile-time error to have any offset, explicit or assigned,
  7926. // that lies within another member of the block."
  7927. offset = memberQualifier.layoutOffset;
  7928. }
  7929. }
  7930. // "The actual alignment of a member will be the greater of the specified align alignment and the standard
  7931. // (e.g., std140) base alignment for the member's type."
  7932. if (memberQualifier.hasAlign())
  7933. memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
  7934. // "If the resulting offset is not a multiple of the actual alignment,
  7935. // increase it to the first offset that is a multiple of
  7936. // the actual alignment."
  7937. RoundToPow2(offset, memberAlignment);
  7938. typeList[member].type->getQualifier().layoutOffset = offset;
  7939. offset += memberSize;
  7940. }
  7941. }
  7942. //
  7943. // Spread LayoutMatrix to uniform block member, if a uniform block member is a struct,
  7944. // we need spread LayoutMatrix to this struct member too. and keep this rule for recursive.
  7945. //
  7946. void TParseContext::fixBlockUniformLayoutMatrix(TQualifier& qualifier, TTypeList* originTypeList,
  7947. TTypeList* tmpTypeList)
  7948. {
  7949. assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
  7950. for (unsigned int member = 0; member < originTypeList->size(); ++member) {
  7951. if (qualifier.layoutPacking != ElpNone) {
  7952. if (tmpTypeList == nullptr) {
  7953. if (((*originTypeList)[member].type->isMatrix() ||
  7954. (*originTypeList)[member].type->getBasicType() == EbtStruct) &&
  7955. (*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
  7956. (*originTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
  7957. }
  7958. } else {
  7959. if (((*tmpTypeList)[member].type->isMatrix() ||
  7960. (*tmpTypeList)[member].type->getBasicType() == EbtStruct) &&
  7961. (*tmpTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
  7962. (*tmpTypeList)[member].type->getQualifier().layoutMatrix = qualifier.layoutMatrix;
  7963. }
  7964. }
  7965. }
  7966. if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
  7967. TQualifier* memberQualifier = nullptr;
  7968. // block member can be declare a matrix style, so it should be update to the member's style
  7969. if ((*originTypeList)[member].type->getQualifier().layoutMatrix == ElmNone) {
  7970. memberQualifier = &qualifier;
  7971. } else {
  7972. memberQualifier = &((*originTypeList)[member].type->getQualifier());
  7973. }
  7974. const TType* tmpType = tmpTypeList == nullptr ?
  7975. (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
  7976. fixBlockUniformLayoutMatrix(*memberQualifier, (*originTypeList)[member].type->getWritableStruct(),
  7977. tmpType->getWritableStruct());
  7978. const TTypeList* structure = recordStructCopy(matrixFixRecord, (*originTypeList)[member].type, tmpType);
  7979. if (tmpTypeList == nullptr) {
  7980. (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
  7981. }
  7982. if (tmpTypeList != nullptr) {
  7983. (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
  7984. }
  7985. }
  7986. }
  7987. }
  7988. //
  7989. // Spread LayoutPacking to matrix or aggregate block members. If a block member is a struct or
  7990. // array of struct, spread LayoutPacking recursively to its matrix or aggregate members.
  7991. //
  7992. void TParseContext::fixBlockUniformLayoutPacking(TQualifier& qualifier, TTypeList* originTypeList,
  7993. TTypeList* tmpTypeList)
  7994. {
  7995. assert(tmpTypeList == nullptr || originTypeList->size() == tmpTypeList->size());
  7996. for (unsigned int member = 0; member < originTypeList->size(); ++member) {
  7997. if (qualifier.layoutPacking != ElpNone) {
  7998. if (tmpTypeList == nullptr) {
  7999. if ((*originTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
  8000. !(*originTypeList)[member].type->isScalarOrVector()) {
  8001. (*originTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
  8002. }
  8003. } else {
  8004. if ((*tmpTypeList)[member].type->getQualifier().layoutPacking == ElpNone &&
  8005. !(*tmpTypeList)[member].type->isScalarOrVector()) {
  8006. (*tmpTypeList)[member].type->getQualifier().layoutPacking = qualifier.layoutPacking;
  8007. }
  8008. }
  8009. }
  8010. if ((*originTypeList)[member].type->getBasicType() == EbtStruct) {
  8011. // Deep copy the type in pool.
  8012. // Because, struct use in different block may have different layout qualifier.
  8013. // We have to new a object to distinguish between them.
  8014. const TType* tmpType = tmpTypeList == nullptr ?
  8015. (*originTypeList)[member].type->clone() : (*tmpTypeList)[member].type;
  8016. fixBlockUniformLayoutPacking(qualifier, (*originTypeList)[member].type->getWritableStruct(),
  8017. tmpType->getWritableStruct());
  8018. const TTypeList* structure = recordStructCopy(packingFixRecord, (*originTypeList)[member].type, tmpType);
  8019. if (tmpTypeList == nullptr) {
  8020. (*originTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
  8021. }
  8022. if (tmpTypeList != nullptr) {
  8023. (*tmpTypeList)[member].type->setStruct(const_cast<TTypeList*>(structure));
  8024. }
  8025. }
  8026. }
  8027. }
  8028. // For an identifier that is already declared, add more qualification to it.
  8029. void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
  8030. {
  8031. TSymbol* symbol = symbolTable.find(identifier);
  8032. // A forward declaration of a block reference looks to the grammar like adding
  8033. // a qualifier to an existing symbol. Detect this and create the block reference
  8034. // type with an empty type list, which will be filled in later in
  8035. // TParseContext::declareBlock.
  8036. if (!symbol && qualifier.hasBufferReference()) {
  8037. TTypeList typeList;
  8038. TType blockType(&typeList, identifier, qualifier);;
  8039. TType blockNameType(EbtReference, blockType, identifier);
  8040. TVariable* blockNameVar = new TVariable(&identifier, blockNameType, true);
  8041. if (! symbolTable.insert(*blockNameVar)) {
  8042. error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
  8043. }
  8044. return;
  8045. }
  8046. if (! symbol) {
  8047. error(loc, "identifier not previously declared", identifier.c_str(), "");
  8048. return;
  8049. }
  8050. if (symbol->getAsFunction()) {
  8051. error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
  8052. return;
  8053. }
  8054. if (qualifier.isAuxiliary() ||
  8055. qualifier.isMemory() ||
  8056. qualifier.isInterpolation() ||
  8057. qualifier.hasLayout() ||
  8058. qualifier.storage != EvqTemporary ||
  8059. qualifier.precision != EpqNone) {
  8060. error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
  8061. return;
  8062. }
  8063. // For read-only built-ins, add a new symbol for holding the modified qualifier.
  8064. // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
  8065. if (symbol->isReadOnly())
  8066. symbol = symbolTable.copyUp(symbol);
  8067. if (qualifier.invariant) {
  8068. if (intermediate.inIoAccessed(identifier))
  8069. error(loc, "cannot change qualification after use", "invariant", "");
  8070. symbol->getWritableType().getQualifier().invariant = true;
  8071. invariantCheck(loc, symbol->getType().getQualifier());
  8072. } else if (qualifier.isNoContraction()) {
  8073. if (intermediate.inIoAccessed(identifier))
  8074. error(loc, "cannot change qualification after use", "precise", "");
  8075. symbol->getWritableType().getQualifier().setNoContraction();
  8076. } else if (qualifier.specConstant) {
  8077. symbol->getWritableType().getQualifier().makeSpecConstant();
  8078. if (qualifier.hasSpecConstantId())
  8079. symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
  8080. } else
  8081. warn(loc, "unknown requalification", "", "");
  8082. }
  8083. void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
  8084. {
  8085. for (unsigned int i = 0; i < identifiers.size(); ++i)
  8086. addQualifierToExisting(loc, qualifier, *identifiers[i]);
  8087. }
  8088. // Make sure 'invariant' isn't being applied to a non-allowed object.
  8089. void TParseContext::invariantCheck(const TSourceLoc& loc, const TQualifier& qualifier)
  8090. {
  8091. if (! qualifier.invariant)
  8092. return;
  8093. bool pipeOut = qualifier.isPipeOutput();
  8094. bool pipeIn = qualifier.isPipeInput();
  8095. if ((version >= 300 && isEsProfile()) || (!isEsProfile() && version >= 420)) {
  8096. if (! pipeOut)
  8097. error(loc, "can only apply to an output", "invariant", "");
  8098. } else {
  8099. if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn))
  8100. error(loc, "can only apply to an output, or to an input in a non-vertex stage\n", "invariant", "");
  8101. }
  8102. }
  8103. //
  8104. // Updating default qualifier for the case of a declaration with just a qualifier,
  8105. // no type, block, or identifier.
  8106. //
  8107. void TParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
  8108. {
  8109. #ifndef GLSLANG_WEB
  8110. if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
  8111. assert(language == EShLangTessControl || language == EShLangGeometry || language == EShLangMesh);
  8112. const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
  8113. if (publicType.qualifier.storage != EvqVaryingOut)
  8114. error(loc, "can only apply to 'out'", id, "");
  8115. if (! intermediate.setVertices(publicType.shaderQualifiers.vertices))
  8116. error(loc, "cannot change previously set layout value", id, "");
  8117. if (language == EShLangTessControl)
  8118. checkIoArraysConsistency(loc);
  8119. }
  8120. if (publicType.shaderQualifiers.primitives != TQualifier::layoutNotSet) {
  8121. assert(language == EShLangMesh);
  8122. const char* id = "max_primitives";
  8123. if (publicType.qualifier.storage != EvqVaryingOut)
  8124. error(loc, "can only apply to 'out'", id, "");
  8125. if (! intermediate.setPrimitives(publicType.shaderQualifiers.primitives))
  8126. error(loc, "cannot change previously set layout value", id, "");
  8127. }
  8128. if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
  8129. if (publicType.qualifier.storage != EvqVaryingIn)
  8130. error(loc, "can only apply to 'in'", "invocations", "");
  8131. if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
  8132. error(loc, "cannot change previously set layout value", "invocations", "");
  8133. }
  8134. if (publicType.shaderQualifiers.geometry != ElgNone) {
  8135. if (publicType.qualifier.storage == EvqVaryingIn) {
  8136. switch (publicType.shaderQualifiers.geometry) {
  8137. case ElgPoints:
  8138. case ElgLines:
  8139. case ElgLinesAdjacency:
  8140. case ElgTriangles:
  8141. case ElgTrianglesAdjacency:
  8142. case ElgQuads:
  8143. case ElgIsolines:
  8144. if (language == EShLangMesh) {
  8145. error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
  8146. break;
  8147. }
  8148. if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
  8149. if (language == EShLangGeometry)
  8150. checkIoArraysConsistency(loc);
  8151. } else
  8152. error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
  8153. break;
  8154. default:
  8155. error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
  8156. }
  8157. } else if (publicType.qualifier.storage == EvqVaryingOut) {
  8158. switch (publicType.shaderQualifiers.geometry) {
  8159. case ElgLines:
  8160. case ElgTriangles:
  8161. if (language != EShLangMesh) {
  8162. error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
  8163. break;
  8164. }
  8165. // Fall through
  8166. case ElgPoints:
  8167. case ElgLineStrip:
  8168. case ElgTriangleStrip:
  8169. if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
  8170. error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
  8171. break;
  8172. default:
  8173. error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
  8174. }
  8175. } else
  8176. error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
  8177. }
  8178. if (publicType.shaderQualifiers.spacing != EvsNone) {
  8179. if (publicType.qualifier.storage == EvqVaryingIn) {
  8180. if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing))
  8181. error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
  8182. } else
  8183. error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
  8184. }
  8185. if (publicType.shaderQualifiers.order != EvoNone) {
  8186. if (publicType.qualifier.storage == EvqVaryingIn) {
  8187. if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order))
  8188. error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
  8189. } else
  8190. error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
  8191. }
  8192. if (publicType.shaderQualifiers.pointMode) {
  8193. if (publicType.qualifier.storage == EvqVaryingIn)
  8194. intermediate.setPointMode();
  8195. else
  8196. error(loc, "can only apply to 'in'", "point_mode", "");
  8197. }
  8198. #endif
  8199. for (int i = 0; i < 3; ++i) {
  8200. if (publicType.shaderQualifiers.localSizeNotDefault[i]) {
  8201. if (publicType.qualifier.storage == EvqVaryingIn) {
  8202. if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i]))
  8203. error(loc, "cannot change previously set size", "local_size", "");
  8204. else {
  8205. int max = 0;
  8206. if (language == EShLangCompute) {
  8207. switch (i) {
  8208. case 0: max = resources.maxComputeWorkGroupSizeX; break;
  8209. case 1: max = resources.maxComputeWorkGroupSizeY; break;
  8210. case 2: max = resources.maxComputeWorkGroupSizeZ; break;
  8211. default: break;
  8212. }
  8213. if (intermediate.getLocalSize(i) > (unsigned int)max)
  8214. error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
  8215. }
  8216. #ifndef GLSLANG_WEB
  8217. else if (language == EShLangMesh) {
  8218. switch (i) {
  8219. case 0:
  8220. max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
  8221. resources.maxMeshWorkGroupSizeX_EXT :
  8222. resources.maxMeshWorkGroupSizeX_NV;
  8223. break;
  8224. case 1:
  8225. max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
  8226. resources.maxMeshWorkGroupSizeY_EXT :
  8227. resources.maxMeshWorkGroupSizeY_NV ;
  8228. break;
  8229. case 2:
  8230. max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
  8231. resources.maxMeshWorkGroupSizeZ_EXT :
  8232. resources.maxMeshWorkGroupSizeZ_NV ;
  8233. break;
  8234. default: break;
  8235. }
  8236. if (intermediate.getLocalSize(i) > (unsigned int)max) {
  8237. TString maxsErrtring = "too large, see ";
  8238. maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ?
  8239. "gl_MaxMeshWorkGroupSizeEXT" : "gl_MaxMeshWorkGroupSizeNV");
  8240. error(loc, maxsErrtring.c_str(), "local_size", "");
  8241. }
  8242. } else if (language == EShLangTask) {
  8243. switch (i) {
  8244. case 0:
  8245. max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
  8246. resources.maxTaskWorkGroupSizeX_EXT :
  8247. resources.maxTaskWorkGroupSizeX_NV;
  8248. break;
  8249. case 1:
  8250. max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
  8251. resources.maxTaskWorkGroupSizeY_EXT:
  8252. resources.maxTaskWorkGroupSizeY_NV;
  8253. break;
  8254. case 2:
  8255. max = extensionTurnedOn(E_GL_EXT_mesh_shader) ?
  8256. resources.maxTaskWorkGroupSizeZ_EXT:
  8257. resources.maxTaskWorkGroupSizeZ_NV;
  8258. break;
  8259. default: break;
  8260. }
  8261. if (intermediate.getLocalSize(i) > (unsigned int)max) {
  8262. TString maxsErrtring = "too large, see ";
  8263. maxsErrtring.append(extensionTurnedOn(E_GL_EXT_mesh_shader) ?
  8264. "gl_MaxTaskWorkGroupSizeEXT" : "gl_MaxTaskWorkGroupSizeNV");
  8265. error(loc, maxsErrtring.c_str(), "local_size", "");
  8266. }
  8267. }
  8268. #endif
  8269. else {
  8270. assert(0);
  8271. }
  8272. // Fix the existing constant gl_WorkGroupSize with this new information.
  8273. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  8274. if (workGroupSize != nullptr)
  8275. workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
  8276. }
  8277. } else
  8278. error(loc, "can only apply to 'in'", "local_size", "");
  8279. }
  8280. if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
  8281. if (publicType.qualifier.storage == EvqVaryingIn) {
  8282. if (! intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]))
  8283. error(loc, "cannot change previously set size", "local_size", "");
  8284. } else
  8285. error(loc, "can only apply to 'in'", "local_size id", "");
  8286. // Set the workgroup built-in variable as a specialization constant
  8287. TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
  8288. if (workGroupSize != nullptr)
  8289. workGroupSize->getWritableType().getQualifier().specConstant = true;
  8290. }
  8291. }
  8292. #ifndef GLSLANG_WEB
  8293. if (publicType.shaderQualifiers.earlyFragmentTests) {
  8294. if (publicType.qualifier.storage == EvqVaryingIn)
  8295. intermediate.setEarlyFragmentTests();
  8296. else
  8297. error(loc, "can only apply to 'in'", "early_fragment_tests", "");
  8298. }
  8299. if (publicType.shaderQualifiers.earlyAndLateFragmentTestsAMD) {
  8300. if (publicType.qualifier.storage == EvqVaryingIn)
  8301. intermediate.setEarlyAndLateFragmentTestsAMD();
  8302. else
  8303. error(loc, "can only apply to 'in'", "early_and_late_fragment_tests_amd", "");
  8304. }
  8305. if (publicType.shaderQualifiers.postDepthCoverage) {
  8306. if (publicType.qualifier.storage == EvqVaryingIn)
  8307. intermediate.setPostDepthCoverage();
  8308. else
  8309. error(loc, "can only apply to 'in'", "post_coverage_coverage", "");
  8310. }
  8311. if (publicType.shaderQualifiers.hasBlendEquation()) {
  8312. if (publicType.qualifier.storage != EvqVaryingOut)
  8313. error(loc, "can only apply to 'out'", "blend equation", "");
  8314. }
  8315. if (publicType.shaderQualifiers.interlockOrdering) {
  8316. if (publicType.qualifier.storage == EvqVaryingIn) {
  8317. if (!intermediate.setInterlockOrdering(publicType.shaderQualifiers.interlockOrdering))
  8318. error(loc, "cannot change previously set fragment shader interlock ordering", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
  8319. }
  8320. else
  8321. error(loc, "can only apply to 'in'", TQualifier::getInterlockOrderingString(publicType.shaderQualifiers.interlockOrdering), "");
  8322. }
  8323. if (publicType.shaderQualifiers.layoutDerivativeGroupQuads &&
  8324. publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
  8325. error(loc, "cannot be both specified", "derivative_group_quadsNV and derivative_group_linearNV", "");
  8326. }
  8327. if (publicType.shaderQualifiers.layoutDerivativeGroupQuads) {
  8328. if (publicType.qualifier.storage == EvqVaryingIn) {
  8329. if ((intermediate.getLocalSize(0) & 1) ||
  8330. (intermediate.getLocalSize(1) & 1))
  8331. error(loc, "requires local_size_x and local_size_y to be multiple of two", "derivative_group_quadsNV", "");
  8332. else
  8333. intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupQuads);
  8334. }
  8335. else
  8336. error(loc, "can only apply to 'in'", "derivative_group_quadsNV", "");
  8337. }
  8338. if (publicType.shaderQualifiers.layoutDerivativeGroupLinear) {
  8339. if (publicType.qualifier.storage == EvqVaryingIn) {
  8340. if((intermediate.getLocalSize(0) *
  8341. intermediate.getLocalSize(1) *
  8342. intermediate.getLocalSize(2)) % 4 != 0)
  8343. error(loc, "requires total group size to be multiple of four", "derivative_group_linearNV", "");
  8344. else
  8345. intermediate.setLayoutDerivativeMode(LayoutDerivativeGroupLinear);
  8346. }
  8347. else
  8348. error(loc, "can only apply to 'in'", "derivative_group_linearNV", "");
  8349. }
  8350. // Check mesh out array sizes, once all the necessary out qualifiers are defined.
  8351. if ((language == EShLangMesh) &&
  8352. (intermediate.getVertices() != TQualifier::layoutNotSet) &&
  8353. (intermediate.getPrimitives() != TQualifier::layoutNotSet) &&
  8354. (intermediate.getOutputPrimitive() != ElgNone))
  8355. {
  8356. checkIoArraysConsistency(loc);
  8357. }
  8358. if (publicType.shaderQualifiers.layoutPrimitiveCulling) {
  8359. if (publicType.qualifier.storage != EvqTemporary)
  8360. error(loc, "layout qualifier can not have storage qualifiers", "primitive_culling","", "");
  8361. else {
  8362. intermediate.setLayoutPrimitiveCulling();
  8363. }
  8364. // Exit early as further checks are not valid
  8365. return;
  8366. }
  8367. #endif
  8368. const TQualifier& qualifier = publicType.qualifier;
  8369. if (qualifier.isAuxiliary() ||
  8370. qualifier.isMemory() ||
  8371. qualifier.isInterpolation() ||
  8372. qualifier.precision != EpqNone)
  8373. error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", "");
  8374. // "The offset qualifier can only be used on block members of blocks..."
  8375. // "The align qualifier can only be used on blocks or block members..."
  8376. if (qualifier.hasOffset() ||
  8377. qualifier.hasAlign())
  8378. error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", "");
  8379. layoutQualifierCheck(loc, qualifier);
  8380. switch (qualifier.storage) {
  8381. case EvqUniform:
  8382. if (qualifier.hasMatrix())
  8383. globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
  8384. if (qualifier.hasPacking())
  8385. globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
  8386. break;
  8387. case EvqBuffer:
  8388. if (qualifier.hasMatrix())
  8389. globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
  8390. if (qualifier.hasPacking())
  8391. globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
  8392. break;
  8393. case EvqVaryingIn:
  8394. break;
  8395. case EvqVaryingOut:
  8396. #ifndef GLSLANG_WEB
  8397. if (qualifier.hasStream())
  8398. globalOutputDefaults.layoutStream = qualifier.layoutStream;
  8399. if (qualifier.hasXfbBuffer())
  8400. globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
  8401. if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
  8402. if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
  8403. error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
  8404. }
  8405. #endif
  8406. break;
  8407. case EvqShared:
  8408. if (qualifier.hasMatrix())
  8409. globalSharedDefaults.layoutMatrix = qualifier.layoutMatrix;
  8410. if (qualifier.hasPacking())
  8411. globalSharedDefaults.layoutPacking = qualifier.layoutPacking;
  8412. break;
  8413. default:
  8414. error(loc, "default qualifier requires 'uniform', 'buffer', 'in', 'out' or 'shared' storage qualification", "", "");
  8415. return;
  8416. }
  8417. if (qualifier.hasBinding())
  8418. error(loc, "cannot declare a default, include a type or full declaration", "binding", "");
  8419. if (qualifier.hasAnyLocation())
  8420. error(loc, "cannot declare a default, use a full declaration", "location/component/index", "");
  8421. if (qualifier.hasXfbOffset())
  8422. error(loc, "cannot declare a default, use a full declaration", "xfb_offset", "");
  8423. if (qualifier.isPushConstant())
  8424. error(loc, "cannot declare a default, can only be used on a block", "push_constant", "");
  8425. if (qualifier.hasBufferReference())
  8426. error(loc, "cannot declare a default, can only be used on a block", "buffer_reference", "");
  8427. if (qualifier.hasSpecConstantId())
  8428. error(loc, "cannot declare a default, can only be used on a scalar", "constant_id", "");
  8429. if (qualifier.isShaderRecord())
  8430. error(loc, "cannot declare a default, can only be used on a block", "shaderRecordNV", "");
  8431. }
  8432. //
  8433. // Take the sequence of statements that has been built up since the last case/default,
  8434. // put it on the list of top-level nodes for the current (inner-most) switch statement,
  8435. // and follow that by the case/default we are on now. (See switch topology comment on
  8436. // TIntermSwitch.)
  8437. //
  8438. void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
  8439. {
  8440. TIntermSequence* switchSequence = switchSequenceStack.back();
  8441. if (statements) {
  8442. if (switchSequence->size() == 0)
  8443. error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
  8444. statements->setOperator(EOpSequence);
  8445. switchSequence->push_back(statements);
  8446. }
  8447. if (branchNode) {
  8448. // check all previous cases for the same label (or both are 'default')
  8449. for (unsigned int s = 0; s < switchSequence->size(); ++s) {
  8450. TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
  8451. if (prevBranch) {
  8452. TIntermTyped* prevExpression = prevBranch->getExpression();
  8453. TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
  8454. if (prevExpression == nullptr && newExpression == nullptr)
  8455. error(branchNode->getLoc(), "duplicate label", "default", "");
  8456. else if (prevExpression != nullptr &&
  8457. newExpression != nullptr &&
  8458. prevExpression->getAsConstantUnion() &&
  8459. newExpression->getAsConstantUnion() &&
  8460. prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
  8461. newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
  8462. error(branchNode->getLoc(), "duplicated value", "case", "");
  8463. }
  8464. }
  8465. switchSequence->push_back(branchNode);
  8466. }
  8467. }
  8468. //
  8469. // Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
  8470. // into a switch node.
  8471. //
  8472. TIntermNode* TParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
  8473. {
  8474. profileRequires(loc, EEsProfile, 300, nullptr, "switch statements");
  8475. profileRequires(loc, ENoProfile, 130, nullptr, "switch statements");
  8476. wrapupSwitchSubsequence(lastStatements, nullptr);
  8477. if (expression == nullptr ||
  8478. (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
  8479. expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
  8480. error(loc, "condition must be a scalar integer expression", "switch", "");
  8481. // If there is nothing to do, drop the switch but still execute the expression
  8482. TIntermSequence* switchSequence = switchSequenceStack.back();
  8483. if (switchSequence->size() == 0)
  8484. return expression;
  8485. if (lastStatements == nullptr) {
  8486. // This was originally an ERRROR, because early versions of the specification said
  8487. // "it is an error to have no statement between a label and the end of the switch statement."
  8488. // The specifications were updated to remove this (being ill-defined what a "statement" was),
  8489. // so, this became a warning. However, 3.0 tests still check for the error.
  8490. if (isEsProfile() && (version <= 300 || version >= 320) && ! relaxedErrors())
  8491. error(loc, "last case/default label not followed by statements", "switch", "");
  8492. else if (!isEsProfile() && (version <= 430 || version >= 460))
  8493. error(loc, "last case/default label not followed by statements", "switch", "");
  8494. else
  8495. warn(loc, "last case/default label not followed by statements", "switch", "");
  8496. // emulate a break for error recovery
  8497. lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
  8498. lastStatements->setOperator(EOpSequence);
  8499. switchSequence->push_back(lastStatements);
  8500. }
  8501. TIntermAggregate* body = new TIntermAggregate(EOpSequence);
  8502. body->getSequence() = *switchSequenceStack.back();
  8503. body->setLoc(loc);
  8504. TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
  8505. switchNode->setLoc(loc);
  8506. return switchNode;
  8507. }
  8508. //
  8509. // When a struct used in block, and has it's own layout packing, layout matrix,
  8510. // record the origin structure of a struct to map, and Record the structure copy to the copy table,
  8511. //
  8512. const TTypeList* TParseContext::recordStructCopy(TStructRecord& record, const TType* originType, const TType* tmpType)
  8513. {
  8514. size_t memberCount = tmpType->getStruct()->size();
  8515. size_t originHash = 0, tmpHash = 0;
  8516. std::hash<size_t> hasher;
  8517. for (size_t i = 0; i < memberCount; i++) {
  8518. size_t originMemberHash = hasher(originType->getStruct()->at(i).type->getQualifier().layoutPacking +
  8519. originType->getStruct()->at(i).type->getQualifier().layoutMatrix);
  8520. size_t tmpMemberHash = hasher(tmpType->getStruct()->at(i).type->getQualifier().layoutPacking +
  8521. tmpType->getStruct()->at(i).type->getQualifier().layoutMatrix);
  8522. originHash = hasher((originHash ^ originMemberHash) << 1);
  8523. tmpHash = hasher((tmpHash ^ tmpMemberHash) << 1);
  8524. }
  8525. const TTypeList* originStruct = originType->getStruct();
  8526. const TTypeList* tmpStruct = tmpType->getStruct();
  8527. if (originHash != tmpHash) {
  8528. auto fixRecords = record.find(originStruct);
  8529. if (fixRecords != record.end()) {
  8530. auto fixRecord = fixRecords->second.find(tmpHash);
  8531. if (fixRecord != fixRecords->second.end()) {
  8532. return fixRecord->second;
  8533. } else {
  8534. record[originStruct][tmpHash] = tmpStruct;
  8535. return tmpStruct;
  8536. }
  8537. } else {
  8538. record[originStruct] = std::map<size_t, const TTypeList*>();
  8539. record[originStruct][tmpHash] = tmpStruct;
  8540. return tmpStruct;
  8541. }
  8542. }
  8543. return originStruct;
  8544. }
  8545. } // end namespace glslang