spirv_cross.cpp 158 KB

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