SpvBuilder.cpp 112 KB

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