SpvBuilder.cpp 93 KB

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