SpvBuilder.cpp 105 KB

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