SpvBuilder.cpp 105 KB

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