SpvBuilder.cpp 143 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089
  1. //
  2. // Copyright (C) 2014-2015 LunarG, Inc.
  3. // Copyright (C) 2015-2018 Google, Inc.
  4. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
  5. //
  6. // All rights reserved.
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions
  10. // are met:
  11. //
  12. // Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. //
  15. // Redistributions in binary form must reproduce the above
  16. // copyright notice, this list of conditions and the following
  17. // disclaimer in the documentation and/or other materials provided
  18. // with the distribution.
  19. //
  20. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  21. // contributors may be used to endorse or promote products derived
  22. // from this software without specific prior written permission.
  23. //
  24. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  27. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  30. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  33. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  34. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  35. // POSSIBILITY OF SUCH DAMAGE.
  36. //
  37. // Helper for making SPIR-V IR. Generally, this is documented in the header
  38. // SpvBuilder.h.
  39. //
  40. #include <cassert>
  41. #include <cstdlib>
  42. #include <unordered_set>
  43. #include <algorithm>
  44. #include "SpvBuilder.h"
  45. #include "hex_float.h"
  46. #ifndef _WIN32
  47. #include <cstdio>
  48. #endif
  49. namespace spv {
  50. Builder::Builder(unsigned int spvVersion, unsigned int magicNumber, SpvBuildLogger* buildLogger) :
  51. spvVersion(spvVersion),
  52. sourceLang(SourceLanguageUnknown),
  53. sourceVersion(0),
  54. sourceFileStringId(NoResult),
  55. currentLine(0),
  56. currentFile(nullptr),
  57. currentFileId(NoResult),
  58. lastDebugScopeId(NoResult),
  59. emitOpLines(false),
  60. emitNonSemanticShaderDebugInfo(false),
  61. addressModel(AddressingModelLogical),
  62. memoryModel(MemoryModelGLSL450),
  63. builderNumber(magicNumber),
  64. buildPoint(nullptr),
  65. uniqueId(0),
  66. entryPointFunction(nullptr),
  67. generatingOpCodeForSpecConst(false),
  68. logger(buildLogger)
  69. {
  70. clearAccessChain();
  71. }
  72. Builder::~Builder()
  73. {
  74. }
  75. Id Builder::import(const char* name)
  76. {
  77. Instruction* import = new Instruction(getUniqueId(), NoType, OpExtInstImport);
  78. import->addStringOperand(name);
  79. module.mapInstruction(import);
  80. imports.push_back(std::unique_ptr<Instruction>(import));
  81. return import->getResultId();
  82. }
  83. // Emit instruction for non-filename-based #line directives (ie. no filename
  84. // seen yet): emit an OpLine if we've been asked to emit OpLines and the line
  85. // number has changed since the last time, and is a valid line number.
  86. void Builder::setLine(int lineNum)
  87. {
  88. if (lineNum != 0 && lineNum != currentLine) {
  89. currentLine = lineNum;
  90. if (emitOpLines) {
  91. if (emitNonSemanticShaderDebugInfo)
  92. addDebugScopeAndLine(currentFileId, currentLine, 0);
  93. else
  94. addLine(sourceFileStringId, currentLine, 0);
  95. }
  96. }
  97. }
  98. // If no filename, do non-filename-based #line emit. Else do filename-based emit.
  99. // Emit OpLine if we've been asked to emit OpLines and the line number or filename
  100. // has changed since the last time, and line number is valid.
  101. void Builder::setLine(int lineNum, const char* filename)
  102. {
  103. if (filename == nullptr) {
  104. setLine(lineNum);
  105. return;
  106. }
  107. if ((lineNum != 0 && lineNum != currentLine) || currentFile == nullptr ||
  108. strncmp(filename, currentFile, strlen(currentFile) + 1) != 0) {
  109. currentLine = lineNum;
  110. currentFile = filename;
  111. if (emitOpLines) {
  112. spv::Id strId = getStringId(filename);
  113. if (emitNonSemanticShaderDebugInfo)
  114. addDebugScopeAndLine(strId, currentLine, 0);
  115. else
  116. addLine(strId, currentLine, 0);
  117. }
  118. }
  119. }
  120. void Builder::addLine(Id fileName, int lineNum, int column)
  121. {
  122. Instruction* line = new Instruction(OpLine);
  123. line->addIdOperand(fileName);
  124. line->addImmediateOperand(lineNum);
  125. line->addImmediateOperand(column);
  126. buildPoint->addInstruction(std::unique_ptr<Instruction>(line));
  127. }
  128. void Builder::addDebugScopeAndLine(Id fileName, int lineNum, int column)
  129. {
  130. assert(!currentDebugScopeId.empty());
  131. if (currentDebugScopeId.top() != lastDebugScopeId) {
  132. spv::Id resultId = getUniqueId();
  133. Instruction* scopeInst = new Instruction(resultId, makeVoidType(), OpExtInst);
  134. scopeInst->addIdOperand(nonSemanticShaderDebugInfo);
  135. scopeInst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugScope);
  136. scopeInst->addIdOperand(currentDebugScopeId.top());
  137. buildPoint->addInstruction(std::unique_ptr<Instruction>(scopeInst));
  138. lastDebugScopeId = currentDebugScopeId.top();
  139. }
  140. spv::Id resultId = getUniqueId();
  141. Instruction* lineInst = new Instruction(resultId, makeVoidType(), OpExtInst);
  142. lineInst->addIdOperand(nonSemanticShaderDebugInfo);
  143. lineInst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugLine);
  144. lineInst->addIdOperand(makeDebugSource(fileName));
  145. lineInst->addIdOperand(makeUintConstant(lineNum));
  146. lineInst->addIdOperand(makeUintConstant(lineNum));
  147. lineInst->addIdOperand(makeUintConstant(column));
  148. lineInst->addIdOperand(makeUintConstant(column));
  149. buildPoint->addInstruction(std::unique_ptr<Instruction>(lineInst));
  150. }
  151. // For creating new groupedTypes (will return old type if the requested one was already made).
  152. Id Builder::makeVoidType()
  153. {
  154. Instruction* type;
  155. if (groupedTypes[OpTypeVoid].size() == 0) {
  156. Id typeId = getUniqueId();
  157. type = new Instruction(typeId, NoType, OpTypeVoid);
  158. groupedTypes[OpTypeVoid].push_back(type);
  159. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  160. module.mapInstruction(type);
  161. // Core OpTypeVoid used for debug void type
  162. if (emitNonSemanticShaderDebugInfo)
  163. debugId[typeId] = typeId;
  164. } else
  165. type = groupedTypes[OpTypeVoid].back();
  166. return type->getResultId();
  167. }
  168. Id Builder::makeBoolType(bool const compilerGenerated)
  169. {
  170. Instruction* type;
  171. if (groupedTypes[OpTypeBool].size() == 0) {
  172. type = new Instruction(getUniqueId(), NoType, OpTypeBool);
  173. groupedTypes[OpTypeBool].push_back(type);
  174. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  175. module.mapInstruction(type);
  176. } else
  177. type = groupedTypes[OpTypeBool].back();
  178. if (emitNonSemanticShaderDebugInfo && !compilerGenerated)
  179. {
  180. auto const debugResultId = makeBoolDebugType(32);
  181. debugId[type->getResultId()] = debugResultId;
  182. }
  183. return type->getResultId();
  184. }
  185. Id Builder::makeSamplerType()
  186. {
  187. Instruction* type;
  188. if (groupedTypes[OpTypeSampler].size() == 0) {
  189. type = new Instruction(getUniqueId(), NoType, OpTypeSampler);
  190. groupedTypes[OpTypeSampler].push_back(type);
  191. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  192. module.mapInstruction(type);
  193. } else
  194. type = groupedTypes[OpTypeSampler].back();
  195. if (emitNonSemanticShaderDebugInfo)
  196. {
  197. auto const debugResultId = makeCompositeDebugType({}, "type.sampler", NonSemanticShaderDebugInfo100Structure, true);
  198. debugId[type->getResultId()] = debugResultId;
  199. }
  200. return type->getResultId();
  201. }
  202. Id Builder::makePointer(StorageClass storageClass, Id pointee)
  203. {
  204. // try to find it
  205. Instruction* type;
  206. for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
  207. type = groupedTypes[OpTypePointer][t];
  208. if (type->getImmediateOperand(0) == (unsigned)storageClass &&
  209. type->getIdOperand(1) == pointee)
  210. return type->getResultId();
  211. }
  212. // not found, make it
  213. type = new Instruction(getUniqueId(), NoType, OpTypePointer);
  214. type->addImmediateOperand(storageClass);
  215. type->addIdOperand(pointee);
  216. groupedTypes[OpTypePointer].push_back(type);
  217. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  218. module.mapInstruction(type);
  219. return type->getResultId();
  220. }
  221. Id Builder::makeForwardPointer(StorageClass storageClass)
  222. {
  223. // Caching/uniquifying doesn't work here, because we don't know the
  224. // pointee type and there can be multiple forward pointers of the same
  225. // storage type. Somebody higher up in the stack must keep track.
  226. Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeForwardPointer);
  227. type->addImmediateOperand(storageClass);
  228. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  229. module.mapInstruction(type);
  230. return type->getResultId();
  231. }
  232. Id Builder::makePointerFromForwardPointer(StorageClass storageClass, Id forwardPointerType, Id pointee)
  233. {
  234. // try to find it
  235. Instruction* type;
  236. for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
  237. type = groupedTypes[OpTypePointer][t];
  238. if (type->getImmediateOperand(0) == (unsigned)storageClass &&
  239. type->getIdOperand(1) == pointee)
  240. return type->getResultId();
  241. }
  242. type = new Instruction(forwardPointerType, NoType, OpTypePointer);
  243. type->addImmediateOperand(storageClass);
  244. type->addIdOperand(pointee);
  245. groupedTypes[OpTypePointer].push_back(type);
  246. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  247. module.mapInstruction(type);
  248. return type->getResultId();
  249. }
  250. Id Builder::makeIntegerType(int width, bool hasSign)
  251. {
  252. // try to find it
  253. Instruction* type;
  254. for (int t = 0; t < (int)groupedTypes[OpTypeInt].size(); ++t) {
  255. type = groupedTypes[OpTypeInt][t];
  256. if (type->getImmediateOperand(0) == (unsigned)width &&
  257. type->getImmediateOperand(1) == (hasSign ? 1u : 0u))
  258. return type->getResultId();
  259. }
  260. // not found, make it
  261. type = new Instruction(getUniqueId(), NoType, OpTypeInt);
  262. type->addImmediateOperand(width);
  263. type->addImmediateOperand(hasSign ? 1 : 0);
  264. groupedTypes[OpTypeInt].push_back(type);
  265. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  266. module.mapInstruction(type);
  267. // deal with capabilities
  268. switch (width) {
  269. case 8:
  270. case 16:
  271. // these are currently handled by storage-type declarations and post processing
  272. break;
  273. case 64:
  274. addCapability(CapabilityInt64);
  275. break;
  276. default:
  277. break;
  278. }
  279. if (emitNonSemanticShaderDebugInfo)
  280. {
  281. auto const debugResultId = makeIntegerDebugType(width, hasSign);
  282. debugId[type->getResultId()] = debugResultId;
  283. }
  284. return type->getResultId();
  285. }
  286. Id Builder::makeFloatType(int width)
  287. {
  288. // try to find it
  289. Instruction* type;
  290. for (int t = 0; t < (int)groupedTypes[OpTypeFloat].size(); ++t) {
  291. type = groupedTypes[OpTypeFloat][t];
  292. if (type->getImmediateOperand(0) == (unsigned)width)
  293. return type->getResultId();
  294. }
  295. // not found, make it
  296. type = new Instruction(getUniqueId(), NoType, OpTypeFloat);
  297. type->addImmediateOperand(width);
  298. groupedTypes[OpTypeFloat].push_back(type);
  299. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  300. module.mapInstruction(type);
  301. // deal with capabilities
  302. switch (width) {
  303. case 16:
  304. // currently handled by storage-type declarations and post processing
  305. break;
  306. case 64:
  307. addCapability(CapabilityFloat64);
  308. break;
  309. default:
  310. break;
  311. }
  312. if (emitNonSemanticShaderDebugInfo)
  313. {
  314. auto const debugResultId = makeFloatDebugType(width);
  315. debugId[type->getResultId()] = debugResultId;
  316. }
  317. return type->getResultId();
  318. }
  319. // Make a struct without checking for duplication.
  320. // See makeStructResultType() for non-decorated structs
  321. // needed as the result of some instructions, which does
  322. // check for duplicates.
  323. Id Builder::makeStructType(const std::vector<Id>& members, const char* name, bool const compilerGenerated)
  324. {
  325. // Don't look for previous one, because in the general case,
  326. // structs can be duplicated except for decorations.
  327. // not found, make it
  328. Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeStruct);
  329. for (int op = 0; op < (int)members.size(); ++op)
  330. type->addIdOperand(members[op]);
  331. groupedTypes[OpTypeStruct].push_back(type);
  332. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  333. module.mapInstruction(type);
  334. addName(type->getResultId(), name);
  335. if (emitNonSemanticShaderDebugInfo && !compilerGenerated)
  336. {
  337. auto const debugResultId = makeCompositeDebugType(members, name, NonSemanticShaderDebugInfo100Structure);
  338. debugId[type->getResultId()] = debugResultId;
  339. }
  340. return type->getResultId();
  341. }
  342. // Make a struct for the simple results of several instructions,
  343. // checking for duplication.
  344. Id Builder::makeStructResultType(Id type0, Id type1)
  345. {
  346. // try to find it
  347. Instruction* type;
  348. for (int t = 0; t < (int)groupedTypes[OpTypeStruct].size(); ++t) {
  349. type = groupedTypes[OpTypeStruct][t];
  350. if (type->getNumOperands() != 2)
  351. continue;
  352. if (type->getIdOperand(0) != type0 ||
  353. type->getIdOperand(1) != type1)
  354. continue;
  355. return type->getResultId();
  356. }
  357. // not found, make it
  358. std::vector<spv::Id> members;
  359. members.push_back(type0);
  360. members.push_back(type1);
  361. return makeStructType(members, "ResType");
  362. }
  363. Id Builder::makeVectorType(Id component, int size)
  364. {
  365. // try to find it
  366. Instruction* type;
  367. for (int t = 0; t < (int)groupedTypes[OpTypeVector].size(); ++t) {
  368. type = groupedTypes[OpTypeVector][t];
  369. if (type->getIdOperand(0) == component &&
  370. type->getImmediateOperand(1) == (unsigned)size)
  371. return type->getResultId();
  372. }
  373. // not found, make it
  374. type = new Instruction(getUniqueId(), NoType, OpTypeVector);
  375. type->addIdOperand(component);
  376. type->addImmediateOperand(size);
  377. groupedTypes[OpTypeVector].push_back(type);
  378. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  379. module.mapInstruction(type);
  380. if (emitNonSemanticShaderDebugInfo)
  381. {
  382. auto const debugResultId = makeVectorDebugType(component, size);
  383. debugId[type->getResultId()] = debugResultId;
  384. }
  385. return type->getResultId();
  386. }
  387. Id Builder::makeMatrixType(Id component, int cols, int rows)
  388. {
  389. assert(cols <= maxMatrixSize && rows <= maxMatrixSize);
  390. Id column = makeVectorType(component, rows);
  391. // try to find it
  392. Instruction* type;
  393. for (int t = 0; t < (int)groupedTypes[OpTypeMatrix].size(); ++t) {
  394. type = groupedTypes[OpTypeMatrix][t];
  395. if (type->getIdOperand(0) == column &&
  396. type->getImmediateOperand(1) == (unsigned)cols)
  397. return type->getResultId();
  398. }
  399. // not found, make it
  400. type = new Instruction(getUniqueId(), NoType, OpTypeMatrix);
  401. type->addIdOperand(column);
  402. type->addImmediateOperand(cols);
  403. groupedTypes[OpTypeMatrix].push_back(type);
  404. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  405. module.mapInstruction(type);
  406. if (emitNonSemanticShaderDebugInfo)
  407. {
  408. auto const debugResultId = makeMatrixDebugType(column, cols);
  409. debugId[type->getResultId()] = debugResultId;
  410. }
  411. return type->getResultId();
  412. }
  413. Id Builder::makeCooperativeMatrixTypeKHR(Id component, Id scope, Id rows, Id cols, Id use)
  414. {
  415. // try to find it
  416. Instruction* type;
  417. for (int t = 0; t < (int)groupedTypes[OpTypeCooperativeMatrixKHR].size(); ++t) {
  418. type = groupedTypes[OpTypeCooperativeMatrixKHR][t];
  419. if (type->getIdOperand(0) == component &&
  420. type->getIdOperand(1) == scope &&
  421. type->getIdOperand(2) == rows &&
  422. type->getIdOperand(3) == cols &&
  423. type->getIdOperand(4) == use)
  424. return type->getResultId();
  425. }
  426. // not found, make it
  427. type = new Instruction(getUniqueId(), NoType, OpTypeCooperativeMatrixKHR);
  428. type->addIdOperand(component);
  429. type->addIdOperand(scope);
  430. type->addIdOperand(rows);
  431. type->addIdOperand(cols);
  432. type->addIdOperand(use);
  433. groupedTypes[OpTypeCooperativeMatrixKHR].push_back(type);
  434. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  435. module.mapInstruction(type);
  436. return type->getResultId();
  437. }
  438. Id Builder::makeCooperativeMatrixTypeNV(Id component, Id scope, Id rows, Id cols)
  439. {
  440. // try to find it
  441. Instruction* type;
  442. for (int t = 0; t < (int)groupedTypes[OpTypeCooperativeMatrixNV].size(); ++t) {
  443. type = groupedTypes[OpTypeCooperativeMatrixNV][t];
  444. if (type->getIdOperand(0) == component && type->getIdOperand(1) == scope && type->getIdOperand(2) == rows &&
  445. type->getIdOperand(3) == cols)
  446. return type->getResultId();
  447. }
  448. // not found, make it
  449. type = new Instruction(getUniqueId(), NoType, OpTypeCooperativeMatrixNV);
  450. type->addIdOperand(component);
  451. type->addIdOperand(scope);
  452. type->addIdOperand(rows);
  453. type->addIdOperand(cols);
  454. groupedTypes[OpTypeCooperativeMatrixNV].push_back(type);
  455. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  456. module.mapInstruction(type);
  457. return type->getResultId();
  458. }
  459. Id Builder::makeCooperativeMatrixTypeWithSameShape(Id component, Id otherType)
  460. {
  461. Instruction* instr = module.getInstruction(otherType);
  462. if (instr->getOpCode() == OpTypeCooperativeMatrixNV) {
  463. return makeCooperativeMatrixTypeNV(component, instr->getIdOperand(1), instr->getIdOperand(2), instr->getIdOperand(3));
  464. } else {
  465. assert(instr->getOpCode() == OpTypeCooperativeMatrixKHR);
  466. return makeCooperativeMatrixTypeKHR(component, instr->getIdOperand(1), instr->getIdOperand(2), instr->getIdOperand(3), instr->getIdOperand(4));
  467. }
  468. }
  469. Id Builder::makeGenericType(spv::Op opcode, std::vector<spv::IdImmediate>& operands)
  470. {
  471. // try to find it
  472. Instruction* type;
  473. for (int t = 0; t < (int)groupedTypes[opcode].size(); ++t) {
  474. type = groupedTypes[opcode][t];
  475. if (static_cast<size_t>(type->getNumOperands()) != operands.size())
  476. continue; // Number mismatch, find next
  477. bool match = true;
  478. for (int op = 0; match && op < (int)operands.size(); ++op) {
  479. match = (operands[op].isId ? type->getIdOperand(op) : type->getImmediateOperand(op)) == operands[op].word;
  480. }
  481. if (match)
  482. return type->getResultId();
  483. }
  484. // not found, make it
  485. type = new Instruction(getUniqueId(), NoType, opcode);
  486. for (size_t op = 0; op < operands.size(); ++op) {
  487. if (operands[op].isId)
  488. type->addIdOperand(operands[op].word);
  489. else
  490. type->addImmediateOperand(operands[op].word);
  491. }
  492. groupedTypes[opcode].push_back(type);
  493. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  494. module.mapInstruction(type);
  495. return type->getResultId();
  496. }
  497. // TODO: performance: track arrays per stride
  498. // If a stride is supplied (non-zero) make an array.
  499. // If no stride (0), reuse previous array types.
  500. // 'size' is an Id of a constant or specialization constant of the array size
  501. Id Builder::makeArrayType(Id element, Id sizeId, int stride)
  502. {
  503. Instruction* type;
  504. if (stride == 0) {
  505. // try to find existing type
  506. for (int t = 0; t < (int)groupedTypes[OpTypeArray].size(); ++t) {
  507. type = groupedTypes[OpTypeArray][t];
  508. if (type->getIdOperand(0) == element &&
  509. type->getIdOperand(1) == sizeId)
  510. return type->getResultId();
  511. }
  512. }
  513. // not found, make it
  514. type = new Instruction(getUniqueId(), NoType, OpTypeArray);
  515. type->addIdOperand(element);
  516. type->addIdOperand(sizeId);
  517. groupedTypes[OpTypeArray].push_back(type);
  518. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  519. module.mapInstruction(type);
  520. if (emitNonSemanticShaderDebugInfo)
  521. {
  522. auto const debugResultId = makeArrayDebugType(element, sizeId);
  523. debugId[type->getResultId()] = debugResultId;
  524. }
  525. return type->getResultId();
  526. }
  527. Id Builder::makeRuntimeArray(Id element)
  528. {
  529. Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeRuntimeArray);
  530. type->addIdOperand(element);
  531. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  532. module.mapInstruction(type);
  533. if (emitNonSemanticShaderDebugInfo)
  534. {
  535. auto const debugResultId = makeArrayDebugType(element, makeUintConstant(0));
  536. debugId[type->getResultId()] = debugResultId;
  537. }
  538. return type->getResultId();
  539. }
  540. Id Builder::makeFunctionType(Id returnType, const std::vector<Id>& paramTypes)
  541. {
  542. // try to find it
  543. Instruction* type;
  544. for (int t = 0; t < (int)groupedTypes[OpTypeFunction].size(); ++t) {
  545. type = groupedTypes[OpTypeFunction][t];
  546. if (type->getIdOperand(0) != returnType || (int)paramTypes.size() != type->getNumOperands() - 1)
  547. continue;
  548. bool mismatch = false;
  549. for (int p = 0; p < (int)paramTypes.size(); ++p) {
  550. if (paramTypes[p] != type->getIdOperand(p + 1)) {
  551. mismatch = true;
  552. break;
  553. }
  554. }
  555. if (! mismatch)
  556. {
  557. // If compiling HLSL, glslang will create a wrapper function around the entrypoint. Accordingly, a void(void)
  558. // function type is created for the wrapper function. However, nonsemantic shader debug information is disabled
  559. // while creating the HLSL wrapper. Consequently, if we encounter another void(void) function, we need to create
  560. // the associated debug function type if it hasn't been created yet.
  561. if(emitNonSemanticShaderDebugInfo && debugId[type->getResultId()] == 0) {
  562. assert(sourceLang == spv::SourceLanguageHLSL);
  563. assert(getTypeClass(returnType) == OpTypeVoid && paramTypes.size() == 0);
  564. Id debugTypeId = makeDebugFunctionType(returnType, {});
  565. debugId[type->getResultId()] = debugTypeId;
  566. }
  567. return type->getResultId();
  568. }
  569. }
  570. // not found, make it
  571. Id typeId = getUniqueId();
  572. type = new Instruction(typeId, NoType, OpTypeFunction);
  573. type->addIdOperand(returnType);
  574. for (int p = 0; p < (int)paramTypes.size(); ++p)
  575. type->addIdOperand(paramTypes[p]);
  576. groupedTypes[OpTypeFunction].push_back(type);
  577. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  578. module.mapInstruction(type);
  579. // make debug type and map it
  580. if (emitNonSemanticShaderDebugInfo) {
  581. Id debugTypeId = makeDebugFunctionType(returnType, paramTypes);
  582. debugId[typeId] = debugTypeId;
  583. }
  584. return type->getResultId();
  585. }
  586. Id Builder::makeDebugFunctionType(Id returnType, const std::vector<Id>& paramTypes)
  587. {
  588. assert(debugId[returnType] != 0);
  589. Id typeId = getUniqueId();
  590. auto type = new Instruction(typeId, makeVoidType(), OpExtInst);
  591. type->addIdOperand(nonSemanticShaderDebugInfo);
  592. type->addImmediateOperand(NonSemanticShaderDebugInfo100DebugTypeFunction);
  593. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100FlagIsPublic));
  594. type->addIdOperand(debugId[returnType]);
  595. for (auto const paramType : paramTypes) {
  596. if (isPointerType(paramType) || isArrayType(paramType)) {
  597. type->addIdOperand(debugId[getContainedTypeId(paramType)]);
  598. }
  599. else {
  600. type->addIdOperand(debugId[paramType]);
  601. }
  602. }
  603. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  604. module.mapInstruction(type);
  605. return typeId;
  606. }
  607. Id Builder::makeImageType(Id sampledType, Dim dim, bool depth, bool arrayed, bool ms, unsigned sampled,
  608. ImageFormat format)
  609. {
  610. assert(sampled == 1 || sampled == 2);
  611. // try to find it
  612. Instruction* type;
  613. for (int t = 0; t < (int)groupedTypes[OpTypeImage].size(); ++t) {
  614. type = groupedTypes[OpTypeImage][t];
  615. if (type->getIdOperand(0) == sampledType &&
  616. type->getImmediateOperand(1) == (unsigned int)dim &&
  617. type->getImmediateOperand(2) == ( depth ? 1u : 0u) &&
  618. type->getImmediateOperand(3) == (arrayed ? 1u : 0u) &&
  619. type->getImmediateOperand(4) == ( ms ? 1u : 0u) &&
  620. type->getImmediateOperand(5) == sampled &&
  621. type->getImmediateOperand(6) == (unsigned int)format)
  622. return type->getResultId();
  623. }
  624. // not found, make it
  625. type = new Instruction(getUniqueId(), NoType, OpTypeImage);
  626. type->addIdOperand(sampledType);
  627. type->addImmediateOperand( dim);
  628. type->addImmediateOperand( depth ? 1 : 0);
  629. type->addImmediateOperand(arrayed ? 1 : 0);
  630. type->addImmediateOperand( ms ? 1 : 0);
  631. type->addImmediateOperand(sampled);
  632. type->addImmediateOperand((unsigned int)format);
  633. groupedTypes[OpTypeImage].push_back(type);
  634. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  635. module.mapInstruction(type);
  636. // deal with capabilities
  637. switch (dim) {
  638. case DimBuffer:
  639. if (sampled == 1)
  640. addCapability(CapabilitySampledBuffer);
  641. else
  642. addCapability(CapabilityImageBuffer);
  643. break;
  644. case Dim1D:
  645. if (sampled == 1)
  646. addCapability(CapabilitySampled1D);
  647. else
  648. addCapability(CapabilityImage1D);
  649. break;
  650. case DimCube:
  651. if (arrayed) {
  652. if (sampled == 1)
  653. addCapability(CapabilitySampledCubeArray);
  654. else
  655. addCapability(CapabilityImageCubeArray);
  656. }
  657. break;
  658. case DimRect:
  659. if (sampled == 1)
  660. addCapability(CapabilitySampledRect);
  661. else
  662. addCapability(CapabilityImageRect);
  663. break;
  664. case DimSubpassData:
  665. addCapability(CapabilityInputAttachment);
  666. break;
  667. default:
  668. break;
  669. }
  670. if (ms) {
  671. if (sampled == 2) {
  672. // Images used with subpass data are not storage
  673. // images, so don't require the capability for them.
  674. if (dim != Dim::DimSubpassData)
  675. addCapability(CapabilityStorageImageMultisample);
  676. if (arrayed)
  677. addCapability(CapabilityImageMSArray);
  678. }
  679. }
  680. if (emitNonSemanticShaderDebugInfo)
  681. {
  682. auto TypeName = [&dim]() -> char const* {
  683. switch (dim) {
  684. case Dim1D: return "type.1d.image";
  685. case Dim2D: return "type.2d.image";
  686. case Dim3D: return "type.3d.image";
  687. case DimCube: return "type.cube.image";
  688. default: return "type.image";
  689. }
  690. };
  691. auto const debugResultId = makeCompositeDebugType({}, TypeName(), NonSemanticShaderDebugInfo100Class, true);
  692. debugId[type->getResultId()] = debugResultId;
  693. }
  694. return type->getResultId();
  695. }
  696. Id Builder::makeSampledImageType(Id imageType)
  697. {
  698. // try to find it
  699. Instruction* type;
  700. for (int t = 0; t < (int)groupedTypes[OpTypeSampledImage].size(); ++t) {
  701. type = groupedTypes[OpTypeSampledImage][t];
  702. if (type->getIdOperand(0) == imageType)
  703. return type->getResultId();
  704. }
  705. // not found, make it
  706. type = new Instruction(getUniqueId(), NoType, OpTypeSampledImage);
  707. type->addIdOperand(imageType);
  708. groupedTypes[OpTypeSampledImage].push_back(type);
  709. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  710. module.mapInstruction(type);
  711. if (emitNonSemanticShaderDebugInfo)
  712. {
  713. auto const debugResultId = makeCompositeDebugType({}, "type.sampled.image", NonSemanticShaderDebugInfo100Class, true);
  714. debugId[type->getResultId()] = debugResultId;
  715. }
  716. return type->getResultId();
  717. }
  718. Id Builder::makeDebugInfoNone()
  719. {
  720. if (debugInfoNone != 0)
  721. return debugInfoNone;
  722. Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  723. inst->addIdOperand(nonSemanticShaderDebugInfo);
  724. inst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugInfoNone);
  725. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
  726. module.mapInstruction(inst);
  727. debugInfoNone = inst->getResultId();
  728. return debugInfoNone;
  729. }
  730. Id Builder::makeBoolDebugType(int const size)
  731. {
  732. // try to find it
  733. Instruction* type;
  734. for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic].size(); ++t) {
  735. type = groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic][t];
  736. if (type->getIdOperand(0) == getStringId("bool") &&
  737. type->getIdOperand(1) == static_cast<unsigned int>(size) &&
  738. type->getIdOperand(2) == NonSemanticShaderDebugInfo100Boolean)
  739. return type->getResultId();
  740. }
  741. type = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  742. type->addIdOperand(nonSemanticShaderDebugInfo);
  743. type->addImmediateOperand(NonSemanticShaderDebugInfo100DebugTypeBasic);
  744. type->addIdOperand(getStringId("bool")); // name id
  745. type->addIdOperand(makeUintConstant(size)); // size id
  746. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100Boolean)); // encoding id
  747. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100None)); // flags id
  748. groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic].push_back(type);
  749. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  750. module.mapInstruction(type);
  751. return type->getResultId();
  752. }
  753. Id Builder::makeIntegerDebugType(int const width, bool const hasSign)
  754. {
  755. // try to find it
  756. Instruction* type;
  757. for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic].size(); ++t) {
  758. type = groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic][t];
  759. if (type->getIdOperand(0) == (hasSign ? getStringId("int") : getStringId("uint")) &&
  760. type->getIdOperand(1) == static_cast<unsigned int>(width) &&
  761. type->getIdOperand(2) == (hasSign ? NonSemanticShaderDebugInfo100Signed : NonSemanticShaderDebugInfo100Unsigned))
  762. return type->getResultId();
  763. }
  764. // not found, make it
  765. type = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  766. type->addIdOperand(nonSemanticShaderDebugInfo);
  767. type->addImmediateOperand(NonSemanticShaderDebugInfo100DebugTypeBasic);
  768. if(hasSign == true) {
  769. type->addIdOperand(getStringId("int")); // name id
  770. } else {
  771. type->addIdOperand(getStringId("uint")); // name id
  772. }
  773. type->addIdOperand(makeUintConstant(width)); // size id
  774. if(hasSign == true) {
  775. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100Signed)); // encoding id
  776. } else {
  777. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100Unsigned)); // encoding id
  778. }
  779. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100None)); // flags id
  780. groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic].push_back(type);
  781. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  782. module.mapInstruction(type);
  783. return type->getResultId();
  784. }
  785. Id Builder::makeFloatDebugType(int const width)
  786. {
  787. // try to find it
  788. Instruction* type;
  789. for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic].size(); ++t) {
  790. type = groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic][t];
  791. if (type->getIdOperand(0) == getStringId("float") &&
  792. type->getIdOperand(1) == static_cast<unsigned int>(width) &&
  793. type->getIdOperand(2) == NonSemanticShaderDebugInfo100Float)
  794. return type->getResultId();
  795. }
  796. // not found, make it
  797. type = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  798. type->addIdOperand(nonSemanticShaderDebugInfo);
  799. type->addImmediateOperand(NonSemanticShaderDebugInfo100DebugTypeBasic);
  800. type->addIdOperand(getStringId("float")); // name id
  801. type->addIdOperand(makeUintConstant(width)); // size id
  802. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100Float)); // encoding id
  803. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100None)); // flags id
  804. groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeBasic].push_back(type);
  805. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  806. module.mapInstruction(type);
  807. return type->getResultId();
  808. }
  809. Id Builder::makeSequentialDebugType(Id const baseType, Id const componentCount, NonSemanticShaderDebugInfo100Instructions const sequenceType)
  810. {
  811. assert(sequenceType == NonSemanticShaderDebugInfo100DebugTypeArray ||
  812. sequenceType == NonSemanticShaderDebugInfo100DebugTypeVector);
  813. // try to find it
  814. Instruction* type;
  815. for (int t = 0; t < (int)groupedDebugTypes[sequenceType].size(); ++t) {
  816. type = groupedDebugTypes[sequenceType][t];
  817. if (type->getIdOperand(0) == baseType &&
  818. type->getIdOperand(1) == makeUintConstant(componentCount))
  819. return type->getResultId();
  820. }
  821. // not found, make it
  822. type = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  823. type->addIdOperand(nonSemanticShaderDebugInfo);
  824. type->addImmediateOperand(sequenceType);
  825. type->addIdOperand(debugId[baseType]); // base type
  826. type->addIdOperand(componentCount); // component count
  827. groupedDebugTypes[sequenceType].push_back(type);
  828. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  829. module.mapInstruction(type);
  830. return type->getResultId();
  831. }
  832. Id Builder::makeArrayDebugType(Id const baseType, Id const componentCount)
  833. {
  834. return makeSequentialDebugType(baseType, componentCount, NonSemanticShaderDebugInfo100DebugTypeArray);
  835. }
  836. Id Builder::makeVectorDebugType(Id const baseType, int const componentCount)
  837. {
  838. return makeSequentialDebugType(baseType, makeUintConstant(componentCount), NonSemanticShaderDebugInfo100DebugTypeVector);
  839. }
  840. Id Builder::makeMatrixDebugType(Id const vectorType, int const vectorCount, bool columnMajor)
  841. {
  842. // try to find it
  843. Instruction* type;
  844. for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeMatrix].size(); ++t) {
  845. type = groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeMatrix][t];
  846. if (type->getIdOperand(0) == vectorType &&
  847. type->getIdOperand(1) == makeUintConstant(vectorCount))
  848. return type->getResultId();
  849. }
  850. // not found, make it
  851. type = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  852. type->addIdOperand(nonSemanticShaderDebugInfo);
  853. type->addImmediateOperand(NonSemanticShaderDebugInfo100DebugTypeMatrix);
  854. type->addIdOperand(debugId[vectorType]); // vector type id
  855. type->addIdOperand(makeUintConstant(vectorCount)); // component count id
  856. type->addIdOperand(makeBoolConstant(columnMajor)); // column-major id
  857. groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeMatrix].push_back(type);
  858. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  859. module.mapInstruction(type);
  860. return type->getResultId();
  861. }
  862. Id Builder::makeMemberDebugType(Id const memberType, DebugTypeLoc const& debugTypeLoc)
  863. {
  864. assert(debugId[memberType] != 0);
  865. Instruction* type = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  866. type->addIdOperand(nonSemanticShaderDebugInfo);
  867. type->addImmediateOperand(NonSemanticShaderDebugInfo100DebugTypeMember);
  868. type->addIdOperand(getStringId(debugTypeLoc.name)); // name id
  869. type->addIdOperand(debugId[memberType]); // type id
  870. type->addIdOperand(makeDebugSource(sourceFileStringId)); // source id TODO: verify this works across include directives
  871. type->addIdOperand(makeUintConstant(debugTypeLoc.line)); // line id TODO: currentLine is always zero
  872. type->addIdOperand(makeUintConstant(debugTypeLoc.column)); // TODO: column id
  873. type->addIdOperand(makeUintConstant(0)); // TODO: offset id
  874. type->addIdOperand(makeUintConstant(0)); // TODO: size id
  875. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100FlagIsPublic)); // flags id
  876. groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeMember].push_back(type);
  877. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  878. module.mapInstruction(type);
  879. return type->getResultId();
  880. }
  881. // Note: To represent a source language opaque type, this instruction must have no Members operands, Size operand must be
  882. // DebugInfoNone, and Name must start with @ to avoid clashes with user defined names.
  883. Id Builder::makeCompositeDebugType(std::vector<Id> const& memberTypes, char const*const name,
  884. NonSemanticShaderDebugInfo100DebugCompositeType const tag, bool const isOpaqueType)
  885. {
  886. // Create the debug member types.
  887. std::vector<Id> memberDebugTypes;
  888. for(auto const memberType : memberTypes) {
  889. assert(debugTypeLocs.find(memberType) != debugTypeLocs.end());
  890. memberDebugTypes.emplace_back(makeMemberDebugType(memberType, debugTypeLocs[memberType]));
  891. // TODO: Need to rethink this method of passing location information.
  892. // debugTypeLocs.erase(memberType);
  893. }
  894. // Create The structure debug type.
  895. Instruction* type = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  896. type->addIdOperand(nonSemanticShaderDebugInfo);
  897. type->addImmediateOperand(NonSemanticShaderDebugInfo100DebugTypeComposite);
  898. type->addIdOperand(getStringId(name)); // name id
  899. type->addIdOperand(makeUintConstant(tag)); // tag id
  900. type->addIdOperand(makeDebugSource(sourceFileStringId)); // source id TODO: verify this works across include directives
  901. type->addIdOperand(makeUintConstant(currentLine)); // line id TODO: currentLine always zero?
  902. type->addIdOperand(makeUintConstant(0)); // TODO: column id
  903. type->addIdOperand(makeDebugCompilationUnit()); // scope id
  904. if(isOpaqueType == true) {
  905. // Prepend '@' to opaque types.
  906. type->addIdOperand(getStringId('@' + std::string(name))); // linkage name id
  907. type->addIdOperand(makeDebugInfoNone()); // size id
  908. } else {
  909. type->addIdOperand(getStringId(name)); // linkage name id
  910. type->addIdOperand(makeUintConstant(0)); // TODO: size id
  911. }
  912. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100FlagIsPublic)); // flags id
  913. assert(isOpaqueType == false || (isOpaqueType == true && memberDebugTypes.empty()));
  914. for(auto const memberDebugType : memberDebugTypes) {
  915. type->addIdOperand(memberDebugType);
  916. }
  917. groupedDebugTypes[NonSemanticShaderDebugInfo100DebugTypeComposite].push_back(type);
  918. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  919. module.mapInstruction(type);
  920. return type->getResultId();
  921. }
  922. Id Builder::makeDebugSource(const Id fileName) {
  923. if (debugSourceId.find(fileName) != debugSourceId.end())
  924. return debugSourceId[fileName];
  925. spv::Id resultId = getUniqueId();
  926. Instruction* sourceInst = new Instruction(resultId, makeVoidType(), OpExtInst);
  927. sourceInst->addIdOperand(nonSemanticShaderDebugInfo);
  928. sourceInst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugSource);
  929. sourceInst->addIdOperand(fileName);
  930. if (emitNonSemanticShaderDebugSource) {
  931. spv::Id sourceId = 0;
  932. if (fileName == sourceFileStringId) {
  933. sourceId = getStringId(sourceText);
  934. } else {
  935. auto incItr = includeFiles.find(fileName);
  936. assert(incItr != includeFiles.end());
  937. sourceId = getStringId(*incItr->second);
  938. }
  939. sourceInst->addIdOperand(sourceId);
  940. }
  941. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(sourceInst));
  942. module.mapInstruction(sourceInst);
  943. debugSourceId[fileName] = resultId;
  944. return resultId;
  945. }
  946. Id Builder::makeDebugCompilationUnit() {
  947. if (nonSemanticShaderCompilationUnitId != 0)
  948. return nonSemanticShaderCompilationUnitId;
  949. spv::Id resultId = getUniqueId();
  950. Instruction* sourceInst = new Instruction(resultId, makeVoidType(), OpExtInst);
  951. sourceInst->addIdOperand(nonSemanticShaderDebugInfo);
  952. sourceInst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugCompilationUnit);
  953. sourceInst->addIdOperand(makeUintConstant(1)); // TODO(greg-lunarg): Get rid of magic number
  954. sourceInst->addIdOperand(makeUintConstant(4)); // TODO(greg-lunarg): Get rid of magic number
  955. sourceInst->addIdOperand(makeDebugSource(sourceFileStringId));
  956. sourceInst->addIdOperand(makeUintConstant(sourceLang));
  957. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(sourceInst));
  958. module.mapInstruction(sourceInst);
  959. nonSemanticShaderCompilationUnitId = resultId;
  960. // We can reasonably assume that makeDebugCompilationUnit will be called before any of
  961. // debug-scope stack. Function scopes and lexical scopes will occur afterward.
  962. assert(currentDebugScopeId.empty());
  963. currentDebugScopeId.push(nonSemanticShaderCompilationUnitId);
  964. return resultId;
  965. }
  966. Id Builder::createDebugGlobalVariable(Id const type, char const*const name, Id const variable)
  967. {
  968. assert(type != 0);
  969. Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  970. inst->addIdOperand(nonSemanticShaderDebugInfo);
  971. inst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugGlobalVariable);
  972. inst->addIdOperand(getStringId(name)); // name id
  973. inst->addIdOperand(type); // type id
  974. inst->addIdOperand(makeDebugSource(sourceFileStringId)); // source id
  975. inst->addIdOperand(makeUintConstant(currentLine)); // line id TODO: currentLine always zero?
  976. inst->addIdOperand(makeUintConstant(0)); // TODO: column id
  977. inst->addIdOperand(makeDebugCompilationUnit()); // scope id
  978. inst->addIdOperand(getStringId(name)); // linkage name id
  979. inst->addIdOperand(variable); // variable id
  980. inst->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100FlagIsDefinition)); // flags id
  981. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
  982. module.mapInstruction(inst);
  983. return inst->getResultId();
  984. }
  985. Id Builder::createDebugLocalVariable(Id type, char const*const name, size_t const argNumber)
  986. {
  987. assert(name != nullptr);
  988. assert(!currentDebugScopeId.empty());
  989. Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  990. inst->addIdOperand(nonSemanticShaderDebugInfo);
  991. inst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugLocalVariable);
  992. inst->addIdOperand(getStringId(name)); // name id
  993. inst->addIdOperand(type); // type id
  994. inst->addIdOperand(makeDebugSource(sourceFileStringId)); // source id
  995. inst->addIdOperand(makeUintConstant(currentLine)); // line id
  996. inst->addIdOperand(makeUintConstant(0)); // TODO: column id
  997. inst->addIdOperand(currentDebugScopeId.top()); // scope id
  998. inst->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100FlagIsLocal)); // flags id
  999. if(argNumber != 0) {
  1000. inst->addIdOperand(makeUintConstant(argNumber));
  1001. }
  1002. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
  1003. module.mapInstruction(inst);
  1004. return inst->getResultId();
  1005. }
  1006. Id Builder::makeDebugExpression()
  1007. {
  1008. if (debugExpression != 0)
  1009. return debugExpression;
  1010. Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  1011. inst->addIdOperand(nonSemanticShaderDebugInfo);
  1012. inst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugExpression);
  1013. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
  1014. module.mapInstruction(inst);
  1015. debugExpression = inst->getResultId();
  1016. return debugExpression;
  1017. }
  1018. Id Builder::makeDebugDeclare(Id const debugLocalVariable, Id const localVariable)
  1019. {
  1020. Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), OpExtInst);
  1021. inst->addIdOperand(nonSemanticShaderDebugInfo);
  1022. inst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugDeclare);
  1023. inst->addIdOperand(debugLocalVariable); // debug local variable id
  1024. inst->addIdOperand(localVariable); // local variable id
  1025. inst->addIdOperand(makeDebugExpression()); // expression id
  1026. buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
  1027. return inst->getResultId();
  1028. }
  1029. Id Builder::makeAccelerationStructureType()
  1030. {
  1031. Instruction *type;
  1032. if (groupedTypes[OpTypeAccelerationStructureKHR].size() == 0) {
  1033. type = new Instruction(getUniqueId(), NoType, OpTypeAccelerationStructureKHR);
  1034. groupedTypes[OpTypeAccelerationStructureKHR].push_back(type);
  1035. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  1036. module.mapInstruction(type);
  1037. } else {
  1038. type = groupedTypes[OpTypeAccelerationStructureKHR].back();
  1039. }
  1040. return type->getResultId();
  1041. }
  1042. Id Builder::makeRayQueryType()
  1043. {
  1044. Instruction *type;
  1045. if (groupedTypes[OpTypeRayQueryKHR].size() == 0) {
  1046. type = new Instruction(getUniqueId(), NoType, OpTypeRayQueryKHR);
  1047. groupedTypes[OpTypeRayQueryKHR].push_back(type);
  1048. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  1049. module.mapInstruction(type);
  1050. } else {
  1051. type = groupedTypes[OpTypeRayQueryKHR].back();
  1052. }
  1053. return type->getResultId();
  1054. }
  1055. Id Builder::makeHitObjectNVType()
  1056. {
  1057. Instruction *type;
  1058. if (groupedTypes[OpTypeHitObjectNV].size() == 0) {
  1059. type = new Instruction(getUniqueId(), NoType, OpTypeHitObjectNV);
  1060. groupedTypes[OpTypeHitObjectNV].push_back(type);
  1061. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  1062. module.mapInstruction(type);
  1063. } else {
  1064. type = groupedTypes[OpTypeHitObjectNV].back();
  1065. }
  1066. return type->getResultId();
  1067. }
  1068. Id Builder::getDerefTypeId(Id resultId) const
  1069. {
  1070. Id typeId = getTypeId(resultId);
  1071. assert(isPointerType(typeId));
  1072. return module.getInstruction(typeId)->getIdOperand(1);
  1073. }
  1074. Op Builder::getMostBasicTypeClass(Id typeId) const
  1075. {
  1076. Instruction* instr = module.getInstruction(typeId);
  1077. Op typeClass = instr->getOpCode();
  1078. switch (typeClass)
  1079. {
  1080. case OpTypeVector:
  1081. case OpTypeMatrix:
  1082. case OpTypeArray:
  1083. case OpTypeRuntimeArray:
  1084. return getMostBasicTypeClass(instr->getIdOperand(0));
  1085. case OpTypePointer:
  1086. return getMostBasicTypeClass(instr->getIdOperand(1));
  1087. default:
  1088. return typeClass;
  1089. }
  1090. }
  1091. int Builder::getNumTypeConstituents(Id typeId) const
  1092. {
  1093. Instruction* instr = module.getInstruction(typeId);
  1094. switch (instr->getOpCode())
  1095. {
  1096. case OpTypeBool:
  1097. case OpTypeInt:
  1098. case OpTypeFloat:
  1099. case OpTypePointer:
  1100. return 1;
  1101. case OpTypeVector:
  1102. case OpTypeMatrix:
  1103. return instr->getImmediateOperand(1);
  1104. case OpTypeArray:
  1105. {
  1106. Id lengthId = instr->getIdOperand(1);
  1107. return module.getInstruction(lengthId)->getImmediateOperand(0);
  1108. }
  1109. case OpTypeStruct:
  1110. return instr->getNumOperands();
  1111. case OpTypeCooperativeMatrixKHR:
  1112. case OpTypeCooperativeMatrixNV:
  1113. // has only one constituent when used with OpCompositeConstruct.
  1114. return 1;
  1115. default:
  1116. assert(0);
  1117. return 1;
  1118. }
  1119. }
  1120. // Return the lowest-level type of scalar that an homogeneous composite is made out of.
  1121. // Typically, this is just to find out if something is made out of ints or floats.
  1122. // However, it includes returning a structure, if say, it is an array of structure.
  1123. Id Builder::getScalarTypeId(Id typeId) const
  1124. {
  1125. Instruction* instr = module.getInstruction(typeId);
  1126. Op typeClass = instr->getOpCode();
  1127. switch (typeClass)
  1128. {
  1129. case OpTypeVoid:
  1130. case OpTypeBool:
  1131. case OpTypeInt:
  1132. case OpTypeFloat:
  1133. case OpTypeStruct:
  1134. return instr->getResultId();
  1135. case OpTypeVector:
  1136. case OpTypeMatrix:
  1137. case OpTypeArray:
  1138. case OpTypeRuntimeArray:
  1139. case OpTypePointer:
  1140. return getScalarTypeId(getContainedTypeId(typeId));
  1141. default:
  1142. assert(0);
  1143. return NoResult;
  1144. }
  1145. }
  1146. // Return the type of 'member' of a composite.
  1147. Id Builder::getContainedTypeId(Id typeId, int member) const
  1148. {
  1149. Instruction* instr = module.getInstruction(typeId);
  1150. Op typeClass = instr->getOpCode();
  1151. switch (typeClass)
  1152. {
  1153. case OpTypeVector:
  1154. case OpTypeMatrix:
  1155. case OpTypeArray:
  1156. case OpTypeRuntimeArray:
  1157. case OpTypeCooperativeMatrixKHR:
  1158. case OpTypeCooperativeMatrixNV:
  1159. return instr->getIdOperand(0);
  1160. case OpTypePointer:
  1161. return instr->getIdOperand(1);
  1162. case OpTypeStruct:
  1163. return instr->getIdOperand(member);
  1164. default:
  1165. assert(0);
  1166. return NoResult;
  1167. }
  1168. }
  1169. // Figure out the final resulting type of the access chain.
  1170. Id Builder::getResultingAccessChainType() const
  1171. {
  1172. assert(accessChain.base != NoResult);
  1173. Id typeId = getTypeId(accessChain.base);
  1174. assert(isPointerType(typeId));
  1175. typeId = getContainedTypeId(typeId);
  1176. for (int i = 0; i < (int)accessChain.indexChain.size(); ++i) {
  1177. if (isStructType(typeId)) {
  1178. assert(isConstantScalar(accessChain.indexChain[i]));
  1179. typeId = getContainedTypeId(typeId, getConstantScalar(accessChain.indexChain[i]));
  1180. } else
  1181. typeId = getContainedTypeId(typeId, accessChain.indexChain[i]);
  1182. }
  1183. return typeId;
  1184. }
  1185. // Return the immediately contained type of a given composite type.
  1186. Id Builder::getContainedTypeId(Id typeId) const
  1187. {
  1188. return getContainedTypeId(typeId, 0);
  1189. }
  1190. // Returns true if 'typeId' is or contains a scalar type declared with 'typeOp'
  1191. // of width 'width'. The 'width' is only consumed for int and float types.
  1192. // Returns false otherwise.
  1193. bool Builder::containsType(Id typeId, spv::Op typeOp, unsigned int width) const
  1194. {
  1195. const Instruction& instr = *module.getInstruction(typeId);
  1196. Op typeClass = instr.getOpCode();
  1197. switch (typeClass)
  1198. {
  1199. case OpTypeInt:
  1200. case OpTypeFloat:
  1201. return typeClass == typeOp && instr.getImmediateOperand(0) == width;
  1202. case OpTypeStruct:
  1203. for (int m = 0; m < instr.getNumOperands(); ++m) {
  1204. if (containsType(instr.getIdOperand(m), typeOp, width))
  1205. return true;
  1206. }
  1207. return false;
  1208. case OpTypePointer:
  1209. return false;
  1210. case OpTypeVector:
  1211. case OpTypeMatrix:
  1212. case OpTypeArray:
  1213. case OpTypeRuntimeArray:
  1214. return containsType(getContainedTypeId(typeId), typeOp, width);
  1215. default:
  1216. return typeClass == typeOp;
  1217. }
  1218. }
  1219. // return true if the type is a pointer to PhysicalStorageBufferEXT or an
  1220. // contains such a pointer. These require restrict/aliased decorations.
  1221. bool Builder::containsPhysicalStorageBufferOrArray(Id typeId) const
  1222. {
  1223. const Instruction& instr = *module.getInstruction(typeId);
  1224. Op typeClass = instr.getOpCode();
  1225. switch (typeClass)
  1226. {
  1227. case OpTypePointer:
  1228. return getTypeStorageClass(typeId) == StorageClassPhysicalStorageBufferEXT;
  1229. case OpTypeArray:
  1230. return containsPhysicalStorageBufferOrArray(getContainedTypeId(typeId));
  1231. case OpTypeStruct:
  1232. for (int m = 0; m < instr.getNumOperands(); ++m) {
  1233. if (containsPhysicalStorageBufferOrArray(instr.getIdOperand(m)))
  1234. return true;
  1235. }
  1236. return false;
  1237. default:
  1238. return false;
  1239. }
  1240. }
  1241. // See if a scalar constant of this type has already been created, so it
  1242. // can be reused rather than duplicated. (Required by the specification).
  1243. Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value)
  1244. {
  1245. Instruction* constant;
  1246. for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
  1247. constant = groupedConstants[typeClass][i];
  1248. if (constant->getOpCode() == opcode &&
  1249. constant->getTypeId() == typeId &&
  1250. constant->getImmediateOperand(0) == value)
  1251. return constant->getResultId();
  1252. }
  1253. return 0;
  1254. }
  1255. // Version of findScalarConstant (see above) for scalars that take two operands (e.g. a 'double' or 'int64').
  1256. Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2)
  1257. {
  1258. Instruction* constant;
  1259. for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
  1260. constant = groupedConstants[typeClass][i];
  1261. if (constant->getOpCode() == opcode &&
  1262. constant->getTypeId() == typeId &&
  1263. constant->getImmediateOperand(0) == v1 &&
  1264. constant->getImmediateOperand(1) == v2)
  1265. return constant->getResultId();
  1266. }
  1267. return 0;
  1268. }
  1269. // Return true if consuming 'opcode' means consuming a constant.
  1270. // "constant" here means after final transform to executable code,
  1271. // the value consumed will be a constant, so includes specialization.
  1272. bool Builder::isConstantOpCode(Op opcode) const
  1273. {
  1274. switch (opcode) {
  1275. case OpUndef:
  1276. case OpConstantTrue:
  1277. case OpConstantFalse:
  1278. case OpConstant:
  1279. case OpConstantComposite:
  1280. case OpConstantSampler:
  1281. case OpConstantNull:
  1282. case OpSpecConstantTrue:
  1283. case OpSpecConstantFalse:
  1284. case OpSpecConstant:
  1285. case OpSpecConstantComposite:
  1286. case OpSpecConstantOp:
  1287. return true;
  1288. default:
  1289. return false;
  1290. }
  1291. }
  1292. // Return true if consuming 'opcode' means consuming a specialization constant.
  1293. bool Builder::isSpecConstantOpCode(Op opcode) const
  1294. {
  1295. switch (opcode) {
  1296. case OpSpecConstantTrue:
  1297. case OpSpecConstantFalse:
  1298. case OpSpecConstant:
  1299. case OpSpecConstantComposite:
  1300. case OpSpecConstantOp:
  1301. return true;
  1302. default:
  1303. return false;
  1304. }
  1305. }
  1306. bool Builder::isRayTracingOpCode(Op opcode) const
  1307. {
  1308. switch (opcode) {
  1309. case OpTypeAccelerationStructureKHR:
  1310. case OpTypeRayQueryKHR:
  1311. return true;
  1312. default:
  1313. return false;
  1314. }
  1315. }
  1316. Id Builder::makeNullConstant(Id typeId)
  1317. {
  1318. Instruction* constant;
  1319. // See if we already made it.
  1320. Id existing = NoResult;
  1321. for (int i = 0; i < (int)nullConstants.size(); ++i) {
  1322. constant = nullConstants[i];
  1323. if (constant->getTypeId() == typeId)
  1324. existing = constant->getResultId();
  1325. }
  1326. if (existing != NoResult)
  1327. return existing;
  1328. // Make it
  1329. Instruction* c = new Instruction(getUniqueId(), typeId, OpConstantNull);
  1330. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1331. nullConstants.push_back(c);
  1332. module.mapInstruction(c);
  1333. return c->getResultId();
  1334. }
  1335. Id Builder::makeBoolConstant(bool b, bool specConstant)
  1336. {
  1337. Id typeId = makeBoolType();
  1338. Instruction* constant;
  1339. Op opcode = specConstant ? (b ? OpSpecConstantTrue : OpSpecConstantFalse) : (b ? OpConstantTrue : OpConstantFalse);
  1340. // See if we already made it. Applies only to regular constants, because specialization constants
  1341. // must remain distinct for the purpose of applying a SpecId decoration.
  1342. if (! specConstant) {
  1343. Id existing = 0;
  1344. for (int i = 0; i < (int)groupedConstants[OpTypeBool].size(); ++i) {
  1345. constant = groupedConstants[OpTypeBool][i];
  1346. if (constant->getTypeId() == typeId && constant->getOpCode() == opcode)
  1347. existing = constant->getResultId();
  1348. }
  1349. if (existing)
  1350. return existing;
  1351. }
  1352. // Make it
  1353. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  1354. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1355. groupedConstants[OpTypeBool].push_back(c);
  1356. module.mapInstruction(c);
  1357. return c->getResultId();
  1358. }
  1359. Id Builder::makeIntConstant(Id typeId, unsigned value, bool specConstant)
  1360. {
  1361. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  1362. // See if we already made it. Applies only to regular constants, because specialization constants
  1363. // must remain distinct for the purpose of applying a SpecId decoration.
  1364. if (! specConstant) {
  1365. Id existing = findScalarConstant(OpTypeInt, opcode, typeId, value);
  1366. if (existing)
  1367. return existing;
  1368. }
  1369. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  1370. c->addImmediateOperand(value);
  1371. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1372. groupedConstants[OpTypeInt].push_back(c);
  1373. module.mapInstruction(c);
  1374. return c->getResultId();
  1375. }
  1376. Id Builder::makeInt64Constant(Id typeId, unsigned long long value, bool specConstant)
  1377. {
  1378. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  1379. unsigned op1 = value & 0xFFFFFFFF;
  1380. unsigned op2 = value >> 32;
  1381. // See if we already made it. Applies only to regular constants, because specialization constants
  1382. // must remain distinct for the purpose of applying a SpecId decoration.
  1383. if (! specConstant) {
  1384. Id existing = findScalarConstant(OpTypeInt, opcode, typeId, op1, op2);
  1385. if (existing)
  1386. return existing;
  1387. }
  1388. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  1389. c->addImmediateOperand(op1);
  1390. c->addImmediateOperand(op2);
  1391. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1392. groupedConstants[OpTypeInt].push_back(c);
  1393. module.mapInstruction(c);
  1394. return c->getResultId();
  1395. }
  1396. Id Builder::makeFloatConstant(float f, bool specConstant)
  1397. {
  1398. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  1399. Id typeId = makeFloatType(32);
  1400. union { float fl; unsigned int ui; } u;
  1401. u.fl = f;
  1402. unsigned value = u.ui;
  1403. // See if we already made it. Applies only to regular constants, because specialization constants
  1404. // must remain distinct for the purpose of applying a SpecId decoration.
  1405. if (! specConstant) {
  1406. Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, value);
  1407. if (existing)
  1408. return existing;
  1409. }
  1410. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  1411. c->addImmediateOperand(value);
  1412. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1413. groupedConstants[OpTypeFloat].push_back(c);
  1414. module.mapInstruction(c);
  1415. return c->getResultId();
  1416. }
  1417. Id Builder::makeDoubleConstant(double d, bool specConstant)
  1418. {
  1419. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  1420. Id typeId = makeFloatType(64);
  1421. union { double db; unsigned long long ull; } u;
  1422. u.db = d;
  1423. unsigned long long value = u.ull;
  1424. unsigned op1 = value & 0xFFFFFFFF;
  1425. unsigned op2 = value >> 32;
  1426. // See if we already made it. Applies only to regular constants, because specialization constants
  1427. // must remain distinct for the purpose of applying a SpecId decoration.
  1428. if (! specConstant) {
  1429. Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, op1, op2);
  1430. if (existing)
  1431. return existing;
  1432. }
  1433. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  1434. c->addImmediateOperand(op1);
  1435. c->addImmediateOperand(op2);
  1436. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1437. groupedConstants[OpTypeFloat].push_back(c);
  1438. module.mapInstruction(c);
  1439. return c->getResultId();
  1440. }
  1441. Id Builder::makeFloat16Constant(float f16, bool specConstant)
  1442. {
  1443. Op opcode = specConstant ? OpSpecConstant : OpConstant;
  1444. Id typeId = makeFloatType(16);
  1445. spvutils::HexFloat<spvutils::FloatProxy<float>> fVal(f16);
  1446. spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>> f16Val(0);
  1447. fVal.castTo(f16Val, spvutils::kRoundToZero);
  1448. unsigned value = f16Val.value().getAsFloat().get_value();
  1449. // See if we already made it. Applies only to regular constants, because specialization constants
  1450. // must remain distinct for the purpose of applying a SpecId decoration.
  1451. if (!specConstant) {
  1452. Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, value);
  1453. if (existing)
  1454. return existing;
  1455. }
  1456. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  1457. c->addImmediateOperand(value);
  1458. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1459. groupedConstants[OpTypeFloat].push_back(c);
  1460. module.mapInstruction(c);
  1461. return c->getResultId();
  1462. }
  1463. Id Builder::makeFpConstant(Id type, double d, bool specConstant)
  1464. {
  1465. const int width = getScalarTypeWidth(type);
  1466. assert(isFloatType(type));
  1467. switch (width) {
  1468. case 16:
  1469. return makeFloat16Constant((float)d, specConstant);
  1470. case 32:
  1471. return makeFloatConstant((float)d, specConstant);
  1472. case 64:
  1473. return makeDoubleConstant(d, specConstant);
  1474. default:
  1475. break;
  1476. }
  1477. assert(false);
  1478. return NoResult;
  1479. }
  1480. Id Builder::importNonSemanticShaderDebugInfoInstructions()
  1481. {
  1482. assert(emitNonSemanticShaderDebugInfo == true);
  1483. if(nonSemanticShaderDebugInfo == 0)
  1484. {
  1485. this->addExtension(spv::E_SPV_KHR_non_semantic_info);
  1486. nonSemanticShaderDebugInfo = this->import("NonSemantic.Shader.DebugInfo.100");
  1487. }
  1488. return nonSemanticShaderDebugInfo;
  1489. }
  1490. Id Builder::findCompositeConstant(Op typeClass, Id typeId, const std::vector<Id>& comps)
  1491. {
  1492. Instruction* constant = nullptr;
  1493. bool found = false;
  1494. for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
  1495. constant = groupedConstants[typeClass][i];
  1496. if (constant->getTypeId() != typeId)
  1497. continue;
  1498. // same contents?
  1499. bool mismatch = false;
  1500. for (int op = 0; op < constant->getNumOperands(); ++op) {
  1501. if (constant->getIdOperand(op) != comps[op]) {
  1502. mismatch = true;
  1503. break;
  1504. }
  1505. }
  1506. if (! mismatch) {
  1507. found = true;
  1508. break;
  1509. }
  1510. }
  1511. return found ? constant->getResultId() : NoResult;
  1512. }
  1513. Id Builder::findStructConstant(Id typeId, const std::vector<Id>& comps)
  1514. {
  1515. Instruction* constant = nullptr;
  1516. bool found = false;
  1517. for (int i = 0; i < (int)groupedStructConstants[typeId].size(); ++i) {
  1518. constant = groupedStructConstants[typeId][i];
  1519. // same contents?
  1520. bool mismatch = false;
  1521. for (int op = 0; op < constant->getNumOperands(); ++op) {
  1522. if (constant->getIdOperand(op) != comps[op]) {
  1523. mismatch = true;
  1524. break;
  1525. }
  1526. }
  1527. if (! mismatch) {
  1528. found = true;
  1529. break;
  1530. }
  1531. }
  1532. return found ? constant->getResultId() : NoResult;
  1533. }
  1534. // Comments in header
  1535. Id Builder::makeCompositeConstant(Id typeId, const std::vector<Id>& members, bool specConstant)
  1536. {
  1537. Op opcode = specConstant ? OpSpecConstantComposite : OpConstantComposite;
  1538. assert(typeId);
  1539. Op typeClass = getTypeClass(typeId);
  1540. switch (typeClass) {
  1541. case OpTypeVector:
  1542. case OpTypeArray:
  1543. case OpTypeMatrix:
  1544. case OpTypeCooperativeMatrixKHR:
  1545. case OpTypeCooperativeMatrixNV:
  1546. if (! specConstant) {
  1547. Id existing = findCompositeConstant(typeClass, typeId, members);
  1548. if (existing)
  1549. return existing;
  1550. }
  1551. break;
  1552. case OpTypeStruct:
  1553. if (! specConstant) {
  1554. Id existing = findStructConstant(typeId, members);
  1555. if (existing)
  1556. return existing;
  1557. }
  1558. break;
  1559. default:
  1560. assert(0);
  1561. return makeFloatConstant(0.0);
  1562. }
  1563. Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
  1564. for (int op = 0; op < (int)members.size(); ++op)
  1565. c->addIdOperand(members[op]);
  1566. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
  1567. if (typeClass == OpTypeStruct)
  1568. groupedStructConstants[typeId].push_back(c);
  1569. else
  1570. groupedConstants[typeClass].push_back(c);
  1571. module.mapInstruction(c);
  1572. return c->getResultId();
  1573. }
  1574. Instruction* Builder::addEntryPoint(ExecutionModel model, Function* function, const char* name)
  1575. {
  1576. Instruction* entryPoint = new Instruction(OpEntryPoint);
  1577. entryPoint->addImmediateOperand(model);
  1578. entryPoint->addIdOperand(function->getId());
  1579. entryPoint->addStringOperand(name);
  1580. entryPoints.push_back(std::unique_ptr<Instruction>(entryPoint));
  1581. return entryPoint;
  1582. }
  1583. // Currently relying on the fact that all 'value' of interest are small non-negative values.
  1584. void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, int value1, int value2, int value3)
  1585. {
  1586. Instruction* instr = new Instruction(OpExecutionMode);
  1587. instr->addIdOperand(entryPoint->getId());
  1588. instr->addImmediateOperand(mode);
  1589. if (value1 >= 0)
  1590. instr->addImmediateOperand(value1);
  1591. if (value2 >= 0)
  1592. instr->addImmediateOperand(value2);
  1593. if (value3 >= 0)
  1594. instr->addImmediateOperand(value3);
  1595. executionModes.push_back(std::unique_ptr<Instruction>(instr));
  1596. }
  1597. void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, const std::vector<unsigned>& literals)
  1598. {
  1599. Instruction* instr = new Instruction(OpExecutionMode);
  1600. instr->addIdOperand(entryPoint->getId());
  1601. instr->addImmediateOperand(mode);
  1602. for (auto literal : literals)
  1603. instr->addImmediateOperand(literal);
  1604. executionModes.push_back(std::unique_ptr<Instruction>(instr));
  1605. }
  1606. void Builder::addExecutionModeId(Function* entryPoint, ExecutionMode mode, const std::vector<Id>& operandIds)
  1607. {
  1608. Instruction* instr = new Instruction(OpExecutionModeId);
  1609. instr->addIdOperand(entryPoint->getId());
  1610. instr->addImmediateOperand(mode);
  1611. for (auto operandId : operandIds)
  1612. instr->addIdOperand(operandId);
  1613. executionModes.push_back(std::unique_ptr<Instruction>(instr));
  1614. }
  1615. void Builder::addName(Id id, const char* string)
  1616. {
  1617. Instruction* name = new Instruction(OpName);
  1618. name->addIdOperand(id);
  1619. name->addStringOperand(string);
  1620. names.push_back(std::unique_ptr<Instruction>(name));
  1621. }
  1622. void Builder::addMemberName(Id id, int memberNumber, const char* string)
  1623. {
  1624. Instruction* name = new Instruction(OpMemberName);
  1625. name->addIdOperand(id);
  1626. name->addImmediateOperand(memberNumber);
  1627. name->addStringOperand(string);
  1628. names.push_back(std::unique_ptr<Instruction>(name));
  1629. }
  1630. void Builder::addDecoration(Id id, Decoration decoration, int num)
  1631. {
  1632. if (decoration == spv::DecorationMax)
  1633. return;
  1634. Instruction* dec = new Instruction(OpDecorate);
  1635. dec->addIdOperand(id);
  1636. dec->addImmediateOperand(decoration);
  1637. if (num >= 0)
  1638. dec->addImmediateOperand(num);
  1639. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1640. }
  1641. void Builder::addDecoration(Id id, Decoration decoration, const char* s)
  1642. {
  1643. if (decoration == spv::DecorationMax)
  1644. return;
  1645. Instruction* dec = new Instruction(OpDecorateString);
  1646. dec->addIdOperand(id);
  1647. dec->addImmediateOperand(decoration);
  1648. dec->addStringOperand(s);
  1649. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1650. }
  1651. void Builder::addDecoration(Id id, Decoration decoration, const std::vector<unsigned>& literals)
  1652. {
  1653. if (decoration == spv::DecorationMax)
  1654. return;
  1655. Instruction* dec = new Instruction(OpDecorate);
  1656. dec->addIdOperand(id);
  1657. dec->addImmediateOperand(decoration);
  1658. for (auto literal : literals)
  1659. dec->addImmediateOperand(literal);
  1660. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1661. }
  1662. void Builder::addDecoration(Id id, Decoration decoration, const std::vector<const char*>& strings)
  1663. {
  1664. if (decoration == spv::DecorationMax)
  1665. return;
  1666. Instruction* dec = new Instruction(OpDecorateString);
  1667. dec->addIdOperand(id);
  1668. dec->addImmediateOperand(decoration);
  1669. for (auto string : strings)
  1670. dec->addStringOperand(string);
  1671. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1672. }
  1673. void Builder::addDecorationId(Id id, Decoration decoration, Id idDecoration)
  1674. {
  1675. if (decoration == spv::DecorationMax)
  1676. return;
  1677. Instruction* dec = new Instruction(OpDecorateId);
  1678. dec->addIdOperand(id);
  1679. dec->addImmediateOperand(decoration);
  1680. dec->addIdOperand(idDecoration);
  1681. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1682. }
  1683. void Builder::addDecorationId(Id id, Decoration decoration, const std::vector<Id>& operandIds)
  1684. {
  1685. if(decoration == spv::DecorationMax)
  1686. return;
  1687. Instruction* dec = new Instruction(OpDecorateId);
  1688. dec->addIdOperand(id);
  1689. dec->addImmediateOperand(decoration);
  1690. for (auto operandId : operandIds)
  1691. dec->addIdOperand(operandId);
  1692. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1693. }
  1694. void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, int num)
  1695. {
  1696. if (decoration == spv::DecorationMax)
  1697. return;
  1698. Instruction* dec = new Instruction(OpMemberDecorate);
  1699. dec->addIdOperand(id);
  1700. dec->addImmediateOperand(member);
  1701. dec->addImmediateOperand(decoration);
  1702. if (num >= 0)
  1703. dec->addImmediateOperand(num);
  1704. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1705. }
  1706. void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const char *s)
  1707. {
  1708. if (decoration == spv::DecorationMax)
  1709. return;
  1710. Instruction* dec = new Instruction(OpMemberDecorateStringGOOGLE);
  1711. dec->addIdOperand(id);
  1712. dec->addImmediateOperand(member);
  1713. dec->addImmediateOperand(decoration);
  1714. dec->addStringOperand(s);
  1715. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1716. }
  1717. void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const std::vector<unsigned>& literals)
  1718. {
  1719. if (decoration == spv::DecorationMax)
  1720. return;
  1721. Instruction* dec = new Instruction(OpMemberDecorate);
  1722. dec->addIdOperand(id);
  1723. dec->addImmediateOperand(member);
  1724. dec->addImmediateOperand(decoration);
  1725. for (auto literal : literals)
  1726. dec->addImmediateOperand(literal);
  1727. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1728. }
  1729. void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const std::vector<const char*>& strings)
  1730. {
  1731. if (decoration == spv::DecorationMax)
  1732. return;
  1733. Instruction* dec = new Instruction(OpMemberDecorateString);
  1734. dec->addIdOperand(id);
  1735. dec->addImmediateOperand(member);
  1736. dec->addImmediateOperand(decoration);
  1737. for (auto string : strings)
  1738. dec->addStringOperand(string);
  1739. decorations.push_back(std::unique_ptr<Instruction>(dec));
  1740. }
  1741. // Comments in header
  1742. Function* Builder::makeEntryPoint(const char* entryPoint)
  1743. {
  1744. assert(! entryPointFunction);
  1745. Block* entry;
  1746. std::vector<Id> paramsTypes;
  1747. std::vector<char const*> paramNames;
  1748. std::vector<std::vector<Decoration>> decorations;
  1749. auto const returnType = makeVoidType();
  1750. restoreNonSemanticShaderDebugInfo = emitNonSemanticShaderDebugInfo;
  1751. if(sourceLang == spv::SourceLanguageHLSL) {
  1752. emitNonSemanticShaderDebugInfo = false;
  1753. }
  1754. entryPointFunction = makeFunctionEntry(NoPrecision, returnType, entryPoint, paramsTypes, paramNames, decorations, &entry);
  1755. emitNonSemanticShaderDebugInfo = restoreNonSemanticShaderDebugInfo;
  1756. return entryPointFunction;
  1757. }
  1758. // Comments in header
  1759. Function* Builder::makeFunctionEntry(Decoration precision, Id returnType, const char* name,
  1760. const std::vector<Id>& paramTypes, const std::vector<char const*>& paramNames,
  1761. const std::vector<std::vector<Decoration>>& decorations, Block **entry)
  1762. {
  1763. // Make the function and initial instructions in it
  1764. Id typeId = makeFunctionType(returnType, paramTypes);
  1765. Id firstParamId = paramTypes.size() == 0 ? 0 : getUniqueIds((int)paramTypes.size());
  1766. Id funcId = getUniqueId();
  1767. Function* function = new Function(funcId, returnType, typeId, firstParamId, module);
  1768. // Set up the precisions
  1769. setPrecision(function->getId(), precision);
  1770. function->setReturnPrecision(precision);
  1771. for (unsigned p = 0; p < (unsigned)decorations.size(); ++p) {
  1772. for (int d = 0; d < (int)decorations[p].size(); ++d) {
  1773. addDecoration(firstParamId + p, decorations[p][d]);
  1774. function->addParamPrecision(p, decorations[p][d]);
  1775. }
  1776. }
  1777. // Make the debug function instruction
  1778. if (emitNonSemanticShaderDebugInfo) {
  1779. Id nameId = getStringId(unmangleFunctionName(name));
  1780. Id debugFuncId = makeDebugFunction(function, nameId, typeId);
  1781. debugId[funcId] = debugFuncId;
  1782. currentDebugScopeId.push(debugFuncId);
  1783. lastDebugScopeId = NoResult;
  1784. }
  1785. // CFG
  1786. assert(entry != nullptr);
  1787. *entry = new Block(getUniqueId(), *function);
  1788. function->addBlock(*entry);
  1789. setBuildPoint(*entry);
  1790. // DebugScope and DebugLine for parameter DebugDeclares
  1791. if (emitNonSemanticShaderDebugInfo && (int)paramTypes.size() > 0) {
  1792. addDebugScopeAndLine(currentFileId, currentLine, 0);
  1793. }
  1794. if (emitNonSemanticShaderDebugInfo) {
  1795. assert(paramTypes.size() == paramNames.size());
  1796. for(size_t p = 0; p < paramTypes.size(); ++p)
  1797. {
  1798. auto getParamTypeId = [this](Id const& typeId) {
  1799. if (isPointerType(typeId) || isArrayType(typeId)) {
  1800. return getContainedTypeId(typeId);
  1801. }
  1802. else {
  1803. return typeId;
  1804. }
  1805. };
  1806. auto const& paramName = paramNames[p];
  1807. auto const debugLocalVariableId = createDebugLocalVariable(debugId[getParamTypeId(paramTypes[p])], paramName, p+1);
  1808. debugId[firstParamId + p] = debugLocalVariableId;
  1809. makeDebugDeclare(debugLocalVariableId, firstParamId + p);
  1810. }
  1811. }
  1812. if (name)
  1813. addName(function->getId(), name);
  1814. functions.push_back(std::unique_ptr<Function>(function));
  1815. // Clear debug scope stack
  1816. if (emitNonSemanticShaderDebugInfo)
  1817. currentDebugScopeId.pop();
  1818. return function;
  1819. }
  1820. Id Builder::makeDebugFunction([[maybe_unused]] Function* function, Id nameId, Id funcTypeId)
  1821. {
  1822. assert(function != nullptr);
  1823. assert(nameId != 0);
  1824. assert(funcTypeId != 0);
  1825. assert(debugId[funcTypeId] != 0);
  1826. Id funcId = getUniqueId();
  1827. auto type = new Instruction(funcId, makeVoidType(), OpExtInst);
  1828. type->addIdOperand(nonSemanticShaderDebugInfo);
  1829. type->addImmediateOperand(NonSemanticShaderDebugInfo100DebugFunction);
  1830. type->addIdOperand(nameId);
  1831. type->addIdOperand(debugId[funcTypeId]);
  1832. type->addIdOperand(makeDebugSource(currentFileId)); // Will be fixed later when true filename available
  1833. type->addIdOperand(makeUintConstant(currentLine)); // Will be fixed later when true line available
  1834. type->addIdOperand(makeUintConstant(0)); // column
  1835. type->addIdOperand(makeDebugCompilationUnit()); // scope
  1836. type->addIdOperand(nameId); // linkage name
  1837. type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfo100FlagIsPublic));
  1838. type->addIdOperand(makeUintConstant(currentLine)); // TODO(greg-lunarg): correct scope line
  1839. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
  1840. module.mapInstruction(type);
  1841. return funcId;
  1842. }
  1843. Id Builder::makeDebugLexicalBlock(uint32_t line) {
  1844. assert(!currentDebugScopeId.empty());
  1845. Id lexId = getUniqueId();
  1846. auto lex = new Instruction(lexId, makeVoidType(), OpExtInst);
  1847. lex->addIdOperand(nonSemanticShaderDebugInfo);
  1848. lex->addImmediateOperand(NonSemanticShaderDebugInfo100DebugLexicalBlock);
  1849. lex->addIdOperand(makeDebugSource(currentFileId));
  1850. lex->addIdOperand(makeUintConstant(line));
  1851. lex->addIdOperand(makeUintConstant(0)); // column
  1852. lex->addIdOperand(currentDebugScopeId.top()); // scope
  1853. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(lex));
  1854. module.mapInstruction(lex);
  1855. return lexId;
  1856. }
  1857. std::string Builder::unmangleFunctionName(std::string const& name) const
  1858. {
  1859. assert(name.length() > 0);
  1860. if(name.rfind('(') != std::string::npos) {
  1861. return name.substr(0, name.rfind('('));
  1862. } else {
  1863. return name;
  1864. }
  1865. }
  1866. // Comments in header
  1867. void Builder::makeReturn(bool implicit, Id retVal)
  1868. {
  1869. if (retVal) {
  1870. Instruction* inst = new Instruction(NoResult, NoType, OpReturnValue);
  1871. inst->addIdOperand(retVal);
  1872. buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
  1873. } else
  1874. buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(NoResult, NoType, OpReturn)));
  1875. if (! implicit)
  1876. createAndSetNoPredecessorBlock("post-return");
  1877. }
  1878. // Comments in header
  1879. void Builder::enterScope(uint32_t line)
  1880. {
  1881. // Generate new lexical scope debug instruction
  1882. Id lexId = makeDebugLexicalBlock(line);
  1883. currentDebugScopeId.push(lexId);
  1884. lastDebugScopeId = NoResult;
  1885. }
  1886. // Comments in header
  1887. void Builder::leaveScope()
  1888. {
  1889. // Pop current scope from stack and clear current scope
  1890. currentDebugScopeId.pop();
  1891. lastDebugScopeId = NoResult;
  1892. }
  1893. // Comments in header
  1894. void Builder::enterFunction(Function const* function)
  1895. {
  1896. // Save and disable debugInfo for HLSL entry point function. It is a wrapper
  1897. // function with no user code in it.
  1898. restoreNonSemanticShaderDebugInfo = emitNonSemanticShaderDebugInfo;
  1899. if (sourceLang == spv::SourceLanguageHLSL && function == entryPointFunction) {
  1900. emitNonSemanticShaderDebugInfo = false;
  1901. }
  1902. if (emitNonSemanticShaderDebugInfo) {
  1903. // Initialize scope state
  1904. Id funcId = function->getFuncId();
  1905. currentDebugScopeId.push(debugId[funcId]);
  1906. // Create DebugFunctionDefinition
  1907. spv::Id resultId = getUniqueId();
  1908. Instruction* defInst = new Instruction(resultId, makeVoidType(), OpExtInst);
  1909. defInst->addIdOperand(nonSemanticShaderDebugInfo);
  1910. defInst->addImmediateOperand(NonSemanticShaderDebugInfo100DebugFunctionDefinition);
  1911. defInst->addIdOperand(debugId[funcId]);
  1912. defInst->addIdOperand(funcId);
  1913. buildPoint->addInstruction(std::unique_ptr<Instruction>(defInst));
  1914. }
  1915. }
  1916. // Comments in header
  1917. void Builder::leaveFunction()
  1918. {
  1919. Block* block = buildPoint;
  1920. Function& function = buildPoint->getParent();
  1921. assert(block);
  1922. // If our function did not contain a return, add a return void now.
  1923. if (! block->isTerminated()) {
  1924. if (function.getReturnType() == makeVoidType())
  1925. makeReturn(true);
  1926. else {
  1927. makeReturn(true, createUndefined(function.getReturnType()));
  1928. }
  1929. }
  1930. // Clear function scope from debug scope stack
  1931. if (emitNonSemanticShaderDebugInfo)
  1932. currentDebugScopeId.pop();
  1933. emitNonSemanticShaderDebugInfo = restoreNonSemanticShaderDebugInfo;
  1934. }
  1935. // Comments in header
  1936. void Builder::makeStatementTerminator(spv::Op opcode, const char *name)
  1937. {
  1938. buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(opcode)));
  1939. createAndSetNoPredecessorBlock(name);
  1940. }
  1941. // Comments in header
  1942. void Builder::makeStatementTerminator(spv::Op opcode, const std::vector<Id>& operands, const char* name)
  1943. {
  1944. // It's assumed that the terminator instruction is always of void return type
  1945. // However in future if there is a need for non void return type, new helper
  1946. // methods can be created.
  1947. createNoResultOp(opcode, operands);
  1948. createAndSetNoPredecessorBlock(name);
  1949. }
  1950. // Comments in header
  1951. Id Builder::createVariable(Decoration precision, StorageClass storageClass, Id type, const char* name, Id initializer,
  1952. bool const compilerGenerated)
  1953. {
  1954. Id pointerType = makePointer(storageClass, type);
  1955. Instruction* inst = new Instruction(getUniqueId(), pointerType, OpVariable);
  1956. inst->addImmediateOperand(storageClass);
  1957. if (initializer != NoResult)
  1958. inst->addIdOperand(initializer);
  1959. switch (storageClass) {
  1960. case StorageClassFunction:
  1961. // Validation rules require the declaration in the entry block
  1962. buildPoint->getParent().addLocalVariable(std::unique_ptr<Instruction>(inst));
  1963. if (emitNonSemanticShaderDebugInfo && !compilerGenerated)
  1964. {
  1965. auto const debugLocalVariableId = createDebugLocalVariable(debugId[type], name);
  1966. debugId[inst->getResultId()] = debugLocalVariableId;
  1967. makeDebugDeclare(debugLocalVariableId, inst->getResultId());
  1968. }
  1969. break;
  1970. default:
  1971. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
  1972. module.mapInstruction(inst);
  1973. if (emitNonSemanticShaderDebugInfo && !isRayTracingOpCode(getOpCode(type)))
  1974. {
  1975. auto const debugResultId = createDebugGlobalVariable(debugId[type], name, inst->getResultId());
  1976. debugId[inst->getResultId()] = debugResultId;
  1977. }
  1978. break;
  1979. }
  1980. if (name)
  1981. addName(inst->getResultId(), name);
  1982. setPrecision(inst->getResultId(), precision);
  1983. return inst->getResultId();
  1984. }
  1985. // Comments in header
  1986. Id Builder::createUndefined(Id type)
  1987. {
  1988. Instruction* inst = new Instruction(getUniqueId(), type, OpUndef);
  1989. buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
  1990. return inst->getResultId();
  1991. }
  1992. // av/vis/nonprivate are unnecessary and illegal for some storage classes.
  1993. spv::MemoryAccessMask Builder::sanitizeMemoryAccessForStorageClass(spv::MemoryAccessMask memoryAccess, StorageClass sc)
  1994. const
  1995. {
  1996. switch (sc) {
  1997. case spv::StorageClassUniform:
  1998. case spv::StorageClassWorkgroup:
  1999. case spv::StorageClassStorageBuffer:
  2000. case spv::StorageClassPhysicalStorageBufferEXT:
  2001. break;
  2002. default:
  2003. memoryAccess = spv::MemoryAccessMask(memoryAccess &
  2004. ~(spv::MemoryAccessMakePointerAvailableKHRMask |
  2005. spv::MemoryAccessMakePointerVisibleKHRMask |
  2006. spv::MemoryAccessNonPrivatePointerKHRMask));
  2007. break;
  2008. }
  2009. return memoryAccess;
  2010. }
  2011. // Comments in header
  2012. void Builder::createStore(Id rValue, Id lValue, spv::MemoryAccessMask memoryAccess, spv::Scope scope,
  2013. unsigned int alignment)
  2014. {
  2015. Instruction* store = new Instruction(OpStore);
  2016. store->addIdOperand(lValue);
  2017. store->addIdOperand(rValue);
  2018. memoryAccess = sanitizeMemoryAccessForStorageClass(memoryAccess, getStorageClass(lValue));
  2019. if (memoryAccess != MemoryAccessMaskNone) {
  2020. store->addImmediateOperand(memoryAccess);
  2021. if (memoryAccess & spv::MemoryAccessAlignedMask) {
  2022. store->addImmediateOperand(alignment);
  2023. }
  2024. if (memoryAccess & spv::MemoryAccessMakePointerAvailableKHRMask) {
  2025. store->addIdOperand(makeUintConstant(scope));
  2026. }
  2027. }
  2028. buildPoint->addInstruction(std::unique_ptr<Instruction>(store));
  2029. }
  2030. // Comments in header
  2031. Id Builder::createLoad(Id lValue, spv::Decoration precision, spv::MemoryAccessMask memoryAccess,
  2032. spv::Scope scope, unsigned int alignment)
  2033. {
  2034. Instruction* load = new Instruction(getUniqueId(), getDerefTypeId(lValue), OpLoad);
  2035. load->addIdOperand(lValue);
  2036. memoryAccess = sanitizeMemoryAccessForStorageClass(memoryAccess, getStorageClass(lValue));
  2037. if (memoryAccess != MemoryAccessMaskNone) {
  2038. load->addImmediateOperand(memoryAccess);
  2039. if (memoryAccess & spv::MemoryAccessAlignedMask) {
  2040. load->addImmediateOperand(alignment);
  2041. }
  2042. if (memoryAccess & spv::MemoryAccessMakePointerVisibleKHRMask) {
  2043. load->addIdOperand(makeUintConstant(scope));
  2044. }
  2045. }
  2046. buildPoint->addInstruction(std::unique_ptr<Instruction>(load));
  2047. setPrecision(load->getResultId(), precision);
  2048. return load->getResultId();
  2049. }
  2050. // Comments in header
  2051. Id Builder::createAccessChain(StorageClass storageClass, Id base, const std::vector<Id>& offsets)
  2052. {
  2053. // Figure out the final resulting type.
  2054. Id typeId = getResultingAccessChainType();
  2055. typeId = makePointer(storageClass, typeId);
  2056. // Make the instruction
  2057. Instruction* chain = new Instruction(getUniqueId(), typeId, OpAccessChain);
  2058. chain->addIdOperand(base);
  2059. for (int i = 0; i < (int)offsets.size(); ++i)
  2060. chain->addIdOperand(offsets[i]);
  2061. buildPoint->addInstruction(std::unique_ptr<Instruction>(chain));
  2062. return chain->getResultId();
  2063. }
  2064. Id Builder::createArrayLength(Id base, unsigned int member)
  2065. {
  2066. spv::Id intType = makeUintType(32);
  2067. Instruction* length = new Instruction(getUniqueId(), intType, OpArrayLength);
  2068. length->addIdOperand(base);
  2069. length->addImmediateOperand(member);
  2070. buildPoint->addInstruction(std::unique_ptr<Instruction>(length));
  2071. return length->getResultId();
  2072. }
  2073. Id Builder::createCooperativeMatrixLengthKHR(Id type)
  2074. {
  2075. spv::Id intType = makeUintType(32);
  2076. // Generate code for spec constants if in spec constant operation
  2077. // generation mode.
  2078. if (generatingOpCodeForSpecConst) {
  2079. return createSpecConstantOp(OpCooperativeMatrixLengthKHR, intType, std::vector<Id>(1, type), std::vector<Id>());
  2080. }
  2081. Instruction* length = new Instruction(getUniqueId(), intType, OpCooperativeMatrixLengthKHR);
  2082. length->addIdOperand(type);
  2083. buildPoint->addInstruction(std::unique_ptr<Instruction>(length));
  2084. return length->getResultId();
  2085. }
  2086. Id Builder::createCooperativeMatrixLengthNV(Id type)
  2087. {
  2088. spv::Id intType = makeUintType(32);
  2089. // Generate code for spec constants if in spec constant operation
  2090. // generation mode.
  2091. if (generatingOpCodeForSpecConst) {
  2092. return createSpecConstantOp(OpCooperativeMatrixLengthNV, intType, std::vector<Id>(1, type), std::vector<Id>());
  2093. }
  2094. Instruction* length = new Instruction(getUniqueId(), intType, OpCooperativeMatrixLengthNV);
  2095. length->addIdOperand(type);
  2096. buildPoint->addInstruction(std::unique_ptr<Instruction>(length));
  2097. return length->getResultId();
  2098. }
  2099. Id Builder::createCompositeExtract(Id composite, Id typeId, unsigned index)
  2100. {
  2101. // Generate code for spec constants if in spec constant operation
  2102. // generation mode.
  2103. if (generatingOpCodeForSpecConst) {
  2104. return createSpecConstantOp(OpCompositeExtract, typeId, std::vector<Id>(1, composite),
  2105. std::vector<Id>(1, index));
  2106. }
  2107. Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
  2108. extract->addIdOperand(composite);
  2109. extract->addImmediateOperand(index);
  2110. buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
  2111. return extract->getResultId();
  2112. }
  2113. Id Builder::createCompositeExtract(Id composite, Id typeId, const std::vector<unsigned>& indexes)
  2114. {
  2115. // Generate code for spec constants if in spec constant operation
  2116. // generation mode.
  2117. if (generatingOpCodeForSpecConst) {
  2118. return createSpecConstantOp(OpCompositeExtract, typeId, std::vector<Id>(1, composite), indexes);
  2119. }
  2120. Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
  2121. extract->addIdOperand(composite);
  2122. for (int i = 0; i < (int)indexes.size(); ++i)
  2123. extract->addImmediateOperand(indexes[i]);
  2124. buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
  2125. return extract->getResultId();
  2126. }
  2127. Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, unsigned index)
  2128. {
  2129. Instruction* insert = new Instruction(getUniqueId(), typeId, OpCompositeInsert);
  2130. insert->addIdOperand(object);
  2131. insert->addIdOperand(composite);
  2132. insert->addImmediateOperand(index);
  2133. buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
  2134. return insert->getResultId();
  2135. }
  2136. Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, const std::vector<unsigned>& indexes)
  2137. {
  2138. Instruction* insert = new Instruction(getUniqueId(), typeId, OpCompositeInsert);
  2139. insert->addIdOperand(object);
  2140. insert->addIdOperand(composite);
  2141. for (int i = 0; i < (int)indexes.size(); ++i)
  2142. insert->addImmediateOperand(indexes[i]);
  2143. buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
  2144. return insert->getResultId();
  2145. }
  2146. Id Builder::createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex)
  2147. {
  2148. Instruction* extract = new Instruction(getUniqueId(), typeId, OpVectorExtractDynamic);
  2149. extract->addIdOperand(vector);
  2150. extract->addIdOperand(componentIndex);
  2151. buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
  2152. return extract->getResultId();
  2153. }
  2154. Id Builder::createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex)
  2155. {
  2156. Instruction* insert = new Instruction(getUniqueId(), typeId, OpVectorInsertDynamic);
  2157. insert->addIdOperand(vector);
  2158. insert->addIdOperand(component);
  2159. insert->addIdOperand(componentIndex);
  2160. buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
  2161. return insert->getResultId();
  2162. }
  2163. // An opcode that has no operands, no result id, and no type
  2164. void Builder::createNoResultOp(Op opCode)
  2165. {
  2166. Instruction* op = new Instruction(opCode);
  2167. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2168. }
  2169. // An opcode that has one id operand, no result id, and no type
  2170. void Builder::createNoResultOp(Op opCode, Id operand)
  2171. {
  2172. Instruction* op = new Instruction(opCode);
  2173. op->addIdOperand(operand);
  2174. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2175. }
  2176. // An opcode that has one or more operands, no result id, and no type
  2177. void Builder::createNoResultOp(Op opCode, const std::vector<Id>& operands)
  2178. {
  2179. Instruction* op = new Instruction(opCode);
  2180. for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
  2181. op->addIdOperand(*it);
  2182. }
  2183. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2184. }
  2185. // An opcode that has multiple operands, no result id, and no type
  2186. void Builder::createNoResultOp(Op opCode, const std::vector<IdImmediate>& operands)
  2187. {
  2188. Instruction* op = new Instruction(opCode);
  2189. for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
  2190. if (it->isId)
  2191. op->addIdOperand(it->word);
  2192. else
  2193. op->addImmediateOperand(it->word);
  2194. }
  2195. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2196. }
  2197. void Builder::createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask semantics)
  2198. {
  2199. Instruction* op = new Instruction(OpControlBarrier);
  2200. op->addIdOperand(makeUintConstant(execution));
  2201. op->addIdOperand(makeUintConstant(memory));
  2202. op->addIdOperand(makeUintConstant(semantics));
  2203. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2204. }
  2205. void Builder::createMemoryBarrier(unsigned executionScope, unsigned memorySemantics)
  2206. {
  2207. Instruction* op = new Instruction(OpMemoryBarrier);
  2208. op->addIdOperand(makeUintConstant(executionScope));
  2209. op->addIdOperand(makeUintConstant(memorySemantics));
  2210. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2211. }
  2212. // An opcode that has one operands, a result id, and a type
  2213. Id Builder::createUnaryOp(Op opCode, Id typeId, Id operand)
  2214. {
  2215. // Generate code for spec constants if in spec constant operation
  2216. // generation mode.
  2217. if (generatingOpCodeForSpecConst) {
  2218. return createSpecConstantOp(opCode, typeId, std::vector<Id>(1, operand), std::vector<Id>());
  2219. }
  2220. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  2221. op->addIdOperand(operand);
  2222. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2223. return op->getResultId();
  2224. }
  2225. Id Builder::createBinOp(Op opCode, Id typeId, Id left, Id right)
  2226. {
  2227. // Generate code for spec constants if in spec constant operation
  2228. // generation mode.
  2229. if (generatingOpCodeForSpecConst) {
  2230. std::vector<Id> operands(2);
  2231. operands[0] = left; operands[1] = right;
  2232. return createSpecConstantOp(opCode, typeId, operands, std::vector<Id>());
  2233. }
  2234. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  2235. op->addIdOperand(left);
  2236. op->addIdOperand(right);
  2237. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2238. return op->getResultId();
  2239. }
  2240. Id Builder::createTriOp(Op opCode, Id typeId, Id op1, Id op2, Id op3)
  2241. {
  2242. // Generate code for spec constants if in spec constant operation
  2243. // generation mode.
  2244. if (generatingOpCodeForSpecConst) {
  2245. std::vector<Id> operands(3);
  2246. operands[0] = op1;
  2247. operands[1] = op2;
  2248. operands[2] = op3;
  2249. return createSpecConstantOp(
  2250. opCode, typeId, operands, std::vector<Id>());
  2251. }
  2252. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  2253. op->addIdOperand(op1);
  2254. op->addIdOperand(op2);
  2255. op->addIdOperand(op3);
  2256. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2257. return op->getResultId();
  2258. }
  2259. Id Builder::createOp(Op opCode, Id typeId, const std::vector<Id>& operands)
  2260. {
  2261. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  2262. for (auto it = operands.cbegin(); it != operands.cend(); ++it)
  2263. op->addIdOperand(*it);
  2264. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2265. return op->getResultId();
  2266. }
  2267. Id Builder::createOp(Op opCode, Id typeId, const std::vector<IdImmediate>& operands)
  2268. {
  2269. Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
  2270. for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
  2271. if (it->isId)
  2272. op->addIdOperand(it->word);
  2273. else
  2274. op->addImmediateOperand(it->word);
  2275. }
  2276. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2277. return op->getResultId();
  2278. }
  2279. Id Builder::createSpecConstantOp(Op opCode, Id typeId, const std::vector<Id>& operands,
  2280. const std::vector<unsigned>& literals)
  2281. {
  2282. Instruction* op = new Instruction(getUniqueId(), typeId, OpSpecConstantOp);
  2283. op->addImmediateOperand((unsigned) opCode);
  2284. for (auto it = operands.cbegin(); it != operands.cend(); ++it)
  2285. op->addIdOperand(*it);
  2286. for (auto it = literals.cbegin(); it != literals.cend(); ++it)
  2287. op->addImmediateOperand(*it);
  2288. module.mapInstruction(op);
  2289. constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(op));
  2290. return op->getResultId();
  2291. }
  2292. Id Builder::createFunctionCall(spv::Function* function, const std::vector<spv::Id>& args)
  2293. {
  2294. Instruction* op = new Instruction(getUniqueId(), function->getReturnType(), OpFunctionCall);
  2295. op->addIdOperand(function->getId());
  2296. for (int a = 0; a < (int)args.size(); ++a)
  2297. op->addIdOperand(args[a]);
  2298. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2299. return op->getResultId();
  2300. }
  2301. // Comments in header
  2302. Id Builder::createRvalueSwizzle(Decoration precision, Id typeId, Id source, const std::vector<unsigned>& channels)
  2303. {
  2304. if (channels.size() == 1)
  2305. return setPrecision(createCompositeExtract(source, typeId, channels.front()), precision);
  2306. if (generatingOpCodeForSpecConst) {
  2307. std::vector<Id> operands(2);
  2308. operands[0] = operands[1] = source;
  2309. return setPrecision(createSpecConstantOp(OpVectorShuffle, typeId, operands, channels), precision);
  2310. }
  2311. Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
  2312. assert(isVector(source));
  2313. swizzle->addIdOperand(source);
  2314. swizzle->addIdOperand(source);
  2315. for (int i = 0; i < (int)channels.size(); ++i)
  2316. swizzle->addImmediateOperand(channels[i]);
  2317. buildPoint->addInstruction(std::unique_ptr<Instruction>(swizzle));
  2318. return setPrecision(swizzle->getResultId(), precision);
  2319. }
  2320. // Comments in header
  2321. Id Builder::createLvalueSwizzle(Id typeId, Id target, Id source, const std::vector<unsigned>& channels)
  2322. {
  2323. if (channels.size() == 1 && getNumComponents(source) == 1)
  2324. return createCompositeInsert(source, target, typeId, channels.front());
  2325. Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
  2326. assert(isVector(target));
  2327. swizzle->addIdOperand(target);
  2328. assert(getNumComponents(source) == (int)channels.size());
  2329. assert(isVector(source));
  2330. swizzle->addIdOperand(source);
  2331. // Set up an identity shuffle from the base value to the result value
  2332. unsigned int components[4];
  2333. int numTargetComponents = getNumComponents(target);
  2334. for (int i = 0; i < numTargetComponents; ++i)
  2335. components[i] = i;
  2336. // Punch in the l-value swizzle
  2337. for (int i = 0; i < (int)channels.size(); ++i)
  2338. components[channels[i]] = numTargetComponents + i;
  2339. // finish the instruction with these components selectors
  2340. for (int i = 0; i < numTargetComponents; ++i)
  2341. swizzle->addImmediateOperand(components[i]);
  2342. buildPoint->addInstruction(std::unique_ptr<Instruction>(swizzle));
  2343. return swizzle->getResultId();
  2344. }
  2345. // Comments in header
  2346. void Builder::promoteScalar(Decoration precision, Id& left, Id& right)
  2347. {
  2348. int direction = getNumComponents(right) - getNumComponents(left);
  2349. if (direction > 0)
  2350. left = smearScalar(precision, left, makeVectorType(getTypeId(left), getNumComponents(right)));
  2351. else if (direction < 0)
  2352. right = smearScalar(precision, right, makeVectorType(getTypeId(right), getNumComponents(left)));
  2353. return;
  2354. }
  2355. // Comments in header
  2356. Id Builder::smearScalar(Decoration precision, Id scalar, Id vectorType)
  2357. {
  2358. assert(getNumComponents(scalar) == 1);
  2359. assert(getTypeId(scalar) == getScalarTypeId(vectorType));
  2360. int numComponents = getNumTypeComponents(vectorType);
  2361. if (numComponents == 1)
  2362. return scalar;
  2363. Instruction* smear = nullptr;
  2364. if (generatingOpCodeForSpecConst) {
  2365. auto members = std::vector<spv::Id>(numComponents, scalar);
  2366. // Sometime even in spec-constant-op mode, the temporary vector created by
  2367. // promoting a scalar might not be a spec constant. This should depend on
  2368. // the scalar.
  2369. // e.g.:
  2370. // const vec2 spec_const_result = a_spec_const_vec2 + a_front_end_const_scalar;
  2371. // In such cases, the temporary vector created from a_front_end_const_scalar
  2372. // is not a spec constant vector, even though the binary operation node is marked
  2373. // as 'specConstant' and we are in spec-constant-op mode.
  2374. auto result_id = makeCompositeConstant(vectorType, members, isSpecConstant(scalar));
  2375. smear = module.getInstruction(result_id);
  2376. } else {
  2377. smear = new Instruction(getUniqueId(), vectorType, OpCompositeConstruct);
  2378. for (int c = 0; c < numComponents; ++c)
  2379. smear->addIdOperand(scalar);
  2380. buildPoint->addInstruction(std::unique_ptr<Instruction>(smear));
  2381. }
  2382. return setPrecision(smear->getResultId(), precision);
  2383. }
  2384. // Comments in header
  2385. Id Builder::createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<Id>& args)
  2386. {
  2387. Instruction* inst = new Instruction(getUniqueId(), resultType, OpExtInst);
  2388. inst->addIdOperand(builtins);
  2389. inst->addImmediateOperand(entryPoint);
  2390. for (int arg = 0; arg < (int)args.size(); ++arg)
  2391. inst->addIdOperand(args[arg]);
  2392. buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
  2393. return inst->getResultId();
  2394. }
  2395. // Accept all parameters needed to create a texture instruction.
  2396. // Create the correct instruction based on the inputs, and make the call.
  2397. Id Builder::createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather,
  2398. bool noImplicitLod, const TextureParameters& parameters, ImageOperandsMask signExtensionMask)
  2399. {
  2400. std::vector<Id> texArgs;
  2401. //
  2402. // Set up the fixed arguments
  2403. //
  2404. bool explicitLod = false;
  2405. texArgs.push_back(parameters.sampler);
  2406. texArgs.push_back(parameters.coords);
  2407. if (parameters.Dref != NoResult)
  2408. texArgs.push_back(parameters.Dref);
  2409. if (parameters.component != NoResult)
  2410. texArgs.push_back(parameters.component);
  2411. if (parameters.granularity != NoResult)
  2412. texArgs.push_back(parameters.granularity);
  2413. if (parameters.coarse != NoResult)
  2414. texArgs.push_back(parameters.coarse);
  2415. //
  2416. // Set up the optional arguments
  2417. //
  2418. size_t optArgNum = texArgs.size(); // the position of the mask for the optional arguments, if any.
  2419. ImageOperandsMask mask = ImageOperandsMaskNone; // the mask operand
  2420. if (parameters.bias) {
  2421. mask = (ImageOperandsMask)(mask | ImageOperandsBiasMask);
  2422. texArgs.push_back(parameters.bias);
  2423. }
  2424. if (parameters.lod) {
  2425. mask = (ImageOperandsMask)(mask | ImageOperandsLodMask);
  2426. texArgs.push_back(parameters.lod);
  2427. explicitLod = true;
  2428. } else if (parameters.gradX) {
  2429. mask = (ImageOperandsMask)(mask | ImageOperandsGradMask);
  2430. texArgs.push_back(parameters.gradX);
  2431. texArgs.push_back(parameters.gradY);
  2432. explicitLod = true;
  2433. } else if (noImplicitLod && ! fetch && ! gather) {
  2434. // have to explicitly use lod of 0 if not allowed to have them be implicit, and
  2435. // we would otherwise be about to issue an implicit instruction
  2436. mask = (ImageOperandsMask)(mask | ImageOperandsLodMask);
  2437. texArgs.push_back(makeFloatConstant(0.0));
  2438. explicitLod = true;
  2439. }
  2440. if (parameters.offset) {
  2441. if (isConstant(parameters.offset))
  2442. mask = (ImageOperandsMask)(mask | ImageOperandsConstOffsetMask);
  2443. else {
  2444. addCapability(CapabilityImageGatherExtended);
  2445. mask = (ImageOperandsMask)(mask | ImageOperandsOffsetMask);
  2446. }
  2447. texArgs.push_back(parameters.offset);
  2448. }
  2449. if (parameters.offsets) {
  2450. addCapability(CapabilityImageGatherExtended);
  2451. mask = (ImageOperandsMask)(mask | ImageOperandsConstOffsetsMask);
  2452. texArgs.push_back(parameters.offsets);
  2453. }
  2454. if (parameters.sample) {
  2455. mask = (ImageOperandsMask)(mask | ImageOperandsSampleMask);
  2456. texArgs.push_back(parameters.sample);
  2457. }
  2458. if (parameters.lodClamp) {
  2459. // capability if this bit is used
  2460. addCapability(CapabilityMinLod);
  2461. mask = (ImageOperandsMask)(mask | ImageOperandsMinLodMask);
  2462. texArgs.push_back(parameters.lodClamp);
  2463. }
  2464. if (parameters.nonprivate) {
  2465. mask = mask | ImageOperandsNonPrivateTexelKHRMask;
  2466. }
  2467. if (parameters.volatil) {
  2468. mask = mask | ImageOperandsVolatileTexelKHRMask;
  2469. }
  2470. mask = mask | signExtensionMask;
  2471. // insert the operand for the mask, if any bits were set.
  2472. if (mask != ImageOperandsMaskNone)
  2473. texArgs.insert(texArgs.begin() + optArgNum, mask);
  2474. //
  2475. // Set up the instruction
  2476. //
  2477. Op opCode = OpNop; // All paths below need to set this
  2478. if (fetch) {
  2479. if (sparse)
  2480. opCode = OpImageSparseFetch;
  2481. else
  2482. opCode = OpImageFetch;
  2483. } else if (parameters.granularity && parameters.coarse) {
  2484. opCode = OpImageSampleFootprintNV;
  2485. } else if (gather) {
  2486. if (parameters.Dref)
  2487. if (sparse)
  2488. opCode = OpImageSparseDrefGather;
  2489. else
  2490. opCode = OpImageDrefGather;
  2491. else
  2492. if (sparse)
  2493. opCode = OpImageSparseGather;
  2494. else
  2495. opCode = OpImageGather;
  2496. } else if (explicitLod) {
  2497. if (parameters.Dref) {
  2498. if (proj)
  2499. if (sparse)
  2500. opCode = OpImageSparseSampleProjDrefExplicitLod;
  2501. else
  2502. opCode = OpImageSampleProjDrefExplicitLod;
  2503. else
  2504. if (sparse)
  2505. opCode = OpImageSparseSampleDrefExplicitLod;
  2506. else
  2507. opCode = OpImageSampleDrefExplicitLod;
  2508. } else {
  2509. if (proj)
  2510. if (sparse)
  2511. opCode = OpImageSparseSampleProjExplicitLod;
  2512. else
  2513. opCode = OpImageSampleProjExplicitLod;
  2514. else
  2515. if (sparse)
  2516. opCode = OpImageSparseSampleExplicitLod;
  2517. else
  2518. opCode = OpImageSampleExplicitLod;
  2519. }
  2520. } else {
  2521. if (parameters.Dref) {
  2522. if (proj)
  2523. if (sparse)
  2524. opCode = OpImageSparseSampleProjDrefImplicitLod;
  2525. else
  2526. opCode = OpImageSampleProjDrefImplicitLod;
  2527. else
  2528. if (sparse)
  2529. opCode = OpImageSparseSampleDrefImplicitLod;
  2530. else
  2531. opCode = OpImageSampleDrefImplicitLod;
  2532. } else {
  2533. if (proj)
  2534. if (sparse)
  2535. opCode = OpImageSparseSampleProjImplicitLod;
  2536. else
  2537. opCode = OpImageSampleProjImplicitLod;
  2538. else
  2539. if (sparse)
  2540. opCode = OpImageSparseSampleImplicitLod;
  2541. else
  2542. opCode = OpImageSampleImplicitLod;
  2543. }
  2544. }
  2545. // See if the result type is expecting a smeared result.
  2546. // This happens when a legacy shadow*() call is made, which
  2547. // gets a vec4 back instead of a float.
  2548. Id smearedType = resultType;
  2549. if (! isScalarType(resultType)) {
  2550. switch (opCode) {
  2551. case OpImageSampleDrefImplicitLod:
  2552. case OpImageSampleDrefExplicitLod:
  2553. case OpImageSampleProjDrefImplicitLod:
  2554. case OpImageSampleProjDrefExplicitLod:
  2555. resultType = getScalarTypeId(resultType);
  2556. break;
  2557. default:
  2558. break;
  2559. }
  2560. }
  2561. Id typeId0 = 0;
  2562. Id typeId1 = 0;
  2563. if (sparse) {
  2564. typeId0 = resultType;
  2565. typeId1 = getDerefTypeId(parameters.texelOut);
  2566. resultType = makeStructResultType(typeId0, typeId1);
  2567. }
  2568. // Build the SPIR-V instruction
  2569. Instruction* textureInst = new Instruction(getUniqueId(), resultType, opCode);
  2570. for (size_t op = 0; op < optArgNum; ++op)
  2571. textureInst->addIdOperand(texArgs[op]);
  2572. if (optArgNum < texArgs.size())
  2573. textureInst->addImmediateOperand(texArgs[optArgNum]);
  2574. for (size_t op = optArgNum + 1; op < texArgs.size(); ++op)
  2575. textureInst->addIdOperand(texArgs[op]);
  2576. setPrecision(textureInst->getResultId(), precision);
  2577. buildPoint->addInstruction(std::unique_ptr<Instruction>(textureInst));
  2578. Id resultId = textureInst->getResultId();
  2579. if (sparse) {
  2580. // set capability
  2581. addCapability(CapabilitySparseResidency);
  2582. // Decode the return type that was a special structure
  2583. createStore(createCompositeExtract(resultId, typeId1, 1), parameters.texelOut);
  2584. resultId = createCompositeExtract(resultId, typeId0, 0);
  2585. setPrecision(resultId, precision);
  2586. } else {
  2587. // When a smear is needed, do it, as per what was computed
  2588. // above when resultType was changed to a scalar type.
  2589. if (resultType != smearedType)
  2590. resultId = smearScalar(precision, resultId, smearedType);
  2591. }
  2592. return resultId;
  2593. }
  2594. // Comments in header
  2595. Id Builder::createTextureQueryCall(Op opCode, const TextureParameters& parameters, bool isUnsignedResult)
  2596. {
  2597. // Figure out the result type
  2598. Id resultType = 0;
  2599. switch (opCode) {
  2600. case OpImageQuerySize:
  2601. case OpImageQuerySizeLod:
  2602. {
  2603. int numComponents = 0;
  2604. switch (getTypeDimensionality(getImageType(parameters.sampler))) {
  2605. case Dim1D:
  2606. case DimBuffer:
  2607. numComponents = 1;
  2608. break;
  2609. case Dim2D:
  2610. case DimCube:
  2611. case DimRect:
  2612. case DimSubpassData:
  2613. numComponents = 2;
  2614. break;
  2615. case Dim3D:
  2616. numComponents = 3;
  2617. break;
  2618. default:
  2619. assert(0);
  2620. break;
  2621. }
  2622. if (isArrayedImageType(getImageType(parameters.sampler)))
  2623. ++numComponents;
  2624. Id intType = isUnsignedResult ? makeUintType(32) : makeIntType(32);
  2625. if (numComponents == 1)
  2626. resultType = intType;
  2627. else
  2628. resultType = makeVectorType(intType, numComponents);
  2629. break;
  2630. }
  2631. case OpImageQueryLod:
  2632. resultType = makeVectorType(getScalarTypeId(getTypeId(parameters.coords)), 2);
  2633. break;
  2634. case OpImageQueryLevels:
  2635. case OpImageQuerySamples:
  2636. resultType = isUnsignedResult ? makeUintType(32) : makeIntType(32);
  2637. break;
  2638. default:
  2639. assert(0);
  2640. break;
  2641. }
  2642. Instruction* query = new Instruction(getUniqueId(), resultType, opCode);
  2643. query->addIdOperand(parameters.sampler);
  2644. if (parameters.coords)
  2645. query->addIdOperand(parameters.coords);
  2646. if (parameters.lod)
  2647. query->addIdOperand(parameters.lod);
  2648. buildPoint->addInstruction(std::unique_ptr<Instruction>(query));
  2649. addCapability(CapabilityImageQuery);
  2650. return query->getResultId();
  2651. }
  2652. // External comments in header.
  2653. // Operates recursively to visit the composite's hierarchy.
  2654. Id Builder::createCompositeCompare(Decoration precision, Id value1, Id value2, bool equal)
  2655. {
  2656. Id boolType = makeBoolType();
  2657. Id valueType = getTypeId(value1);
  2658. Id resultId = NoResult;
  2659. int numConstituents = getNumTypeConstituents(valueType);
  2660. // Scalars and Vectors
  2661. if (isScalarType(valueType) || isVectorType(valueType)) {
  2662. assert(valueType == getTypeId(value2));
  2663. // These just need a single comparison, just have
  2664. // to figure out what it is.
  2665. Op op;
  2666. switch (getMostBasicTypeClass(valueType)) {
  2667. case OpTypeFloat:
  2668. op = equal ? OpFOrdEqual : OpFUnordNotEqual;
  2669. break;
  2670. case OpTypeInt:
  2671. default:
  2672. op = equal ? OpIEqual : OpINotEqual;
  2673. break;
  2674. case OpTypeBool:
  2675. op = equal ? OpLogicalEqual : OpLogicalNotEqual;
  2676. precision = NoPrecision;
  2677. break;
  2678. }
  2679. if (isScalarType(valueType)) {
  2680. // scalar
  2681. resultId = createBinOp(op, boolType, value1, value2);
  2682. } else {
  2683. // vector
  2684. resultId = createBinOp(op, makeVectorType(boolType, numConstituents), value1, value2);
  2685. setPrecision(resultId, precision);
  2686. // reduce vector compares...
  2687. resultId = createUnaryOp(equal ? OpAll : OpAny, boolType, resultId);
  2688. }
  2689. return setPrecision(resultId, precision);
  2690. }
  2691. // Only structs, arrays, and matrices should be left.
  2692. // They share in common the reduction operation across their constituents.
  2693. assert(isAggregateType(valueType) || isMatrixType(valueType));
  2694. // Compare each pair of constituents
  2695. for (int constituent = 0; constituent < numConstituents; ++constituent) {
  2696. std::vector<unsigned> indexes(1, constituent);
  2697. Id constituentType1 = getContainedTypeId(getTypeId(value1), constituent);
  2698. Id constituentType2 = getContainedTypeId(getTypeId(value2), constituent);
  2699. Id constituent1 = createCompositeExtract(value1, constituentType1, indexes);
  2700. Id constituent2 = createCompositeExtract(value2, constituentType2, indexes);
  2701. Id subResultId = createCompositeCompare(precision, constituent1, constituent2, equal);
  2702. if (constituent == 0)
  2703. resultId = subResultId;
  2704. else
  2705. resultId = setPrecision(createBinOp(equal ? OpLogicalAnd : OpLogicalOr, boolType, resultId, subResultId),
  2706. precision);
  2707. }
  2708. return resultId;
  2709. }
  2710. // OpCompositeConstruct
  2711. Id Builder::createCompositeConstruct(Id typeId, const std::vector<Id>& constituents)
  2712. {
  2713. assert(isAggregateType(typeId) || (getNumTypeConstituents(typeId) > 1 &&
  2714. getNumTypeConstituents(typeId) == (int)constituents.size()));
  2715. if (generatingOpCodeForSpecConst) {
  2716. // Sometime, even in spec-constant-op mode, the constant composite to be
  2717. // constructed may not be a specialization constant.
  2718. // e.g.:
  2719. // const mat2 m2 = mat2(a_spec_const, a_front_end_const, another_front_end_const, third_front_end_const);
  2720. // The first column vector should be a spec constant one, as a_spec_const is a spec constant.
  2721. // The second column vector should NOT be spec constant, as it does not contain any spec constants.
  2722. // To handle such cases, we check the constituents of the constant vector to determine whether this
  2723. // vector should be created as a spec constant.
  2724. return makeCompositeConstant(typeId, constituents,
  2725. std::any_of(constituents.begin(), constituents.end(),
  2726. [&](spv::Id id) { return isSpecConstant(id); }));
  2727. }
  2728. Instruction* op = new Instruction(getUniqueId(), typeId, OpCompositeConstruct);
  2729. for (int c = 0; c < (int)constituents.size(); ++c)
  2730. op->addIdOperand(constituents[c]);
  2731. buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
  2732. return op->getResultId();
  2733. }
  2734. // Vector or scalar constructor
  2735. Id Builder::createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
  2736. {
  2737. Id result = NoResult;
  2738. unsigned int numTargetComponents = getNumTypeComponents(resultTypeId);
  2739. unsigned int targetComponent = 0;
  2740. // Special case: when calling a vector constructor with a single scalar
  2741. // argument, smear the scalar
  2742. if (sources.size() == 1 && isScalar(sources[0]) && numTargetComponents > 1)
  2743. return smearScalar(precision, sources[0], resultTypeId);
  2744. // accumulate the arguments for OpCompositeConstruct
  2745. std::vector<Id> constituents;
  2746. Id scalarTypeId = getScalarTypeId(resultTypeId);
  2747. // lambda to store the result of visiting an argument component
  2748. const auto latchResult = [&](Id comp) {
  2749. if (numTargetComponents > 1)
  2750. constituents.push_back(comp);
  2751. else
  2752. result = comp;
  2753. ++targetComponent;
  2754. };
  2755. // lambda to visit a vector argument's components
  2756. const auto accumulateVectorConstituents = [&](Id sourceArg) {
  2757. unsigned int sourceSize = getNumComponents(sourceArg);
  2758. unsigned int sourcesToUse = sourceSize;
  2759. if (sourcesToUse + targetComponent > numTargetComponents)
  2760. sourcesToUse = numTargetComponents - targetComponent;
  2761. for (unsigned int s = 0; s < sourcesToUse; ++s) {
  2762. std::vector<unsigned> swiz;
  2763. swiz.push_back(s);
  2764. latchResult(createRvalueSwizzle(precision, scalarTypeId, sourceArg, swiz));
  2765. }
  2766. };
  2767. // lambda to visit a matrix argument's components
  2768. const auto accumulateMatrixConstituents = [&](Id sourceArg) {
  2769. unsigned int sourceSize = getNumColumns(sourceArg) * getNumRows(sourceArg);
  2770. unsigned int sourcesToUse = sourceSize;
  2771. if (sourcesToUse + targetComponent > numTargetComponents)
  2772. sourcesToUse = numTargetComponents - targetComponent;
  2773. int col = 0;
  2774. int row = 0;
  2775. for (unsigned int s = 0; s < sourcesToUse; ++s) {
  2776. if (row >= getNumRows(sourceArg)) {
  2777. row = 0;
  2778. col++;
  2779. }
  2780. std::vector<Id> indexes;
  2781. indexes.push_back(col);
  2782. indexes.push_back(row);
  2783. latchResult(createCompositeExtract(sourceArg, scalarTypeId, indexes));
  2784. row++;
  2785. }
  2786. };
  2787. // Go through the source arguments, each one could have either
  2788. // a single or multiple components to contribute.
  2789. for (unsigned int i = 0; i < sources.size(); ++i) {
  2790. if (isScalar(sources[i]) || isPointer(sources[i]))
  2791. latchResult(sources[i]);
  2792. else if (isVector(sources[i]))
  2793. accumulateVectorConstituents(sources[i]);
  2794. else if (isMatrix(sources[i]))
  2795. accumulateMatrixConstituents(sources[i]);
  2796. else
  2797. assert(0);
  2798. if (targetComponent >= numTargetComponents)
  2799. break;
  2800. }
  2801. // If the result is a vector, make it from the gathered constituents.
  2802. if (constituents.size() > 0)
  2803. result = createCompositeConstruct(resultTypeId, constituents);
  2804. return setPrecision(result, precision);
  2805. }
  2806. // Comments in header
  2807. Id Builder::createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
  2808. {
  2809. Id componentTypeId = getScalarTypeId(resultTypeId);
  2810. int numCols = getTypeNumColumns(resultTypeId);
  2811. int numRows = getTypeNumRows(resultTypeId);
  2812. Instruction* instr = module.getInstruction(componentTypeId);
  2813. const unsigned bitCount = instr->getImmediateOperand(0);
  2814. // Optimize matrix constructed from a bigger matrix
  2815. if (isMatrix(sources[0]) && getNumColumns(sources[0]) >= numCols && getNumRows(sources[0]) >= numRows) {
  2816. // To truncate the matrix to a smaller number of rows/columns, we need to:
  2817. // 1. For each column, extract the column and truncate it to the required size using shuffle
  2818. // 2. Assemble the resulting matrix from all columns
  2819. Id matrix = sources[0];
  2820. Id columnTypeId = getContainedTypeId(resultTypeId);
  2821. Id sourceColumnTypeId = getContainedTypeId(getTypeId(matrix));
  2822. std::vector<unsigned> channels;
  2823. for (int row = 0; row < numRows; ++row)
  2824. channels.push_back(row);
  2825. std::vector<Id> matrixColumns;
  2826. for (int col = 0; col < numCols; ++col) {
  2827. std::vector<unsigned> indexes;
  2828. indexes.push_back(col);
  2829. Id colv = createCompositeExtract(matrix, sourceColumnTypeId, indexes);
  2830. setPrecision(colv, precision);
  2831. if (numRows != getNumRows(matrix)) {
  2832. matrixColumns.push_back(createRvalueSwizzle(precision, columnTypeId, colv, channels));
  2833. } else {
  2834. matrixColumns.push_back(colv);
  2835. }
  2836. }
  2837. return setPrecision(createCompositeConstruct(resultTypeId, matrixColumns), precision);
  2838. }
  2839. // Otherwise, will use a two step process
  2840. // 1. make a compile-time 2D array of values
  2841. // 2. construct a matrix from that array
  2842. // Step 1.
  2843. // initialize the array to the identity matrix
  2844. Id ids[maxMatrixSize][maxMatrixSize];
  2845. Id one = (bitCount == 64 ? makeDoubleConstant(1.0) : makeFloatConstant(1.0));
  2846. Id zero = (bitCount == 64 ? makeDoubleConstant(0.0) : makeFloatConstant(0.0));
  2847. for (int col = 0; col < 4; ++col) {
  2848. for (int row = 0; row < 4; ++row) {
  2849. if (col == row)
  2850. ids[col][row] = one;
  2851. else
  2852. ids[col][row] = zero;
  2853. }
  2854. }
  2855. // modify components as dictated by the arguments
  2856. if (sources.size() == 1 && isScalar(sources[0])) {
  2857. // a single scalar; resets the diagonals
  2858. for (int col = 0; col < 4; ++col)
  2859. ids[col][col] = sources[0];
  2860. } else if (isMatrix(sources[0])) {
  2861. // constructing from another matrix; copy over the parts that exist in both the argument and constructee
  2862. Id matrix = sources[0];
  2863. int minCols = std::min(numCols, getNumColumns(matrix));
  2864. int minRows = std::min(numRows, getNumRows(matrix));
  2865. for (int col = 0; col < minCols; ++col) {
  2866. std::vector<unsigned> indexes;
  2867. indexes.push_back(col);
  2868. for (int row = 0; row < minRows; ++row) {
  2869. indexes.push_back(row);
  2870. ids[col][row] = createCompositeExtract(matrix, componentTypeId, indexes);
  2871. indexes.pop_back();
  2872. setPrecision(ids[col][row], precision);
  2873. }
  2874. }
  2875. } else {
  2876. // fill in the matrix in column-major order with whatever argument components are available
  2877. int row = 0;
  2878. int col = 0;
  2879. for (int arg = 0; arg < (int)sources.size() && col < numCols; ++arg) {
  2880. Id argComp = sources[arg];
  2881. for (int comp = 0; comp < getNumComponents(sources[arg]); ++comp) {
  2882. if (getNumComponents(sources[arg]) > 1) {
  2883. argComp = createCompositeExtract(sources[arg], componentTypeId, comp);
  2884. setPrecision(argComp, precision);
  2885. }
  2886. ids[col][row++] = argComp;
  2887. if (row == numRows) {
  2888. row = 0;
  2889. col++;
  2890. }
  2891. if (col == numCols) {
  2892. // If more components are provided than fit the matrix, discard the rest.
  2893. break;
  2894. }
  2895. }
  2896. }
  2897. }
  2898. // Step 2: Construct a matrix from that array.
  2899. // First make the column vectors, then make the matrix.
  2900. // make the column vectors
  2901. Id columnTypeId = getContainedTypeId(resultTypeId);
  2902. std::vector<Id> matrixColumns;
  2903. for (int col = 0; col < numCols; ++col) {
  2904. std::vector<Id> vectorComponents;
  2905. for (int row = 0; row < numRows; ++row)
  2906. vectorComponents.push_back(ids[col][row]);
  2907. Id column = createCompositeConstruct(columnTypeId, vectorComponents);
  2908. setPrecision(column, precision);
  2909. matrixColumns.push_back(column);
  2910. }
  2911. // make the matrix
  2912. return setPrecision(createCompositeConstruct(resultTypeId, matrixColumns), precision);
  2913. }
  2914. // Comments in header
  2915. Builder::If::If(Id cond, unsigned int ctrl, Builder& gb) :
  2916. builder(gb),
  2917. condition(cond),
  2918. control(ctrl),
  2919. elseBlock(nullptr)
  2920. {
  2921. function = &builder.getBuildPoint()->getParent();
  2922. // make the blocks, but only put the then-block into the function,
  2923. // the else-block and merge-block will be added later, in order, after
  2924. // earlier code is emitted
  2925. thenBlock = new Block(builder.getUniqueId(), *function);
  2926. mergeBlock = new Block(builder.getUniqueId(), *function);
  2927. // Save the current block, so that we can add in the flow control split when
  2928. // makeEndIf is called.
  2929. headerBlock = builder.getBuildPoint();
  2930. function->addBlock(thenBlock);
  2931. builder.setBuildPoint(thenBlock);
  2932. }
  2933. // Comments in header
  2934. void Builder::If::makeBeginElse()
  2935. {
  2936. // Close out the "then" by having it jump to the mergeBlock
  2937. builder.createBranch(mergeBlock);
  2938. // Make the first else block and add it to the function
  2939. elseBlock = new Block(builder.getUniqueId(), *function);
  2940. function->addBlock(elseBlock);
  2941. // Start building the else block
  2942. builder.setBuildPoint(elseBlock);
  2943. }
  2944. // Comments in header
  2945. void Builder::If::makeEndIf()
  2946. {
  2947. // jump to the merge block
  2948. builder.createBranch(mergeBlock);
  2949. // Go back to the headerBlock and make the flow control split
  2950. builder.setBuildPoint(headerBlock);
  2951. builder.createSelectionMerge(mergeBlock, control);
  2952. if (elseBlock)
  2953. builder.createConditionalBranch(condition, thenBlock, elseBlock);
  2954. else
  2955. builder.createConditionalBranch(condition, thenBlock, mergeBlock);
  2956. // add the merge block to the function
  2957. function->addBlock(mergeBlock);
  2958. builder.setBuildPoint(mergeBlock);
  2959. }
  2960. // Comments in header
  2961. void Builder::makeSwitch(Id selector, unsigned int control, int numSegments, const std::vector<int>& caseValues,
  2962. const std::vector<int>& valueIndexToSegment, int defaultSegment,
  2963. std::vector<Block*>& segmentBlocks)
  2964. {
  2965. Function& function = buildPoint->getParent();
  2966. // make all the blocks
  2967. for (int s = 0; s < numSegments; ++s)
  2968. segmentBlocks.push_back(new Block(getUniqueId(), function));
  2969. Block* mergeBlock = new Block(getUniqueId(), function);
  2970. // make and insert the switch's selection-merge instruction
  2971. createSelectionMerge(mergeBlock, control);
  2972. // make the switch instruction
  2973. Instruction* switchInst = new Instruction(NoResult, NoType, OpSwitch);
  2974. switchInst->addIdOperand(selector);
  2975. auto defaultOrMerge = (defaultSegment >= 0) ? segmentBlocks[defaultSegment] : mergeBlock;
  2976. switchInst->addIdOperand(defaultOrMerge->getId());
  2977. defaultOrMerge->addPredecessor(buildPoint);
  2978. for (int i = 0; i < (int)caseValues.size(); ++i) {
  2979. switchInst->addImmediateOperand(caseValues[i]);
  2980. switchInst->addIdOperand(segmentBlocks[valueIndexToSegment[i]]->getId());
  2981. segmentBlocks[valueIndexToSegment[i]]->addPredecessor(buildPoint);
  2982. }
  2983. buildPoint->addInstruction(std::unique_ptr<Instruction>(switchInst));
  2984. // push the merge block
  2985. switchMerges.push(mergeBlock);
  2986. }
  2987. // Comments in header
  2988. void Builder::addSwitchBreak()
  2989. {
  2990. // branch to the top of the merge block stack
  2991. createBranch(switchMerges.top());
  2992. createAndSetNoPredecessorBlock("post-switch-break");
  2993. }
  2994. // Comments in header
  2995. void Builder::nextSwitchSegment(std::vector<Block*>& segmentBlock, int nextSegment)
  2996. {
  2997. int lastSegment = nextSegment - 1;
  2998. if (lastSegment >= 0) {
  2999. // Close out previous segment by jumping, if necessary, to next segment
  3000. if (! buildPoint->isTerminated())
  3001. createBranch(segmentBlock[nextSegment]);
  3002. }
  3003. Block* block = segmentBlock[nextSegment];
  3004. block->getParent().addBlock(block);
  3005. setBuildPoint(block);
  3006. }
  3007. // Comments in header
  3008. void Builder::endSwitch(std::vector<Block*>& /*segmentBlock*/)
  3009. {
  3010. // Close out previous segment by jumping, if necessary, to next segment
  3011. if (! buildPoint->isTerminated())
  3012. addSwitchBreak();
  3013. switchMerges.top()->getParent().addBlock(switchMerges.top());
  3014. setBuildPoint(switchMerges.top());
  3015. switchMerges.pop();
  3016. }
  3017. Block& Builder::makeNewBlock()
  3018. {
  3019. Function& function = buildPoint->getParent();
  3020. auto block = new Block(getUniqueId(), function);
  3021. function.addBlock(block);
  3022. return *block;
  3023. }
  3024. Builder::LoopBlocks& Builder::makeNewLoop()
  3025. {
  3026. // This verbosity is needed to simultaneously get the same behavior
  3027. // everywhere (id's in the same order), have a syntax that works
  3028. // across lots of versions of C++, have no warnings from pedantic
  3029. // compilation modes, and leave the rest of the code alone.
  3030. Block& head = makeNewBlock();
  3031. Block& body = makeNewBlock();
  3032. Block& merge = makeNewBlock();
  3033. Block& continue_target = makeNewBlock();
  3034. LoopBlocks blocks(head, body, merge, continue_target);
  3035. loops.push(blocks);
  3036. return loops.top();
  3037. }
  3038. void Builder::createLoopContinue()
  3039. {
  3040. createBranch(&loops.top().continue_target);
  3041. // Set up a block for dead code.
  3042. createAndSetNoPredecessorBlock("post-loop-continue");
  3043. }
  3044. void Builder::createLoopExit()
  3045. {
  3046. createBranch(&loops.top().merge);
  3047. // Set up a block for dead code.
  3048. createAndSetNoPredecessorBlock("post-loop-break");
  3049. }
  3050. void Builder::closeLoop()
  3051. {
  3052. loops.pop();
  3053. }
  3054. void Builder::clearAccessChain()
  3055. {
  3056. accessChain.base = NoResult;
  3057. accessChain.indexChain.clear();
  3058. accessChain.instr = NoResult;
  3059. accessChain.swizzle.clear();
  3060. accessChain.component = NoResult;
  3061. accessChain.preSwizzleBaseType = NoType;
  3062. accessChain.isRValue = false;
  3063. accessChain.coherentFlags.clear();
  3064. accessChain.alignment = 0;
  3065. }
  3066. // Comments in header
  3067. void Builder::accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType,
  3068. AccessChain::CoherentFlags coherentFlags, unsigned int alignment)
  3069. {
  3070. accessChain.coherentFlags |= coherentFlags;
  3071. accessChain.alignment |= alignment;
  3072. // swizzles can be stacked in GLSL, but simplified to a single
  3073. // one here; the base type doesn't change
  3074. if (accessChain.preSwizzleBaseType == NoType)
  3075. accessChain.preSwizzleBaseType = preSwizzleBaseType;
  3076. // if needed, propagate the swizzle for the current access chain
  3077. if (accessChain.swizzle.size() > 0) {
  3078. std::vector<unsigned> oldSwizzle = accessChain.swizzle;
  3079. accessChain.swizzle.resize(0);
  3080. for (unsigned int i = 0; i < swizzle.size(); ++i) {
  3081. assert(swizzle[i] < oldSwizzle.size());
  3082. accessChain.swizzle.push_back(oldSwizzle[swizzle[i]]);
  3083. }
  3084. } else
  3085. accessChain.swizzle = swizzle;
  3086. // determine if we need to track this swizzle anymore
  3087. simplifyAccessChainSwizzle();
  3088. }
  3089. // Comments in header
  3090. void Builder::accessChainStore(Id rvalue, Decoration nonUniform, spv::MemoryAccessMask memoryAccess, spv::Scope scope, unsigned int alignment)
  3091. {
  3092. assert(accessChain.isRValue == false);
  3093. transferAccessChainSwizzle(true);
  3094. // If a swizzle exists and is not full and is not dynamic, then the swizzle will be broken into individual stores.
  3095. if (accessChain.swizzle.size() > 0 &&
  3096. getNumTypeComponents(getResultingAccessChainType()) != (int)accessChain.swizzle.size() &&
  3097. accessChain.component == NoResult) {
  3098. for (unsigned int i = 0; i < accessChain.swizzle.size(); ++i) {
  3099. accessChain.indexChain.push_back(makeUintConstant(accessChain.swizzle[i]));
  3100. accessChain.instr = NoResult;
  3101. Id base = collapseAccessChain();
  3102. addDecoration(base, nonUniform);
  3103. accessChain.indexChain.pop_back();
  3104. accessChain.instr = NoResult;
  3105. // dynamic component should be gone
  3106. assert(accessChain.component == NoResult);
  3107. Id source = createCompositeExtract(rvalue, getContainedTypeId(getTypeId(rvalue)), i);
  3108. // take LSB of alignment
  3109. alignment = alignment & ~(alignment & (alignment-1));
  3110. if (getStorageClass(base) == StorageClassPhysicalStorageBufferEXT) {
  3111. memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
  3112. }
  3113. createStore(source, base, memoryAccess, scope, alignment);
  3114. }
  3115. }
  3116. else {
  3117. Id base = collapseAccessChain();
  3118. addDecoration(base, nonUniform);
  3119. Id source = rvalue;
  3120. // dynamic component should be gone
  3121. assert(accessChain.component == NoResult);
  3122. // If swizzle still exists, it may be out-of-order, we must load the target vector,
  3123. // extract and insert elements to perform writeMask and/or swizzle.
  3124. if (accessChain.swizzle.size() > 0) {
  3125. Id tempBaseId = createLoad(base, spv::NoPrecision);
  3126. source = createLvalueSwizzle(getTypeId(tempBaseId), tempBaseId, source, accessChain.swizzle);
  3127. }
  3128. // take LSB of alignment
  3129. alignment = alignment & ~(alignment & (alignment-1));
  3130. if (getStorageClass(base) == StorageClassPhysicalStorageBufferEXT) {
  3131. memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
  3132. }
  3133. createStore(source, base, memoryAccess, scope, alignment);
  3134. }
  3135. }
  3136. // Comments in header
  3137. Id Builder::accessChainLoad(Decoration precision, Decoration l_nonUniform,
  3138. Decoration r_nonUniform, Id resultType, spv::MemoryAccessMask memoryAccess,
  3139. spv::Scope scope, unsigned int alignment)
  3140. {
  3141. Id id;
  3142. if (accessChain.isRValue) {
  3143. // transfer access chain, but try to stay in registers
  3144. transferAccessChainSwizzle(false);
  3145. if (accessChain.indexChain.size() > 0) {
  3146. Id swizzleBase = accessChain.preSwizzleBaseType != NoType ? accessChain.preSwizzleBaseType : resultType;
  3147. // if all the accesses are constants, we can use OpCompositeExtract
  3148. std::vector<unsigned> indexes;
  3149. bool constant = true;
  3150. for (int i = 0; i < (int)accessChain.indexChain.size(); ++i) {
  3151. if (isConstantScalar(accessChain.indexChain[i]))
  3152. indexes.push_back(getConstantScalar(accessChain.indexChain[i]));
  3153. else {
  3154. constant = false;
  3155. break;
  3156. }
  3157. }
  3158. if (constant) {
  3159. id = createCompositeExtract(accessChain.base, swizzleBase, indexes);
  3160. setPrecision(id, precision);
  3161. } else {
  3162. Id lValue = NoResult;
  3163. if (spvVersion >= Spv_1_4 && isValidInitializer(accessChain.base)) {
  3164. // make a new function variable for this r-value, using an initializer,
  3165. // and mark it as NonWritable so that downstream it can be detected as a lookup
  3166. // table
  3167. lValue = createVariable(NoPrecision, StorageClassFunction, getTypeId(accessChain.base),
  3168. "indexable", accessChain.base);
  3169. addDecoration(lValue, DecorationNonWritable);
  3170. } else {
  3171. lValue = createVariable(NoPrecision, StorageClassFunction, getTypeId(accessChain.base),
  3172. "indexable");
  3173. // store into it
  3174. createStore(accessChain.base, lValue);
  3175. }
  3176. // move base to the new variable
  3177. accessChain.base = lValue;
  3178. accessChain.isRValue = false;
  3179. // load through the access chain
  3180. id = createLoad(collapseAccessChain(), precision);
  3181. }
  3182. } else
  3183. id = accessChain.base; // no precision, it was set when this was defined
  3184. } else {
  3185. transferAccessChainSwizzle(true);
  3186. // take LSB of alignment
  3187. alignment = alignment & ~(alignment & (alignment-1));
  3188. if (getStorageClass(accessChain.base) == StorageClassPhysicalStorageBufferEXT) {
  3189. memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
  3190. }
  3191. // load through the access chain
  3192. id = collapseAccessChain();
  3193. // Apply nonuniform both to the access chain and the loaded value.
  3194. // Buffer accesses need the access chain decorated, and this is where
  3195. // loaded image types get decorated. TODO: This should maybe move to
  3196. // createImageTextureFunctionCall.
  3197. addDecoration(id, l_nonUniform);
  3198. id = createLoad(id, precision, memoryAccess, scope, alignment);
  3199. addDecoration(id, r_nonUniform);
  3200. }
  3201. // Done, unless there are swizzles to do
  3202. if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
  3203. return id;
  3204. // Do remaining swizzling
  3205. // Do the basic swizzle
  3206. if (accessChain.swizzle.size() > 0) {
  3207. Id swizzledType = getScalarTypeId(getTypeId(id));
  3208. if (accessChain.swizzle.size() > 1)
  3209. swizzledType = makeVectorType(swizzledType, (int)accessChain.swizzle.size());
  3210. id = createRvalueSwizzle(precision, swizzledType, id, accessChain.swizzle);
  3211. }
  3212. // Do the dynamic component
  3213. if (accessChain.component != NoResult)
  3214. id = setPrecision(createVectorExtractDynamic(id, resultType, accessChain.component), precision);
  3215. addDecoration(id, r_nonUniform);
  3216. return id;
  3217. }
  3218. Id Builder::accessChainGetLValue()
  3219. {
  3220. assert(accessChain.isRValue == false);
  3221. transferAccessChainSwizzle(true);
  3222. Id lvalue = collapseAccessChain();
  3223. // If swizzle exists, it is out-of-order or not full, we must load the target vector,
  3224. // extract and insert elements to perform writeMask and/or swizzle. This does not
  3225. // go with getting a direct l-value pointer.
  3226. assert(accessChain.swizzle.size() == 0);
  3227. assert(accessChain.component == NoResult);
  3228. return lvalue;
  3229. }
  3230. // comment in header
  3231. Id Builder::accessChainGetInferredType()
  3232. {
  3233. // anything to operate on?
  3234. if (accessChain.base == NoResult)
  3235. return NoType;
  3236. Id type = getTypeId(accessChain.base);
  3237. // do initial dereference
  3238. if (! accessChain.isRValue)
  3239. type = getContainedTypeId(type);
  3240. // dereference each index
  3241. for (auto it = accessChain.indexChain.cbegin(); it != accessChain.indexChain.cend(); ++it) {
  3242. if (isStructType(type))
  3243. type = getContainedTypeId(type, getConstantScalar(*it));
  3244. else
  3245. type = getContainedTypeId(type);
  3246. }
  3247. // dereference swizzle
  3248. if (accessChain.swizzle.size() == 1)
  3249. type = getContainedTypeId(type);
  3250. else if (accessChain.swizzle.size() > 1)
  3251. type = makeVectorType(getContainedTypeId(type), (int)accessChain.swizzle.size());
  3252. // dereference component selection
  3253. if (accessChain.component)
  3254. type = getContainedTypeId(type);
  3255. return type;
  3256. }
  3257. void Builder::dump(std::vector<unsigned int>& out) const
  3258. {
  3259. // Header, before first instructions:
  3260. out.push_back(MagicNumber);
  3261. out.push_back(spvVersion);
  3262. out.push_back(builderNumber);
  3263. out.push_back(uniqueId + 1);
  3264. out.push_back(0);
  3265. // Capabilities
  3266. for (auto it = capabilities.cbegin(); it != capabilities.cend(); ++it) {
  3267. Instruction capInst(0, 0, OpCapability);
  3268. capInst.addImmediateOperand(*it);
  3269. capInst.dump(out);
  3270. }
  3271. for (auto it = extensions.cbegin(); it != extensions.cend(); ++it) {
  3272. Instruction extInst(0, 0, OpExtension);
  3273. extInst.addStringOperand(it->c_str());
  3274. extInst.dump(out);
  3275. }
  3276. dumpInstructions(out, imports);
  3277. Instruction memInst(0, 0, OpMemoryModel);
  3278. memInst.addImmediateOperand(addressModel);
  3279. memInst.addImmediateOperand(memoryModel);
  3280. memInst.dump(out);
  3281. // Instructions saved up while building:
  3282. dumpInstructions(out, entryPoints);
  3283. dumpInstructions(out, executionModes);
  3284. // Debug instructions
  3285. dumpInstructions(out, strings);
  3286. dumpSourceInstructions(out);
  3287. for (int e = 0; e < (int)sourceExtensions.size(); ++e) {
  3288. Instruction sourceExtInst(0, 0, OpSourceExtension);
  3289. sourceExtInst.addStringOperand(sourceExtensions[e]);
  3290. sourceExtInst.dump(out);
  3291. }
  3292. dumpInstructions(out, names);
  3293. dumpModuleProcesses(out);
  3294. // Annotation instructions
  3295. dumpInstructions(out, decorations);
  3296. dumpInstructions(out, constantsTypesGlobals);
  3297. dumpInstructions(out, externals);
  3298. // The functions
  3299. module.dump(out);
  3300. }
  3301. //
  3302. // Protected methods.
  3303. //
  3304. // Turn the described access chain in 'accessChain' into an instruction(s)
  3305. // computing its address. This *cannot* include complex swizzles, which must
  3306. // be handled after this is called.
  3307. //
  3308. // Can generate code.
  3309. Id Builder::collapseAccessChain()
  3310. {
  3311. assert(accessChain.isRValue == false);
  3312. // did we already emit an access chain for this?
  3313. if (accessChain.instr != NoResult)
  3314. return accessChain.instr;
  3315. // If we have a dynamic component, we can still transfer
  3316. // that into a final operand to the access chain. We need to remap the
  3317. // dynamic component through the swizzle to get a new dynamic component to
  3318. // update.
  3319. //
  3320. // This was not done in transferAccessChainSwizzle() because it might
  3321. // generate code.
  3322. remapDynamicSwizzle();
  3323. if (accessChain.component != NoResult) {
  3324. // transfer the dynamic component to the access chain
  3325. accessChain.indexChain.push_back(accessChain.component);
  3326. accessChain.component = NoResult;
  3327. }
  3328. // note that non-trivial swizzling is left pending
  3329. // do we have an access chain?
  3330. if (accessChain.indexChain.size() == 0)
  3331. return accessChain.base;
  3332. // emit the access chain
  3333. StorageClass storageClass = (StorageClass)module.getStorageClass(getTypeId(accessChain.base));
  3334. accessChain.instr = createAccessChain(storageClass, accessChain.base, accessChain.indexChain);
  3335. return accessChain.instr;
  3336. }
  3337. // For a dynamic component selection of a swizzle.
  3338. //
  3339. // Turn the swizzle and dynamic component into just a dynamic component.
  3340. //
  3341. // Generates code.
  3342. void Builder::remapDynamicSwizzle()
  3343. {
  3344. // do we have a swizzle to remap a dynamic component through?
  3345. if (accessChain.component != NoResult && accessChain.swizzle.size() > 1) {
  3346. // build a vector of the swizzle for the component to map into
  3347. std::vector<Id> components;
  3348. for (int c = 0; c < (int)accessChain.swizzle.size(); ++c)
  3349. components.push_back(makeUintConstant(accessChain.swizzle[c]));
  3350. Id mapType = makeVectorType(makeUintType(32), (int)accessChain.swizzle.size());
  3351. Id map = makeCompositeConstant(mapType, components);
  3352. // use it
  3353. accessChain.component = createVectorExtractDynamic(map, makeUintType(32), accessChain.component);
  3354. accessChain.swizzle.clear();
  3355. }
  3356. }
  3357. // clear out swizzle if it is redundant, that is reselecting the same components
  3358. // that would be present without the swizzle.
  3359. void Builder::simplifyAccessChainSwizzle()
  3360. {
  3361. // If the swizzle has fewer components than the vector, it is subsetting, and must stay
  3362. // to preserve that fact.
  3363. if (getNumTypeComponents(accessChain.preSwizzleBaseType) > (int)accessChain.swizzle.size())
  3364. return;
  3365. // if components are out of order, it is a swizzle
  3366. for (unsigned int i = 0; i < accessChain.swizzle.size(); ++i) {
  3367. if (i != accessChain.swizzle[i])
  3368. return;
  3369. }
  3370. // otherwise, there is no need to track this swizzle
  3371. accessChain.swizzle.clear();
  3372. if (accessChain.component == NoResult)
  3373. accessChain.preSwizzleBaseType = NoType;
  3374. }
  3375. // To the extent any swizzling can become part of the chain
  3376. // of accesses instead of a post operation, make it so.
  3377. // If 'dynamic' is true, include transferring the dynamic component,
  3378. // otherwise, leave it pending.
  3379. //
  3380. // Does not generate code. just updates the access chain.
  3381. void Builder::transferAccessChainSwizzle(bool dynamic)
  3382. {
  3383. // non existent?
  3384. if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
  3385. return;
  3386. // too complex?
  3387. // (this requires either a swizzle, or generating code for a dynamic component)
  3388. if (accessChain.swizzle.size() > 1)
  3389. return;
  3390. // single component, either in the swizzle and/or dynamic component
  3391. if (accessChain.swizzle.size() == 1) {
  3392. assert(accessChain.component == NoResult);
  3393. // handle static component selection
  3394. accessChain.indexChain.push_back(makeUintConstant(accessChain.swizzle.front()));
  3395. accessChain.swizzle.clear();
  3396. accessChain.preSwizzleBaseType = NoType;
  3397. } else if (dynamic && accessChain.component != NoResult) {
  3398. assert(accessChain.swizzle.size() == 0);
  3399. // handle dynamic component
  3400. accessChain.indexChain.push_back(accessChain.component);
  3401. accessChain.preSwizzleBaseType = NoType;
  3402. accessChain.component = NoResult;
  3403. }
  3404. }
  3405. // Utility method for creating a new block and setting the insert point to
  3406. // be in it. This is useful for flow-control operations that need a "dummy"
  3407. // block proceeding them (e.g. instructions after a discard, etc).
  3408. void Builder::createAndSetNoPredecessorBlock(const char* /*name*/)
  3409. {
  3410. Block* block = new Block(getUniqueId(), buildPoint->getParent());
  3411. block->setUnreachable();
  3412. buildPoint->getParent().addBlock(block);
  3413. setBuildPoint(block);
  3414. // if (name)
  3415. // addName(block->getId(), name);
  3416. }
  3417. // Comments in header
  3418. void Builder::createBranch(Block* block)
  3419. {
  3420. Instruction* branch = new Instruction(OpBranch);
  3421. branch->addIdOperand(block->getId());
  3422. buildPoint->addInstruction(std::unique_ptr<Instruction>(branch));
  3423. block->addPredecessor(buildPoint);
  3424. }
  3425. void Builder::createSelectionMerge(Block* mergeBlock, unsigned int control)
  3426. {
  3427. Instruction* merge = new Instruction(OpSelectionMerge);
  3428. merge->addIdOperand(mergeBlock->getId());
  3429. merge->addImmediateOperand(control);
  3430. buildPoint->addInstruction(std::unique_ptr<Instruction>(merge));
  3431. }
  3432. void Builder::createLoopMerge(Block* mergeBlock, Block* continueBlock, unsigned int control,
  3433. const std::vector<unsigned int>& operands)
  3434. {
  3435. Instruction* merge = new Instruction(OpLoopMerge);
  3436. merge->addIdOperand(mergeBlock->getId());
  3437. merge->addIdOperand(continueBlock->getId());
  3438. merge->addImmediateOperand(control);
  3439. for (int op = 0; op < (int)operands.size(); ++op)
  3440. merge->addImmediateOperand(operands[op]);
  3441. buildPoint->addInstruction(std::unique_ptr<Instruction>(merge));
  3442. }
  3443. void Builder::createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock)
  3444. {
  3445. Instruction* branch = new Instruction(OpBranchConditional);
  3446. branch->addIdOperand(condition);
  3447. branch->addIdOperand(thenBlock->getId());
  3448. branch->addIdOperand(elseBlock->getId());
  3449. buildPoint->addInstruction(std::unique_ptr<Instruction>(branch));
  3450. thenBlock->addPredecessor(buildPoint);
  3451. elseBlock->addPredecessor(buildPoint);
  3452. }
  3453. // OpSource
  3454. // [OpSourceContinued]
  3455. // ...
  3456. void Builder::dumpSourceInstructions(const spv::Id fileId, const std::string& text,
  3457. std::vector<unsigned int>& out) const
  3458. {
  3459. const int maxWordCount = 0xFFFF;
  3460. const int opSourceWordCount = 4;
  3461. const int nonNullBytesPerInstruction = 4 * (maxWordCount - opSourceWordCount) - 1;
  3462. if (sourceLang != SourceLanguageUnknown) {
  3463. // OpSource Language Version File Source
  3464. Instruction sourceInst(NoResult, NoType, OpSource);
  3465. sourceInst.addImmediateOperand(sourceLang);
  3466. sourceInst.addImmediateOperand(sourceVersion);
  3467. // File operand
  3468. if (fileId != NoResult) {
  3469. sourceInst.addIdOperand(fileId);
  3470. // Source operand
  3471. if (text.size() > 0) {
  3472. int nextByte = 0;
  3473. std::string subString;
  3474. while ((int)text.size() - nextByte > 0) {
  3475. subString = text.substr(nextByte, nonNullBytesPerInstruction);
  3476. if (nextByte == 0) {
  3477. // OpSource
  3478. sourceInst.addStringOperand(subString.c_str());
  3479. sourceInst.dump(out);
  3480. } else {
  3481. // OpSourcContinued
  3482. Instruction sourceContinuedInst(OpSourceContinued);
  3483. sourceContinuedInst.addStringOperand(subString.c_str());
  3484. sourceContinuedInst.dump(out);
  3485. }
  3486. nextByte += nonNullBytesPerInstruction;
  3487. }
  3488. } else
  3489. sourceInst.dump(out);
  3490. } else
  3491. sourceInst.dump(out);
  3492. }
  3493. }
  3494. // Dump an OpSource[Continued] sequence for the source and every include file
  3495. void Builder::dumpSourceInstructions(std::vector<unsigned int>& out) const
  3496. {
  3497. if (emitNonSemanticShaderDebugInfo) return;
  3498. dumpSourceInstructions(sourceFileStringId, sourceText, out);
  3499. for (auto iItr = includeFiles.begin(); iItr != includeFiles.end(); ++iItr)
  3500. dumpSourceInstructions(iItr->first, *iItr->second, out);
  3501. }
  3502. void Builder::dumpInstructions(std::vector<unsigned int>& out,
  3503. const std::vector<std::unique_ptr<Instruction> >& instructions) const
  3504. {
  3505. for (int i = 0; i < (int)instructions.size(); ++i) {
  3506. instructions[i]->dump(out);
  3507. }
  3508. }
  3509. void Builder::dumpModuleProcesses(std::vector<unsigned int>& out) const
  3510. {
  3511. for (int i = 0; i < (int)moduleProcesses.size(); ++i) {
  3512. Instruction moduleProcessed(OpModuleProcessed);
  3513. moduleProcessed.addStringOperand(moduleProcesses[i]);
  3514. moduleProcessed.dump(out);
  3515. }
  3516. }
  3517. } // end spv namespace