spirv_cross.cpp 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749
  1. /*
  2. * Copyright 2015-2021 Arm Limited
  3. * SPDX-License-Identifier: Apache-2.0 OR MIT
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*
  18. * At your option, you may choose to accept this material under either:
  19. * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
  20. * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
  21. */
  22. #include "spirv_cross.hpp"
  23. #include "GLSL.std.450.h"
  24. #include "spirv_cfg.hpp"
  25. #include "spirv_common.hpp"
  26. #include "spirv_parser.hpp"
  27. #include <algorithm>
  28. #include <cstring>
  29. #include <utility>
  30. using namespace std;
  31. using namespace spv;
  32. using namespace SPIRV_CROSS_NAMESPACE;
  33. Compiler::Compiler(vector<uint32_t> ir_)
  34. {
  35. Parser parser(std::move(ir_));
  36. parser.parse();
  37. set_ir(std::move(parser.get_parsed_ir()));
  38. }
  39. Compiler::Compiler(const uint32_t *ir_, size_t word_count)
  40. {
  41. Parser parser(ir_, word_count);
  42. parser.parse();
  43. set_ir(std::move(parser.get_parsed_ir()));
  44. }
  45. Compiler::Compiler(const ParsedIR &ir_)
  46. {
  47. set_ir(ir_);
  48. }
  49. Compiler::Compiler(ParsedIR &&ir_)
  50. {
  51. set_ir(std::move(ir_));
  52. }
  53. void Compiler::set_ir(ParsedIR &&ir_)
  54. {
  55. ir = std::move(ir_);
  56. parse_fixup();
  57. }
  58. void Compiler::set_ir(const ParsedIR &ir_)
  59. {
  60. ir = ir_;
  61. parse_fixup();
  62. }
  63. string Compiler::compile()
  64. {
  65. return "";
  66. }
  67. bool Compiler::variable_storage_is_aliased(const SPIRVariable &v)
  68. {
  69. auto &type = get<SPIRType>(v.basetype);
  70. bool ssbo = v.storage == StorageClassStorageBuffer ||
  71. ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
  72. bool image = type.basetype == SPIRType::Image;
  73. bool counter = type.basetype == SPIRType::AtomicCounter;
  74. bool buffer_reference = type.storage == StorageClassPhysicalStorageBuffer;
  75. bool is_restrict;
  76. if (ssbo)
  77. is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
  78. else
  79. is_restrict = has_decoration(v.self, DecorationRestrict);
  80. return !is_restrict && (ssbo || image || counter || buffer_reference);
  81. }
  82. bool Compiler::block_is_control_dependent(const SPIRBlock &block)
  83. {
  84. for (auto &i : block.ops)
  85. {
  86. auto ops = stream(i);
  87. auto op = static_cast<Op>(i.op);
  88. switch (op)
  89. {
  90. case OpFunctionCall:
  91. {
  92. uint32_t func = ops[2];
  93. if (function_is_control_dependent(get<SPIRFunction>(func)))
  94. return true;
  95. break;
  96. }
  97. // Derivatives
  98. case OpDPdx:
  99. case OpDPdxCoarse:
  100. case OpDPdxFine:
  101. case OpDPdy:
  102. case OpDPdyCoarse:
  103. case OpDPdyFine:
  104. case OpFwidth:
  105. case OpFwidthCoarse:
  106. case OpFwidthFine:
  107. // Anything implicit LOD
  108. case OpImageSampleImplicitLod:
  109. case OpImageSampleDrefImplicitLod:
  110. case OpImageSampleProjImplicitLod:
  111. case OpImageSampleProjDrefImplicitLod:
  112. case OpImageSparseSampleImplicitLod:
  113. case OpImageSparseSampleDrefImplicitLod:
  114. case OpImageSparseSampleProjImplicitLod:
  115. case OpImageSparseSampleProjDrefImplicitLod:
  116. case OpImageQueryLod:
  117. case OpImageDrefGather:
  118. case OpImageGather:
  119. case OpImageSparseDrefGather:
  120. case OpImageSparseGather:
  121. // Anything subgroups
  122. case OpGroupNonUniformElect:
  123. case OpGroupNonUniformAll:
  124. case OpGroupNonUniformAny:
  125. case OpGroupNonUniformAllEqual:
  126. case OpGroupNonUniformBroadcast:
  127. case OpGroupNonUniformBroadcastFirst:
  128. case OpGroupNonUniformBallot:
  129. case OpGroupNonUniformInverseBallot:
  130. case OpGroupNonUniformBallotBitExtract:
  131. case OpGroupNonUniformBallotBitCount:
  132. case OpGroupNonUniformBallotFindLSB:
  133. case OpGroupNonUniformBallotFindMSB:
  134. case OpGroupNonUniformShuffle:
  135. case OpGroupNonUniformShuffleXor:
  136. case OpGroupNonUniformShuffleUp:
  137. case OpGroupNonUniformShuffleDown:
  138. case OpGroupNonUniformIAdd:
  139. case OpGroupNonUniformFAdd:
  140. case OpGroupNonUniformIMul:
  141. case OpGroupNonUniformFMul:
  142. case OpGroupNonUniformSMin:
  143. case OpGroupNonUniformUMin:
  144. case OpGroupNonUniformFMin:
  145. case OpGroupNonUniformSMax:
  146. case OpGroupNonUniformUMax:
  147. case OpGroupNonUniformFMax:
  148. case OpGroupNonUniformBitwiseAnd:
  149. case OpGroupNonUniformBitwiseOr:
  150. case OpGroupNonUniformBitwiseXor:
  151. case OpGroupNonUniformLogicalAnd:
  152. case OpGroupNonUniformLogicalOr:
  153. case OpGroupNonUniformLogicalXor:
  154. case OpGroupNonUniformQuadBroadcast:
  155. case OpGroupNonUniformQuadSwap:
  156. case OpGroupNonUniformRotateKHR:
  157. // Control barriers
  158. case OpControlBarrier:
  159. return true;
  160. default:
  161. break;
  162. }
  163. }
  164. return false;
  165. }
  166. bool Compiler::block_is_pure(const SPIRBlock &block)
  167. {
  168. // This is a global side effect of the function.
  169. if (block.terminator == SPIRBlock::Kill ||
  170. block.terminator == SPIRBlock::TerminateRay ||
  171. block.terminator == SPIRBlock::IgnoreIntersection ||
  172. block.terminator == SPIRBlock::EmitMeshTasks)
  173. return false;
  174. for (auto &i : block.ops)
  175. {
  176. auto ops = stream(i);
  177. auto op = static_cast<Op>(i.op);
  178. switch (op)
  179. {
  180. case OpFunctionCall:
  181. {
  182. uint32_t func = ops[2];
  183. if (!function_is_pure(get<SPIRFunction>(func)))
  184. return false;
  185. break;
  186. }
  187. case OpCopyMemory:
  188. case OpStore:
  189. case OpCooperativeMatrixStoreKHR:
  190. {
  191. auto &type = expression_type(ops[0]);
  192. if (type.storage != StorageClassFunction)
  193. return false;
  194. break;
  195. }
  196. case OpImageWrite:
  197. return false;
  198. // Atomics are impure.
  199. case OpAtomicLoad:
  200. case OpAtomicStore:
  201. case OpAtomicExchange:
  202. case OpAtomicCompareExchange:
  203. case OpAtomicCompareExchangeWeak:
  204. case OpAtomicIIncrement:
  205. case OpAtomicIDecrement:
  206. case OpAtomicIAdd:
  207. case OpAtomicISub:
  208. case OpAtomicSMin:
  209. case OpAtomicUMin:
  210. case OpAtomicSMax:
  211. case OpAtomicUMax:
  212. case OpAtomicAnd:
  213. case OpAtomicOr:
  214. case OpAtomicXor:
  215. return false;
  216. // Geometry shader builtins modify global state.
  217. case OpEndPrimitive:
  218. case OpEmitStreamVertex:
  219. case OpEndStreamPrimitive:
  220. case OpEmitVertex:
  221. return false;
  222. // Mesh shader functions modify global state.
  223. // (EmitMeshTasks is a terminator).
  224. case OpSetMeshOutputsEXT:
  225. return false;
  226. // Barriers disallow any reordering, so we should treat blocks with barrier as writing.
  227. case OpControlBarrier:
  228. case OpMemoryBarrier:
  229. return false;
  230. // Ray tracing builtins are impure.
  231. case OpReportIntersectionKHR:
  232. case OpIgnoreIntersectionNV:
  233. case OpTerminateRayNV:
  234. case OpTraceNV:
  235. case OpTraceRayKHR:
  236. case OpExecuteCallableNV:
  237. case OpExecuteCallableKHR:
  238. case OpRayQueryInitializeKHR:
  239. case OpRayQueryTerminateKHR:
  240. case OpRayQueryGenerateIntersectionKHR:
  241. case OpRayQueryConfirmIntersectionKHR:
  242. case OpRayQueryProceedKHR:
  243. // There are various getters in ray query, but they are considered pure.
  244. return false;
  245. // OpExtInst is potentially impure depending on extension, but GLSL builtins are at least pure.
  246. case OpDemoteToHelperInvocationEXT:
  247. // This is a global side effect of the function.
  248. return false;
  249. case OpExtInst:
  250. {
  251. uint32_t extension_set = ops[2];
  252. if (get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
  253. {
  254. auto op_450 = static_cast<GLSLstd450>(ops[3]);
  255. switch (op_450)
  256. {
  257. case GLSLstd450Modf:
  258. case GLSLstd450Frexp:
  259. {
  260. auto &type = expression_type(ops[5]);
  261. if (type.storage != StorageClassFunction)
  262. return false;
  263. break;
  264. }
  265. default:
  266. break;
  267. }
  268. }
  269. break;
  270. }
  271. default:
  272. break;
  273. }
  274. }
  275. return true;
  276. }
  277. string Compiler::to_name(uint32_t id, bool allow_alias) const
  278. {
  279. if (allow_alias && ir.ids[id].get_type() == TypeType)
  280. {
  281. // If this type is a simple alias, emit the
  282. // name of the original type instead.
  283. // We don't want to override the meta alias
  284. // as that can be overridden by the reflection APIs after parse.
  285. auto &type = get<SPIRType>(id);
  286. if (type.type_alias)
  287. {
  288. // If the alias master has been specially packed, we will have emitted a clean variant as well,
  289. // so skip the name aliasing here.
  290. if (!has_extended_decoration(type.type_alias, SPIRVCrossDecorationBufferBlockRepacked))
  291. return to_name(type.type_alias);
  292. }
  293. }
  294. auto &alias = ir.get_name(id);
  295. if (alias.empty())
  296. return join("_", id);
  297. else
  298. return alias;
  299. }
  300. bool Compiler::function_is_pure(const SPIRFunction &func)
  301. {
  302. for (auto block : func.blocks)
  303. if (!block_is_pure(get<SPIRBlock>(block)))
  304. return false;
  305. return true;
  306. }
  307. bool Compiler::function_is_control_dependent(const SPIRFunction &func)
  308. {
  309. for (auto block : func.blocks)
  310. if (block_is_control_dependent(get<SPIRBlock>(block)))
  311. return true;
  312. return false;
  313. }
  314. void Compiler::register_global_read_dependencies(const SPIRBlock &block, uint32_t id)
  315. {
  316. for (auto &i : block.ops)
  317. {
  318. auto ops = stream(i);
  319. auto op = static_cast<Op>(i.op);
  320. switch (op)
  321. {
  322. case OpFunctionCall:
  323. {
  324. uint32_t func = ops[2];
  325. register_global_read_dependencies(get<SPIRFunction>(func), id);
  326. break;
  327. }
  328. case OpLoad:
  329. case OpCooperativeMatrixLoadKHR:
  330. case OpImageRead:
  331. {
  332. // If we're in a storage class which does not get invalidated, adding dependencies here is no big deal.
  333. auto *var = maybe_get_backing_variable(ops[2]);
  334. if (var && var->storage != StorageClassFunction)
  335. {
  336. auto &type = get<SPIRType>(var->basetype);
  337. // InputTargets are immutable.
  338. if (type.basetype != SPIRType::Image && type.image.dim != DimSubpassData)
  339. var->dependees.push_back(id);
  340. }
  341. break;
  342. }
  343. default:
  344. break;
  345. }
  346. }
  347. }
  348. void Compiler::register_global_read_dependencies(const SPIRFunction &func, uint32_t id)
  349. {
  350. for (auto block : func.blocks)
  351. register_global_read_dependencies(get<SPIRBlock>(block), id);
  352. }
  353. SPIRVariable *Compiler::maybe_get_backing_variable(uint32_t chain)
  354. {
  355. auto *var = maybe_get<SPIRVariable>(chain);
  356. if (!var)
  357. {
  358. auto *cexpr = maybe_get<SPIRExpression>(chain);
  359. if (cexpr)
  360. var = maybe_get<SPIRVariable>(cexpr->loaded_from);
  361. auto *access_chain = maybe_get<SPIRAccessChain>(chain);
  362. if (access_chain)
  363. var = maybe_get<SPIRVariable>(access_chain->loaded_from);
  364. }
  365. return var;
  366. }
  367. void Compiler::register_read(uint32_t expr, uint32_t chain, bool forwarded)
  368. {
  369. auto &e = get<SPIRExpression>(expr);
  370. auto *var = maybe_get_backing_variable(chain);
  371. if (var)
  372. {
  373. e.loaded_from = var->self;
  374. // If the backing variable is immutable, we do not need to depend on the variable.
  375. if (forwarded && !is_immutable(var->self))
  376. var->dependees.push_back(e.self);
  377. // If we load from a parameter, make sure we create "inout" if we also write to the parameter.
  378. // The default is "in" however, so we never invalidate our compilation by reading.
  379. if (var && var->parameter)
  380. var->parameter->read_count++;
  381. }
  382. }
  383. void Compiler::register_write(uint32_t chain)
  384. {
  385. auto *var = maybe_get<SPIRVariable>(chain);
  386. if (!var)
  387. {
  388. // If we're storing through an access chain, invalidate the backing variable instead.
  389. auto *expr = maybe_get<SPIRExpression>(chain);
  390. if (expr && expr->loaded_from)
  391. var = maybe_get<SPIRVariable>(expr->loaded_from);
  392. auto *access_chain = maybe_get<SPIRAccessChain>(chain);
  393. if (access_chain && access_chain->loaded_from)
  394. var = maybe_get<SPIRVariable>(access_chain->loaded_from);
  395. }
  396. auto &chain_type = expression_type(chain);
  397. if (var)
  398. {
  399. bool check_argument_storage_qualifier = true;
  400. auto &type = expression_type(chain);
  401. // If our variable is in a storage class which can alias with other buffers,
  402. // invalidate all variables which depend on aliased variables. And if this is a
  403. // variable pointer, then invalidate all variables regardless.
  404. if (get_variable_data_type(*var).pointer)
  405. {
  406. flush_all_active_variables();
  407. if (type.pointer_depth == 1)
  408. {
  409. // We have a backing variable which is a pointer-to-pointer type.
  410. // We are storing some data through a pointer acquired through that variable,
  411. // but we are not writing to the value of the variable itself,
  412. // i.e., we are not modifying the pointer directly.
  413. // If we are storing a non-pointer type (pointer_depth == 1),
  414. // we know that we are storing some unrelated data.
  415. // A case here would be
  416. // void foo(Foo * const *arg) {
  417. // Foo *bar = *arg;
  418. // bar->unrelated = 42;
  419. // }
  420. // arg, the argument is constant.
  421. check_argument_storage_qualifier = false;
  422. }
  423. }
  424. if (type.storage == StorageClassPhysicalStorageBuffer || variable_storage_is_aliased(*var))
  425. flush_all_aliased_variables();
  426. else if (var)
  427. flush_dependees(*var);
  428. // We tried to write to a parameter which is not marked with out qualifier, force a recompile.
  429. if (check_argument_storage_qualifier && var->parameter && var->parameter->write_count == 0)
  430. {
  431. var->parameter->write_count++;
  432. force_recompile();
  433. }
  434. }
  435. else if (chain_type.pointer)
  436. {
  437. // If we stored through a variable pointer, then we don't know which
  438. // variable we stored to. So *all* expressions after this point need to
  439. // be invalidated.
  440. // FIXME: If we can prove that the variable pointer will point to
  441. // only certain variables, we can invalidate only those.
  442. flush_all_active_variables();
  443. }
  444. // If chain_type.pointer is false, we're not writing to memory backed variables, but temporaries instead.
  445. // This can happen in copy_logical_type where we unroll complex reads and writes to temporaries.
  446. }
  447. void Compiler::flush_dependees(SPIRVariable &var)
  448. {
  449. for (auto expr : var.dependees)
  450. invalid_expressions.insert(expr);
  451. var.dependees.clear();
  452. }
  453. void Compiler::flush_all_aliased_variables()
  454. {
  455. for (auto aliased : aliased_variables)
  456. flush_dependees(get<SPIRVariable>(aliased));
  457. }
  458. void Compiler::flush_all_atomic_capable_variables()
  459. {
  460. for (auto global : global_variables)
  461. flush_dependees(get<SPIRVariable>(global));
  462. flush_all_aliased_variables();
  463. }
  464. void Compiler::flush_control_dependent_expressions(uint32_t block_id)
  465. {
  466. auto &block = get<SPIRBlock>(block_id);
  467. for (auto &expr : block.invalidate_expressions)
  468. invalid_expressions.insert(expr);
  469. block.invalidate_expressions.clear();
  470. }
  471. void Compiler::flush_all_active_variables()
  472. {
  473. // Invalidate all temporaries we read from variables in this block since they were forwarded.
  474. // Invalidate all temporaries we read from globals.
  475. for (auto &v : current_function->local_variables)
  476. flush_dependees(get<SPIRVariable>(v));
  477. for (auto &arg : current_function->arguments)
  478. flush_dependees(get<SPIRVariable>(arg.id));
  479. for (auto global : global_variables)
  480. flush_dependees(get<SPIRVariable>(global));
  481. flush_all_aliased_variables();
  482. }
  483. uint32_t Compiler::expression_type_id(uint32_t id) const
  484. {
  485. switch (ir.ids[id].get_type())
  486. {
  487. case TypeVariable:
  488. return get<SPIRVariable>(id).basetype;
  489. case TypeExpression:
  490. return get<SPIRExpression>(id).expression_type;
  491. case TypeConstant:
  492. return get<SPIRConstant>(id).constant_type;
  493. case TypeConstantOp:
  494. return get<SPIRConstantOp>(id).basetype;
  495. case TypeUndef:
  496. return get<SPIRUndef>(id).basetype;
  497. case TypeCombinedImageSampler:
  498. return get<SPIRCombinedImageSampler>(id).combined_type;
  499. case TypeAccessChain:
  500. return get<SPIRAccessChain>(id).basetype;
  501. default:
  502. SPIRV_CROSS_THROW("Cannot resolve expression type.");
  503. }
  504. }
  505. const SPIRType &Compiler::expression_type(uint32_t id) const
  506. {
  507. return get<SPIRType>(expression_type_id(id));
  508. }
  509. bool Compiler::expression_is_lvalue(uint32_t id) const
  510. {
  511. auto &type = expression_type(id);
  512. switch (type.basetype)
  513. {
  514. case SPIRType::SampledImage:
  515. case SPIRType::Image:
  516. case SPIRType::Sampler:
  517. return false;
  518. default:
  519. return true;
  520. }
  521. }
  522. bool Compiler::is_immutable(uint32_t id) const
  523. {
  524. if (ir.ids[id].get_type() == TypeVariable)
  525. {
  526. auto &var = get<SPIRVariable>(id);
  527. // Anything we load from the UniformConstant address space is guaranteed to be immutable.
  528. bool pointer_to_const = var.storage == StorageClassUniformConstant;
  529. return pointer_to_const || var.phi_variable || !expression_is_lvalue(id);
  530. }
  531. else if (ir.ids[id].get_type() == TypeAccessChain)
  532. return get<SPIRAccessChain>(id).immutable;
  533. else if (ir.ids[id].get_type() == TypeExpression)
  534. return get<SPIRExpression>(id).immutable;
  535. else if (ir.ids[id].get_type() == TypeConstant || ir.ids[id].get_type() == TypeConstantOp ||
  536. ir.ids[id].get_type() == TypeUndef)
  537. return true;
  538. else
  539. return false;
  540. }
  541. static inline bool storage_class_is_interface(spv::StorageClass storage)
  542. {
  543. switch (storage)
  544. {
  545. case StorageClassInput:
  546. case StorageClassOutput:
  547. case StorageClassUniform:
  548. case StorageClassUniformConstant:
  549. case StorageClassAtomicCounter:
  550. case StorageClassPushConstant:
  551. case StorageClassStorageBuffer:
  552. return true;
  553. default:
  554. return false;
  555. }
  556. }
  557. bool Compiler::is_hidden_variable(const SPIRVariable &var, bool include_builtins) const
  558. {
  559. if ((is_builtin_variable(var) && !include_builtins) || var.remapped_variable)
  560. return true;
  561. // Combined image samplers are always considered active as they are "magic" variables.
  562. if (find_if(begin(combined_image_samplers), end(combined_image_samplers), [&var](const CombinedImageSampler &samp) {
  563. return samp.combined_id == var.self;
  564. }) != end(combined_image_samplers))
  565. {
  566. return false;
  567. }
  568. // In SPIR-V 1.4 and up we must also use the active variable interface to disable global variables
  569. // which are not part of the entry point.
  570. if (ir.get_spirv_version() >= 0x10400 && var.storage != spv::StorageClassGeneric &&
  571. var.storage != spv::StorageClassFunction && !interface_variable_exists_in_entry_point(var.self))
  572. {
  573. return true;
  574. }
  575. return check_active_interface_variables && storage_class_is_interface(var.storage) &&
  576. active_interface_variables.find(var.self) == end(active_interface_variables);
  577. }
  578. bool Compiler::is_builtin_type(const SPIRType &type) const
  579. {
  580. auto *type_meta = ir.find_meta(type.self);
  581. // We can have builtin structs as well. If one member of a struct is builtin, the struct must also be builtin.
  582. if (type_meta)
  583. for (auto &m : type_meta->members)
  584. if (m.builtin)
  585. return true;
  586. return false;
  587. }
  588. bool Compiler::is_builtin_variable(const SPIRVariable &var) const
  589. {
  590. auto *m = ir.find_meta(var.self);
  591. if (var.compat_builtin || (m && m->decoration.builtin))
  592. return true;
  593. else
  594. return is_builtin_type(get<SPIRType>(var.basetype));
  595. }
  596. bool Compiler::is_member_builtin(const SPIRType &type, uint32_t index, BuiltIn *builtin) const
  597. {
  598. auto *type_meta = ir.find_meta(type.self);
  599. if (type_meta)
  600. {
  601. auto &memb = type_meta->members;
  602. if (index < memb.size() && memb[index].builtin)
  603. {
  604. if (builtin)
  605. *builtin = memb[index].builtin_type;
  606. return true;
  607. }
  608. }
  609. return false;
  610. }
  611. bool Compiler::is_scalar(const SPIRType &type) const
  612. {
  613. return type.basetype != SPIRType::Struct && type.vecsize == 1 && type.columns == 1;
  614. }
  615. bool Compiler::is_vector(const SPIRType &type) const
  616. {
  617. return type.vecsize > 1 && type.columns == 1;
  618. }
  619. bool Compiler::is_matrix(const SPIRType &type) const
  620. {
  621. return type.vecsize > 1 && type.columns > 1;
  622. }
  623. bool Compiler::is_array(const SPIRType &type) const
  624. {
  625. return type.op == OpTypeArray || type.op == OpTypeRuntimeArray;
  626. }
  627. bool Compiler::is_pointer(const SPIRType &type) const
  628. {
  629. return type.op == OpTypePointer && type.basetype != SPIRType::Unknown; // Ignore function pointers.
  630. }
  631. bool Compiler::is_physical_pointer(const SPIRType &type) const
  632. {
  633. return type.op == OpTypePointer && type.storage == StorageClassPhysicalStorageBuffer;
  634. }
  635. bool Compiler::is_physical_pointer_to_buffer_block(const SPIRType &type) const
  636. {
  637. return is_physical_pointer(type) && get_pointee_type(type).self == type.parent_type &&
  638. (has_decoration(type.self, DecorationBlock) ||
  639. has_decoration(type.self, DecorationBufferBlock));
  640. }
  641. bool Compiler::is_runtime_size_array(const SPIRType &type)
  642. {
  643. return type.op == OpTypeRuntimeArray;
  644. }
  645. ShaderResources Compiler::get_shader_resources() const
  646. {
  647. return get_shader_resources(nullptr);
  648. }
  649. ShaderResources Compiler::get_shader_resources(const unordered_set<VariableID> &active_variables) const
  650. {
  651. return get_shader_resources(&active_variables);
  652. }
  653. bool Compiler::InterfaceVariableAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  654. {
  655. uint32_t variable = 0;
  656. switch (opcode)
  657. {
  658. // Need this first, otherwise, GCC complains about unhandled switch statements.
  659. default:
  660. break;
  661. case OpFunctionCall:
  662. {
  663. // Invalid SPIR-V.
  664. if (length < 3)
  665. return false;
  666. uint32_t count = length - 3;
  667. args += 3;
  668. for (uint32_t i = 0; i < count; i++)
  669. {
  670. auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
  671. if (var && storage_class_is_interface(var->storage))
  672. variables.insert(args[i]);
  673. }
  674. break;
  675. }
  676. case OpSelect:
  677. {
  678. // Invalid SPIR-V.
  679. if (length < 5)
  680. return false;
  681. uint32_t count = length - 3;
  682. args += 3;
  683. for (uint32_t i = 0; i < count; i++)
  684. {
  685. auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
  686. if (var && storage_class_is_interface(var->storage))
  687. variables.insert(args[i]);
  688. }
  689. break;
  690. }
  691. case OpPhi:
  692. {
  693. // Invalid SPIR-V.
  694. if (length < 2)
  695. return false;
  696. uint32_t count = length - 2;
  697. args += 2;
  698. for (uint32_t i = 0; i < count; i += 2)
  699. {
  700. auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
  701. if (var && storage_class_is_interface(var->storage))
  702. variables.insert(args[i]);
  703. }
  704. break;
  705. }
  706. case OpAtomicStore:
  707. case OpStore:
  708. case OpCooperativeMatrixStoreKHR:
  709. // Invalid SPIR-V.
  710. if (length < 1)
  711. return false;
  712. variable = args[0];
  713. break;
  714. case OpCopyMemory:
  715. {
  716. if (length < 2)
  717. return false;
  718. auto *var = compiler.maybe_get<SPIRVariable>(args[0]);
  719. if (var && storage_class_is_interface(var->storage))
  720. variables.insert(args[0]);
  721. var = compiler.maybe_get<SPIRVariable>(args[1]);
  722. if (var && storage_class_is_interface(var->storage))
  723. variables.insert(args[1]);
  724. break;
  725. }
  726. case OpExtInst:
  727. {
  728. if (length < 3)
  729. return false;
  730. auto &extension_set = compiler.get<SPIRExtension>(args[2]);
  731. switch (extension_set.ext)
  732. {
  733. case SPIRExtension::GLSL:
  734. {
  735. auto op = static_cast<GLSLstd450>(args[3]);
  736. switch (op)
  737. {
  738. case GLSLstd450InterpolateAtCentroid:
  739. case GLSLstd450InterpolateAtSample:
  740. case GLSLstd450InterpolateAtOffset:
  741. {
  742. auto *var = compiler.maybe_get<SPIRVariable>(args[4]);
  743. if (var && storage_class_is_interface(var->storage))
  744. variables.insert(args[4]);
  745. break;
  746. }
  747. case GLSLstd450Modf:
  748. case GLSLstd450Fract:
  749. {
  750. auto *var = compiler.maybe_get<SPIRVariable>(args[5]);
  751. if (var && storage_class_is_interface(var->storage))
  752. variables.insert(args[5]);
  753. break;
  754. }
  755. default:
  756. break;
  757. }
  758. break;
  759. }
  760. case SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter:
  761. {
  762. enum AMDShaderExplicitVertexParameter
  763. {
  764. InterpolateAtVertexAMD = 1
  765. };
  766. auto op = static_cast<AMDShaderExplicitVertexParameter>(args[3]);
  767. switch (op)
  768. {
  769. case InterpolateAtVertexAMD:
  770. {
  771. auto *var = compiler.maybe_get<SPIRVariable>(args[4]);
  772. if (var && storage_class_is_interface(var->storage))
  773. variables.insert(args[4]);
  774. break;
  775. }
  776. default:
  777. break;
  778. }
  779. break;
  780. }
  781. default:
  782. break;
  783. }
  784. break;
  785. }
  786. case OpAccessChain:
  787. case OpInBoundsAccessChain:
  788. case OpPtrAccessChain:
  789. case OpLoad:
  790. case OpCooperativeMatrixLoadKHR:
  791. case OpCopyObject:
  792. case OpImageTexelPointer:
  793. case OpAtomicLoad:
  794. case OpAtomicExchange:
  795. case OpAtomicCompareExchange:
  796. case OpAtomicCompareExchangeWeak:
  797. case OpAtomicIIncrement:
  798. case OpAtomicIDecrement:
  799. case OpAtomicIAdd:
  800. case OpAtomicISub:
  801. case OpAtomicSMin:
  802. case OpAtomicUMin:
  803. case OpAtomicSMax:
  804. case OpAtomicUMax:
  805. case OpAtomicAnd:
  806. case OpAtomicOr:
  807. case OpAtomicXor:
  808. case OpArrayLength:
  809. // Invalid SPIR-V.
  810. if (length < 3)
  811. return false;
  812. variable = args[2];
  813. break;
  814. }
  815. if (variable)
  816. {
  817. auto *var = compiler.maybe_get<SPIRVariable>(variable);
  818. if (var && storage_class_is_interface(var->storage))
  819. variables.insert(variable);
  820. }
  821. return true;
  822. }
  823. unordered_set<VariableID> Compiler::get_active_interface_variables() const
  824. {
  825. // Traverse the call graph and find all interface variables which are in use.
  826. unordered_set<VariableID> variables;
  827. InterfaceVariableAccessHandler handler(*this, variables);
  828. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  829. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
  830. if (var.storage != StorageClassOutput)
  831. return;
  832. if (!interface_variable_exists_in_entry_point(var.self))
  833. return;
  834. // An output variable which is just declared (but uninitialized) might be read by subsequent stages
  835. // so we should force-enable these outputs,
  836. // since compilation will fail if a subsequent stage attempts to read from the variable in question.
  837. // Also, make sure we preserve output variables which are only initialized, but never accessed by any code.
  838. if (var.initializer != ID(0) || get_execution_model() != ExecutionModelFragment)
  839. variables.insert(var.self);
  840. });
  841. // If we needed to create one, we'll need it.
  842. if (dummy_sampler_id)
  843. variables.insert(dummy_sampler_id);
  844. return variables;
  845. }
  846. void Compiler::set_enabled_interface_variables(std::unordered_set<VariableID> active_variables)
  847. {
  848. active_interface_variables = std::move(active_variables);
  849. check_active_interface_variables = true;
  850. }
  851. ShaderResources Compiler::get_shader_resources(const unordered_set<VariableID> *active_variables) const
  852. {
  853. ShaderResources res;
  854. bool ssbo_instance_name = reflection_ssbo_instance_name_is_significant();
  855. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
  856. auto &type = this->get<SPIRType>(var.basetype);
  857. // It is possible for uniform storage classes to be passed as function parameters, so detect
  858. // that. To detect function parameters, check of StorageClass of variable is function scope.
  859. if (var.storage == StorageClassFunction || !type.pointer)
  860. return;
  861. if (active_variables && active_variables->find(var.self) == end(*active_variables))
  862. return;
  863. // In SPIR-V 1.4 and up, every global must be present in the entry point interface list,
  864. // not just IO variables.
  865. bool active_in_entry_point = true;
  866. if (ir.get_spirv_version() < 0x10400)
  867. {
  868. if (var.storage == StorageClassInput || var.storage == StorageClassOutput)
  869. active_in_entry_point = interface_variable_exists_in_entry_point(var.self);
  870. }
  871. else
  872. active_in_entry_point = interface_variable_exists_in_entry_point(var.self);
  873. if (!active_in_entry_point)
  874. return;
  875. bool is_builtin = is_builtin_variable(var);
  876. if (is_builtin)
  877. {
  878. if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
  879. return;
  880. auto &list = var.storage == StorageClassInput ? res.builtin_inputs : res.builtin_outputs;
  881. BuiltInResource resource;
  882. if (has_decoration(type.self, DecorationBlock))
  883. {
  884. resource.resource = { var.self, var.basetype, type.self,
  885. get_remapped_declared_block_name(var.self, false) };
  886. for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
  887. {
  888. resource.value_type_id = type.member_types[i];
  889. resource.builtin = BuiltIn(get_member_decoration(type.self, i, DecorationBuiltIn));
  890. list.push_back(resource);
  891. }
  892. }
  893. else
  894. {
  895. bool strip_array =
  896. !has_decoration(var.self, DecorationPatch) && (
  897. get_execution_model() == ExecutionModelTessellationControl ||
  898. (get_execution_model() == ExecutionModelTessellationEvaluation &&
  899. var.storage == StorageClassInput));
  900. resource.resource = { var.self, var.basetype, type.self, get_name(var.self) };
  901. if (strip_array && !type.array.empty())
  902. resource.value_type_id = get_variable_data_type(var).parent_type;
  903. else
  904. resource.value_type_id = get_variable_data_type_id(var);
  905. assert(resource.value_type_id);
  906. resource.builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
  907. list.push_back(std::move(resource));
  908. }
  909. return;
  910. }
  911. // Input
  912. if (var.storage == StorageClassInput)
  913. {
  914. if (has_decoration(type.self, DecorationBlock))
  915. {
  916. res.stage_inputs.push_back(
  917. { var.self, var.basetype, type.self,
  918. get_remapped_declared_block_name(var.self, false) });
  919. }
  920. else
  921. res.stage_inputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  922. }
  923. // Subpass inputs
  924. else if (var.storage == StorageClassUniformConstant && type.image.dim == DimSubpassData)
  925. {
  926. res.subpass_inputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  927. }
  928. // Outputs
  929. else if (var.storage == StorageClassOutput)
  930. {
  931. if (has_decoration(type.self, DecorationBlock))
  932. {
  933. res.stage_outputs.push_back(
  934. { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, false) });
  935. }
  936. else
  937. res.stage_outputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  938. }
  939. // UBOs
  940. else if (type.storage == StorageClassUniform && has_decoration(type.self, DecorationBlock))
  941. {
  942. res.uniform_buffers.push_back(
  943. { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, false) });
  944. }
  945. // Old way to declare SSBOs.
  946. else if (type.storage == StorageClassUniform && has_decoration(type.self, DecorationBufferBlock))
  947. {
  948. res.storage_buffers.push_back(
  949. { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
  950. }
  951. // Modern way to declare SSBOs.
  952. else if (type.storage == StorageClassStorageBuffer)
  953. {
  954. res.storage_buffers.push_back(
  955. { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
  956. }
  957. // Push constant blocks
  958. else if (type.storage == StorageClassPushConstant)
  959. {
  960. // There can only be one push constant block, but keep the vector in case this restriction is lifted
  961. // in the future.
  962. res.push_constant_buffers.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  963. }
  964. else if (type.storage == StorageClassShaderRecordBufferKHR)
  965. {
  966. res.shader_record_buffers.push_back({ var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
  967. }
  968. // Atomic counters
  969. else if (type.storage == StorageClassAtomicCounter)
  970. {
  971. res.atomic_counters.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  972. }
  973. else if (type.storage == StorageClassUniformConstant)
  974. {
  975. if (type.basetype == SPIRType::Image)
  976. {
  977. // Images
  978. if (type.image.sampled == 2)
  979. {
  980. res.storage_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  981. }
  982. // Separate images
  983. else if (type.image.sampled == 1)
  984. {
  985. res.separate_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  986. }
  987. }
  988. // Separate samplers
  989. else if (type.basetype == SPIRType::Sampler)
  990. {
  991. res.separate_samplers.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  992. }
  993. // Textures
  994. else if (type.basetype == SPIRType::SampledImage)
  995. {
  996. res.sampled_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  997. }
  998. // Acceleration structures
  999. else if (type.basetype == SPIRType::AccelerationStructure)
  1000. {
  1001. res.acceleration_structures.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  1002. }
  1003. else
  1004. {
  1005. res.gl_plain_uniforms.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
  1006. }
  1007. }
  1008. });
  1009. return res;
  1010. }
  1011. bool Compiler::type_is_top_level_block(const SPIRType &type) const
  1012. {
  1013. if (type.basetype != SPIRType::Struct)
  1014. return false;
  1015. return has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
  1016. }
  1017. bool Compiler::type_is_block_like(const SPIRType &type) const
  1018. {
  1019. if (type_is_top_level_block(type))
  1020. return true;
  1021. if (type.basetype == SPIRType::Struct)
  1022. {
  1023. // Block-like types may have Offset decorations.
  1024. for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
  1025. if (has_member_decoration(type.self, i, DecorationOffset))
  1026. return true;
  1027. }
  1028. return false;
  1029. }
  1030. void Compiler::parse_fixup()
  1031. {
  1032. // Figure out specialization constants for work group sizes.
  1033. for (auto id_ : ir.ids_for_constant_or_variable)
  1034. {
  1035. auto &id = ir.ids[id_];
  1036. if (id.get_type() == TypeConstant)
  1037. {
  1038. auto &c = id.get<SPIRConstant>();
  1039. if (has_decoration(c.self, DecorationBuiltIn) &&
  1040. BuiltIn(get_decoration(c.self, DecorationBuiltIn)) == BuiltInWorkgroupSize)
  1041. {
  1042. // In current SPIR-V, there can be just one constant like this.
  1043. // All entry points will receive the constant value.
  1044. // WorkgroupSize take precedence over LocalSizeId.
  1045. for (auto &entry : ir.entry_points)
  1046. {
  1047. entry.second.workgroup_size.constant = c.self;
  1048. entry.second.workgroup_size.x = c.scalar(0, 0);
  1049. entry.second.workgroup_size.y = c.scalar(0, 1);
  1050. entry.second.workgroup_size.z = c.scalar(0, 2);
  1051. }
  1052. }
  1053. }
  1054. else if (id.get_type() == TypeVariable)
  1055. {
  1056. auto &var = id.get<SPIRVariable>();
  1057. if (var.storage == StorageClassPrivate || var.storage == StorageClassWorkgroup ||
  1058. var.storage == StorageClassTaskPayloadWorkgroupEXT ||
  1059. var.storage == StorageClassOutput)
  1060. {
  1061. global_variables.push_back(var.self);
  1062. }
  1063. if (variable_storage_is_aliased(var))
  1064. aliased_variables.push_back(var.self);
  1065. }
  1066. }
  1067. }
  1068. void Compiler::update_name_cache(unordered_set<string> &cache_primary, const unordered_set<string> &cache_secondary,
  1069. string &name)
  1070. {
  1071. if (name.empty())
  1072. return;
  1073. const auto find_name = [&](const string &n) -> bool {
  1074. if (cache_primary.find(n) != end(cache_primary))
  1075. return true;
  1076. if (&cache_primary != &cache_secondary)
  1077. if (cache_secondary.find(n) != end(cache_secondary))
  1078. return true;
  1079. return false;
  1080. };
  1081. const auto insert_name = [&](const string &n) { cache_primary.insert(n); };
  1082. if (!find_name(name))
  1083. {
  1084. insert_name(name);
  1085. return;
  1086. }
  1087. uint32_t counter = 0;
  1088. auto tmpname = name;
  1089. bool use_linked_underscore = true;
  1090. if (tmpname == "_")
  1091. {
  1092. // We cannot just append numbers, as we will end up creating internally reserved names.
  1093. // Make it like _0_<counter> instead.
  1094. tmpname += "0";
  1095. }
  1096. else if (tmpname.back() == '_')
  1097. {
  1098. // The last_character is an underscore, so we don't need to link in underscore.
  1099. // This would violate double underscore rules.
  1100. use_linked_underscore = false;
  1101. }
  1102. // If there is a collision (very rare),
  1103. // keep tacking on extra identifier until it's unique.
  1104. do
  1105. {
  1106. counter++;
  1107. name = tmpname + (use_linked_underscore ? "_" : "") + convert_to_string(counter);
  1108. } while (find_name(name));
  1109. insert_name(name);
  1110. }
  1111. void Compiler::update_name_cache(unordered_set<string> &cache, string &name)
  1112. {
  1113. update_name_cache(cache, cache, name);
  1114. }
  1115. void Compiler::set_name(ID id, const std::string &name)
  1116. {
  1117. ir.set_name(id, name);
  1118. }
  1119. const SPIRType &Compiler::get_type(TypeID id) const
  1120. {
  1121. return get<SPIRType>(id);
  1122. }
  1123. const SPIRType &Compiler::get_type_from_variable(VariableID id) const
  1124. {
  1125. return get<SPIRType>(get<SPIRVariable>(id).basetype);
  1126. }
  1127. uint32_t Compiler::get_pointee_type_id(uint32_t type_id) const
  1128. {
  1129. auto *p_type = &get<SPIRType>(type_id);
  1130. if (p_type->pointer)
  1131. {
  1132. assert(p_type->parent_type);
  1133. type_id = p_type->parent_type;
  1134. }
  1135. return type_id;
  1136. }
  1137. const SPIRType &Compiler::get_pointee_type(const SPIRType &type) const
  1138. {
  1139. auto *p_type = &type;
  1140. if (p_type->pointer)
  1141. {
  1142. assert(p_type->parent_type);
  1143. p_type = &get<SPIRType>(p_type->parent_type);
  1144. }
  1145. return *p_type;
  1146. }
  1147. const SPIRType &Compiler::get_pointee_type(uint32_t type_id) const
  1148. {
  1149. return get_pointee_type(get<SPIRType>(type_id));
  1150. }
  1151. uint32_t Compiler::get_variable_data_type_id(const SPIRVariable &var) const
  1152. {
  1153. if (var.phi_variable || var.storage == spv::StorageClass::StorageClassAtomicCounter)
  1154. return var.basetype;
  1155. return get_pointee_type_id(var.basetype);
  1156. }
  1157. SPIRType &Compiler::get_variable_data_type(const SPIRVariable &var)
  1158. {
  1159. return get<SPIRType>(get_variable_data_type_id(var));
  1160. }
  1161. const SPIRType &Compiler::get_variable_data_type(const SPIRVariable &var) const
  1162. {
  1163. return get<SPIRType>(get_variable_data_type_id(var));
  1164. }
  1165. SPIRType &Compiler::get_variable_element_type(const SPIRVariable &var)
  1166. {
  1167. SPIRType *type = &get_variable_data_type(var);
  1168. if (is_array(*type))
  1169. type = &get<SPIRType>(type->parent_type);
  1170. return *type;
  1171. }
  1172. const SPIRType &Compiler::get_variable_element_type(const SPIRVariable &var) const
  1173. {
  1174. const SPIRType *type = &get_variable_data_type(var);
  1175. if (is_array(*type))
  1176. type = &get<SPIRType>(type->parent_type);
  1177. return *type;
  1178. }
  1179. bool Compiler::is_sampled_image_type(const SPIRType &type)
  1180. {
  1181. return (type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage) && type.image.sampled == 1 &&
  1182. type.image.dim != DimBuffer;
  1183. }
  1184. void Compiler::set_member_decoration_string(TypeID id, uint32_t index, spv::Decoration decoration,
  1185. const std::string &argument)
  1186. {
  1187. ir.set_member_decoration_string(id, index, decoration, argument);
  1188. }
  1189. void Compiler::set_member_decoration(TypeID id, uint32_t index, Decoration decoration, uint32_t argument)
  1190. {
  1191. ir.set_member_decoration(id, index, decoration, argument);
  1192. }
  1193. void Compiler::set_member_name(TypeID id, uint32_t index, const std::string &name)
  1194. {
  1195. ir.set_member_name(id, index, name);
  1196. }
  1197. const std::string &Compiler::get_member_name(TypeID id, uint32_t index) const
  1198. {
  1199. return ir.get_member_name(id, index);
  1200. }
  1201. void Compiler::set_qualified_name(uint32_t id, const string &name)
  1202. {
  1203. ir.meta[id].decoration.qualified_alias = name;
  1204. }
  1205. void Compiler::set_member_qualified_name(uint32_t type_id, uint32_t index, const std::string &name)
  1206. {
  1207. ir.meta[type_id].members.resize(max(ir.meta[type_id].members.size(), size_t(index) + 1));
  1208. ir.meta[type_id].members[index].qualified_alias = name;
  1209. }
  1210. const string &Compiler::get_member_qualified_name(TypeID type_id, uint32_t index) const
  1211. {
  1212. auto *m = ir.find_meta(type_id);
  1213. if (m && index < m->members.size())
  1214. return m->members[index].qualified_alias;
  1215. else
  1216. return ir.get_empty_string();
  1217. }
  1218. uint32_t Compiler::get_member_decoration(TypeID id, uint32_t index, Decoration decoration) const
  1219. {
  1220. return ir.get_member_decoration(id, index, decoration);
  1221. }
  1222. const Bitset &Compiler::get_member_decoration_bitset(TypeID id, uint32_t index) const
  1223. {
  1224. return ir.get_member_decoration_bitset(id, index);
  1225. }
  1226. bool Compiler::has_member_decoration(TypeID id, uint32_t index, Decoration decoration) const
  1227. {
  1228. return ir.has_member_decoration(id, index, decoration);
  1229. }
  1230. void Compiler::unset_member_decoration(TypeID id, uint32_t index, Decoration decoration)
  1231. {
  1232. ir.unset_member_decoration(id, index, decoration);
  1233. }
  1234. void Compiler::set_decoration_string(ID id, spv::Decoration decoration, const std::string &argument)
  1235. {
  1236. ir.set_decoration_string(id, decoration, argument);
  1237. }
  1238. void Compiler::set_decoration(ID id, Decoration decoration, uint32_t argument)
  1239. {
  1240. ir.set_decoration(id, decoration, argument);
  1241. }
  1242. void Compiler::set_extended_decoration(uint32_t id, ExtendedDecorations decoration, uint32_t value)
  1243. {
  1244. auto &dec = ir.meta[id].decoration;
  1245. dec.extended.flags.set(decoration);
  1246. dec.extended.values[decoration] = value;
  1247. }
  1248. void Compiler::set_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration,
  1249. uint32_t value)
  1250. {
  1251. ir.meta[type].members.resize(max(ir.meta[type].members.size(), size_t(index) + 1));
  1252. auto &dec = ir.meta[type].members[index];
  1253. dec.extended.flags.set(decoration);
  1254. dec.extended.values[decoration] = value;
  1255. }
  1256. static uint32_t get_default_extended_decoration(ExtendedDecorations decoration)
  1257. {
  1258. switch (decoration)
  1259. {
  1260. case SPIRVCrossDecorationResourceIndexPrimary:
  1261. case SPIRVCrossDecorationResourceIndexSecondary:
  1262. case SPIRVCrossDecorationResourceIndexTertiary:
  1263. case SPIRVCrossDecorationResourceIndexQuaternary:
  1264. case SPIRVCrossDecorationInterfaceMemberIndex:
  1265. return ~(0u);
  1266. default:
  1267. return 0;
  1268. }
  1269. }
  1270. uint32_t Compiler::get_extended_decoration(uint32_t id, ExtendedDecorations decoration) const
  1271. {
  1272. auto *m = ir.find_meta(id);
  1273. if (!m)
  1274. return 0;
  1275. auto &dec = m->decoration;
  1276. if (!dec.extended.flags.get(decoration))
  1277. return get_default_extended_decoration(decoration);
  1278. return dec.extended.values[decoration];
  1279. }
  1280. uint32_t Compiler::get_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration) const
  1281. {
  1282. auto *m = ir.find_meta(type);
  1283. if (!m)
  1284. return 0;
  1285. if (index >= m->members.size())
  1286. return 0;
  1287. auto &dec = m->members[index];
  1288. if (!dec.extended.flags.get(decoration))
  1289. return get_default_extended_decoration(decoration);
  1290. return dec.extended.values[decoration];
  1291. }
  1292. bool Compiler::has_extended_decoration(uint32_t id, ExtendedDecorations decoration) const
  1293. {
  1294. auto *m = ir.find_meta(id);
  1295. if (!m)
  1296. return false;
  1297. auto &dec = m->decoration;
  1298. return dec.extended.flags.get(decoration);
  1299. }
  1300. bool Compiler::has_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration) const
  1301. {
  1302. auto *m = ir.find_meta(type);
  1303. if (!m)
  1304. return false;
  1305. if (index >= m->members.size())
  1306. return false;
  1307. auto &dec = m->members[index];
  1308. return dec.extended.flags.get(decoration);
  1309. }
  1310. void Compiler::unset_extended_decoration(uint32_t id, ExtendedDecorations decoration)
  1311. {
  1312. auto &dec = ir.meta[id].decoration;
  1313. dec.extended.flags.clear(decoration);
  1314. dec.extended.values[decoration] = 0;
  1315. }
  1316. void Compiler::unset_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration)
  1317. {
  1318. ir.meta[type].members.resize(max(ir.meta[type].members.size(), size_t(index) + 1));
  1319. auto &dec = ir.meta[type].members[index];
  1320. dec.extended.flags.clear(decoration);
  1321. dec.extended.values[decoration] = 0;
  1322. }
  1323. StorageClass Compiler::get_storage_class(VariableID id) const
  1324. {
  1325. return get<SPIRVariable>(id).storage;
  1326. }
  1327. const std::string &Compiler::get_name(ID id) const
  1328. {
  1329. return ir.get_name(id);
  1330. }
  1331. const std::string Compiler::get_fallback_name(ID id) const
  1332. {
  1333. return join("_", id);
  1334. }
  1335. const std::string Compiler::get_block_fallback_name(VariableID id) const
  1336. {
  1337. auto &var = get<SPIRVariable>(id);
  1338. if (get_name(id).empty())
  1339. return join("_", get<SPIRType>(var.basetype).self, "_", id);
  1340. else
  1341. return get_name(id);
  1342. }
  1343. const Bitset &Compiler::get_decoration_bitset(ID id) const
  1344. {
  1345. return ir.get_decoration_bitset(id);
  1346. }
  1347. bool Compiler::has_decoration(ID id, Decoration decoration) const
  1348. {
  1349. return ir.has_decoration(id, decoration);
  1350. }
  1351. const string &Compiler::get_decoration_string(ID id, Decoration decoration) const
  1352. {
  1353. return ir.get_decoration_string(id, decoration);
  1354. }
  1355. const string &Compiler::get_member_decoration_string(TypeID id, uint32_t index, Decoration decoration) const
  1356. {
  1357. return ir.get_member_decoration_string(id, index, decoration);
  1358. }
  1359. uint32_t Compiler::get_decoration(ID id, Decoration decoration) const
  1360. {
  1361. return ir.get_decoration(id, decoration);
  1362. }
  1363. void Compiler::unset_decoration(ID id, Decoration decoration)
  1364. {
  1365. ir.unset_decoration(id, decoration);
  1366. }
  1367. bool Compiler::get_binary_offset_for_decoration(VariableID id, spv::Decoration decoration, uint32_t &word_offset) const
  1368. {
  1369. auto *m = ir.find_meta(id);
  1370. if (!m)
  1371. return false;
  1372. auto &word_offsets = m->decoration_word_offset;
  1373. auto itr = word_offsets.find(decoration);
  1374. if (itr == end(word_offsets))
  1375. return false;
  1376. word_offset = itr->second;
  1377. return true;
  1378. }
  1379. bool Compiler::block_is_noop(const SPIRBlock &block) const
  1380. {
  1381. if (block.terminator != SPIRBlock::Direct)
  1382. return false;
  1383. auto &child = get<SPIRBlock>(block.next_block);
  1384. // If this block participates in PHI, the block isn't really noop.
  1385. for (auto &phi : block.phi_variables)
  1386. if (phi.parent == block.self || phi.parent == child.self)
  1387. return false;
  1388. for (auto &phi : child.phi_variables)
  1389. if (phi.parent == block.self)
  1390. return false;
  1391. // Verify all instructions have no semantic impact.
  1392. for (auto &i : block.ops)
  1393. {
  1394. auto op = static_cast<Op>(i.op);
  1395. switch (op)
  1396. {
  1397. // Non-Semantic instructions.
  1398. case OpLine:
  1399. case OpNoLine:
  1400. break;
  1401. case OpExtInst:
  1402. {
  1403. auto *ops = stream(i);
  1404. auto ext = get<SPIRExtension>(ops[2]).ext;
  1405. bool ext_is_nonsemantic_only =
  1406. ext == SPIRExtension::NonSemanticShaderDebugInfo ||
  1407. ext == SPIRExtension::SPV_debug_info ||
  1408. ext == SPIRExtension::NonSemanticGeneric;
  1409. if (!ext_is_nonsemantic_only)
  1410. return false;
  1411. break;
  1412. }
  1413. default:
  1414. return false;
  1415. }
  1416. }
  1417. return true;
  1418. }
  1419. bool Compiler::block_is_loop_candidate(const SPIRBlock &block, SPIRBlock::Method method) const
  1420. {
  1421. // Tried and failed.
  1422. if (block.disable_block_optimization || block.complex_continue)
  1423. return false;
  1424. if (method == SPIRBlock::MergeToSelectForLoop || method == SPIRBlock::MergeToSelectContinueForLoop)
  1425. {
  1426. // Try to detect common for loop pattern
  1427. // which the code backend can use to create cleaner code.
  1428. // for(;;) { if (cond) { some_body; } else { break; } }
  1429. // is the pattern we're looking for.
  1430. const auto *false_block = maybe_get<SPIRBlock>(block.false_block);
  1431. const auto *true_block = maybe_get<SPIRBlock>(block.true_block);
  1432. const auto *merge_block = maybe_get<SPIRBlock>(block.merge_block);
  1433. bool false_block_is_merge = block.false_block == block.merge_block ||
  1434. (false_block && merge_block && execution_is_noop(*false_block, *merge_block));
  1435. bool true_block_is_merge = block.true_block == block.merge_block ||
  1436. (true_block && merge_block && execution_is_noop(*true_block, *merge_block));
  1437. bool positive_candidate =
  1438. block.true_block != block.merge_block && block.true_block != block.self && false_block_is_merge;
  1439. bool negative_candidate =
  1440. block.false_block != block.merge_block && block.false_block != block.self && true_block_is_merge;
  1441. bool ret = block.terminator == SPIRBlock::Select && block.merge == SPIRBlock::MergeLoop &&
  1442. (positive_candidate || negative_candidate);
  1443. if (ret && positive_candidate && method == SPIRBlock::MergeToSelectContinueForLoop)
  1444. ret = block.true_block == block.continue_block;
  1445. else if (ret && negative_candidate && method == SPIRBlock::MergeToSelectContinueForLoop)
  1446. ret = block.false_block == block.continue_block;
  1447. // If we have OpPhi which depends on branches which came from our own block,
  1448. // we need to flush phi variables in else block instead of a trivial break,
  1449. // so we cannot assume this is a for loop candidate.
  1450. if (ret)
  1451. {
  1452. for (auto &phi : block.phi_variables)
  1453. if (phi.parent == block.self)
  1454. return false;
  1455. auto *merge = maybe_get<SPIRBlock>(block.merge_block);
  1456. if (merge)
  1457. for (auto &phi : merge->phi_variables)
  1458. if (phi.parent == block.self)
  1459. return false;
  1460. }
  1461. return ret;
  1462. }
  1463. else if (method == SPIRBlock::MergeToDirectForLoop)
  1464. {
  1465. // Empty loop header that just sets up merge target
  1466. // and branches to loop body.
  1467. bool ret = block.terminator == SPIRBlock::Direct && block.merge == SPIRBlock::MergeLoop && block_is_noop(block);
  1468. if (!ret)
  1469. return false;
  1470. auto &child = get<SPIRBlock>(block.next_block);
  1471. const auto *false_block = maybe_get<SPIRBlock>(child.false_block);
  1472. const auto *true_block = maybe_get<SPIRBlock>(child.true_block);
  1473. const auto *merge_block = maybe_get<SPIRBlock>(block.merge_block);
  1474. bool false_block_is_merge = child.false_block == block.merge_block ||
  1475. (false_block && merge_block && execution_is_noop(*false_block, *merge_block));
  1476. bool true_block_is_merge = child.true_block == block.merge_block ||
  1477. (true_block && merge_block && execution_is_noop(*true_block, *merge_block));
  1478. bool positive_candidate =
  1479. child.true_block != block.merge_block && child.true_block != block.self && false_block_is_merge;
  1480. bool negative_candidate =
  1481. child.false_block != block.merge_block && child.false_block != block.self && true_block_is_merge;
  1482. ret = child.terminator == SPIRBlock::Select && child.merge == SPIRBlock::MergeNone &&
  1483. (positive_candidate || negative_candidate);
  1484. if (ret)
  1485. {
  1486. auto *merge = maybe_get<SPIRBlock>(block.merge_block);
  1487. if (merge)
  1488. for (auto &phi : merge->phi_variables)
  1489. if (phi.parent == block.self || phi.parent == child.false_block)
  1490. return false;
  1491. }
  1492. return ret;
  1493. }
  1494. else
  1495. return false;
  1496. }
  1497. bool Compiler::execution_is_noop(const SPIRBlock &from, const SPIRBlock &to) const
  1498. {
  1499. if (!execution_is_branchless(from, to))
  1500. return false;
  1501. auto *start = &from;
  1502. for (;;)
  1503. {
  1504. if (start->self == to.self)
  1505. return true;
  1506. if (!block_is_noop(*start))
  1507. return false;
  1508. auto &next = get<SPIRBlock>(start->next_block);
  1509. start = &next;
  1510. }
  1511. }
  1512. bool Compiler::execution_is_branchless(const SPIRBlock &from, const SPIRBlock &to) const
  1513. {
  1514. auto *start = &from;
  1515. for (;;)
  1516. {
  1517. if (start->self == to.self)
  1518. return true;
  1519. if (start->terminator == SPIRBlock::Direct && start->merge == SPIRBlock::MergeNone)
  1520. start = &get<SPIRBlock>(start->next_block);
  1521. else
  1522. return false;
  1523. }
  1524. }
  1525. bool Compiler::execution_is_direct_branch(const SPIRBlock &from, const SPIRBlock &to) const
  1526. {
  1527. return from.terminator == SPIRBlock::Direct && from.merge == SPIRBlock::MergeNone && from.next_block == to.self;
  1528. }
  1529. SPIRBlock::ContinueBlockType Compiler::continue_block_type(const SPIRBlock &block) const
  1530. {
  1531. // The block was deemed too complex during code emit, pick conservative fallback paths.
  1532. if (block.complex_continue)
  1533. return SPIRBlock::ComplexLoop;
  1534. // In older glslang output continue block can be equal to the loop header.
  1535. // In this case, execution is clearly branchless, so just assume a while loop header here.
  1536. if (block.merge == SPIRBlock::MergeLoop)
  1537. return SPIRBlock::WhileLoop;
  1538. if (block.loop_dominator == BlockID(SPIRBlock::NoDominator))
  1539. {
  1540. // Continue block is never reached from CFG.
  1541. return SPIRBlock::ComplexLoop;
  1542. }
  1543. auto &dominator = get<SPIRBlock>(block.loop_dominator);
  1544. if (execution_is_noop(block, dominator))
  1545. return SPIRBlock::WhileLoop;
  1546. else if (execution_is_branchless(block, dominator))
  1547. return SPIRBlock::ForLoop;
  1548. else
  1549. {
  1550. const auto *false_block = maybe_get<SPIRBlock>(block.false_block);
  1551. const auto *true_block = maybe_get<SPIRBlock>(block.true_block);
  1552. const auto *merge_block = maybe_get<SPIRBlock>(dominator.merge_block);
  1553. // If we need to flush Phi in this block, we cannot have a DoWhile loop.
  1554. bool flush_phi_to_false = false_block && flush_phi_required(block.self, block.false_block);
  1555. bool flush_phi_to_true = true_block && flush_phi_required(block.self, block.true_block);
  1556. if (flush_phi_to_false || flush_phi_to_true)
  1557. return SPIRBlock::ComplexLoop;
  1558. bool positive_do_while = block.true_block == dominator.self &&
  1559. (block.false_block == dominator.merge_block ||
  1560. (false_block && merge_block && execution_is_noop(*false_block, *merge_block)));
  1561. bool negative_do_while = block.false_block == dominator.self &&
  1562. (block.true_block == dominator.merge_block ||
  1563. (true_block && merge_block && execution_is_noop(*true_block, *merge_block)));
  1564. if (block.merge == SPIRBlock::MergeNone && block.terminator == SPIRBlock::Select &&
  1565. (positive_do_while || negative_do_while))
  1566. {
  1567. return SPIRBlock::DoWhileLoop;
  1568. }
  1569. else
  1570. return SPIRBlock::ComplexLoop;
  1571. }
  1572. }
  1573. const SmallVector<SPIRBlock::Case> &Compiler::get_case_list(const SPIRBlock &block) const
  1574. {
  1575. uint32_t width = 0;
  1576. // First we check if we can get the type directly from the block.condition
  1577. // since it can be a SPIRConstant or a SPIRVariable.
  1578. if (const auto *constant = maybe_get<SPIRConstant>(block.condition))
  1579. {
  1580. const auto &type = get<SPIRType>(constant->constant_type);
  1581. width = type.width;
  1582. }
  1583. else if (const auto *op = maybe_get<SPIRConstantOp>(block.condition))
  1584. {
  1585. const auto &type = get<SPIRType>(op->basetype);
  1586. width = type.width;
  1587. }
  1588. else if (const auto *var = maybe_get<SPIRVariable>(block.condition))
  1589. {
  1590. const auto &type = get<SPIRType>(var->basetype);
  1591. width = type.width;
  1592. }
  1593. else if (const auto *undef = maybe_get<SPIRUndef>(block.condition))
  1594. {
  1595. const auto &type = get<SPIRType>(undef->basetype);
  1596. width = type.width;
  1597. }
  1598. else
  1599. {
  1600. auto search = ir.load_type_width.find(block.condition);
  1601. if (search == ir.load_type_width.end())
  1602. {
  1603. SPIRV_CROSS_THROW("Use of undeclared variable on a switch statement.");
  1604. }
  1605. width = search->second;
  1606. }
  1607. if (width > 32)
  1608. return block.cases_64bit;
  1609. return block.cases_32bit;
  1610. }
  1611. bool Compiler::traverse_all_reachable_opcodes(const SPIRBlock &block, OpcodeHandler &handler) const
  1612. {
  1613. handler.set_current_block(block);
  1614. handler.rearm_current_block(block);
  1615. // Ideally, perhaps traverse the CFG instead of all blocks in order to eliminate dead blocks,
  1616. // but this shouldn't be a problem in practice unless the SPIR-V is doing insane things like recursing
  1617. // inside dead blocks ...
  1618. for (auto &i : block.ops)
  1619. {
  1620. auto ops = stream(i);
  1621. auto op = static_cast<Op>(i.op);
  1622. if (!handler.handle(op, ops, i.length))
  1623. return false;
  1624. if (op == OpFunctionCall)
  1625. {
  1626. auto &func = get<SPIRFunction>(ops[2]);
  1627. if (handler.follow_function_call(func))
  1628. {
  1629. if (!handler.begin_function_scope(ops, i.length))
  1630. return false;
  1631. if (!traverse_all_reachable_opcodes(get<SPIRFunction>(ops[2]), handler))
  1632. return false;
  1633. if (!handler.end_function_scope(ops, i.length))
  1634. return false;
  1635. handler.rearm_current_block(block);
  1636. }
  1637. }
  1638. }
  1639. if (!handler.handle_terminator(block))
  1640. return false;
  1641. return true;
  1642. }
  1643. bool Compiler::traverse_all_reachable_opcodes(const SPIRFunction &func, OpcodeHandler &handler) const
  1644. {
  1645. for (auto block : func.blocks)
  1646. if (!traverse_all_reachable_opcodes(get<SPIRBlock>(block), handler))
  1647. return false;
  1648. return true;
  1649. }
  1650. uint32_t Compiler::type_struct_member_offset(const SPIRType &type, uint32_t index) const
  1651. {
  1652. auto *type_meta = ir.find_meta(type.self);
  1653. if (type_meta)
  1654. {
  1655. // Decoration must be set in valid SPIR-V, otherwise throw.
  1656. auto &dec = type_meta->members[index];
  1657. if (dec.decoration_flags.get(DecorationOffset))
  1658. return dec.offset;
  1659. else
  1660. SPIRV_CROSS_THROW("Struct member does not have Offset set.");
  1661. }
  1662. else
  1663. SPIRV_CROSS_THROW("Struct member does not have Offset set.");
  1664. }
  1665. uint32_t Compiler::type_struct_member_array_stride(const SPIRType &type, uint32_t index) const
  1666. {
  1667. auto *type_meta = ir.find_meta(type.member_types[index]);
  1668. if (type_meta)
  1669. {
  1670. // Decoration must be set in valid SPIR-V, otherwise throw.
  1671. // ArrayStride is part of the array type not OpMemberDecorate.
  1672. auto &dec = type_meta->decoration;
  1673. if (dec.decoration_flags.get(DecorationArrayStride))
  1674. return dec.array_stride;
  1675. else
  1676. SPIRV_CROSS_THROW("Struct member does not have ArrayStride set.");
  1677. }
  1678. else
  1679. SPIRV_CROSS_THROW("Struct member does not have ArrayStride set.");
  1680. }
  1681. uint32_t Compiler::type_struct_member_matrix_stride(const SPIRType &type, uint32_t index) const
  1682. {
  1683. auto *type_meta = ir.find_meta(type.self);
  1684. if (type_meta)
  1685. {
  1686. // Decoration must be set in valid SPIR-V, otherwise throw.
  1687. // MatrixStride is part of OpMemberDecorate.
  1688. auto &dec = type_meta->members[index];
  1689. if (dec.decoration_flags.get(DecorationMatrixStride))
  1690. return dec.matrix_stride;
  1691. else
  1692. SPIRV_CROSS_THROW("Struct member does not have MatrixStride set.");
  1693. }
  1694. else
  1695. SPIRV_CROSS_THROW("Struct member does not have MatrixStride set.");
  1696. }
  1697. size_t Compiler::get_declared_struct_size(const SPIRType &type) const
  1698. {
  1699. if (type.member_types.empty())
  1700. SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
  1701. // Offsets can be declared out of order, so we need to deduce the actual size
  1702. // based on last member instead.
  1703. uint32_t member_index = 0;
  1704. size_t highest_offset = 0;
  1705. for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
  1706. {
  1707. size_t offset = type_struct_member_offset(type, i);
  1708. if (offset > highest_offset)
  1709. {
  1710. highest_offset = offset;
  1711. member_index = i;
  1712. }
  1713. }
  1714. size_t size = get_declared_struct_member_size(type, member_index);
  1715. return highest_offset + size;
  1716. }
  1717. size_t Compiler::get_declared_struct_size_runtime_array(const SPIRType &type, size_t array_size) const
  1718. {
  1719. if (type.member_types.empty())
  1720. SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
  1721. size_t size = get_declared_struct_size(type);
  1722. auto &last_type = get<SPIRType>(type.member_types.back());
  1723. if (!last_type.array.empty() && last_type.array_size_literal[0] && last_type.array[0] == 0) // Runtime array
  1724. size += array_size * type_struct_member_array_stride(type, uint32_t(type.member_types.size() - 1));
  1725. return size;
  1726. }
  1727. uint32_t Compiler::evaluate_spec_constant_u32(const SPIRConstantOp &spec) const
  1728. {
  1729. auto &result_type = get<SPIRType>(spec.basetype);
  1730. if (result_type.basetype != SPIRType::UInt && result_type.basetype != SPIRType::Int &&
  1731. result_type.basetype != SPIRType::Boolean)
  1732. {
  1733. SPIRV_CROSS_THROW(
  1734. "Only 32-bit integers and booleans are currently supported when evaluating specialization constants.\n");
  1735. }
  1736. if (!is_scalar(result_type))
  1737. SPIRV_CROSS_THROW("Spec constant evaluation must be a scalar.\n");
  1738. uint32_t value = 0;
  1739. const auto eval_u32 = [&](uint32_t id) -> uint32_t {
  1740. auto &type = expression_type(id);
  1741. if (type.basetype != SPIRType::UInt && type.basetype != SPIRType::Int && type.basetype != SPIRType::Boolean)
  1742. {
  1743. SPIRV_CROSS_THROW("Only 32-bit integers and booleans are currently supported when evaluating "
  1744. "specialization constants.\n");
  1745. }
  1746. if (!is_scalar(type))
  1747. SPIRV_CROSS_THROW("Spec constant evaluation must be a scalar.\n");
  1748. if (const auto *c = this->maybe_get<SPIRConstant>(id))
  1749. return c->scalar();
  1750. else
  1751. return evaluate_spec_constant_u32(this->get<SPIRConstantOp>(id));
  1752. };
  1753. #define binary_spec_op(op, binary_op) \
  1754. case Op##op: \
  1755. value = eval_u32(spec.arguments[0]) binary_op eval_u32(spec.arguments[1]); \
  1756. break
  1757. #define binary_spec_op_cast(op, binary_op, type) \
  1758. case Op##op: \
  1759. value = uint32_t(type(eval_u32(spec.arguments[0])) binary_op type(eval_u32(spec.arguments[1]))); \
  1760. break
  1761. // Support the basic opcodes which are typically used when computing array sizes.
  1762. switch (spec.opcode)
  1763. {
  1764. binary_spec_op(IAdd, +);
  1765. binary_spec_op(ISub, -);
  1766. binary_spec_op(IMul, *);
  1767. binary_spec_op(BitwiseAnd, &);
  1768. binary_spec_op(BitwiseOr, |);
  1769. binary_spec_op(BitwiseXor, ^);
  1770. binary_spec_op(LogicalAnd, &);
  1771. binary_spec_op(LogicalOr, |);
  1772. binary_spec_op(ShiftLeftLogical, <<);
  1773. binary_spec_op(ShiftRightLogical, >>);
  1774. binary_spec_op_cast(ShiftRightArithmetic, >>, int32_t);
  1775. binary_spec_op(LogicalEqual, ==);
  1776. binary_spec_op(LogicalNotEqual, !=);
  1777. binary_spec_op(IEqual, ==);
  1778. binary_spec_op(INotEqual, !=);
  1779. binary_spec_op(ULessThan, <);
  1780. binary_spec_op(ULessThanEqual, <=);
  1781. binary_spec_op(UGreaterThan, >);
  1782. binary_spec_op(UGreaterThanEqual, >=);
  1783. binary_spec_op_cast(SLessThan, <, int32_t);
  1784. binary_spec_op_cast(SLessThanEqual, <=, int32_t);
  1785. binary_spec_op_cast(SGreaterThan, >, int32_t);
  1786. binary_spec_op_cast(SGreaterThanEqual, >=, int32_t);
  1787. #undef binary_spec_op
  1788. #undef binary_spec_op_cast
  1789. case OpLogicalNot:
  1790. value = uint32_t(!eval_u32(spec.arguments[0]));
  1791. break;
  1792. case OpNot:
  1793. value = ~eval_u32(spec.arguments[0]);
  1794. break;
  1795. case OpSNegate:
  1796. value = uint32_t(-int32_t(eval_u32(spec.arguments[0])));
  1797. break;
  1798. case OpSelect:
  1799. value = eval_u32(spec.arguments[0]) ? eval_u32(spec.arguments[1]) : eval_u32(spec.arguments[2]);
  1800. break;
  1801. case OpUMod:
  1802. {
  1803. uint32_t a = eval_u32(spec.arguments[0]);
  1804. uint32_t b = eval_u32(spec.arguments[1]);
  1805. if (b == 0)
  1806. SPIRV_CROSS_THROW("Undefined behavior in UMod, b == 0.\n");
  1807. value = a % b;
  1808. break;
  1809. }
  1810. case OpSRem:
  1811. {
  1812. auto a = int32_t(eval_u32(spec.arguments[0]));
  1813. auto b = int32_t(eval_u32(spec.arguments[1]));
  1814. if (b == 0)
  1815. SPIRV_CROSS_THROW("Undefined behavior in SRem, b == 0.\n");
  1816. value = a % b;
  1817. break;
  1818. }
  1819. case OpSMod:
  1820. {
  1821. auto a = int32_t(eval_u32(spec.arguments[0]));
  1822. auto b = int32_t(eval_u32(spec.arguments[1]));
  1823. if (b == 0)
  1824. SPIRV_CROSS_THROW("Undefined behavior in SMod, b == 0.\n");
  1825. auto v = a % b;
  1826. // Makes sure we match the sign of b, not a.
  1827. if ((b < 0 && v > 0) || (b > 0 && v < 0))
  1828. v += b;
  1829. value = v;
  1830. break;
  1831. }
  1832. case OpUDiv:
  1833. {
  1834. uint32_t a = eval_u32(spec.arguments[0]);
  1835. uint32_t b = eval_u32(spec.arguments[1]);
  1836. if (b == 0)
  1837. SPIRV_CROSS_THROW("Undefined behavior in UDiv, b == 0.\n");
  1838. value = a / b;
  1839. break;
  1840. }
  1841. case OpSDiv:
  1842. {
  1843. auto a = int32_t(eval_u32(spec.arguments[0]));
  1844. auto b = int32_t(eval_u32(spec.arguments[1]));
  1845. if (b == 0)
  1846. SPIRV_CROSS_THROW("Undefined behavior in SDiv, b == 0.\n");
  1847. value = a / b;
  1848. break;
  1849. }
  1850. default:
  1851. SPIRV_CROSS_THROW("Unsupported spec constant opcode for evaluation.\n");
  1852. }
  1853. return value;
  1854. }
  1855. uint32_t Compiler::evaluate_constant_u32(uint32_t id) const
  1856. {
  1857. if (const auto *c = maybe_get<SPIRConstant>(id))
  1858. return c->scalar();
  1859. else
  1860. return evaluate_spec_constant_u32(get<SPIRConstantOp>(id));
  1861. }
  1862. size_t Compiler::get_declared_struct_member_size(const SPIRType &struct_type, uint32_t index) const
  1863. {
  1864. if (struct_type.member_types.empty())
  1865. SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
  1866. auto &flags = get_member_decoration_bitset(struct_type.self, index);
  1867. auto &type = get<SPIRType>(struct_type.member_types[index]);
  1868. switch (type.basetype)
  1869. {
  1870. case SPIRType::Unknown:
  1871. case SPIRType::Void:
  1872. case SPIRType::Boolean: // Bools are purely logical, and cannot be used for externally visible types.
  1873. case SPIRType::AtomicCounter:
  1874. case SPIRType::Image:
  1875. case SPIRType::SampledImage:
  1876. case SPIRType::Sampler:
  1877. SPIRV_CROSS_THROW("Querying size for object with opaque size.");
  1878. default:
  1879. break;
  1880. }
  1881. if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer)
  1882. {
  1883. // Check if this is a top-level pointer type, and not an array of pointers.
  1884. if (type.pointer_depth > get<SPIRType>(type.parent_type).pointer_depth)
  1885. return 8;
  1886. }
  1887. if (!type.array.empty())
  1888. {
  1889. // For arrays, we can use ArrayStride to get an easy check.
  1890. bool array_size_literal = type.array_size_literal.back();
  1891. uint32_t array_size = array_size_literal ? type.array.back() : evaluate_constant_u32(type.array.back());
  1892. return type_struct_member_array_stride(struct_type, index) * array_size;
  1893. }
  1894. else if (type.basetype == SPIRType::Struct)
  1895. {
  1896. return get_declared_struct_size(type);
  1897. }
  1898. else
  1899. {
  1900. unsigned vecsize = type.vecsize;
  1901. unsigned columns = type.columns;
  1902. // Vectors.
  1903. if (columns == 1)
  1904. {
  1905. size_t component_size = type.width / 8;
  1906. return vecsize * component_size;
  1907. }
  1908. else
  1909. {
  1910. uint32_t matrix_stride = type_struct_member_matrix_stride(struct_type, index);
  1911. // Per SPIR-V spec, matrices must be tightly packed and aligned up for vec3 accesses.
  1912. if (flags.get(DecorationRowMajor))
  1913. return matrix_stride * vecsize;
  1914. else if (flags.get(DecorationColMajor))
  1915. return matrix_stride * columns;
  1916. else
  1917. SPIRV_CROSS_THROW("Either row-major or column-major must be declared for matrices.");
  1918. }
  1919. }
  1920. }
  1921. bool Compiler::BufferAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  1922. {
  1923. if (opcode != OpAccessChain && opcode != OpInBoundsAccessChain && opcode != OpPtrAccessChain)
  1924. return true;
  1925. bool ptr_chain = (opcode == OpPtrAccessChain);
  1926. // Invalid SPIR-V.
  1927. if (length < (ptr_chain ? 5u : 4u))
  1928. return false;
  1929. if (args[2] != id)
  1930. return true;
  1931. // Don't bother traversing the entire access chain tree yet.
  1932. // If we access a struct member, assume we access the entire member.
  1933. uint32_t index = compiler.get<SPIRConstant>(args[ptr_chain ? 4 : 3]).scalar();
  1934. // Seen this index already.
  1935. if (seen.find(index) != end(seen))
  1936. return true;
  1937. seen.insert(index);
  1938. auto &type = compiler.expression_type(id);
  1939. uint32_t offset = compiler.type_struct_member_offset(type, index);
  1940. size_t range;
  1941. // If we have another member in the struct, deduce the range by looking at the next member.
  1942. // This is okay since structs in SPIR-V can have padding, but Offset decoration must be
  1943. // monotonically increasing.
  1944. // Of course, this doesn't take into account if the SPIR-V for some reason decided to add
  1945. // very large amounts of padding, but that's not really a big deal.
  1946. if (index + 1 < type.member_types.size())
  1947. {
  1948. range = compiler.type_struct_member_offset(type, index + 1) - offset;
  1949. }
  1950. else
  1951. {
  1952. // No padding, so just deduce it from the size of the member directly.
  1953. range = compiler.get_declared_struct_member_size(type, index);
  1954. }
  1955. ranges.push_back({ index, offset, range });
  1956. return true;
  1957. }
  1958. SmallVector<BufferRange> Compiler::get_active_buffer_ranges(VariableID id) const
  1959. {
  1960. SmallVector<BufferRange> ranges;
  1961. BufferAccessHandler handler(*this, ranges, id);
  1962. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  1963. return ranges;
  1964. }
  1965. bool Compiler::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
  1966. {
  1967. if (a.basetype != b.basetype)
  1968. return false;
  1969. if (a.width != b.width)
  1970. return false;
  1971. if (a.vecsize != b.vecsize)
  1972. return false;
  1973. if (a.columns != b.columns)
  1974. return false;
  1975. if (a.array.size() != b.array.size())
  1976. return false;
  1977. size_t array_count = a.array.size();
  1978. if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
  1979. return false;
  1980. if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
  1981. {
  1982. if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
  1983. return false;
  1984. }
  1985. if (a.member_types.size() != b.member_types.size())
  1986. return false;
  1987. size_t member_types = a.member_types.size();
  1988. for (size_t i = 0; i < member_types; i++)
  1989. {
  1990. if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
  1991. return false;
  1992. }
  1993. return true;
  1994. }
  1995. const Bitset &Compiler::get_execution_mode_bitset() const
  1996. {
  1997. return get_entry_point().flags;
  1998. }
  1999. void Compiler::set_execution_mode(ExecutionMode mode, uint32_t arg0, uint32_t arg1, uint32_t arg2)
  2000. {
  2001. auto &execution = get_entry_point();
  2002. execution.flags.set(mode);
  2003. switch (mode)
  2004. {
  2005. case ExecutionModeLocalSize:
  2006. execution.workgroup_size.x = arg0;
  2007. execution.workgroup_size.y = arg1;
  2008. execution.workgroup_size.z = arg2;
  2009. break;
  2010. case ExecutionModeLocalSizeId:
  2011. execution.workgroup_size.id_x = arg0;
  2012. execution.workgroup_size.id_y = arg1;
  2013. execution.workgroup_size.id_z = arg2;
  2014. break;
  2015. case ExecutionModeInvocations:
  2016. execution.invocations = arg0;
  2017. break;
  2018. case ExecutionModeOutputVertices:
  2019. execution.output_vertices = arg0;
  2020. break;
  2021. case ExecutionModeOutputPrimitivesEXT:
  2022. execution.output_primitives = arg0;
  2023. break;
  2024. case ExecutionModeFPFastMathDefault:
  2025. execution.fp_fast_math_defaults[arg0] = arg1;
  2026. break;
  2027. default:
  2028. break;
  2029. }
  2030. }
  2031. void Compiler::unset_execution_mode(ExecutionMode mode)
  2032. {
  2033. auto &execution = get_entry_point();
  2034. execution.flags.clear(mode);
  2035. }
  2036. uint32_t Compiler::get_work_group_size_specialization_constants(SpecializationConstant &x, SpecializationConstant &y,
  2037. SpecializationConstant &z) const
  2038. {
  2039. auto &execution = get_entry_point();
  2040. x = { 0, 0 };
  2041. y = { 0, 0 };
  2042. z = { 0, 0 };
  2043. // WorkgroupSize builtin takes precedence over LocalSize / LocalSizeId.
  2044. if (execution.workgroup_size.constant != 0)
  2045. {
  2046. auto &c = get<SPIRConstant>(execution.workgroup_size.constant);
  2047. if (c.m.c[0].id[0] != ID(0))
  2048. {
  2049. x.id = c.m.c[0].id[0];
  2050. x.constant_id = get_decoration(c.m.c[0].id[0], DecorationSpecId);
  2051. }
  2052. if (c.m.c[0].id[1] != ID(0))
  2053. {
  2054. y.id = c.m.c[0].id[1];
  2055. y.constant_id = get_decoration(c.m.c[0].id[1], DecorationSpecId);
  2056. }
  2057. if (c.m.c[0].id[2] != ID(0))
  2058. {
  2059. z.id = c.m.c[0].id[2];
  2060. z.constant_id = get_decoration(c.m.c[0].id[2], DecorationSpecId);
  2061. }
  2062. }
  2063. else if (execution.flags.get(ExecutionModeLocalSizeId))
  2064. {
  2065. auto &cx = get<SPIRConstant>(execution.workgroup_size.id_x);
  2066. if (cx.specialization)
  2067. {
  2068. x.id = execution.workgroup_size.id_x;
  2069. x.constant_id = get_decoration(execution.workgroup_size.id_x, DecorationSpecId);
  2070. }
  2071. auto &cy = get<SPIRConstant>(execution.workgroup_size.id_y);
  2072. if (cy.specialization)
  2073. {
  2074. y.id = execution.workgroup_size.id_y;
  2075. y.constant_id = get_decoration(execution.workgroup_size.id_y, DecorationSpecId);
  2076. }
  2077. auto &cz = get<SPIRConstant>(execution.workgroup_size.id_z);
  2078. if (cz.specialization)
  2079. {
  2080. z.id = execution.workgroup_size.id_z;
  2081. z.constant_id = get_decoration(execution.workgroup_size.id_z, DecorationSpecId);
  2082. }
  2083. }
  2084. return execution.workgroup_size.constant;
  2085. }
  2086. uint32_t Compiler::get_execution_mode_argument(spv::ExecutionMode mode, uint32_t index) const
  2087. {
  2088. auto &execution = get_entry_point();
  2089. switch (mode)
  2090. {
  2091. case ExecutionModeLocalSizeId:
  2092. if (execution.flags.get(ExecutionModeLocalSizeId))
  2093. {
  2094. switch (index)
  2095. {
  2096. case 0:
  2097. return execution.workgroup_size.id_x;
  2098. case 1:
  2099. return execution.workgroup_size.id_y;
  2100. case 2:
  2101. return execution.workgroup_size.id_z;
  2102. default:
  2103. return 0;
  2104. }
  2105. }
  2106. else
  2107. return 0;
  2108. case ExecutionModeLocalSize:
  2109. switch (index)
  2110. {
  2111. case 0:
  2112. if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_x != 0)
  2113. return get<SPIRConstant>(execution.workgroup_size.id_x).scalar();
  2114. else
  2115. return execution.workgroup_size.x;
  2116. case 1:
  2117. if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_y != 0)
  2118. return get<SPIRConstant>(execution.workgroup_size.id_y).scalar();
  2119. else
  2120. return execution.workgroup_size.y;
  2121. case 2:
  2122. if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_z != 0)
  2123. return get<SPIRConstant>(execution.workgroup_size.id_z).scalar();
  2124. else
  2125. return execution.workgroup_size.z;
  2126. default:
  2127. return 0;
  2128. }
  2129. case ExecutionModeInvocations:
  2130. return execution.invocations;
  2131. case ExecutionModeOutputVertices:
  2132. return execution.output_vertices;
  2133. case ExecutionModeOutputPrimitivesEXT:
  2134. return execution.output_primitives;
  2135. default:
  2136. return 0;
  2137. }
  2138. }
  2139. ExecutionModel Compiler::get_execution_model() const
  2140. {
  2141. auto &execution = get_entry_point();
  2142. return execution.model;
  2143. }
  2144. bool Compiler::is_tessellation_shader(ExecutionModel model)
  2145. {
  2146. return model == ExecutionModelTessellationControl || model == ExecutionModelTessellationEvaluation;
  2147. }
  2148. bool Compiler::is_vertex_like_shader() const
  2149. {
  2150. auto model = get_execution_model();
  2151. return model == ExecutionModelVertex || model == ExecutionModelGeometry ||
  2152. model == ExecutionModelTessellationControl || model == ExecutionModelTessellationEvaluation;
  2153. }
  2154. bool Compiler::is_tessellation_shader() const
  2155. {
  2156. return is_tessellation_shader(get_execution_model());
  2157. }
  2158. bool Compiler::is_tessellating_triangles() const
  2159. {
  2160. return get_execution_mode_bitset().get(ExecutionModeTriangles);
  2161. }
  2162. void Compiler::set_remapped_variable_state(VariableID id, bool remap_enable)
  2163. {
  2164. get<SPIRVariable>(id).remapped_variable = remap_enable;
  2165. }
  2166. bool Compiler::get_remapped_variable_state(VariableID id) const
  2167. {
  2168. return get<SPIRVariable>(id).remapped_variable;
  2169. }
  2170. void Compiler::set_subpass_input_remapped_components(VariableID id, uint32_t components)
  2171. {
  2172. get<SPIRVariable>(id).remapped_components = components;
  2173. }
  2174. uint32_t Compiler::get_subpass_input_remapped_components(VariableID id) const
  2175. {
  2176. return get<SPIRVariable>(id).remapped_components;
  2177. }
  2178. void Compiler::add_implied_read_expression(SPIRExpression &e, uint32_t source)
  2179. {
  2180. auto itr = find(begin(e.implied_read_expressions), end(e.implied_read_expressions), ID(source));
  2181. if (itr == end(e.implied_read_expressions))
  2182. e.implied_read_expressions.push_back(source);
  2183. }
  2184. void Compiler::add_implied_read_expression(SPIRAccessChain &e, uint32_t source)
  2185. {
  2186. auto itr = find(begin(e.implied_read_expressions), end(e.implied_read_expressions), ID(source));
  2187. if (itr == end(e.implied_read_expressions))
  2188. e.implied_read_expressions.push_back(source);
  2189. }
  2190. void Compiler::add_active_interface_variable(uint32_t var_id)
  2191. {
  2192. active_interface_variables.insert(var_id);
  2193. // In SPIR-V 1.4 and up we must also track the interface variable in the entry point.
  2194. if (ir.get_spirv_version() >= 0x10400)
  2195. {
  2196. auto &vars = get_entry_point().interface_variables;
  2197. if (find(begin(vars), end(vars), VariableID(var_id)) == end(vars))
  2198. vars.push_back(var_id);
  2199. }
  2200. }
  2201. void Compiler::inherit_expression_dependencies(uint32_t dst, uint32_t source_expression)
  2202. {
  2203. auto *ptr_e = maybe_get<SPIRExpression>(dst);
  2204. if (is_position_invariant() && ptr_e && maybe_get<SPIRExpression>(source_expression))
  2205. {
  2206. auto &deps = ptr_e->invariance_dependencies;
  2207. if (std::find(deps.begin(), deps.end(), source_expression) == deps.end())
  2208. deps.push_back(source_expression);
  2209. }
  2210. // Don't inherit any expression dependencies if the expression in dst
  2211. // is not a forwarded temporary.
  2212. if (forwarded_temporaries.find(dst) == end(forwarded_temporaries) ||
  2213. forced_temporaries.find(dst) != end(forced_temporaries))
  2214. {
  2215. return;
  2216. }
  2217. auto &e = *ptr_e;
  2218. auto *phi = maybe_get<SPIRVariable>(source_expression);
  2219. if (phi && phi->phi_variable)
  2220. {
  2221. // We have used a phi variable, which can change at the end of the block,
  2222. // so make sure we take a dependency on this phi variable.
  2223. phi->dependees.push_back(dst);
  2224. }
  2225. auto *s = maybe_get<SPIRExpression>(source_expression);
  2226. if (!s)
  2227. return;
  2228. auto &e_deps = e.expression_dependencies;
  2229. auto &s_deps = s->expression_dependencies;
  2230. // If we depend on a expression, we also depend on all sub-dependencies from source.
  2231. e_deps.push_back(source_expression);
  2232. e_deps.insert(end(e_deps), begin(s_deps), end(s_deps));
  2233. // Eliminate duplicated dependencies.
  2234. sort(begin(e_deps), end(e_deps));
  2235. e_deps.erase(unique(begin(e_deps), end(e_deps)), end(e_deps));
  2236. }
  2237. SmallVector<EntryPoint> Compiler::get_entry_points_and_stages() const
  2238. {
  2239. SmallVector<EntryPoint> entries;
  2240. for (auto &entry : ir.entry_points)
  2241. entries.push_back({ entry.second.orig_name, entry.second.model });
  2242. return entries;
  2243. }
  2244. void Compiler::rename_entry_point(const std::string &old_name, const std::string &new_name, spv::ExecutionModel model)
  2245. {
  2246. auto &entry = get_entry_point(old_name, model);
  2247. entry.orig_name = new_name;
  2248. entry.name = new_name;
  2249. }
  2250. void Compiler::set_entry_point(const std::string &name, spv::ExecutionModel model)
  2251. {
  2252. auto &entry = get_entry_point(name, model);
  2253. ir.default_entry_point = entry.self;
  2254. }
  2255. SPIREntryPoint &Compiler::get_first_entry_point(const std::string &name)
  2256. {
  2257. auto itr = find_if(
  2258. begin(ir.entry_points), end(ir.entry_points),
  2259. [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool { return entry.second.orig_name == name; });
  2260. if (itr == end(ir.entry_points))
  2261. SPIRV_CROSS_THROW("Entry point does not exist.");
  2262. return itr->second;
  2263. }
  2264. const SPIREntryPoint &Compiler::get_first_entry_point(const std::string &name) const
  2265. {
  2266. auto itr = find_if(
  2267. begin(ir.entry_points), end(ir.entry_points),
  2268. [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool { return entry.second.orig_name == name; });
  2269. if (itr == end(ir.entry_points))
  2270. SPIRV_CROSS_THROW("Entry point does not exist.");
  2271. return itr->second;
  2272. }
  2273. SPIREntryPoint &Compiler::get_entry_point(const std::string &name, ExecutionModel model)
  2274. {
  2275. auto itr = find_if(begin(ir.entry_points), end(ir.entry_points),
  2276. [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool {
  2277. return entry.second.orig_name == name && entry.second.model == model;
  2278. });
  2279. if (itr == end(ir.entry_points))
  2280. SPIRV_CROSS_THROW("Entry point does not exist.");
  2281. return itr->second;
  2282. }
  2283. const SPIREntryPoint &Compiler::get_entry_point(const std::string &name, ExecutionModel model) const
  2284. {
  2285. auto itr = find_if(begin(ir.entry_points), end(ir.entry_points),
  2286. [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool {
  2287. return entry.second.orig_name == name && entry.second.model == model;
  2288. });
  2289. if (itr == end(ir.entry_points))
  2290. SPIRV_CROSS_THROW("Entry point does not exist.");
  2291. return itr->second;
  2292. }
  2293. const string &Compiler::get_cleansed_entry_point_name(const std::string &name, ExecutionModel model) const
  2294. {
  2295. return get_entry_point(name, model).name;
  2296. }
  2297. const SPIREntryPoint &Compiler::get_entry_point() const
  2298. {
  2299. return ir.entry_points.find(ir.default_entry_point)->second;
  2300. }
  2301. SPIREntryPoint &Compiler::get_entry_point()
  2302. {
  2303. return ir.entry_points.find(ir.default_entry_point)->second;
  2304. }
  2305. bool Compiler::interface_variable_exists_in_entry_point(uint32_t id) const
  2306. {
  2307. auto &var = get<SPIRVariable>(id);
  2308. if (ir.get_spirv_version() < 0x10400)
  2309. {
  2310. if (var.storage != StorageClassInput && var.storage != StorageClassOutput &&
  2311. var.storage != StorageClassUniformConstant)
  2312. SPIRV_CROSS_THROW("Only Input, Output variables and Uniform constants are part of a shader linking interface.");
  2313. // This is to avoid potential problems with very old glslang versions which did
  2314. // not emit input/output interfaces properly.
  2315. // We can assume they only had a single entry point, and single entry point
  2316. // shaders could easily be assumed to use every interface variable anyways.
  2317. if (ir.entry_points.size() <= 1)
  2318. return true;
  2319. }
  2320. // In SPIR-V 1.4 and later, all global resource variables must be present.
  2321. auto &execution = get_entry_point();
  2322. return find(begin(execution.interface_variables), end(execution.interface_variables), VariableID(id)) !=
  2323. end(execution.interface_variables);
  2324. }
  2325. void Compiler::CombinedImageSamplerHandler::push_remap_parameters(const SPIRFunction &func, const uint32_t *args,
  2326. uint32_t length)
  2327. {
  2328. // If possible, pipe through a remapping table so that parameters know
  2329. // which variables they actually bind to in this scope.
  2330. unordered_map<uint32_t, uint32_t> remapping;
  2331. for (uint32_t i = 0; i < length; i++)
  2332. remapping[func.arguments[i].id] = remap_parameter(args[i]);
  2333. parameter_remapping.push(std::move(remapping));
  2334. }
  2335. void Compiler::CombinedImageSamplerHandler::pop_remap_parameters()
  2336. {
  2337. parameter_remapping.pop();
  2338. }
  2339. uint32_t Compiler::CombinedImageSamplerHandler::remap_parameter(uint32_t id)
  2340. {
  2341. auto *var = compiler.maybe_get_backing_variable(id);
  2342. if (var)
  2343. id = var->self;
  2344. if (parameter_remapping.empty())
  2345. return id;
  2346. auto &remapping = parameter_remapping.top();
  2347. auto itr = remapping.find(id);
  2348. if (itr != end(remapping))
  2349. return itr->second;
  2350. else
  2351. return id;
  2352. }
  2353. bool Compiler::CombinedImageSamplerHandler::begin_function_scope(const uint32_t *args, uint32_t length)
  2354. {
  2355. if (length < 3)
  2356. return false;
  2357. auto &callee = compiler.get<SPIRFunction>(args[2]);
  2358. args += 3;
  2359. length -= 3;
  2360. push_remap_parameters(callee, args, length);
  2361. functions.push(&callee);
  2362. return true;
  2363. }
  2364. bool Compiler::CombinedImageSamplerHandler::end_function_scope(const uint32_t *args, uint32_t length)
  2365. {
  2366. if (length < 3)
  2367. return false;
  2368. auto &callee = compiler.get<SPIRFunction>(args[2]);
  2369. args += 3;
  2370. // There are two types of cases we have to handle,
  2371. // a callee might call sampler2D(texture2D, sampler) directly where
  2372. // one or more parameters originate from parameters.
  2373. // Alternatively, we need to provide combined image samplers to our callees,
  2374. // and in this case we need to add those as well.
  2375. pop_remap_parameters();
  2376. // Our callee has now been processed at least once.
  2377. // No point in doing it again.
  2378. callee.do_combined_parameters = false;
  2379. auto &params = functions.top()->combined_parameters;
  2380. functions.pop();
  2381. if (functions.empty())
  2382. return true;
  2383. auto &caller = *functions.top();
  2384. if (caller.do_combined_parameters)
  2385. {
  2386. for (auto &param : params)
  2387. {
  2388. VariableID image_id = param.global_image ? param.image_id : VariableID(args[param.image_id]);
  2389. VariableID sampler_id = param.global_sampler ? param.sampler_id : VariableID(args[param.sampler_id]);
  2390. auto *i = compiler.maybe_get_backing_variable(image_id);
  2391. auto *s = compiler.maybe_get_backing_variable(sampler_id);
  2392. if (i)
  2393. image_id = i->self;
  2394. if (s)
  2395. sampler_id = s->self;
  2396. register_combined_image_sampler(caller, 0, image_id, sampler_id, param.depth);
  2397. }
  2398. }
  2399. return true;
  2400. }
  2401. void Compiler::CombinedImageSamplerHandler::register_combined_image_sampler(SPIRFunction &caller,
  2402. VariableID combined_module_id,
  2403. VariableID image_id, VariableID sampler_id,
  2404. bool depth)
  2405. {
  2406. // We now have a texture ID and a sampler ID which will either be found as a global
  2407. // or a parameter in our own function. If both are global, they will not need a parameter,
  2408. // otherwise, add it to our list.
  2409. SPIRFunction::CombinedImageSamplerParameter param = {
  2410. 0u, image_id, sampler_id, true, true, depth,
  2411. };
  2412. auto texture_itr = find_if(begin(caller.arguments), end(caller.arguments),
  2413. [image_id](const SPIRFunction::Parameter &p) { return p.id == image_id; });
  2414. auto sampler_itr = find_if(begin(caller.arguments), end(caller.arguments),
  2415. [sampler_id](const SPIRFunction::Parameter &p) { return p.id == sampler_id; });
  2416. if (texture_itr != end(caller.arguments))
  2417. {
  2418. param.global_image = false;
  2419. param.image_id = uint32_t(texture_itr - begin(caller.arguments));
  2420. }
  2421. if (sampler_itr != end(caller.arguments))
  2422. {
  2423. param.global_sampler = false;
  2424. param.sampler_id = uint32_t(sampler_itr - begin(caller.arguments));
  2425. }
  2426. if (param.global_image && param.global_sampler)
  2427. return;
  2428. auto itr = find_if(begin(caller.combined_parameters), end(caller.combined_parameters),
  2429. [&param](const SPIRFunction::CombinedImageSamplerParameter &p) {
  2430. return param.image_id == p.image_id && param.sampler_id == p.sampler_id &&
  2431. param.global_image == p.global_image && param.global_sampler == p.global_sampler;
  2432. });
  2433. if (itr == end(caller.combined_parameters))
  2434. {
  2435. uint32_t id = compiler.ir.increase_bound_by(3);
  2436. auto type_id = id + 0;
  2437. auto ptr_type_id = id + 1;
  2438. auto combined_id = id + 2;
  2439. auto &base = compiler.expression_type(image_id);
  2440. auto &type = compiler.set<SPIRType>(type_id, OpTypeSampledImage);
  2441. auto &ptr_type = compiler.set<SPIRType>(ptr_type_id, OpTypePointer);
  2442. type = base;
  2443. type.self = type_id;
  2444. type.basetype = SPIRType::SampledImage;
  2445. type.pointer = false;
  2446. type.storage = StorageClassGeneric;
  2447. type.image.depth = depth;
  2448. ptr_type = type;
  2449. ptr_type.pointer = true;
  2450. ptr_type.storage = StorageClassUniformConstant;
  2451. ptr_type.parent_type = type_id;
  2452. // Build new variable.
  2453. compiler.set<SPIRVariable>(combined_id, ptr_type_id, StorageClassFunction, 0);
  2454. // Inherit RelaxedPrecision.
  2455. // If any of OpSampledImage, underlying image or sampler are marked, inherit the decoration.
  2456. bool relaxed_precision =
  2457. compiler.has_decoration(sampler_id, DecorationRelaxedPrecision) ||
  2458. compiler.has_decoration(image_id, DecorationRelaxedPrecision) ||
  2459. (combined_module_id && compiler.has_decoration(combined_module_id, DecorationRelaxedPrecision));
  2460. if (relaxed_precision)
  2461. compiler.set_decoration(combined_id, DecorationRelaxedPrecision);
  2462. param.id = combined_id;
  2463. compiler.set_name(combined_id,
  2464. join("SPIRV_Cross_Combined", compiler.to_name(image_id), compiler.to_name(sampler_id)));
  2465. caller.combined_parameters.push_back(param);
  2466. caller.shadow_arguments.push_back({ ptr_type_id, combined_id, 0u, 0u, true });
  2467. }
  2468. }
  2469. bool Compiler::DummySamplerForCombinedImageHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  2470. {
  2471. if (need_dummy_sampler)
  2472. {
  2473. // No need to traverse further, we know the result.
  2474. return false;
  2475. }
  2476. switch (opcode)
  2477. {
  2478. case OpLoad:
  2479. {
  2480. if (length < 3)
  2481. return false;
  2482. uint32_t result_type = args[0];
  2483. auto &type = compiler.get<SPIRType>(result_type);
  2484. bool separate_image =
  2485. type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer;
  2486. // If not separate image, don't bother.
  2487. if (!separate_image)
  2488. return true;
  2489. uint32_t id = args[1];
  2490. uint32_t ptr = args[2];
  2491. compiler.set<SPIRExpression>(id, "", result_type, true);
  2492. compiler.register_read(id, ptr, true);
  2493. break;
  2494. }
  2495. case OpImageFetch:
  2496. case OpImageQuerySizeLod:
  2497. case OpImageQuerySize:
  2498. case OpImageQueryLevels:
  2499. case OpImageQuerySamples:
  2500. {
  2501. // If we are fetching or querying LOD from a plain OpTypeImage, we must pre-combine with our dummy sampler.
  2502. auto *var = compiler.maybe_get_backing_variable(args[2]);
  2503. if (var)
  2504. {
  2505. auto &type = compiler.get<SPIRType>(var->basetype);
  2506. if (type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer)
  2507. need_dummy_sampler = true;
  2508. }
  2509. break;
  2510. }
  2511. case OpInBoundsAccessChain:
  2512. case OpAccessChain:
  2513. case OpPtrAccessChain:
  2514. {
  2515. if (length < 3)
  2516. return false;
  2517. uint32_t result_type = args[0];
  2518. auto &type = compiler.get<SPIRType>(result_type);
  2519. bool separate_image =
  2520. type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer;
  2521. if (!separate_image)
  2522. return true;
  2523. uint32_t id = args[1];
  2524. uint32_t ptr = args[2];
  2525. compiler.set<SPIRExpression>(id, "", result_type, true);
  2526. compiler.register_read(id, ptr, true);
  2527. // Other backends might use SPIRAccessChain for this later.
  2528. compiler.ir.ids[id].set_allow_type_rewrite();
  2529. break;
  2530. }
  2531. default:
  2532. break;
  2533. }
  2534. return true;
  2535. }
  2536. bool Compiler::CombinedImageSamplerHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  2537. {
  2538. // We need to figure out where samplers and images are loaded from, so do only the bare bones compilation we need.
  2539. bool is_fetch = false;
  2540. switch (opcode)
  2541. {
  2542. case OpLoad:
  2543. {
  2544. if (length < 3)
  2545. return false;
  2546. uint32_t result_type = args[0];
  2547. auto &type = compiler.get<SPIRType>(result_type);
  2548. bool separate_image = type.basetype == SPIRType::Image && type.image.sampled == 1;
  2549. bool separate_sampler = type.basetype == SPIRType::Sampler;
  2550. // If not separate image or sampler, don't bother.
  2551. if (!separate_image && !separate_sampler)
  2552. return true;
  2553. uint32_t id = args[1];
  2554. uint32_t ptr = args[2];
  2555. compiler.set<SPIRExpression>(id, "", result_type, true);
  2556. compiler.register_read(id, ptr, true);
  2557. return true;
  2558. }
  2559. case OpInBoundsAccessChain:
  2560. case OpAccessChain:
  2561. case OpPtrAccessChain:
  2562. {
  2563. if (length < 3)
  2564. return false;
  2565. // Technically, it is possible to have arrays of textures and arrays of samplers and combine them, but this becomes essentially
  2566. // impossible to implement, since we don't know which concrete sampler we are accessing.
  2567. // One potential way is to create a combinatorial explosion where N textures and M samplers are combined into N * M sampler2Ds,
  2568. // but this seems ridiculously complicated for a problem which is easy to work around.
  2569. // Checking access chains like this assumes we don't have samplers or textures inside uniform structs, but this makes no sense.
  2570. uint32_t result_type = args[0];
  2571. auto &type = compiler.get<SPIRType>(result_type);
  2572. bool separate_image = type.basetype == SPIRType::Image && type.image.sampled == 1;
  2573. bool separate_sampler = type.basetype == SPIRType::Sampler;
  2574. if (separate_sampler)
  2575. SPIRV_CROSS_THROW(
  2576. "Attempting to use arrays or structs of separate samplers. This is not possible to statically "
  2577. "remap to plain GLSL.");
  2578. if (separate_image)
  2579. {
  2580. uint32_t id = args[1];
  2581. uint32_t ptr = args[2];
  2582. compiler.set<SPIRExpression>(id, "", result_type, true);
  2583. compiler.register_read(id, ptr, true);
  2584. }
  2585. return true;
  2586. }
  2587. case OpImageFetch:
  2588. case OpImageQuerySizeLod:
  2589. case OpImageQuerySize:
  2590. case OpImageQueryLevels:
  2591. case OpImageQuerySamples:
  2592. {
  2593. // If we are fetching from a plain OpTypeImage or querying LOD, we must pre-combine with our dummy sampler.
  2594. auto *var = compiler.maybe_get_backing_variable(args[2]);
  2595. if (!var)
  2596. return true;
  2597. auto &type = compiler.get<SPIRType>(var->basetype);
  2598. if (type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer)
  2599. {
  2600. if (compiler.dummy_sampler_id == 0)
  2601. SPIRV_CROSS_THROW("texelFetch without sampler was found, but no dummy sampler has been created with "
  2602. "build_dummy_sampler_for_combined_images().");
  2603. // Do it outside.
  2604. is_fetch = true;
  2605. break;
  2606. }
  2607. return true;
  2608. }
  2609. case OpSampledImage:
  2610. // Do it outside.
  2611. break;
  2612. default:
  2613. return true;
  2614. }
  2615. // Registers sampler2D calls used in case they are parameters so
  2616. // that their callees know which combined image samplers to propagate down the call stack.
  2617. if (!functions.empty())
  2618. {
  2619. auto &callee = *functions.top();
  2620. if (callee.do_combined_parameters)
  2621. {
  2622. uint32_t image_id = args[2];
  2623. auto *image = compiler.maybe_get_backing_variable(image_id);
  2624. if (image)
  2625. image_id = image->self;
  2626. uint32_t sampler_id = is_fetch ? compiler.dummy_sampler_id : args[3];
  2627. auto *sampler = compiler.maybe_get_backing_variable(sampler_id);
  2628. if (sampler)
  2629. sampler_id = sampler->self;
  2630. uint32_t combined_id = args[1];
  2631. auto &combined_type = compiler.get<SPIRType>(args[0]);
  2632. register_combined_image_sampler(callee, combined_id, image_id, sampler_id, combined_type.image.depth);
  2633. }
  2634. }
  2635. // For function calls, we need to remap IDs which are function parameters into global variables.
  2636. // This information is statically known from the current place in the call stack.
  2637. // Function parameters are not necessarily pointers, so if we don't have a backing variable, remapping will know
  2638. // which backing variable the image/sample came from.
  2639. VariableID image_id = remap_parameter(args[2]);
  2640. VariableID sampler_id = is_fetch ? compiler.dummy_sampler_id : remap_parameter(args[3]);
  2641. auto itr = find_if(begin(compiler.combined_image_samplers), end(compiler.combined_image_samplers),
  2642. [image_id, sampler_id](const CombinedImageSampler &combined) {
  2643. return combined.image_id == image_id && combined.sampler_id == sampler_id;
  2644. });
  2645. if (itr == end(compiler.combined_image_samplers))
  2646. {
  2647. uint32_t sampled_type;
  2648. uint32_t combined_module_id;
  2649. if (is_fetch)
  2650. {
  2651. // Have to invent the sampled image type.
  2652. sampled_type = compiler.ir.increase_bound_by(1);
  2653. auto &type = compiler.set<SPIRType>(sampled_type, OpTypeSampledImage);
  2654. type = compiler.expression_type(args[2]);
  2655. type.self = sampled_type;
  2656. type.basetype = SPIRType::SampledImage;
  2657. type.image.depth = false;
  2658. combined_module_id = 0;
  2659. }
  2660. else
  2661. {
  2662. sampled_type = args[0];
  2663. combined_module_id = args[1];
  2664. }
  2665. auto id = compiler.ir.increase_bound_by(2);
  2666. auto type_id = id + 0;
  2667. auto combined_id = id + 1;
  2668. // Make a new type, pointer to OpTypeSampledImage, so we can make a variable of this type.
  2669. // We will probably have this type lying around, but it doesn't hurt to make duplicates for internal purposes.
  2670. auto &type = compiler.set<SPIRType>(type_id, OpTypePointer);
  2671. auto &base = compiler.get<SPIRType>(sampled_type);
  2672. type = base;
  2673. type.pointer = true;
  2674. type.storage = StorageClassUniformConstant;
  2675. type.parent_type = type_id;
  2676. // Build new variable.
  2677. compiler.set<SPIRVariable>(combined_id, type_id, StorageClassUniformConstant, 0);
  2678. // Inherit RelaxedPrecision (and potentially other useful flags if deemed relevant).
  2679. // If any of OpSampledImage, underlying image or sampler are marked, inherit the decoration.
  2680. bool relaxed_precision =
  2681. (sampler_id && compiler.has_decoration(sampler_id, DecorationRelaxedPrecision)) ||
  2682. (image_id && compiler.has_decoration(image_id, DecorationRelaxedPrecision)) ||
  2683. (combined_module_id && compiler.has_decoration(combined_module_id, DecorationRelaxedPrecision));
  2684. if (relaxed_precision)
  2685. compiler.set_decoration(combined_id, DecorationRelaxedPrecision);
  2686. // Propagate the array type for the original image as well.
  2687. auto *var = compiler.maybe_get_backing_variable(image_id);
  2688. if (var)
  2689. {
  2690. auto &parent_type = compiler.get<SPIRType>(var->basetype);
  2691. type.array = parent_type.array;
  2692. type.array_size_literal = parent_type.array_size_literal;
  2693. }
  2694. compiler.combined_image_samplers.push_back({ combined_id, image_id, sampler_id });
  2695. }
  2696. return true;
  2697. }
  2698. VariableID Compiler::build_dummy_sampler_for_combined_images()
  2699. {
  2700. DummySamplerForCombinedImageHandler handler(*this);
  2701. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  2702. if (handler.need_dummy_sampler)
  2703. {
  2704. uint32_t offset = ir.increase_bound_by(3);
  2705. auto type_id = offset + 0;
  2706. auto ptr_type_id = offset + 1;
  2707. auto var_id = offset + 2;
  2708. auto &sampler = set<SPIRType>(type_id, OpTypeSampler);
  2709. sampler.basetype = SPIRType::Sampler;
  2710. auto &ptr_sampler = set<SPIRType>(ptr_type_id, OpTypePointer);
  2711. ptr_sampler = sampler;
  2712. ptr_sampler.self = type_id;
  2713. ptr_sampler.storage = StorageClassUniformConstant;
  2714. ptr_sampler.pointer = true;
  2715. ptr_sampler.parent_type = type_id;
  2716. set<SPIRVariable>(var_id, ptr_type_id, StorageClassUniformConstant, 0);
  2717. set_name(var_id, "SPIRV_Cross_DummySampler");
  2718. dummy_sampler_id = var_id;
  2719. return var_id;
  2720. }
  2721. else
  2722. return 0;
  2723. }
  2724. void Compiler::build_combined_image_samplers()
  2725. {
  2726. ir.for_each_typed_id<SPIRFunction>([&](uint32_t, SPIRFunction &func) {
  2727. func.combined_parameters.clear();
  2728. func.shadow_arguments.clear();
  2729. func.do_combined_parameters = true;
  2730. });
  2731. combined_image_samplers.clear();
  2732. CombinedImageSamplerHandler handler(*this);
  2733. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  2734. }
  2735. SmallVector<SpecializationConstant> Compiler::get_specialization_constants() const
  2736. {
  2737. SmallVector<SpecializationConstant> spec_consts;
  2738. ir.for_each_typed_id<SPIRConstant>([&](uint32_t, const SPIRConstant &c) {
  2739. if (c.specialization && has_decoration(c.self, DecorationSpecId))
  2740. spec_consts.push_back({ c.self, get_decoration(c.self, DecorationSpecId) });
  2741. });
  2742. return spec_consts;
  2743. }
  2744. SPIRConstant &Compiler::get_constant(ConstantID id)
  2745. {
  2746. return get<SPIRConstant>(id);
  2747. }
  2748. const SPIRConstant &Compiler::get_constant(ConstantID id) const
  2749. {
  2750. return get<SPIRConstant>(id);
  2751. }
  2752. static bool exists_unaccessed_path_to_return(const CFG &cfg, uint32_t block, const unordered_set<uint32_t> &blocks,
  2753. unordered_set<uint32_t> &visit_cache)
  2754. {
  2755. // This block accesses the variable.
  2756. if (blocks.find(block) != end(blocks))
  2757. return false;
  2758. // We are at the end of the CFG.
  2759. if (cfg.get_succeeding_edges(block).empty())
  2760. return true;
  2761. // If any of our successors have a path to the end, there exists a path from block.
  2762. for (auto &succ : cfg.get_succeeding_edges(block))
  2763. {
  2764. if (visit_cache.count(succ) == 0)
  2765. {
  2766. if (exists_unaccessed_path_to_return(cfg, succ, blocks, visit_cache))
  2767. return true;
  2768. visit_cache.insert(succ);
  2769. }
  2770. }
  2771. return false;
  2772. }
  2773. void Compiler::analyze_parameter_preservation(
  2774. SPIRFunction &entry, const CFG &cfg, const unordered_map<uint32_t, unordered_set<uint32_t>> &variable_to_blocks,
  2775. const unordered_map<uint32_t, unordered_set<uint32_t>> &complete_write_blocks)
  2776. {
  2777. for (auto &arg : entry.arguments)
  2778. {
  2779. // Non-pointers are always inputs.
  2780. auto &type = get<SPIRType>(arg.type);
  2781. if (!type.pointer)
  2782. continue;
  2783. // Opaque argument types are always in
  2784. bool potential_preserve;
  2785. switch (type.basetype)
  2786. {
  2787. case SPIRType::Sampler:
  2788. case SPIRType::Image:
  2789. case SPIRType::SampledImage:
  2790. case SPIRType::AtomicCounter:
  2791. potential_preserve = false;
  2792. break;
  2793. default:
  2794. potential_preserve = true;
  2795. break;
  2796. }
  2797. if (!potential_preserve)
  2798. continue;
  2799. auto itr = variable_to_blocks.find(arg.id);
  2800. if (itr == end(variable_to_blocks))
  2801. {
  2802. // Variable is never accessed.
  2803. continue;
  2804. }
  2805. // We have accessed a variable, but there was no complete writes to that variable.
  2806. // We deduce that we must preserve the argument.
  2807. itr = complete_write_blocks.find(arg.id);
  2808. if (itr == end(complete_write_blocks))
  2809. {
  2810. arg.read_count++;
  2811. continue;
  2812. }
  2813. // If there is a path through the CFG where no block completely writes to the variable, the variable will be in an undefined state
  2814. // when the function returns. We therefore need to implicitly preserve the variable in case there are writers in the function.
  2815. // Major case here is if a function is
  2816. // void foo(int &var) { if (cond) var = 10; }
  2817. // Using read/write counts, we will think it's just an out variable, but it really needs to be inout,
  2818. // because if we don't write anything whatever we put into the function must return back to the caller.
  2819. unordered_set<uint32_t> visit_cache;
  2820. if (exists_unaccessed_path_to_return(cfg, entry.entry_block, itr->second, visit_cache))
  2821. arg.read_count++;
  2822. }
  2823. }
  2824. Compiler::AnalyzeVariableScopeAccessHandler::AnalyzeVariableScopeAccessHandler(Compiler &compiler_,
  2825. SPIRFunction &entry_)
  2826. : compiler(compiler_)
  2827. , entry(entry_)
  2828. {
  2829. }
  2830. bool Compiler::AnalyzeVariableScopeAccessHandler::follow_function_call(const SPIRFunction &)
  2831. {
  2832. // Only analyze within this function.
  2833. return false;
  2834. }
  2835. void Compiler::AnalyzeVariableScopeAccessHandler::set_current_block(const SPIRBlock &block)
  2836. {
  2837. current_block = &block;
  2838. // If we're branching to a block which uses OpPhi, in GLSL
  2839. // this will be a variable write when we branch,
  2840. // so we need to track access to these variables as well to
  2841. // have a complete picture.
  2842. const auto test_phi = [this, &block](uint32_t to) {
  2843. auto &next = compiler.get<SPIRBlock>(to);
  2844. for (auto &phi : next.phi_variables)
  2845. {
  2846. if (phi.parent == block.self)
  2847. {
  2848. accessed_variables_to_block[phi.function_variable].insert(block.self);
  2849. // Phi variables are also accessed in our target branch block.
  2850. accessed_variables_to_block[phi.function_variable].insert(next.self);
  2851. notify_variable_access(phi.local_variable, block.self);
  2852. }
  2853. }
  2854. };
  2855. switch (block.terminator)
  2856. {
  2857. case SPIRBlock::Direct:
  2858. notify_variable_access(block.condition, block.self);
  2859. test_phi(block.next_block);
  2860. break;
  2861. case SPIRBlock::Select:
  2862. notify_variable_access(block.condition, block.self);
  2863. test_phi(block.true_block);
  2864. test_phi(block.false_block);
  2865. break;
  2866. case SPIRBlock::MultiSelect:
  2867. {
  2868. notify_variable_access(block.condition, block.self);
  2869. auto &cases = compiler.get_case_list(block);
  2870. for (auto &target : cases)
  2871. test_phi(target.block);
  2872. if (block.default_block)
  2873. test_phi(block.default_block);
  2874. break;
  2875. }
  2876. default:
  2877. break;
  2878. }
  2879. }
  2880. void Compiler::AnalyzeVariableScopeAccessHandler::notify_variable_access(uint32_t id, uint32_t block)
  2881. {
  2882. if (id == 0)
  2883. return;
  2884. // Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
  2885. auto itr = rvalue_forward_children.find(id);
  2886. if (itr != end(rvalue_forward_children))
  2887. for (auto child_id : itr->second)
  2888. notify_variable_access(child_id, block);
  2889. if (id_is_phi_variable(id))
  2890. accessed_variables_to_block[id].insert(block);
  2891. else if (id_is_potential_temporary(id))
  2892. accessed_temporaries_to_block[id].insert(block);
  2893. }
  2894. bool Compiler::AnalyzeVariableScopeAccessHandler::id_is_phi_variable(uint32_t id) const
  2895. {
  2896. if (id >= compiler.get_current_id_bound())
  2897. return false;
  2898. auto *var = compiler.maybe_get<SPIRVariable>(id);
  2899. return var && var->phi_variable;
  2900. }
  2901. bool Compiler::AnalyzeVariableScopeAccessHandler::id_is_potential_temporary(uint32_t id) const
  2902. {
  2903. if (id >= compiler.get_current_id_bound())
  2904. return false;
  2905. // Temporaries are not created before we start emitting code.
  2906. return compiler.ir.ids[id].empty() || (compiler.ir.ids[id].get_type() == TypeExpression);
  2907. }
  2908. bool Compiler::AnalyzeVariableScopeAccessHandler::handle_terminator(const SPIRBlock &block)
  2909. {
  2910. switch (block.terminator)
  2911. {
  2912. case SPIRBlock::Return:
  2913. if (block.return_value)
  2914. notify_variable_access(block.return_value, block.self);
  2915. break;
  2916. case SPIRBlock::Select:
  2917. case SPIRBlock::MultiSelect:
  2918. notify_variable_access(block.condition, block.self);
  2919. break;
  2920. default:
  2921. break;
  2922. }
  2923. return true;
  2924. }
  2925. bool Compiler::AnalyzeVariableScopeAccessHandler::handle(spv::Op op, const uint32_t *args, uint32_t length)
  2926. {
  2927. // Keep track of the types of temporaries, so we can hoist them out as necessary.
  2928. uint32_t result_type = 0, result_id = 0;
  2929. if (compiler.instruction_to_result_type(result_type, result_id, op, args, length))
  2930. {
  2931. // For some opcodes, we will need to override the result id.
  2932. // If we need to hoist the temporary, the temporary type is the input, not the result.
  2933. if (op == OpConvertUToAccelerationStructureKHR)
  2934. {
  2935. auto itr = result_id_to_type.find(args[2]);
  2936. if (itr != result_id_to_type.end())
  2937. result_type = itr->second;
  2938. }
  2939. result_id_to_type[result_id] = result_type;
  2940. }
  2941. switch (op)
  2942. {
  2943. case OpStore:
  2944. case OpCooperativeMatrixStoreKHR:
  2945. {
  2946. if (length < 2)
  2947. return false;
  2948. ID ptr = args[0];
  2949. auto *var = compiler.maybe_get_backing_variable(ptr);
  2950. // If we store through an access chain, we have a partial write.
  2951. if (var)
  2952. {
  2953. accessed_variables_to_block[var->self].insert(current_block->self);
  2954. if (var->self == ptr)
  2955. complete_write_variables_to_block[var->self].insert(current_block->self);
  2956. else
  2957. partial_write_variables_to_block[var->self].insert(current_block->self);
  2958. }
  2959. // args[0] might be an access chain we have to track use of.
  2960. notify_variable_access(args[0], current_block->self);
  2961. // Might try to store a Phi variable here.
  2962. notify_variable_access(args[1], current_block->self);
  2963. break;
  2964. }
  2965. case OpAccessChain:
  2966. case OpInBoundsAccessChain:
  2967. case OpPtrAccessChain:
  2968. {
  2969. if (length < 3)
  2970. return false;
  2971. // Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
  2972. uint32_t ptr = args[2];
  2973. auto *var = compiler.maybe_get<SPIRVariable>(ptr);
  2974. if (var)
  2975. {
  2976. accessed_variables_to_block[var->self].insert(current_block->self);
  2977. rvalue_forward_children[args[1]].insert(var->self);
  2978. }
  2979. // args[2] might be another access chain we have to track use of.
  2980. for (uint32_t i = 2; i < length; i++)
  2981. {
  2982. notify_variable_access(args[i], current_block->self);
  2983. rvalue_forward_children[args[1]].insert(args[i]);
  2984. }
  2985. // Also keep track of the access chain pointer itself.
  2986. // In exceptionally rare cases, we can end up with a case where
  2987. // the access chain is generated in the loop body, but is consumed in continue block.
  2988. // This means we need complex loop workarounds, and we must detect this via CFG analysis.
  2989. notify_variable_access(args[1], current_block->self);
  2990. // The result of an access chain is a fixed expression and is not really considered a temporary.
  2991. auto &e = compiler.set<SPIRExpression>(args[1], "", args[0], true);
  2992. auto *backing_variable = compiler.maybe_get_backing_variable(ptr);
  2993. e.loaded_from = backing_variable ? VariableID(backing_variable->self) : VariableID(0);
  2994. // Other backends might use SPIRAccessChain for this later.
  2995. compiler.ir.ids[args[1]].set_allow_type_rewrite();
  2996. access_chain_expressions.insert(args[1]);
  2997. break;
  2998. }
  2999. case OpCopyMemory:
  3000. {
  3001. if (length < 2)
  3002. return false;
  3003. ID lhs = args[0];
  3004. ID rhs = args[1];
  3005. auto *var = compiler.maybe_get_backing_variable(lhs);
  3006. // If we store through an access chain, we have a partial write.
  3007. if (var)
  3008. {
  3009. accessed_variables_to_block[var->self].insert(current_block->self);
  3010. if (var->self == lhs)
  3011. complete_write_variables_to_block[var->self].insert(current_block->self);
  3012. else
  3013. partial_write_variables_to_block[var->self].insert(current_block->self);
  3014. }
  3015. // args[0:1] might be access chains we have to track use of.
  3016. for (uint32_t i = 0; i < 2; i++)
  3017. notify_variable_access(args[i], current_block->self);
  3018. var = compiler.maybe_get_backing_variable(rhs);
  3019. if (var)
  3020. accessed_variables_to_block[var->self].insert(current_block->self);
  3021. break;
  3022. }
  3023. case OpCopyObject:
  3024. {
  3025. // OpCopyObject copies the underlying non-pointer type,
  3026. // so any temp variable should be declared using the underlying type.
  3027. // If the type is a pointer, get its base type and overwrite the result type mapping.
  3028. auto &type = compiler.get<SPIRType>(result_type);
  3029. if (type.pointer)
  3030. result_id_to_type[result_id] = type.parent_type;
  3031. if (length < 3)
  3032. return false;
  3033. auto *var = compiler.maybe_get_backing_variable(args[2]);
  3034. if (var)
  3035. accessed_variables_to_block[var->self].insert(current_block->self);
  3036. // Might be an access chain which we have to keep track of.
  3037. notify_variable_access(args[1], current_block->self);
  3038. if (access_chain_expressions.count(args[2]))
  3039. access_chain_expressions.insert(args[1]);
  3040. // Might try to copy a Phi variable here.
  3041. notify_variable_access(args[2], current_block->self);
  3042. break;
  3043. }
  3044. case OpLoad:
  3045. case OpCooperativeMatrixLoadKHR:
  3046. {
  3047. if (length < 3)
  3048. return false;
  3049. uint32_t ptr = args[2];
  3050. auto *var = compiler.maybe_get_backing_variable(ptr);
  3051. if (var)
  3052. accessed_variables_to_block[var->self].insert(current_block->self);
  3053. // Loaded value is a temporary.
  3054. notify_variable_access(args[1], current_block->self);
  3055. // Might be an access chain we have to track use of.
  3056. notify_variable_access(args[2], current_block->self);
  3057. // If we're loading an opaque type we cannot lower it to a temporary,
  3058. // we must defer access of args[2] until it's used.
  3059. auto &type = compiler.get<SPIRType>(args[0]);
  3060. if (compiler.type_is_opaque_value(type))
  3061. rvalue_forward_children[args[1]].insert(args[2]);
  3062. break;
  3063. }
  3064. case OpFunctionCall:
  3065. {
  3066. if (length < 3)
  3067. return false;
  3068. // Return value may be a temporary.
  3069. if (compiler.get_type(args[0]).basetype != SPIRType::Void)
  3070. notify_variable_access(args[1], current_block->self);
  3071. length -= 3;
  3072. args += 3;
  3073. for (uint32_t i = 0; i < length; i++)
  3074. {
  3075. auto *var = compiler.maybe_get_backing_variable(args[i]);
  3076. if (var)
  3077. {
  3078. accessed_variables_to_block[var->self].insert(current_block->self);
  3079. // Assume we can get partial writes to this variable.
  3080. partial_write_variables_to_block[var->self].insert(current_block->self);
  3081. }
  3082. // Cannot easily prove if argument we pass to a function is completely written.
  3083. // Usually, functions write to a dummy variable,
  3084. // which is then copied to in full to the real argument.
  3085. // Might try to copy a Phi variable here.
  3086. notify_variable_access(args[i], current_block->self);
  3087. }
  3088. break;
  3089. }
  3090. case OpSelect:
  3091. {
  3092. // In case of variable pointers, we might access a variable here.
  3093. // We cannot prove anything about these accesses however.
  3094. for (uint32_t i = 1; i < length; i++)
  3095. {
  3096. if (i >= 3)
  3097. {
  3098. auto *var = compiler.maybe_get_backing_variable(args[i]);
  3099. if (var)
  3100. {
  3101. accessed_variables_to_block[var->self].insert(current_block->self);
  3102. // Assume we can get partial writes to this variable.
  3103. partial_write_variables_to_block[var->self].insert(current_block->self);
  3104. }
  3105. }
  3106. // Might try to copy a Phi variable here.
  3107. notify_variable_access(args[i], current_block->self);
  3108. }
  3109. break;
  3110. }
  3111. case OpExtInst:
  3112. {
  3113. for (uint32_t i = 4; i < length; i++)
  3114. notify_variable_access(args[i], current_block->self);
  3115. notify_variable_access(args[1], current_block->self);
  3116. uint32_t extension_set = args[2];
  3117. if (compiler.get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
  3118. {
  3119. auto op_450 = static_cast<GLSLstd450>(args[3]);
  3120. switch (op_450)
  3121. {
  3122. case GLSLstd450Modf:
  3123. case GLSLstd450Frexp:
  3124. {
  3125. uint32_t ptr = args[5];
  3126. auto *var = compiler.maybe_get_backing_variable(ptr);
  3127. if (var)
  3128. {
  3129. accessed_variables_to_block[var->self].insert(current_block->self);
  3130. if (var->self == ptr)
  3131. complete_write_variables_to_block[var->self].insert(current_block->self);
  3132. else
  3133. partial_write_variables_to_block[var->self].insert(current_block->self);
  3134. }
  3135. break;
  3136. }
  3137. default:
  3138. break;
  3139. }
  3140. }
  3141. break;
  3142. }
  3143. case OpArrayLength:
  3144. // Only result is a temporary.
  3145. notify_variable_access(args[1], current_block->self);
  3146. break;
  3147. case OpLine:
  3148. case OpNoLine:
  3149. // Uses literals, but cannot be a phi variable or temporary, so ignore.
  3150. break;
  3151. // Atomics shouldn't be able to access function-local variables.
  3152. // Some GLSL builtins access a pointer.
  3153. case OpCompositeInsert:
  3154. case OpVectorShuffle:
  3155. // Specialize for opcode which contains literals.
  3156. for (uint32_t i = 1; i < 4; i++)
  3157. notify_variable_access(args[i], current_block->self);
  3158. break;
  3159. case OpCompositeExtract:
  3160. // Specialize for opcode which contains literals.
  3161. for (uint32_t i = 1; i < 3; i++)
  3162. notify_variable_access(args[i], current_block->self);
  3163. break;
  3164. case OpImageWrite:
  3165. for (uint32_t i = 0; i < length; i++)
  3166. {
  3167. // Argument 3 is a literal.
  3168. if (i != 3)
  3169. notify_variable_access(args[i], current_block->self);
  3170. }
  3171. break;
  3172. case OpImageSampleImplicitLod:
  3173. case OpImageSampleExplicitLod:
  3174. case OpImageSparseSampleImplicitLod:
  3175. case OpImageSparseSampleExplicitLod:
  3176. case OpImageSampleProjImplicitLod:
  3177. case OpImageSampleProjExplicitLod:
  3178. case OpImageSparseSampleProjImplicitLod:
  3179. case OpImageSparseSampleProjExplicitLod:
  3180. case OpImageFetch:
  3181. case OpImageSparseFetch:
  3182. case OpImageRead:
  3183. case OpImageSparseRead:
  3184. for (uint32_t i = 1; i < length; i++)
  3185. {
  3186. // Argument 4 is a literal.
  3187. if (i != 4)
  3188. notify_variable_access(args[i], current_block->self);
  3189. }
  3190. break;
  3191. case OpImageSampleDrefImplicitLod:
  3192. case OpImageSampleDrefExplicitLod:
  3193. case OpImageSparseSampleDrefImplicitLod:
  3194. case OpImageSparseSampleDrefExplicitLod:
  3195. case OpImageSampleProjDrefImplicitLod:
  3196. case OpImageSampleProjDrefExplicitLod:
  3197. case OpImageSparseSampleProjDrefImplicitLod:
  3198. case OpImageSparseSampleProjDrefExplicitLod:
  3199. case OpImageGather:
  3200. case OpImageSparseGather:
  3201. case OpImageDrefGather:
  3202. case OpImageSparseDrefGather:
  3203. for (uint32_t i = 1; i < length; i++)
  3204. {
  3205. // Argument 5 is a literal.
  3206. if (i != 5)
  3207. notify_variable_access(args[i], current_block->self);
  3208. }
  3209. break;
  3210. default:
  3211. {
  3212. // Rather dirty way of figuring out where Phi variables are used.
  3213. // As long as only IDs are used, we can scan through instructions and try to find any evidence that
  3214. // the ID of a variable has been used.
  3215. // There are potential false positives here where a literal is used in-place of an ID,
  3216. // but worst case, it does not affect the correctness of the compile.
  3217. // Exhaustive analysis would be better here, but it's not worth it for now.
  3218. for (uint32_t i = 0; i < length; i++)
  3219. notify_variable_access(args[i], current_block->self);
  3220. break;
  3221. }
  3222. }
  3223. return true;
  3224. }
  3225. Compiler::StaticExpressionAccessHandler::StaticExpressionAccessHandler(Compiler &compiler_, uint32_t variable_id_)
  3226. : compiler(compiler_)
  3227. , variable_id(variable_id_)
  3228. {
  3229. }
  3230. bool Compiler::StaticExpressionAccessHandler::follow_function_call(const SPIRFunction &)
  3231. {
  3232. return false;
  3233. }
  3234. bool Compiler::StaticExpressionAccessHandler::handle(spv::Op op, const uint32_t *args, uint32_t length)
  3235. {
  3236. switch (op)
  3237. {
  3238. case OpStore:
  3239. case OpCooperativeMatrixStoreKHR:
  3240. if (length < 2)
  3241. return false;
  3242. if (args[0] == variable_id)
  3243. {
  3244. static_expression = args[1];
  3245. write_count++;
  3246. }
  3247. break;
  3248. case OpLoad:
  3249. case OpCooperativeMatrixLoadKHR:
  3250. if (length < 3)
  3251. return false;
  3252. if (args[2] == variable_id && static_expression == 0) // Tried to read from variable before it was initialized.
  3253. return false;
  3254. break;
  3255. case OpAccessChain:
  3256. case OpInBoundsAccessChain:
  3257. case OpPtrAccessChain:
  3258. if (length < 3)
  3259. return false;
  3260. if (args[2] == variable_id) // If we try to access chain our candidate variable before we store to it, bail.
  3261. return false;
  3262. break;
  3263. default:
  3264. break;
  3265. }
  3266. return true;
  3267. }
  3268. void Compiler::find_function_local_luts(SPIRFunction &entry, const AnalyzeVariableScopeAccessHandler &handler,
  3269. bool single_function)
  3270. {
  3271. auto &cfg = *function_cfgs.find(entry.self)->second;
  3272. // For each variable which is statically accessed.
  3273. for (auto &accessed_var : handler.accessed_variables_to_block)
  3274. {
  3275. auto &blocks = accessed_var.second;
  3276. auto &var = get<SPIRVariable>(accessed_var.first);
  3277. auto &type = expression_type(accessed_var.first);
  3278. // First check if there are writes to the variable. Later, if there are none, we'll
  3279. // reconsider it as globally accessed LUT.
  3280. if (!var.is_written_to)
  3281. {
  3282. var.is_written_to = handler.complete_write_variables_to_block.count(var.self) != 0 ||
  3283. handler.partial_write_variables_to_block.count(var.self) != 0;
  3284. }
  3285. // Only consider function local variables here.
  3286. // If we only have a single function in our CFG, private storage is also fine,
  3287. // since it behaves like a function local variable.
  3288. bool allow_lut = var.storage == StorageClassFunction || (single_function && var.storage == StorageClassPrivate);
  3289. if (!allow_lut)
  3290. continue;
  3291. // We cannot be a phi variable.
  3292. if (var.phi_variable)
  3293. continue;
  3294. // Only consider arrays here.
  3295. if (type.array.empty())
  3296. continue;
  3297. // If the variable has an initializer, make sure it is a constant expression.
  3298. uint32_t static_constant_expression = 0;
  3299. if (var.initializer)
  3300. {
  3301. if (ir.ids[var.initializer].get_type() != TypeConstant)
  3302. continue;
  3303. static_constant_expression = var.initializer;
  3304. // There can be no stores to this variable, we have now proved we have a LUT.
  3305. if (var.is_written_to)
  3306. continue;
  3307. }
  3308. else
  3309. {
  3310. // We can have one, and only one write to the variable, and that write needs to be a constant.
  3311. // No partial writes allowed.
  3312. if (handler.partial_write_variables_to_block.count(var.self) != 0)
  3313. continue;
  3314. auto itr = handler.complete_write_variables_to_block.find(var.self);
  3315. // No writes?
  3316. if (itr == end(handler.complete_write_variables_to_block))
  3317. continue;
  3318. // We write to the variable in more than one block.
  3319. auto &write_blocks = itr->second;
  3320. if (write_blocks.size() != 1)
  3321. continue;
  3322. // The write needs to happen in the dominating block.
  3323. DominatorBuilder builder(cfg);
  3324. for (auto &block : blocks)
  3325. builder.add_block(block);
  3326. uint32_t dominator = builder.get_dominator();
  3327. // The complete write happened in a branch or similar, cannot deduce static expression.
  3328. if (write_blocks.count(dominator) == 0)
  3329. continue;
  3330. // Find the static expression for this variable.
  3331. StaticExpressionAccessHandler static_expression_handler(*this, var.self);
  3332. traverse_all_reachable_opcodes(get<SPIRBlock>(dominator), static_expression_handler);
  3333. // We want one, and exactly one write
  3334. if (static_expression_handler.write_count != 1 || static_expression_handler.static_expression == 0)
  3335. continue;
  3336. // Is it a constant expression?
  3337. if (ir.ids[static_expression_handler.static_expression].get_type() != TypeConstant)
  3338. continue;
  3339. // We found a LUT!
  3340. static_constant_expression = static_expression_handler.static_expression;
  3341. }
  3342. get<SPIRConstant>(static_constant_expression).is_used_as_lut = true;
  3343. var.static_expression = static_constant_expression;
  3344. var.statically_assigned = true;
  3345. var.remapped_variable = true;
  3346. }
  3347. }
  3348. void Compiler::analyze_variable_scope(SPIRFunction &entry, AnalyzeVariableScopeAccessHandler &handler)
  3349. {
  3350. // First, we map out all variable access within a function.
  3351. // Essentially a map of block -> { variables accessed in the basic block }
  3352. traverse_all_reachable_opcodes(entry, handler);
  3353. auto &cfg = *function_cfgs.find(entry.self)->second;
  3354. // Analyze if there are parameters which need to be implicitly preserved with an "in" qualifier.
  3355. analyze_parameter_preservation(entry, cfg, handler.accessed_variables_to_block,
  3356. handler.complete_write_variables_to_block);
  3357. unordered_map<uint32_t, uint32_t> potential_loop_variables;
  3358. // Find the loop dominator block for each block.
  3359. for (auto &block_id : entry.blocks)
  3360. {
  3361. auto &block = get<SPIRBlock>(block_id);
  3362. auto itr = ir.continue_block_to_loop_header.find(block_id);
  3363. if (itr != end(ir.continue_block_to_loop_header) && itr->second != block_id)
  3364. {
  3365. // Continue block might be unreachable in the CFG, but we still like to know the loop dominator.
  3366. // Edge case is when continue block is also the loop header, don't set the dominator in this case.
  3367. block.loop_dominator = itr->second;
  3368. }
  3369. else
  3370. {
  3371. uint32_t loop_dominator = cfg.find_loop_dominator(block_id);
  3372. if (loop_dominator != block_id)
  3373. block.loop_dominator = loop_dominator;
  3374. else
  3375. block.loop_dominator = SPIRBlock::NoDominator;
  3376. }
  3377. }
  3378. // For each variable which is statically accessed.
  3379. for (auto &var : handler.accessed_variables_to_block)
  3380. {
  3381. // Only deal with variables which are considered local variables in this function.
  3382. if (find(begin(entry.local_variables), end(entry.local_variables), VariableID(var.first)) ==
  3383. end(entry.local_variables))
  3384. continue;
  3385. DominatorBuilder builder(cfg);
  3386. auto &blocks = var.second;
  3387. auto &type = expression_type(var.first);
  3388. BlockID potential_continue_block = 0;
  3389. // Figure out which block is dominating all accesses of those variables.
  3390. for (auto &block : blocks)
  3391. {
  3392. // If we're accessing a variable inside a continue block, this variable might be a loop variable.
  3393. // We can only use loop variables with scalars, as we cannot track static expressions for vectors.
  3394. if (is_continue(block))
  3395. {
  3396. // Potentially awkward case to check for.
  3397. // We might have a variable inside a loop, which is touched by the continue block,
  3398. // but is not actually a loop variable.
  3399. // The continue block is dominated by the inner part of the loop, which does not make sense in high-level
  3400. // language output because it will be declared before the body,
  3401. // so we will have to lift the dominator up to the relevant loop header instead.
  3402. builder.add_block(ir.continue_block_to_loop_header[block]);
  3403. // Arrays or structs cannot be loop variables.
  3404. if (type.vecsize == 1 && type.columns == 1 && type.basetype != SPIRType::Struct && type.array.empty())
  3405. {
  3406. // The variable is used in multiple continue blocks, this is not a loop
  3407. // candidate, signal that by setting block to -1u.
  3408. if (potential_continue_block == 0)
  3409. potential_continue_block = block;
  3410. else
  3411. potential_continue_block = ~(0u);
  3412. }
  3413. }
  3414. builder.add_block(block);
  3415. }
  3416. builder.lift_continue_block_dominator();
  3417. // Add it to a per-block list of variables.
  3418. BlockID dominating_block = builder.get_dominator();
  3419. if (dominating_block && potential_continue_block != 0 && potential_continue_block != ~0u)
  3420. {
  3421. auto &inner_block = get<SPIRBlock>(dominating_block);
  3422. BlockID merge_candidate = 0;
  3423. // Analyze the dominator. If it lives in a different loop scope than the candidate continue
  3424. // block, reject the loop variable candidate.
  3425. if (inner_block.merge == SPIRBlock::MergeLoop)
  3426. merge_candidate = inner_block.merge_block;
  3427. else if (inner_block.loop_dominator != SPIRBlock::NoDominator)
  3428. merge_candidate = get<SPIRBlock>(inner_block.loop_dominator).merge_block;
  3429. if (merge_candidate != 0 && cfg.is_reachable(merge_candidate))
  3430. {
  3431. // If the merge block has a higher post-visit order, we know that continue candidate
  3432. // cannot reach the merge block, and we have two separate scopes.
  3433. if (!cfg.is_reachable(potential_continue_block) ||
  3434. cfg.get_visit_order(merge_candidate) > cfg.get_visit_order(potential_continue_block))
  3435. {
  3436. potential_continue_block = 0;
  3437. }
  3438. }
  3439. }
  3440. if (potential_continue_block != 0 && potential_continue_block != ~0u)
  3441. potential_loop_variables[var.first] = potential_continue_block;
  3442. // For variables whose dominating block is inside a loop, there is a risk that these variables
  3443. // actually need to be preserved across loop iterations. We can express this by adding
  3444. // a "read" access to the loop header.
  3445. // In the dominating block, we must see an OpStore or equivalent as the first access of an OpVariable.
  3446. // Should that fail, we look for the outermost loop header and tack on an access there.
  3447. // Phi nodes cannot have this problem.
  3448. if (dominating_block)
  3449. {
  3450. auto &variable = get<SPIRVariable>(var.first);
  3451. if (!variable.phi_variable)
  3452. {
  3453. auto *block = &get<SPIRBlock>(dominating_block);
  3454. bool preserve = may_read_undefined_variable_in_block(*block, var.first);
  3455. if (preserve)
  3456. {
  3457. // Find the outermost loop scope.
  3458. while (block->loop_dominator != BlockID(SPIRBlock::NoDominator))
  3459. block = &get<SPIRBlock>(block->loop_dominator);
  3460. if (block->self != dominating_block)
  3461. {
  3462. builder.add_block(block->self);
  3463. dominating_block = builder.get_dominator();
  3464. }
  3465. }
  3466. }
  3467. }
  3468. // If all blocks here are dead code, this will be 0, so the variable in question
  3469. // will be completely eliminated.
  3470. if (dominating_block)
  3471. {
  3472. auto &block = get<SPIRBlock>(dominating_block);
  3473. block.dominated_variables.push_back(var.first);
  3474. get<SPIRVariable>(var.first).dominator = dominating_block;
  3475. }
  3476. }
  3477. for (auto &var : handler.accessed_temporaries_to_block)
  3478. {
  3479. auto itr = handler.result_id_to_type.find(var.first);
  3480. if (itr == end(handler.result_id_to_type))
  3481. {
  3482. // We found a false positive ID being used, ignore.
  3483. // This should probably be an assert.
  3484. continue;
  3485. }
  3486. // There is no point in doing domination analysis for opaque types.
  3487. auto &type = get<SPIRType>(itr->second);
  3488. if (type_is_opaque_value(type))
  3489. continue;
  3490. DominatorBuilder builder(cfg);
  3491. bool force_temporary = false;
  3492. bool used_in_header_hoisted_continue_block = false;
  3493. // Figure out which block is dominating all accesses of those temporaries.
  3494. auto &blocks = var.second;
  3495. for (auto &block : blocks)
  3496. {
  3497. builder.add_block(block);
  3498. if (blocks.size() != 1 && is_continue(block))
  3499. {
  3500. // The risk here is that inner loop can dominate the continue block.
  3501. // Any temporary we access in the continue block must be declared before the loop.
  3502. // This is moot for complex loops however.
  3503. auto &loop_header_block = get<SPIRBlock>(ir.continue_block_to_loop_header[block]);
  3504. assert(loop_header_block.merge == SPIRBlock::MergeLoop);
  3505. builder.add_block(loop_header_block.self);
  3506. used_in_header_hoisted_continue_block = true;
  3507. }
  3508. }
  3509. uint32_t dominating_block = builder.get_dominator();
  3510. if (blocks.size() != 1 && is_single_block_loop(dominating_block))
  3511. {
  3512. // Awkward case, because the loop header is also the continue block,
  3513. // so hoisting to loop header does not help.
  3514. force_temporary = true;
  3515. }
  3516. if (dominating_block)
  3517. {
  3518. // If we touch a variable in the dominating block, this is the expected setup.
  3519. // SPIR-V normally mandates this, but we have extra cases for temporary use inside loops.
  3520. bool first_use_is_dominator = blocks.count(dominating_block) != 0;
  3521. if (!first_use_is_dominator || force_temporary)
  3522. {
  3523. if (handler.access_chain_expressions.count(var.first))
  3524. {
  3525. // Exceptionally rare case.
  3526. // We cannot declare temporaries of access chains (except on MSL perhaps with pointers).
  3527. // Rather than do that, we force the indexing expressions to be declared in the right scope by
  3528. // tracking their usage to that end. There is no temporary to hoist.
  3529. // However, we still need to observe declaration order of the access chain.
  3530. if (used_in_header_hoisted_continue_block)
  3531. {
  3532. // For this scenario, we used an access chain inside a continue block where we also registered an access to header block.
  3533. // This is a problem as we need to declare an access chain properly first with full definition.
  3534. // We cannot use temporaries for these expressions,
  3535. // so we must make sure the access chain is declared ahead of time.
  3536. // Force a complex for loop to deal with this.
  3537. // TODO: Out-of-order declaring for loops where continue blocks are emitted last might be another option.
  3538. auto &loop_header_block = get<SPIRBlock>(dominating_block);
  3539. assert(loop_header_block.merge == SPIRBlock::MergeLoop);
  3540. loop_header_block.complex_continue = true;
  3541. }
  3542. }
  3543. else
  3544. {
  3545. // This should be very rare, but if we try to declare a temporary inside a loop,
  3546. // and that temporary is used outside the loop as well (spirv-opt inliner likes this)
  3547. // we should actually emit the temporary outside the loop.
  3548. hoisted_temporaries.insert(var.first);
  3549. forced_temporaries.insert(var.first);
  3550. auto &block_temporaries = get<SPIRBlock>(dominating_block).declare_temporary;
  3551. block_temporaries.emplace_back(handler.result_id_to_type[var.first], var.first);
  3552. }
  3553. }
  3554. else if (blocks.size() > 1)
  3555. {
  3556. // Keep track of the temporary as we might have to declare this temporary.
  3557. // This can happen if the loop header dominates a temporary, but we have a complex fallback loop.
  3558. // In this case, the header is actually inside the for (;;) {} block, and we have problems.
  3559. // What we need to do is hoist the temporaries outside the for (;;) {} block in case the header block
  3560. // declares the temporary.
  3561. auto &block_temporaries = get<SPIRBlock>(dominating_block).potential_declare_temporary;
  3562. block_temporaries.emplace_back(handler.result_id_to_type[var.first], var.first);
  3563. }
  3564. }
  3565. }
  3566. unordered_set<uint32_t> seen_blocks;
  3567. // Now, try to analyze whether or not these variables are actually loop variables.
  3568. for (auto &loop_variable : potential_loop_variables)
  3569. {
  3570. auto &var = get<SPIRVariable>(loop_variable.first);
  3571. auto dominator = var.dominator;
  3572. BlockID block = loop_variable.second;
  3573. // The variable was accessed in multiple continue blocks, ignore.
  3574. if (block == BlockID(~(0u)) || block == BlockID(0))
  3575. continue;
  3576. // Dead code.
  3577. if (dominator == ID(0))
  3578. continue;
  3579. BlockID header = 0;
  3580. // Find the loop header for this block if we are a continue block.
  3581. {
  3582. auto itr = ir.continue_block_to_loop_header.find(block);
  3583. if (itr != end(ir.continue_block_to_loop_header))
  3584. {
  3585. header = itr->second;
  3586. }
  3587. else if (get<SPIRBlock>(block).continue_block == block)
  3588. {
  3589. // Also check for self-referential continue block.
  3590. header = block;
  3591. }
  3592. }
  3593. assert(header);
  3594. auto &header_block = get<SPIRBlock>(header);
  3595. auto &blocks = handler.accessed_variables_to_block[loop_variable.first];
  3596. // If a loop variable is not used before the loop, it's probably not a loop variable.
  3597. bool has_accessed_variable = blocks.count(header) != 0;
  3598. // Now, there are two conditions we need to meet for the variable to be a loop variable.
  3599. // 1. The dominating block must have a branch-free path to the loop header,
  3600. // this way we statically know which expression should be part of the loop variable initializer.
  3601. // Walk from the dominator, if there is one straight edge connecting
  3602. // dominator and loop header, we statically know the loop initializer.
  3603. bool static_loop_init = true;
  3604. while (dominator != header)
  3605. {
  3606. if (blocks.count(dominator) != 0)
  3607. has_accessed_variable = true;
  3608. auto &succ = cfg.get_succeeding_edges(dominator);
  3609. if (succ.size() != 1)
  3610. {
  3611. static_loop_init = false;
  3612. break;
  3613. }
  3614. auto &pred = cfg.get_preceding_edges(succ.front());
  3615. if (pred.size() != 1 || pred.front() != dominator)
  3616. {
  3617. static_loop_init = false;
  3618. break;
  3619. }
  3620. dominator = succ.front();
  3621. }
  3622. if (!static_loop_init || !has_accessed_variable)
  3623. continue;
  3624. // The second condition we need to meet is that no access after the loop
  3625. // merge can occur. Walk the CFG to see if we find anything.
  3626. seen_blocks.clear();
  3627. cfg.walk_from(seen_blocks, header_block.merge_block, [&](uint32_t walk_block) -> bool {
  3628. // We found a block which accesses the variable outside the loop.
  3629. if (blocks.find(walk_block) != end(blocks))
  3630. static_loop_init = false;
  3631. return true;
  3632. });
  3633. if (!static_loop_init)
  3634. continue;
  3635. // We have a loop variable.
  3636. header_block.loop_variables.push_back(loop_variable.first);
  3637. // Need to sort here as variables come from an unordered container, and pushing stuff in wrong order
  3638. // will break reproducability in regression runs.
  3639. sort(begin(header_block.loop_variables), end(header_block.loop_variables));
  3640. get<SPIRVariable>(loop_variable.first).loop_variable = true;
  3641. }
  3642. }
  3643. bool Compiler::may_read_undefined_variable_in_block(const SPIRBlock &block, uint32_t var)
  3644. {
  3645. for (auto &op : block.ops)
  3646. {
  3647. auto *ops = stream(op);
  3648. switch (op.op)
  3649. {
  3650. case OpStore:
  3651. case OpCooperativeMatrixStoreKHR:
  3652. case OpCopyMemory:
  3653. if (ops[0] == var)
  3654. return false;
  3655. break;
  3656. case OpAccessChain:
  3657. case OpInBoundsAccessChain:
  3658. case OpPtrAccessChain:
  3659. // Access chains are generally used to partially read and write. It's too hard to analyze
  3660. // if all constituents are written fully before continuing, so just assume it's preserved.
  3661. // This is the same as the parameter preservation analysis.
  3662. if (ops[2] == var)
  3663. return true;
  3664. break;
  3665. case OpSelect:
  3666. // Variable pointers.
  3667. // We might read before writing.
  3668. if (ops[3] == var || ops[4] == var)
  3669. return true;
  3670. break;
  3671. case OpPhi:
  3672. {
  3673. // Variable pointers.
  3674. // We might read before writing.
  3675. if (op.length < 2)
  3676. break;
  3677. uint32_t count = op.length - 2;
  3678. for (uint32_t i = 0; i < count; i += 2)
  3679. if (ops[i + 2] == var)
  3680. return true;
  3681. break;
  3682. }
  3683. case OpCopyObject:
  3684. case OpLoad:
  3685. case OpCooperativeMatrixLoadKHR:
  3686. if (ops[2] == var)
  3687. return true;
  3688. break;
  3689. case OpFunctionCall:
  3690. {
  3691. if (op.length < 3)
  3692. break;
  3693. // May read before writing.
  3694. uint32_t count = op.length - 3;
  3695. for (uint32_t i = 0; i < count; i++)
  3696. if (ops[i + 3] == var)
  3697. return true;
  3698. break;
  3699. }
  3700. default:
  3701. break;
  3702. }
  3703. }
  3704. // Not accessed somehow, at least not in a usual fashion.
  3705. // It's likely accessed in a branch, so assume we must preserve.
  3706. return true;
  3707. }
  3708. bool Compiler::GeometryEmitDisocveryHandler::handle(spv::Op opcode, const uint32_t *, uint32_t)
  3709. {
  3710. if (opcode == OpEmitVertex || opcode == OpEndPrimitive)
  3711. {
  3712. for (auto *func : function_stack)
  3713. func->emits_geometry = true;
  3714. }
  3715. return true;
  3716. }
  3717. bool Compiler::GeometryEmitDisocveryHandler::begin_function_scope(const uint32_t *stream, uint32_t)
  3718. {
  3719. auto &callee = compiler.get<SPIRFunction>(stream[2]);
  3720. function_stack.push_back(&callee);
  3721. return true;
  3722. }
  3723. bool Compiler::GeometryEmitDisocveryHandler::end_function_scope([[maybe_unused]] const uint32_t *stream, uint32_t)
  3724. {
  3725. assert(function_stack.back() == &compiler.get<SPIRFunction>(stream[2]));
  3726. function_stack.pop_back();
  3727. return true;
  3728. }
  3729. void Compiler::discover_geometry_emitters()
  3730. {
  3731. GeometryEmitDisocveryHandler handler(*this);
  3732. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  3733. }
  3734. Bitset Compiler::get_buffer_block_flags(VariableID id) const
  3735. {
  3736. return ir.get_buffer_block_flags(get<SPIRVariable>(id));
  3737. }
  3738. bool Compiler::get_common_basic_type(const SPIRType &type, SPIRType::BaseType &base_type)
  3739. {
  3740. if (type.basetype == SPIRType::Struct)
  3741. {
  3742. base_type = SPIRType::Unknown;
  3743. for (auto &member_type : type.member_types)
  3744. {
  3745. SPIRType::BaseType member_base;
  3746. if (!get_common_basic_type(get<SPIRType>(member_type), member_base))
  3747. return false;
  3748. if (base_type == SPIRType::Unknown)
  3749. base_type = member_base;
  3750. else if (base_type != member_base)
  3751. return false;
  3752. }
  3753. return true;
  3754. }
  3755. else
  3756. {
  3757. base_type = type.basetype;
  3758. return true;
  3759. }
  3760. }
  3761. void Compiler::ActiveBuiltinHandler::handle_builtin(const SPIRType &type, BuiltIn builtin,
  3762. const Bitset &decoration_flags)
  3763. {
  3764. // If used, we will need to explicitly declare a new array size for these builtins.
  3765. if (builtin == BuiltInClipDistance)
  3766. {
  3767. if (!type.array_size_literal[0])
  3768. SPIRV_CROSS_THROW("Array size for ClipDistance must be a literal.");
  3769. uint32_t array_size = type.array[0];
  3770. if (array_size == 0)
  3771. SPIRV_CROSS_THROW("Array size for ClipDistance must not be unsized.");
  3772. compiler.clip_distance_count = array_size;
  3773. }
  3774. else if (builtin == BuiltInCullDistance)
  3775. {
  3776. if (!type.array_size_literal[0])
  3777. SPIRV_CROSS_THROW("Array size for CullDistance must be a literal.");
  3778. uint32_t array_size = type.array[0];
  3779. if (array_size == 0)
  3780. SPIRV_CROSS_THROW("Array size for CullDistance must not be unsized.");
  3781. compiler.cull_distance_count = array_size;
  3782. }
  3783. else if (builtin == BuiltInPosition)
  3784. {
  3785. if (decoration_flags.get(DecorationInvariant))
  3786. compiler.position_invariant = true;
  3787. }
  3788. }
  3789. void Compiler::ActiveBuiltinHandler::add_if_builtin(uint32_t id, bool allow_blocks)
  3790. {
  3791. // Only handle plain variables here.
  3792. // Builtins which are part of a block are handled in AccessChain.
  3793. // If allow_blocks is used however, this is to handle initializers of blocks,
  3794. // which implies that all members are written to.
  3795. auto *var = compiler.maybe_get<SPIRVariable>(id);
  3796. auto *m = compiler.ir.find_meta(id);
  3797. if (var && m)
  3798. {
  3799. auto &type = compiler.get<SPIRType>(var->basetype);
  3800. auto &decorations = m->decoration;
  3801. auto &flags = type.storage == StorageClassInput ?
  3802. compiler.active_input_builtins : compiler.active_output_builtins;
  3803. if (decorations.builtin)
  3804. {
  3805. flags.set(decorations.builtin_type);
  3806. handle_builtin(type, decorations.builtin_type, decorations.decoration_flags);
  3807. }
  3808. else if (allow_blocks && compiler.has_decoration(type.self, DecorationBlock))
  3809. {
  3810. uint32_t member_count = uint32_t(type.member_types.size());
  3811. for (uint32_t i = 0; i < member_count; i++)
  3812. {
  3813. if (compiler.has_member_decoration(type.self, i, DecorationBuiltIn))
  3814. {
  3815. auto &member_type = compiler.get<SPIRType>(type.member_types[i]);
  3816. BuiltIn builtin = BuiltIn(compiler.get_member_decoration(type.self, i, DecorationBuiltIn));
  3817. flags.set(builtin);
  3818. handle_builtin(member_type, builtin, compiler.get_member_decoration_bitset(type.self, i));
  3819. }
  3820. }
  3821. }
  3822. }
  3823. }
  3824. void Compiler::ActiveBuiltinHandler::add_if_builtin(uint32_t id)
  3825. {
  3826. add_if_builtin(id, false);
  3827. }
  3828. void Compiler::ActiveBuiltinHandler::add_if_builtin_or_block(uint32_t id)
  3829. {
  3830. add_if_builtin(id, true);
  3831. }
  3832. bool Compiler::ActiveBuiltinHandler::handle(spv::Op opcode, const uint32_t *args, uint32_t length)
  3833. {
  3834. switch (opcode)
  3835. {
  3836. case OpStore:
  3837. case OpCooperativeMatrixStoreKHR:
  3838. if (length < 1)
  3839. return false;
  3840. add_if_builtin(args[0]);
  3841. break;
  3842. case OpCopyMemory:
  3843. if (length < 2)
  3844. return false;
  3845. add_if_builtin(args[0]);
  3846. add_if_builtin(args[1]);
  3847. break;
  3848. case OpCopyObject:
  3849. case OpLoad:
  3850. case OpCooperativeMatrixLoadKHR:
  3851. if (length < 3)
  3852. return false;
  3853. add_if_builtin(args[2]);
  3854. break;
  3855. case OpSelect:
  3856. if (length < 5)
  3857. return false;
  3858. add_if_builtin(args[3]);
  3859. add_if_builtin(args[4]);
  3860. break;
  3861. case OpPhi:
  3862. {
  3863. if (length < 2)
  3864. return false;
  3865. uint32_t count = length - 2;
  3866. args += 2;
  3867. for (uint32_t i = 0; i < count; i += 2)
  3868. add_if_builtin(args[i]);
  3869. break;
  3870. }
  3871. case OpFunctionCall:
  3872. {
  3873. if (length < 3)
  3874. return false;
  3875. uint32_t count = length - 3;
  3876. args += 3;
  3877. for (uint32_t i = 0; i < count; i++)
  3878. add_if_builtin(args[i]);
  3879. break;
  3880. }
  3881. case OpAccessChain:
  3882. case OpInBoundsAccessChain:
  3883. case OpPtrAccessChain:
  3884. {
  3885. if (length < 4)
  3886. return false;
  3887. // Only consider global variables, cannot consider variables in functions yet, or other
  3888. // access chains as they have not been created yet.
  3889. auto *var = compiler.maybe_get<SPIRVariable>(args[2]);
  3890. if (!var)
  3891. break;
  3892. // Required if we access chain into builtins like gl_GlobalInvocationID.
  3893. add_if_builtin(args[2]);
  3894. // Start traversing type hierarchy at the proper non-pointer types.
  3895. auto *type = &compiler.get_variable_data_type(*var);
  3896. auto &flags =
  3897. var->storage == StorageClassInput ? compiler.active_input_builtins : compiler.active_output_builtins;
  3898. uint32_t count = length - 3;
  3899. args += 3;
  3900. for (uint32_t i = 0; i < count; i++)
  3901. {
  3902. // Pointers
  3903. // PtrAccessChain functions more like a pointer offset. Type remains the same.
  3904. if (opcode == OpPtrAccessChain && i == 0)
  3905. continue;
  3906. // Arrays
  3907. if (!type->array.empty())
  3908. {
  3909. type = &compiler.get<SPIRType>(type->parent_type);
  3910. }
  3911. // Structs
  3912. else if (type->basetype == SPIRType::Struct)
  3913. {
  3914. uint32_t index = compiler.get<SPIRConstant>(args[i]).scalar();
  3915. if (index < uint32_t(compiler.ir.meta[type->self].members.size()))
  3916. {
  3917. auto &decorations = compiler.ir.meta[type->self].members[index];
  3918. if (decorations.builtin)
  3919. {
  3920. flags.set(decorations.builtin_type);
  3921. handle_builtin(compiler.get<SPIRType>(type->member_types[index]), decorations.builtin_type,
  3922. decorations.decoration_flags);
  3923. }
  3924. }
  3925. type = &compiler.get<SPIRType>(type->member_types[index]);
  3926. }
  3927. else
  3928. {
  3929. // No point in traversing further. We won't find any extra builtins.
  3930. break;
  3931. }
  3932. }
  3933. break;
  3934. }
  3935. default:
  3936. break;
  3937. }
  3938. return true;
  3939. }
  3940. void Compiler::update_active_builtins()
  3941. {
  3942. active_input_builtins.reset();
  3943. active_output_builtins.reset();
  3944. cull_distance_count = 0;
  3945. clip_distance_count = 0;
  3946. ActiveBuiltinHandler handler(*this);
  3947. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  3948. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
  3949. if (var.storage != StorageClassOutput)
  3950. return;
  3951. if (!interface_variable_exists_in_entry_point(var.self))
  3952. return;
  3953. // Also, make sure we preserve output variables which are only initialized, but never accessed by any code.
  3954. if (var.initializer != ID(0))
  3955. handler.add_if_builtin_or_block(var.self);
  3956. });
  3957. }
  3958. // Returns whether this shader uses a builtin of the storage class
  3959. bool Compiler::has_active_builtin(BuiltIn builtin, StorageClass storage) const
  3960. {
  3961. const Bitset *flags;
  3962. switch (storage)
  3963. {
  3964. case StorageClassInput:
  3965. flags = &active_input_builtins;
  3966. break;
  3967. case StorageClassOutput:
  3968. flags = &active_output_builtins;
  3969. break;
  3970. default:
  3971. return false;
  3972. }
  3973. return flags->get(builtin);
  3974. }
  3975. void Compiler::analyze_image_and_sampler_usage()
  3976. {
  3977. CombinedImageSamplerDrefHandler dref_handler(*this);
  3978. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), dref_handler);
  3979. CombinedImageSamplerUsageHandler handler(*this, dref_handler.dref_combined_samplers);
  3980. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  3981. // Need to run this traversal twice. First time, we propagate any comparison sampler usage from leaf functions
  3982. // down to main().
  3983. // In the second pass, we can propagate up forced depth state coming from main() up into leaf functions.
  3984. handler.dependency_hierarchy.clear();
  3985. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  3986. comparison_ids = std::move(handler.comparison_ids);
  3987. need_subpass_input = handler.need_subpass_input;
  3988. need_subpass_input_ms = handler.need_subpass_input_ms;
  3989. // Forward information from separate images and samplers into combined image samplers.
  3990. for (auto &combined : combined_image_samplers)
  3991. if (comparison_ids.count(combined.sampler_id))
  3992. comparison_ids.insert(combined.combined_id);
  3993. }
  3994. bool Compiler::CombinedImageSamplerDrefHandler::handle(spv::Op opcode, const uint32_t *args, uint32_t)
  3995. {
  3996. // Mark all sampled images which are used with Dref.
  3997. switch (opcode)
  3998. {
  3999. case OpImageSampleDrefExplicitLod:
  4000. case OpImageSampleDrefImplicitLod:
  4001. case OpImageSampleProjDrefExplicitLod:
  4002. case OpImageSampleProjDrefImplicitLod:
  4003. case OpImageSparseSampleProjDrefImplicitLod:
  4004. case OpImageSparseSampleDrefImplicitLod:
  4005. case OpImageSparseSampleProjDrefExplicitLod:
  4006. case OpImageSparseSampleDrefExplicitLod:
  4007. case OpImageDrefGather:
  4008. case OpImageSparseDrefGather:
  4009. dref_combined_samplers.insert(args[2]);
  4010. return true;
  4011. default:
  4012. break;
  4013. }
  4014. return true;
  4015. }
  4016. const CFG &Compiler::get_cfg_for_current_function() const
  4017. {
  4018. assert(current_function);
  4019. return get_cfg_for_function(current_function->self);
  4020. }
  4021. const CFG &Compiler::get_cfg_for_function(uint32_t id) const
  4022. {
  4023. auto cfg_itr = function_cfgs.find(id);
  4024. assert(cfg_itr != end(function_cfgs));
  4025. assert(cfg_itr->second);
  4026. return *cfg_itr->second;
  4027. }
  4028. void Compiler::build_function_control_flow_graphs_and_analyze()
  4029. {
  4030. CFGBuilder handler(*this);
  4031. handler.function_cfgs[ir.default_entry_point].reset(new CFG(*this, get<SPIRFunction>(ir.default_entry_point)));
  4032. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  4033. function_cfgs = std::move(handler.function_cfgs);
  4034. bool single_function = function_cfgs.size() <= 1;
  4035. for (auto &f : function_cfgs)
  4036. {
  4037. auto &func = get<SPIRFunction>(f.first);
  4038. AnalyzeVariableScopeAccessHandler scope_handler(*this, func);
  4039. analyze_variable_scope(func, scope_handler);
  4040. find_function_local_luts(func, scope_handler, single_function);
  4041. // Check if we can actually use the loop variables we found in analyze_variable_scope.
  4042. // To use multiple initializers, we need the same type and qualifiers.
  4043. for (auto block : func.blocks)
  4044. {
  4045. auto &b = get<SPIRBlock>(block);
  4046. if (b.loop_variables.size() < 2)
  4047. continue;
  4048. auto &flags = get_decoration_bitset(b.loop_variables.front());
  4049. uint32_t type = get<SPIRVariable>(b.loop_variables.front()).basetype;
  4050. bool invalid_initializers = false;
  4051. for (auto loop_variable : b.loop_variables)
  4052. {
  4053. if (flags != get_decoration_bitset(loop_variable) ||
  4054. type != get<SPIRVariable>(b.loop_variables.front()).basetype)
  4055. {
  4056. invalid_initializers = true;
  4057. break;
  4058. }
  4059. }
  4060. if (invalid_initializers)
  4061. {
  4062. for (auto loop_variable : b.loop_variables)
  4063. get<SPIRVariable>(loop_variable).loop_variable = false;
  4064. b.loop_variables.clear();
  4065. }
  4066. }
  4067. }
  4068. // Find LUTs which are not function local. Only consider this case if the CFG is multi-function,
  4069. // otherwise we treat Private as Function trivially.
  4070. // Needs to be analyzed from the outside since we have to block the LUT optimization if at least
  4071. // one function writes to it.
  4072. if (!single_function)
  4073. {
  4074. for (auto &id : global_variables)
  4075. {
  4076. auto &var = get<SPIRVariable>(id);
  4077. auto &type = get_variable_data_type(var);
  4078. if (is_array(type) && var.storage == StorageClassPrivate &&
  4079. var.initializer && !var.is_written_to &&
  4080. ir.ids[var.initializer].get_type() == TypeConstant)
  4081. {
  4082. get<SPIRConstant>(var.initializer).is_used_as_lut = true;
  4083. var.static_expression = var.initializer;
  4084. var.statically_assigned = true;
  4085. var.remapped_variable = true;
  4086. }
  4087. }
  4088. }
  4089. }
  4090. Compiler::CFGBuilder::CFGBuilder(Compiler &compiler_)
  4091. : compiler(compiler_)
  4092. {
  4093. }
  4094. bool Compiler::CFGBuilder::handle(spv::Op, const uint32_t *, uint32_t)
  4095. {
  4096. return true;
  4097. }
  4098. bool Compiler::CFGBuilder::follow_function_call(const SPIRFunction &func)
  4099. {
  4100. if (function_cfgs.find(func.self) == end(function_cfgs))
  4101. {
  4102. function_cfgs[func.self].reset(new CFG(compiler, func));
  4103. return true;
  4104. }
  4105. else
  4106. return false;
  4107. }
  4108. void Compiler::CombinedImageSamplerUsageHandler::add_dependency(uint32_t dst, uint32_t src)
  4109. {
  4110. dependency_hierarchy[dst].insert(src);
  4111. // Propagate up any comparison state if we're loading from one such variable.
  4112. if (comparison_ids.count(src))
  4113. comparison_ids.insert(dst);
  4114. }
  4115. bool Compiler::CombinedImageSamplerUsageHandler::begin_function_scope(const uint32_t *args, uint32_t length)
  4116. {
  4117. if (length < 3)
  4118. return false;
  4119. auto &func = compiler.get<SPIRFunction>(args[2]);
  4120. const auto *arg = &args[3];
  4121. length -= 3;
  4122. for (uint32_t i = 0; i < length; i++)
  4123. {
  4124. auto &argument = func.arguments[i];
  4125. add_dependency(argument.id, arg[i]);
  4126. }
  4127. return true;
  4128. }
  4129. void Compiler::CombinedImageSamplerUsageHandler::add_hierarchy_to_comparison_ids(uint32_t id)
  4130. {
  4131. // Traverse the variable dependency hierarchy and tag everything in its path with comparison ids.
  4132. comparison_ids.insert(id);
  4133. for (auto &dep_id : dependency_hierarchy[id])
  4134. add_hierarchy_to_comparison_ids(dep_id);
  4135. }
  4136. bool Compiler::CombinedImageSamplerUsageHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  4137. {
  4138. switch (opcode)
  4139. {
  4140. case OpAccessChain:
  4141. case OpInBoundsAccessChain:
  4142. case OpPtrAccessChain:
  4143. case OpLoad:
  4144. {
  4145. if (length < 3)
  4146. return false;
  4147. add_dependency(args[1], args[2]);
  4148. // Ideally defer this to OpImageRead, but then we'd need to track loaded IDs.
  4149. // If we load an image, we're going to use it and there is little harm in declaring an unused gl_FragCoord.
  4150. auto &type = compiler.get<SPIRType>(args[0]);
  4151. if (type.image.dim == DimSubpassData)
  4152. {
  4153. need_subpass_input = true;
  4154. if (type.image.ms)
  4155. need_subpass_input_ms = true;
  4156. }
  4157. // If we load a SampledImage and it will be used with Dref, propagate the state up.
  4158. if (dref_combined_samplers.count(args[1]) != 0)
  4159. add_hierarchy_to_comparison_ids(args[1]);
  4160. break;
  4161. }
  4162. case OpSampledImage:
  4163. {
  4164. if (length < 4)
  4165. return false;
  4166. // If the underlying resource has been used for comparison then duplicate loads of that resource must be too.
  4167. // This image must be a depth image.
  4168. uint32_t result_id = args[1];
  4169. uint32_t image = args[2];
  4170. uint32_t sampler = args[3];
  4171. if (dref_combined_samplers.count(result_id) != 0)
  4172. {
  4173. add_hierarchy_to_comparison_ids(image);
  4174. // This sampler must be a SamplerComparisonState, and not a regular SamplerState.
  4175. add_hierarchy_to_comparison_ids(sampler);
  4176. // Mark the OpSampledImage itself as being comparison state.
  4177. comparison_ids.insert(result_id);
  4178. }
  4179. return true;
  4180. }
  4181. default:
  4182. break;
  4183. }
  4184. return true;
  4185. }
  4186. bool Compiler::buffer_is_hlsl_counter_buffer(VariableID id) const
  4187. {
  4188. auto *m = ir.find_meta(id);
  4189. return m && m->hlsl_is_magic_counter_buffer;
  4190. }
  4191. bool Compiler::buffer_get_hlsl_counter_buffer(VariableID id, uint32_t &counter_id) const
  4192. {
  4193. auto *m = ir.find_meta(id);
  4194. // First, check for the proper decoration.
  4195. if (m && m->hlsl_magic_counter_buffer != 0)
  4196. {
  4197. counter_id = m->hlsl_magic_counter_buffer;
  4198. return true;
  4199. }
  4200. else
  4201. return false;
  4202. }
  4203. void Compiler::make_constant_null(uint32_t id, uint32_t type)
  4204. {
  4205. auto &constant_type = get<SPIRType>(type);
  4206. if (constant_type.pointer)
  4207. {
  4208. auto &constant = set<SPIRConstant>(id, type);
  4209. constant.make_null(constant_type);
  4210. }
  4211. else if (!constant_type.array.empty())
  4212. {
  4213. assert(constant_type.parent_type);
  4214. uint32_t parent_id = ir.increase_bound_by(1);
  4215. make_constant_null(parent_id, constant_type.parent_type);
  4216. // The array size of OpConstantNull can be either literal or specialization constant.
  4217. // In the latter case, we cannot take the value as-is, as it can be changed to anything.
  4218. // Rather, we assume it to be *one* for the sake of initializer.
  4219. bool is_literal_array_size = constant_type.array_size_literal.back();
  4220. uint32_t count = is_literal_array_size ? constant_type.array.back() : 1;
  4221. SmallVector<uint32_t> elements(count);
  4222. for (uint32_t i = 0; i < count; i++)
  4223. elements[i] = parent_id;
  4224. auto &constant = set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
  4225. constant.is_null_array_specialized_length = !is_literal_array_size;
  4226. }
  4227. else if (!constant_type.member_types.empty())
  4228. {
  4229. uint32_t member_ids = ir.increase_bound_by(uint32_t(constant_type.member_types.size()));
  4230. SmallVector<uint32_t> elements(constant_type.member_types.size());
  4231. for (uint32_t i = 0; i < constant_type.member_types.size(); i++)
  4232. {
  4233. make_constant_null(member_ids + i, constant_type.member_types[i]);
  4234. elements[i] = member_ids + i;
  4235. }
  4236. set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
  4237. }
  4238. else
  4239. {
  4240. auto &constant = set<SPIRConstant>(id, type);
  4241. constant.make_null(constant_type);
  4242. }
  4243. }
  4244. const SmallVector<spv::Capability> &Compiler::get_declared_capabilities() const
  4245. {
  4246. return ir.declared_capabilities;
  4247. }
  4248. const SmallVector<std::string> &Compiler::get_declared_extensions() const
  4249. {
  4250. return ir.declared_extensions;
  4251. }
  4252. std::string Compiler::get_remapped_declared_block_name(VariableID id) const
  4253. {
  4254. return get_remapped_declared_block_name(id, false);
  4255. }
  4256. std::string Compiler::get_remapped_declared_block_name(uint32_t id, bool fallback_prefer_instance_name) const
  4257. {
  4258. auto itr = declared_block_names.find(id);
  4259. if (itr != end(declared_block_names))
  4260. {
  4261. return itr->second;
  4262. }
  4263. else
  4264. {
  4265. auto &var = get<SPIRVariable>(id);
  4266. if (fallback_prefer_instance_name)
  4267. {
  4268. return to_name(var.self);
  4269. }
  4270. else
  4271. {
  4272. auto &type = get<SPIRType>(var.basetype);
  4273. auto *type_meta = ir.find_meta(type.self);
  4274. auto *block_name = type_meta ? &type_meta->decoration.alias : nullptr;
  4275. return (!block_name || block_name->empty()) ? get_block_fallback_name(id) : *block_name;
  4276. }
  4277. }
  4278. }
  4279. bool Compiler::reflection_ssbo_instance_name_is_significant() const
  4280. {
  4281. if (ir.source.known)
  4282. {
  4283. // UAVs from HLSL source tend to be declared in a way where the type is reused
  4284. // but the instance name is significant, and that's the name we should report.
  4285. // For GLSL, SSBOs each have their own block type as that's how GLSL is written.
  4286. return ir.source.hlsl;
  4287. }
  4288. unordered_set<uint32_t> ssbo_type_ids;
  4289. bool aliased_ssbo_types = false;
  4290. // If we don't have any OpSource information, we need to perform some shaky heuristics.
  4291. ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
  4292. auto &type = this->get<SPIRType>(var.basetype);
  4293. if (!type.pointer || var.storage == StorageClassFunction)
  4294. return;
  4295. bool ssbo = var.storage == StorageClassStorageBuffer ||
  4296. (var.storage == StorageClassUniform && has_decoration(type.self, DecorationBufferBlock));
  4297. if (ssbo)
  4298. {
  4299. if (ssbo_type_ids.count(type.self))
  4300. aliased_ssbo_types = true;
  4301. else
  4302. ssbo_type_ids.insert(type.self);
  4303. }
  4304. });
  4305. // If the block name is aliased, assume we have HLSL-style UAV declarations.
  4306. return aliased_ssbo_types;
  4307. }
  4308. bool Compiler::instruction_to_result_type(uint32_t &result_type, uint32_t &result_id, spv::Op op,
  4309. const uint32_t *args, uint32_t length)
  4310. {
  4311. if (length < 2)
  4312. return false;
  4313. bool has_result_id = false, has_result_type = false;
  4314. HasResultAndType(op, &has_result_id, &has_result_type);
  4315. if (has_result_id && has_result_type)
  4316. {
  4317. result_type = args[0];
  4318. result_id = args[1];
  4319. return true;
  4320. }
  4321. else
  4322. return false;
  4323. }
  4324. Bitset Compiler::combined_decoration_for_member(const SPIRType &type, uint32_t index) const
  4325. {
  4326. Bitset flags;
  4327. auto *type_meta = ir.find_meta(type.self);
  4328. if (type_meta)
  4329. {
  4330. auto &members = type_meta->members;
  4331. if (index >= members.size())
  4332. return flags;
  4333. auto &dec = members[index];
  4334. flags.merge_or(dec.decoration_flags);
  4335. auto &member_type = get<SPIRType>(type.member_types[index]);
  4336. // If our member type is a struct, traverse all the child members as well recursively.
  4337. auto &member_childs = member_type.member_types;
  4338. for (uint32_t i = 0; i < member_childs.size(); i++)
  4339. {
  4340. auto &child_member_type = get<SPIRType>(member_childs[i]);
  4341. if (!child_member_type.pointer)
  4342. flags.merge_or(combined_decoration_for_member(member_type, i));
  4343. }
  4344. }
  4345. return flags;
  4346. }
  4347. bool Compiler::is_desktop_only_format(spv::ImageFormat format)
  4348. {
  4349. switch (format)
  4350. {
  4351. // Desktop-only formats
  4352. case ImageFormatR11fG11fB10f:
  4353. case ImageFormatR16f:
  4354. case ImageFormatRgb10A2:
  4355. case ImageFormatR8:
  4356. case ImageFormatRg8:
  4357. case ImageFormatR16:
  4358. case ImageFormatRg16:
  4359. case ImageFormatRgba16:
  4360. case ImageFormatR16Snorm:
  4361. case ImageFormatRg16Snorm:
  4362. case ImageFormatRgba16Snorm:
  4363. case ImageFormatR8Snorm:
  4364. case ImageFormatRg8Snorm:
  4365. case ImageFormatR8ui:
  4366. case ImageFormatRg8ui:
  4367. case ImageFormatR16ui:
  4368. case ImageFormatRgb10a2ui:
  4369. case ImageFormatR8i:
  4370. case ImageFormatRg8i:
  4371. case ImageFormatR16i:
  4372. return true;
  4373. default:
  4374. break;
  4375. }
  4376. return false;
  4377. }
  4378. // An image is determined to be a depth image if it is marked as a depth image and is not also
  4379. // explicitly marked with a color format, or if there are any sample/gather compare operations on it.
  4380. bool Compiler::is_depth_image(const SPIRType &type, uint32_t id) const
  4381. {
  4382. return (type.image.depth && type.image.format == ImageFormatUnknown) || comparison_ids.count(id);
  4383. }
  4384. bool Compiler::type_is_opaque_value(const SPIRType &type) const
  4385. {
  4386. return !type.pointer && (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Image ||
  4387. type.basetype == SPIRType::Sampler);
  4388. }
  4389. // Make these member functions so we can easily break on any force_recompile events.
  4390. void Compiler::force_recompile()
  4391. {
  4392. is_force_recompile = true;
  4393. }
  4394. void Compiler::force_recompile_guarantee_forward_progress()
  4395. {
  4396. force_recompile();
  4397. is_force_recompile_forward_progress = true;
  4398. }
  4399. bool Compiler::is_forcing_recompilation() const
  4400. {
  4401. return is_force_recompile;
  4402. }
  4403. void Compiler::clear_force_recompile()
  4404. {
  4405. is_force_recompile = false;
  4406. is_force_recompile_forward_progress = false;
  4407. }
  4408. Compiler::PhysicalStorageBufferPointerHandler::PhysicalStorageBufferPointerHandler(Compiler &compiler_)
  4409. : compiler(compiler_)
  4410. {
  4411. }
  4412. Compiler::PhysicalBlockMeta *Compiler::PhysicalStorageBufferPointerHandler::find_block_meta(uint32_t id) const
  4413. {
  4414. auto chain_itr = access_chain_to_physical_block.find(id);
  4415. if (chain_itr != access_chain_to_physical_block.end())
  4416. return chain_itr->second;
  4417. else
  4418. return nullptr;
  4419. }
  4420. void Compiler::PhysicalStorageBufferPointerHandler::mark_aligned_access(uint32_t id, const uint32_t *args, uint32_t length)
  4421. {
  4422. uint32_t mask = *args;
  4423. args++;
  4424. length--;
  4425. if (length && (mask & MemoryAccessVolatileMask) != 0)
  4426. {
  4427. args++;
  4428. length--;
  4429. }
  4430. if (length && (mask & MemoryAccessAlignedMask) != 0)
  4431. {
  4432. uint32_t alignment = *args;
  4433. auto *meta = find_block_meta(id);
  4434. // This makes the assumption that the application does not rely on insane edge cases like:
  4435. // Bind buffer with ADDR = 8, use block offset of 8 bytes, load/store with 16 byte alignment.
  4436. // If we emit the buffer with alignment = 16 here, the first element at offset = 0 should
  4437. // actually have alignment of 8 bytes, but this is too theoretical and awkward to support.
  4438. // We could potentially keep track of any offset in the access chain, but it's
  4439. // practically impossible for high level compilers to emit code like that,
  4440. // so deducing overall alignment requirement based on maximum observed Alignment value is probably fine.
  4441. if (meta && alignment > meta->alignment)
  4442. meta->alignment = alignment;
  4443. }
  4444. }
  4445. bool Compiler::PhysicalStorageBufferPointerHandler::type_is_bda_block_entry(uint32_t type_id) const
  4446. {
  4447. auto &type = compiler.get<SPIRType>(type_id);
  4448. return compiler.is_physical_pointer(type);
  4449. }
  4450. uint32_t Compiler::PhysicalStorageBufferPointerHandler::get_minimum_scalar_alignment(const SPIRType &type) const
  4451. {
  4452. if (type.storage == spv::StorageClassPhysicalStorageBuffer)
  4453. return 8;
  4454. else if (type.basetype == SPIRType::Struct)
  4455. {
  4456. uint32_t alignment = 0;
  4457. for (auto &member_type : type.member_types)
  4458. {
  4459. uint32_t member_align = get_minimum_scalar_alignment(compiler.get<SPIRType>(member_type));
  4460. if (member_align > alignment)
  4461. alignment = member_align;
  4462. }
  4463. return alignment;
  4464. }
  4465. else
  4466. return type.width / 8;
  4467. }
  4468. void Compiler::PhysicalStorageBufferPointerHandler::setup_meta_chain(uint32_t type_id, uint32_t var_id)
  4469. {
  4470. if (type_is_bda_block_entry(type_id))
  4471. {
  4472. auto &meta = physical_block_type_meta[type_id];
  4473. access_chain_to_physical_block[var_id] = &meta;
  4474. auto &type = compiler.get<SPIRType>(type_id);
  4475. if (!compiler.is_physical_pointer_to_buffer_block(type))
  4476. non_block_types.insert(type_id);
  4477. if (meta.alignment == 0)
  4478. meta.alignment = get_minimum_scalar_alignment(compiler.get_pointee_type(type));
  4479. }
  4480. }
  4481. bool Compiler::PhysicalStorageBufferPointerHandler::handle(Op op, const uint32_t *args, uint32_t length)
  4482. {
  4483. // When a BDA pointer comes to life, we need to keep a mapping of SSA ID -> type ID for the pointer type.
  4484. // For every load and store, we'll need to be able to look up the type ID being accessed and mark any alignment
  4485. // requirements.
  4486. switch (op)
  4487. {
  4488. case OpConvertUToPtr:
  4489. case OpBitcast:
  4490. case OpCompositeExtract:
  4491. // Extract can begin a new chain if we had a struct or array of pointers as input.
  4492. // We don't begin chains before we have a pure scalar pointer.
  4493. setup_meta_chain(args[0], args[1]);
  4494. break;
  4495. case OpAccessChain:
  4496. case OpInBoundsAccessChain:
  4497. case OpPtrAccessChain:
  4498. case OpCopyObject:
  4499. {
  4500. auto itr = access_chain_to_physical_block.find(args[2]);
  4501. if (itr != access_chain_to_physical_block.end())
  4502. access_chain_to_physical_block[args[1]] = itr->second;
  4503. break;
  4504. }
  4505. case OpLoad:
  4506. {
  4507. setup_meta_chain(args[0], args[1]);
  4508. if (length >= 4)
  4509. mark_aligned_access(args[2], args + 3, length - 3);
  4510. break;
  4511. }
  4512. case OpStore:
  4513. {
  4514. if (length >= 3)
  4515. mark_aligned_access(args[0], args + 2, length - 2);
  4516. break;
  4517. }
  4518. case OpCooperativeMatrixLoadKHR:
  4519. case OpCooperativeMatrixStoreKHR:
  4520. {
  4521. // TODO: Can we meaningfully deal with this?
  4522. break;
  4523. }
  4524. default:
  4525. break;
  4526. }
  4527. return true;
  4528. }
  4529. uint32_t Compiler::PhysicalStorageBufferPointerHandler::get_base_non_block_type_id(uint32_t type_id) const
  4530. {
  4531. auto *type = &compiler.get<SPIRType>(type_id);
  4532. while (compiler.is_physical_pointer(*type) && !type_is_bda_block_entry(type_id))
  4533. {
  4534. type_id = type->parent_type;
  4535. type = &compiler.get<SPIRType>(type_id);
  4536. }
  4537. assert(type_is_bda_block_entry(type_id));
  4538. return type_id;
  4539. }
  4540. void Compiler::PhysicalStorageBufferPointerHandler::analyze_non_block_types_from_block(const SPIRType &type)
  4541. {
  4542. if (analyzed_type_ids.count(type.self))
  4543. return;
  4544. analyzed_type_ids.insert(type.self);
  4545. for (auto &member : type.member_types)
  4546. {
  4547. auto &subtype = compiler.get<SPIRType>(member);
  4548. if (compiler.is_physical_pointer(subtype) && !compiler.is_physical_pointer_to_buffer_block(subtype))
  4549. non_block_types.insert(get_base_non_block_type_id(member));
  4550. else if (subtype.basetype == SPIRType::Struct && !compiler.is_pointer(subtype))
  4551. analyze_non_block_types_from_block(subtype);
  4552. }
  4553. }
  4554. void Compiler::analyze_non_block_pointer_types()
  4555. {
  4556. PhysicalStorageBufferPointerHandler handler(*this);
  4557. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  4558. // Analyze any block declaration we have to make. It might contain
  4559. // physical pointers to POD types which we never used, and thus never added to the list.
  4560. // We'll need to add those pointer types to the set of types we declare.
  4561. ir.for_each_typed_id<SPIRType>([&](uint32_t id, SPIRType &type) {
  4562. // Only analyze the raw block struct, not any pointer-to-struct, since that's just redundant.
  4563. if (type.self == id &&
  4564. (has_decoration(type.self, DecorationBlock) ||
  4565. has_decoration(type.self, DecorationBufferBlock)))
  4566. {
  4567. handler.analyze_non_block_types_from_block(type);
  4568. }
  4569. });
  4570. physical_storage_non_block_pointer_types.reserve(handler.non_block_types.size());
  4571. for (auto type : handler.non_block_types)
  4572. physical_storage_non_block_pointer_types.push_back(type);
  4573. sort(begin(physical_storage_non_block_pointer_types), end(physical_storage_non_block_pointer_types));
  4574. physical_storage_type_to_alignment = std::move(handler.physical_block_type_meta);
  4575. }
  4576. bool Compiler::InterlockedResourceAccessPrepassHandler::handle(Op op, const uint32_t *, uint32_t)
  4577. {
  4578. if (op == OpBeginInvocationInterlockEXT || op == OpEndInvocationInterlockEXT)
  4579. {
  4580. if (interlock_function_id != 0 && interlock_function_id != call_stack.back())
  4581. {
  4582. // Most complex case, we have no sensible way of dealing with this
  4583. // other than taking the 100% conservative approach, exit early.
  4584. split_function_case = true;
  4585. return false;
  4586. }
  4587. else
  4588. {
  4589. interlock_function_id = call_stack.back();
  4590. // If this call is performed inside control flow we have a problem.
  4591. auto &cfg = compiler.get_cfg_for_function(interlock_function_id);
  4592. uint32_t from_block_id = compiler.get<SPIRFunction>(interlock_function_id).entry_block;
  4593. bool outside_control_flow = cfg.node_terminates_control_flow_in_sub_graph(from_block_id, current_block_id);
  4594. if (!outside_control_flow)
  4595. control_flow_interlock = true;
  4596. }
  4597. }
  4598. return true;
  4599. }
  4600. void Compiler::InterlockedResourceAccessPrepassHandler::rearm_current_block(const SPIRBlock &block)
  4601. {
  4602. current_block_id = block.self;
  4603. }
  4604. bool Compiler::InterlockedResourceAccessPrepassHandler::begin_function_scope(const uint32_t *args, uint32_t length)
  4605. {
  4606. if (length < 3)
  4607. return false;
  4608. call_stack.push_back(args[2]);
  4609. return true;
  4610. }
  4611. bool Compiler::InterlockedResourceAccessPrepassHandler::end_function_scope(const uint32_t *, uint32_t)
  4612. {
  4613. call_stack.pop_back();
  4614. return true;
  4615. }
  4616. bool Compiler::InterlockedResourceAccessHandler::begin_function_scope(const uint32_t *args, uint32_t length)
  4617. {
  4618. if (length < 3)
  4619. return false;
  4620. if (args[2] == interlock_function_id)
  4621. call_stack_is_interlocked = true;
  4622. call_stack.push_back(args[2]);
  4623. return true;
  4624. }
  4625. bool Compiler::InterlockedResourceAccessHandler::end_function_scope(const uint32_t *, uint32_t)
  4626. {
  4627. if (call_stack.back() == interlock_function_id)
  4628. call_stack_is_interlocked = false;
  4629. call_stack.pop_back();
  4630. return true;
  4631. }
  4632. void Compiler::InterlockedResourceAccessHandler::access_potential_resource(uint32_t id)
  4633. {
  4634. if ((use_critical_section && in_crit_sec) || (control_flow_interlock && call_stack_is_interlocked) ||
  4635. split_function_case)
  4636. {
  4637. compiler.interlocked_resources.insert(id);
  4638. }
  4639. }
  4640. bool Compiler::InterlockedResourceAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
  4641. {
  4642. // Only care about critical section analysis if we have simple case.
  4643. if (use_critical_section)
  4644. {
  4645. if (opcode == OpBeginInvocationInterlockEXT)
  4646. {
  4647. in_crit_sec = true;
  4648. return true;
  4649. }
  4650. if (opcode == OpEndInvocationInterlockEXT)
  4651. {
  4652. // End critical section--nothing more to do.
  4653. return false;
  4654. }
  4655. }
  4656. // We need to figure out where images and buffers are loaded from, so do only the bare bones compilation we need.
  4657. switch (opcode)
  4658. {
  4659. case OpLoad:
  4660. case OpCooperativeMatrixLoadKHR:
  4661. {
  4662. if (length < 3)
  4663. return false;
  4664. uint32_t ptr = args[2];
  4665. auto *var = compiler.maybe_get_backing_variable(ptr);
  4666. // We're only concerned with buffer and image memory here.
  4667. if (!var)
  4668. break;
  4669. switch (var->storage)
  4670. {
  4671. default:
  4672. break;
  4673. case StorageClassUniformConstant:
  4674. {
  4675. uint32_t result_type = args[0];
  4676. uint32_t id = args[1];
  4677. compiler.set<SPIRExpression>(id, "", result_type, true);
  4678. compiler.register_read(id, ptr, true);
  4679. break;
  4680. }
  4681. case StorageClassUniform:
  4682. // Must have BufferBlock; we only care about SSBOs.
  4683. if (!compiler.has_decoration(compiler.get<SPIRType>(var->basetype).self, DecorationBufferBlock))
  4684. break;
  4685. // fallthrough
  4686. case StorageClassStorageBuffer:
  4687. access_potential_resource(var->self);
  4688. break;
  4689. }
  4690. break;
  4691. }
  4692. case OpInBoundsAccessChain:
  4693. case OpAccessChain:
  4694. case OpPtrAccessChain:
  4695. {
  4696. if (length < 3)
  4697. return false;
  4698. uint32_t result_type = args[0];
  4699. auto &type = compiler.get<SPIRType>(result_type);
  4700. if (type.storage == StorageClassUniform || type.storage == StorageClassUniformConstant ||
  4701. type.storage == StorageClassStorageBuffer)
  4702. {
  4703. uint32_t id = args[1];
  4704. uint32_t ptr = args[2];
  4705. compiler.set<SPIRExpression>(id, "", result_type, true);
  4706. compiler.register_read(id, ptr, true);
  4707. compiler.ir.ids[id].set_allow_type_rewrite();
  4708. }
  4709. break;
  4710. }
  4711. case OpImageTexelPointer:
  4712. {
  4713. if (length < 3)
  4714. return false;
  4715. uint32_t result_type = args[0];
  4716. uint32_t id = args[1];
  4717. uint32_t ptr = args[2];
  4718. auto &e = compiler.set<SPIRExpression>(id, "", result_type, true);
  4719. auto *var = compiler.maybe_get_backing_variable(ptr);
  4720. if (var)
  4721. e.loaded_from = var->self;
  4722. break;
  4723. }
  4724. case OpStore:
  4725. case OpImageWrite:
  4726. case OpAtomicStore:
  4727. case OpCooperativeMatrixStoreKHR:
  4728. {
  4729. if (length < 1)
  4730. return false;
  4731. uint32_t ptr = args[0];
  4732. auto *var = compiler.maybe_get_backing_variable(ptr);
  4733. if (var && (var->storage == StorageClassUniform || var->storage == StorageClassUniformConstant ||
  4734. var->storage == StorageClassStorageBuffer))
  4735. {
  4736. access_potential_resource(var->self);
  4737. }
  4738. break;
  4739. }
  4740. case OpCopyMemory:
  4741. {
  4742. if (length < 2)
  4743. return false;
  4744. uint32_t dst = args[0];
  4745. uint32_t src = args[1];
  4746. auto *dst_var = compiler.maybe_get_backing_variable(dst);
  4747. auto *src_var = compiler.maybe_get_backing_variable(src);
  4748. if (dst_var && (dst_var->storage == StorageClassUniform || dst_var->storage == StorageClassStorageBuffer))
  4749. access_potential_resource(dst_var->self);
  4750. if (src_var)
  4751. {
  4752. if (src_var->storage != StorageClassUniform && src_var->storage != StorageClassStorageBuffer)
  4753. break;
  4754. if (src_var->storage == StorageClassUniform &&
  4755. !compiler.has_decoration(compiler.get<SPIRType>(src_var->basetype).self, DecorationBufferBlock))
  4756. {
  4757. break;
  4758. }
  4759. access_potential_resource(src_var->self);
  4760. }
  4761. break;
  4762. }
  4763. case OpImageRead:
  4764. case OpAtomicLoad:
  4765. {
  4766. if (length < 3)
  4767. return false;
  4768. uint32_t ptr = args[2];
  4769. auto *var = compiler.maybe_get_backing_variable(ptr);
  4770. // We're only concerned with buffer and image memory here.
  4771. if (!var)
  4772. break;
  4773. switch (var->storage)
  4774. {
  4775. default:
  4776. break;
  4777. case StorageClassUniform:
  4778. // Must have BufferBlock; we only care about SSBOs.
  4779. if (!compiler.has_decoration(compiler.get<SPIRType>(var->basetype).self, DecorationBufferBlock))
  4780. break;
  4781. // fallthrough
  4782. case StorageClassUniformConstant:
  4783. case StorageClassStorageBuffer:
  4784. access_potential_resource(var->self);
  4785. break;
  4786. }
  4787. break;
  4788. }
  4789. case OpAtomicExchange:
  4790. case OpAtomicCompareExchange:
  4791. case OpAtomicIIncrement:
  4792. case OpAtomicIDecrement:
  4793. case OpAtomicIAdd:
  4794. case OpAtomicISub:
  4795. case OpAtomicSMin:
  4796. case OpAtomicUMin:
  4797. case OpAtomicSMax:
  4798. case OpAtomicUMax:
  4799. case OpAtomicAnd:
  4800. case OpAtomicOr:
  4801. case OpAtomicXor:
  4802. {
  4803. if (length < 3)
  4804. return false;
  4805. uint32_t ptr = args[2];
  4806. auto *var = compiler.maybe_get_backing_variable(ptr);
  4807. if (var && (var->storage == StorageClassUniform || var->storage == StorageClassUniformConstant ||
  4808. var->storage == StorageClassStorageBuffer))
  4809. {
  4810. access_potential_resource(var->self);
  4811. }
  4812. break;
  4813. }
  4814. default:
  4815. break;
  4816. }
  4817. return true;
  4818. }
  4819. void Compiler::analyze_interlocked_resource_usage()
  4820. {
  4821. if (get_execution_model() == ExecutionModelFragment &&
  4822. (get_entry_point().flags.get(ExecutionModePixelInterlockOrderedEXT) ||
  4823. get_entry_point().flags.get(ExecutionModePixelInterlockUnorderedEXT) ||
  4824. get_entry_point().flags.get(ExecutionModeSampleInterlockOrderedEXT) ||
  4825. get_entry_point().flags.get(ExecutionModeSampleInterlockUnorderedEXT)))
  4826. {
  4827. InterlockedResourceAccessPrepassHandler prepass_handler(*this, ir.default_entry_point);
  4828. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), prepass_handler);
  4829. InterlockedResourceAccessHandler handler(*this, ir.default_entry_point);
  4830. handler.interlock_function_id = prepass_handler.interlock_function_id;
  4831. handler.split_function_case = prepass_handler.split_function_case;
  4832. handler.control_flow_interlock = prepass_handler.control_flow_interlock;
  4833. handler.use_critical_section = !handler.split_function_case && !handler.control_flow_interlock;
  4834. traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
  4835. // For GLSL. If we hit any of these cases, we have to fall back to conservative approach.
  4836. interlocked_is_complex =
  4837. !handler.use_critical_section || handler.interlock_function_id != ir.default_entry_point;
  4838. }
  4839. }
  4840. // Helper function
  4841. bool Compiler::check_internal_recursion(const SPIRType &type, std::unordered_set<uint32_t> &checked_ids)
  4842. {
  4843. if (type.basetype != SPIRType::Struct)
  4844. return false;
  4845. if (checked_ids.count(type.self))
  4846. return true;
  4847. // Recurse into struct members
  4848. bool is_recursive = false;
  4849. checked_ids.insert(type.self);
  4850. uint32_t mbr_cnt = uint32_t(type.member_types.size());
  4851. for (uint32_t mbr_idx = 0; !is_recursive && mbr_idx < mbr_cnt; mbr_idx++)
  4852. {
  4853. uint32_t mbr_type_id = type.member_types[mbr_idx];
  4854. auto &mbr_type = get<SPIRType>(mbr_type_id);
  4855. is_recursive |= check_internal_recursion(mbr_type, checked_ids);
  4856. }
  4857. checked_ids.erase(type.self);
  4858. return is_recursive;
  4859. }
  4860. // Return whether the struct type contains a structural recursion nested somewhere within its content.
  4861. bool Compiler::type_contains_recursion(const SPIRType &type)
  4862. {
  4863. std::unordered_set<uint32_t> checked_ids;
  4864. return check_internal_recursion(type, checked_ids);
  4865. }
  4866. bool Compiler::type_is_array_of_pointers(const SPIRType &type) const
  4867. {
  4868. if (!is_array(type))
  4869. return false;
  4870. // BDA types must have parent type hierarchy.
  4871. if (!type.parent_type)
  4872. return false;
  4873. // Punch through all array layers.
  4874. auto *parent = &get<SPIRType>(type.parent_type);
  4875. while (is_array(*parent))
  4876. parent = &get<SPIRType>(parent->parent_type);
  4877. return is_pointer(*parent);
  4878. }
  4879. bool Compiler::flush_phi_required(BlockID from, BlockID to) const
  4880. {
  4881. auto &child = get<SPIRBlock>(to);
  4882. for (auto &phi : child.phi_variables)
  4883. if (phi.parent == from)
  4884. return true;
  4885. return false;
  4886. }
  4887. void Compiler::add_loop_level()
  4888. {
  4889. current_loop_level++;
  4890. }