SpvBuilder.cpp 109 KB

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