SpvBuilder.cpp 103 KB

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