spirv_cross.cpp 142 KB

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