SPVRemapper.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. //
  2. // Copyright (C) 2015 LunarG, Inc.
  3. //
  4. // All rights reserved.
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions
  8. // are met:
  9. //
  10. // Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. //
  13. // Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following
  15. // disclaimer in the documentation and/or other materials provided
  16. // with the distribution.
  17. //
  18. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  19. // contributors may be used to endorse or promote products derived
  20. // from this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  25. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  26. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  27. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  28. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  30. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  31. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  32. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. // POSSIBILITY OF SUCH DAMAGE.
  34. //
  35. #include "SPVRemapper.h"
  36. #include "doc.h"
  37. #if !defined (use_cpp11)
  38. // ... not supported before C++11
  39. #else // defined (use_cpp11)
  40. #include <algorithm>
  41. #include <cassert>
  42. #include "../glslang/Include/Common.h"
  43. namespace spv {
  44. // By default, just abort on error. Can be overridden via RegisterErrorHandler
  45. spirvbin_t::errorfn_t spirvbin_t::errorHandler = [](const std::string&) { exit(5); };
  46. // By default, eat log messages. Can be overridden via RegisterLogHandler
  47. spirvbin_t::logfn_t spirvbin_t::logHandler = [](const std::string&) { };
  48. // This can be overridden to provide other message behavior if needed
  49. void spirvbin_t::msg(int minVerbosity, int indent, const std::string& txt) const
  50. {
  51. if (verbose >= minVerbosity)
  52. logHandler(std::string(indent, ' ') + txt);
  53. }
  54. // hash opcode, with special handling for OpExtInst
  55. std::uint32_t spirvbin_t::asOpCodeHash(unsigned word)
  56. {
  57. const spv::Op opCode = asOpCode(word);
  58. std::uint32_t offset = 0;
  59. switch (opCode) {
  60. case spv::OpExtInst:
  61. offset += asId(word + 4); break;
  62. default:
  63. break;
  64. }
  65. return opCode * 19 + offset; // 19 = small prime
  66. }
  67. spirvbin_t::range_t spirvbin_t::literalRange(spv::Op opCode) const
  68. {
  69. static const int maxCount = 1<<30;
  70. switch (opCode) {
  71. case spv::OpTypeFloat: // fall through...
  72. case spv::OpTypePointer: return range_t(2, 3);
  73. case spv::OpTypeInt: return range_t(2, 4);
  74. // TODO: case spv::OpTypeImage:
  75. // TODO: case spv::OpTypeSampledImage:
  76. case spv::OpTypeSampler: return range_t(3, 8);
  77. case spv::OpTypeVector: // fall through
  78. case spv::OpTypeMatrix: // ...
  79. case spv::OpTypePipe: return range_t(3, 4);
  80. case spv::OpConstant: return range_t(3, maxCount);
  81. default: return range_t(0, 0);
  82. }
  83. }
  84. spirvbin_t::range_t spirvbin_t::typeRange(spv::Op opCode) const
  85. {
  86. static const int maxCount = 1<<30;
  87. if (isConstOp(opCode))
  88. return range_t(1, 2);
  89. switch (opCode) {
  90. case spv::OpTypeVector: // fall through
  91. case spv::OpTypeMatrix: // ...
  92. case spv::OpTypeSampler: // ...
  93. case spv::OpTypeArray: // ...
  94. case spv::OpTypeRuntimeArray: // ...
  95. case spv::OpTypePipe: return range_t(2, 3);
  96. case spv::OpTypeStruct: // fall through
  97. case spv::OpTypeFunction: return range_t(2, maxCount);
  98. case spv::OpTypePointer: return range_t(3, 4);
  99. default: return range_t(0, 0);
  100. }
  101. }
  102. spirvbin_t::range_t spirvbin_t::constRange(spv::Op opCode) const
  103. {
  104. static const int maxCount = 1<<30;
  105. switch (opCode) {
  106. case spv::OpTypeArray: // fall through...
  107. case spv::OpTypeRuntimeArray: return range_t(3, 4);
  108. case spv::OpConstantComposite: return range_t(3, maxCount);
  109. default: return range_t(0, 0);
  110. }
  111. }
  112. // Return the size of a type in 32-bit words. This currently only
  113. // handles ints and floats, and is only invoked by queries which must be
  114. // integer types. If ever needed, it can be generalized.
  115. unsigned spirvbin_t::typeSizeInWords(spv::Id id) const
  116. {
  117. const unsigned typeStart = idPos(id);
  118. const spv::Op opCode = asOpCode(typeStart);
  119. if (errorLatch)
  120. return 0;
  121. switch (opCode) {
  122. case spv::OpTypeInt: // fall through...
  123. case spv::OpTypeFloat: return (spv[typeStart+2]+31)/32;
  124. default:
  125. return 0;
  126. }
  127. }
  128. // Looks up the type of a given const or variable ID, and
  129. // returns its size in 32-bit words.
  130. unsigned spirvbin_t::idTypeSizeInWords(spv::Id id) const
  131. {
  132. const auto tid_it = idTypeSizeMap.find(id);
  133. if (tid_it == idTypeSizeMap.end()) {
  134. error("type size for ID not found");
  135. return 0;
  136. }
  137. return tid_it->second;
  138. }
  139. // Is this an opcode we should remove when using --strip?
  140. bool spirvbin_t::isStripOp(spv::Op opCode, unsigned start) const
  141. {
  142. switch (opCode) {
  143. case spv::OpSource:
  144. case spv::OpSourceExtension:
  145. case spv::OpName:
  146. case spv::OpMemberName:
  147. case spv::OpLine :
  148. {
  149. const std::string name = literalString(start + 2);
  150. std::vector<std::string>::const_iterator it;
  151. for (it = stripWhiteList.begin(); it < stripWhiteList.end(); it++)
  152. {
  153. if (name.find(*it) != std::string::npos) {
  154. return false;
  155. }
  156. }
  157. return true;
  158. }
  159. default :
  160. return false;
  161. }
  162. }
  163. // Return true if this opcode is flow control
  164. bool spirvbin_t::isFlowCtrl(spv::Op opCode) const
  165. {
  166. switch (opCode) {
  167. case spv::OpBranchConditional:
  168. case spv::OpBranch:
  169. case spv::OpSwitch:
  170. case spv::OpLoopMerge:
  171. case spv::OpSelectionMerge:
  172. case spv::OpLabel:
  173. case spv::OpFunction:
  174. case spv::OpFunctionEnd: return true;
  175. default: return false;
  176. }
  177. }
  178. // Return true if this opcode defines a type
  179. bool spirvbin_t::isTypeOp(spv::Op opCode) const
  180. {
  181. switch (opCode) {
  182. case spv::OpTypeVoid:
  183. case spv::OpTypeBool:
  184. case spv::OpTypeInt:
  185. case spv::OpTypeFloat:
  186. case spv::OpTypeVector:
  187. case spv::OpTypeMatrix:
  188. case spv::OpTypeImage:
  189. case spv::OpTypeSampler:
  190. case spv::OpTypeArray:
  191. case spv::OpTypeRuntimeArray:
  192. case spv::OpTypeStruct:
  193. case spv::OpTypeOpaque:
  194. case spv::OpTypePointer:
  195. case spv::OpTypeFunction:
  196. case spv::OpTypeEvent:
  197. case spv::OpTypeDeviceEvent:
  198. case spv::OpTypeReserveId:
  199. case spv::OpTypeQueue:
  200. case spv::OpTypeSampledImage:
  201. case spv::OpTypePipe: return true;
  202. default: return false;
  203. }
  204. }
  205. // Return true if this opcode defines a constant
  206. bool spirvbin_t::isConstOp(spv::Op opCode) const
  207. {
  208. switch (opCode) {
  209. case spv::OpConstantSampler:
  210. error("unimplemented constant type");
  211. return true;
  212. case spv::OpConstantNull:
  213. case spv::OpConstantTrue:
  214. case spv::OpConstantFalse:
  215. case spv::OpConstantComposite:
  216. case spv::OpConstant:
  217. return true;
  218. default:
  219. return false;
  220. }
  221. }
  222. const auto inst_fn_nop = [](spv::Op, unsigned) { return false; };
  223. const auto op_fn_nop = [](spv::Id&) { };
  224. // g++ doesn't like these defined in the class proper in an anonymous namespace.
  225. // Dunno why. Also MSVC doesn't like the constexpr keyword. Also dunno why.
  226. // Defining them externally seems to please both compilers, so, here they are.
  227. const spv::Id spirvbin_t::unmapped = spv::Id(-10000);
  228. const spv::Id spirvbin_t::unused = spv::Id(-10001);
  229. const int spirvbin_t::header_size = 5;
  230. spv::Id spirvbin_t::nextUnusedId(spv::Id id)
  231. {
  232. while (isNewIdMapped(id)) // search for an unused ID
  233. ++id;
  234. return id;
  235. }
  236. spv::Id spirvbin_t::localId(spv::Id id, spv::Id newId)
  237. {
  238. //assert(id != spv::NoResult && newId != spv::NoResult);
  239. if (id > bound()) {
  240. error(std::string("ID out of range: ") + std::to_string(id));
  241. return spirvbin_t::unused;
  242. }
  243. if (id >= idMapL.size())
  244. idMapL.resize(id+1, unused);
  245. if (newId != unmapped && newId != unused) {
  246. if (isOldIdUnused(id)) {
  247. error(std::string("ID unused in module: ") + std::to_string(id));
  248. return spirvbin_t::unused;
  249. }
  250. if (!isOldIdUnmapped(id)) {
  251. error(std::string("ID already mapped: ") + std::to_string(id) + " -> "
  252. + std::to_string(localId(id)));
  253. return spirvbin_t::unused;
  254. }
  255. if (isNewIdMapped(newId)) {
  256. error(std::string("ID already used in module: ") + std::to_string(newId));
  257. return spirvbin_t::unused;
  258. }
  259. msg(4, 4, std::string("map: ") + std::to_string(id) + " -> " + std::to_string(newId));
  260. setMapped(newId);
  261. largestNewId = std::max(largestNewId, newId);
  262. }
  263. return idMapL[id] = newId;
  264. }
  265. // Parse a literal string from the SPIR binary and return it as an std::string
  266. // Due to C++11 RValue references, this doesn't copy the result string.
  267. std::string spirvbin_t::literalString(unsigned word) const
  268. {
  269. std::string literal;
  270. const spirword_t * pos = spv.data() + word;
  271. literal.reserve(16);
  272. do {
  273. spirword_t word = *pos;
  274. for (int i = 0; i < 4; i++) {
  275. char c = word & 0xff;
  276. if (c == '\0')
  277. return literal;
  278. literal += c;
  279. word >>= 8;
  280. }
  281. pos++;
  282. } while (true);
  283. }
  284. void spirvbin_t::applyMap()
  285. {
  286. msg(3, 2, std::string("Applying map: "));
  287. // Map local IDs through the ID map
  288. process(inst_fn_nop, // ignore instructions
  289. [this](spv::Id& id) {
  290. id = localId(id);
  291. if (errorLatch)
  292. return;
  293. assert(id != unused && id != unmapped);
  294. }
  295. );
  296. }
  297. // Find free IDs for anything we haven't mapped
  298. void spirvbin_t::mapRemainder()
  299. {
  300. msg(3, 2, std::string("Remapping remainder: "));
  301. spv::Id unusedId = 1; // can't use 0: that's NoResult
  302. spirword_t maxBound = 0;
  303. for (spv::Id id = 0; id < idMapL.size(); ++id) {
  304. if (isOldIdUnused(id))
  305. continue;
  306. // Find a new mapping for any used but unmapped IDs
  307. if (isOldIdUnmapped(id)) {
  308. localId(id, unusedId = nextUnusedId(unusedId));
  309. if (errorLatch)
  310. return;
  311. }
  312. if (isOldIdUnmapped(id)) {
  313. error(std::string("old ID not mapped: ") + std::to_string(id));
  314. return;
  315. }
  316. // Track max bound
  317. maxBound = std::max(maxBound, localId(id) + 1);
  318. if (errorLatch)
  319. return;
  320. }
  321. bound(maxBound); // reset header ID bound to as big as it now needs to be
  322. }
  323. // Mark debug instructions for stripping
  324. void spirvbin_t::stripDebug()
  325. {
  326. // Strip instructions in the stripOp set: debug info.
  327. process(
  328. [&](spv::Op opCode, unsigned start) {
  329. // remember opcodes we want to strip later
  330. if (isStripOp(opCode, start))
  331. stripInst(start);
  332. return true;
  333. },
  334. op_fn_nop);
  335. }
  336. // Mark instructions that refer to now-removed IDs for stripping
  337. void spirvbin_t::stripDeadRefs()
  338. {
  339. process(
  340. [&](spv::Op opCode, unsigned start) {
  341. // strip opcodes pointing to removed data
  342. switch (opCode) {
  343. case spv::OpName:
  344. case spv::OpMemberName:
  345. case spv::OpDecorate:
  346. case spv::OpMemberDecorate:
  347. if (idPosR.find(asId(start+1)) == idPosR.end())
  348. stripInst(start);
  349. break;
  350. default:
  351. break; // leave it alone
  352. }
  353. return true;
  354. },
  355. op_fn_nop);
  356. strip();
  357. }
  358. // Update local maps of ID, type, etc positions
  359. void spirvbin_t::buildLocalMaps()
  360. {
  361. msg(2, 2, std::string("build local maps: "));
  362. mapped.clear();
  363. idMapL.clear();
  364. // preserve nameMap, so we don't clear that.
  365. fnPos.clear();
  366. fnCalls.clear();
  367. typeConstPos.clear();
  368. idPosR.clear();
  369. entryPoint = spv::NoResult;
  370. largestNewId = 0;
  371. idMapL.resize(bound(), unused);
  372. int fnStart = 0;
  373. spv::Id fnRes = spv::NoResult;
  374. // build local Id and name maps
  375. process(
  376. [&](spv::Op opCode, unsigned start) {
  377. unsigned word = start+1;
  378. spv::Id typeId = spv::NoResult;
  379. if (spv::InstructionDesc[opCode].hasType())
  380. typeId = asId(word++);
  381. // If there's a result ID, remember the size of its type
  382. if (spv::InstructionDesc[opCode].hasResult()) {
  383. const spv::Id resultId = asId(word++);
  384. idPosR[resultId] = start;
  385. if (typeId != spv::NoResult) {
  386. const unsigned idTypeSize = typeSizeInWords(typeId);
  387. if (errorLatch)
  388. return false;
  389. if (idTypeSize != 0)
  390. idTypeSizeMap[resultId] = idTypeSize;
  391. }
  392. }
  393. if (opCode == spv::Op::OpName) {
  394. const spv::Id target = asId(start+1);
  395. const std::string name = literalString(start+2);
  396. nameMap[name] = target;
  397. } else if (opCode == spv::Op::OpFunctionCall) {
  398. ++fnCalls[asId(start + 3)];
  399. } else if (opCode == spv::Op::OpEntryPoint) {
  400. entryPoint = asId(start + 2);
  401. } else if (opCode == spv::Op::OpFunction) {
  402. if (fnStart != 0) {
  403. error("nested function found");
  404. return false;
  405. }
  406. fnStart = start;
  407. fnRes = asId(start + 2);
  408. } else if (opCode == spv::Op::OpFunctionEnd) {
  409. assert(fnRes != spv::NoResult);
  410. if (fnStart == 0) {
  411. error("function end without function start");
  412. return false;
  413. }
  414. fnPos[fnRes] = range_t(fnStart, start + asWordCount(start));
  415. fnStart = 0;
  416. } else if (isConstOp(opCode)) {
  417. if (errorLatch)
  418. return false;
  419. assert(asId(start + 2) != spv::NoResult);
  420. typeConstPos.insert(start);
  421. } else if (isTypeOp(opCode)) {
  422. assert(asId(start + 1) != spv::NoResult);
  423. typeConstPos.insert(start);
  424. }
  425. return false;
  426. },
  427. [this](spv::Id& id) { localId(id, unmapped); }
  428. );
  429. }
  430. // Validate the SPIR header
  431. void spirvbin_t::validate() const
  432. {
  433. msg(2, 2, std::string("validating: "));
  434. if (spv.size() < header_size) {
  435. error("file too short: ");
  436. return;
  437. }
  438. if (magic() != spv::MagicNumber) {
  439. error("bad magic number");
  440. return;
  441. }
  442. // field 1 = version
  443. // field 2 = generator magic
  444. // field 3 = result <id> bound
  445. if (schemaNum() != 0) {
  446. error("bad schema, must be 0");
  447. return;
  448. }
  449. }
  450. int spirvbin_t::processInstruction(unsigned word, instfn_t instFn, idfn_t idFn)
  451. {
  452. const auto instructionStart = word;
  453. const unsigned wordCount = asWordCount(instructionStart);
  454. const int nextInst = word++ + wordCount;
  455. spv::Op opCode = asOpCode(instructionStart);
  456. if (nextInst > int(spv.size())) {
  457. error("spir instruction terminated too early");
  458. return -1;
  459. }
  460. // Base for computing number of operands; will be updated as more is learned
  461. unsigned numOperands = wordCount - 1;
  462. if (instFn(opCode, instructionStart))
  463. return nextInst;
  464. // Read type and result ID from instruction desc table
  465. if (spv::InstructionDesc[opCode].hasType()) {
  466. idFn(asId(word++));
  467. --numOperands;
  468. }
  469. if (spv::InstructionDesc[opCode].hasResult()) {
  470. idFn(asId(word++));
  471. --numOperands;
  472. }
  473. // Extended instructions: currently, assume everything is an ID.
  474. // TODO: add whatever data we need for exceptions to that
  475. if (opCode == spv::OpExtInst) {
  476. idFn(asId(word)); // Instruction set is an ID that also needs to be mapped
  477. word += 2; // instruction set, and instruction from set
  478. numOperands -= 2;
  479. for (unsigned op=0; op < numOperands; ++op)
  480. idFn(asId(word++)); // ID
  481. return nextInst;
  482. }
  483. // Circular buffer so we can look back at previous unmapped values during the mapping pass.
  484. static const unsigned idBufferSize = 4;
  485. spv::Id idBuffer[idBufferSize];
  486. unsigned idBufferPos = 0;
  487. // Store IDs from instruction in our map
  488. for (int op = 0; numOperands > 0; ++op, --numOperands) {
  489. // SpecConstantOp is special: it includes the operands of another opcode which is
  490. // given as a literal in the 3rd word. We will switch over to pretending that the
  491. // opcode being processed is the literal opcode value of the SpecConstantOp. See the
  492. // SPIRV spec for details. This way we will handle IDs and literals as appropriate for
  493. // the embedded op.
  494. if (opCode == spv::OpSpecConstantOp) {
  495. if (op == 0) {
  496. opCode = asOpCode(word++); // this is the opcode embedded in the SpecConstantOp.
  497. --numOperands;
  498. }
  499. }
  500. switch (spv::InstructionDesc[opCode].operands.getClass(op)) {
  501. case spv::OperandId:
  502. case spv::OperandScope:
  503. case spv::OperandMemorySemantics:
  504. idBuffer[idBufferPos] = asId(word);
  505. idBufferPos = (idBufferPos + 1) % idBufferSize;
  506. idFn(asId(word++));
  507. break;
  508. case spv::OperandVariableIds:
  509. for (unsigned i = 0; i < numOperands; ++i)
  510. idFn(asId(word++));
  511. return nextInst;
  512. case spv::OperandVariableLiterals:
  513. // for clarity
  514. // if (opCode == spv::OpDecorate && asDecoration(word - 1) == spv::DecorationBuiltIn) {
  515. // ++word;
  516. // --numOperands;
  517. // }
  518. // word += numOperands;
  519. return nextInst;
  520. case spv::OperandVariableLiteralId: {
  521. if (opCode == OpSwitch) {
  522. // word-2 is the position of the selector ID. OpSwitch Literals match its type.
  523. // In case the IDs are currently being remapped, we get the word[-2] ID from
  524. // the circular idBuffer.
  525. const unsigned literalSizePos = (idBufferPos+idBufferSize-2) % idBufferSize;
  526. const unsigned literalSize = idTypeSizeInWords(idBuffer[literalSizePos]);
  527. const unsigned numLiteralIdPairs = (nextInst-word) / (1+literalSize);
  528. if (errorLatch)
  529. return -1;
  530. for (unsigned arg=0; arg<numLiteralIdPairs; ++arg) {
  531. word += literalSize; // literal
  532. idFn(asId(word++)); // label
  533. }
  534. } else {
  535. assert(0); // currentely, only OpSwitch uses OperandVariableLiteralId
  536. }
  537. return nextInst;
  538. }
  539. case spv::OperandLiteralString: {
  540. const int stringWordCount = literalStringWords(literalString(word));
  541. word += stringWordCount;
  542. numOperands -= (stringWordCount-1); // -1 because for() header post-decrements
  543. break;
  544. }
  545. case spv::OperandVariableLiteralStrings:
  546. return nextInst;
  547. // Execution mode might have extra literal operands. Skip them.
  548. case spv::OperandExecutionMode:
  549. return nextInst;
  550. // Single word operands we simply ignore, as they hold no IDs
  551. case spv::OperandLiteralNumber:
  552. case spv::OperandSource:
  553. case spv::OperandExecutionModel:
  554. case spv::OperandAddressing:
  555. case spv::OperandMemory:
  556. case spv::OperandStorage:
  557. case spv::OperandDimensionality:
  558. case spv::OperandSamplerAddressingMode:
  559. case spv::OperandSamplerFilterMode:
  560. case spv::OperandSamplerImageFormat:
  561. case spv::OperandImageChannelOrder:
  562. case spv::OperandImageChannelDataType:
  563. case spv::OperandImageOperands:
  564. case spv::OperandFPFastMath:
  565. case spv::OperandFPRoundingMode:
  566. case spv::OperandLinkageType:
  567. case spv::OperandAccessQualifier:
  568. case spv::OperandFuncParamAttr:
  569. case spv::OperandDecoration:
  570. case spv::OperandBuiltIn:
  571. case spv::OperandSelect:
  572. case spv::OperandLoop:
  573. case spv::OperandFunction:
  574. case spv::OperandMemoryAccess:
  575. case spv::OperandGroupOperation:
  576. case spv::OperandKernelEnqueueFlags:
  577. case spv::OperandKernelProfilingInfo:
  578. case spv::OperandCapability:
  579. ++word;
  580. break;
  581. default:
  582. assert(0 && "Unhandled Operand Class");
  583. break;
  584. }
  585. }
  586. return nextInst;
  587. }
  588. // Make a pass over all the instructions and process them given appropriate functions
  589. spirvbin_t& spirvbin_t::process(instfn_t instFn, idfn_t idFn, unsigned begin, unsigned end)
  590. {
  591. // For efficiency, reserve name map space. It can grow if needed.
  592. nameMap.reserve(32);
  593. // If begin or end == 0, use defaults
  594. begin = (begin == 0 ? header_size : begin);
  595. end = (end == 0 ? unsigned(spv.size()) : end);
  596. // basic parsing and InstructionDesc table borrowed from SpvDisassemble.cpp...
  597. unsigned nextInst = unsigned(spv.size());
  598. for (unsigned word = begin; word < end; word = nextInst) {
  599. nextInst = processInstruction(word, instFn, idFn);
  600. if (errorLatch)
  601. return *this;
  602. }
  603. return *this;
  604. }
  605. // Apply global name mapping to a single module
  606. void spirvbin_t::mapNames()
  607. {
  608. static const std::uint32_t softTypeIdLimit = 3011; // small prime. TODO: get from options
  609. static const std::uint32_t firstMappedID = 3019; // offset into ID space
  610. for (const auto& name : nameMap) {
  611. std::uint32_t hashval = 1911;
  612. for (const char c : name.first)
  613. hashval = hashval * 1009 + c;
  614. if (isOldIdUnmapped(name.second)) {
  615. localId(name.second, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  616. if (errorLatch)
  617. return;
  618. }
  619. }
  620. }
  621. // Map fn contents to IDs of similar functions in other modules
  622. void spirvbin_t::mapFnBodies()
  623. {
  624. static const std::uint32_t softTypeIdLimit = 19071; // small prime. TODO: get from options
  625. static const std::uint32_t firstMappedID = 6203; // offset into ID space
  626. // Initial approach: go through some high priority opcodes first and assign them
  627. // hash values.
  628. spv::Id fnId = spv::NoResult;
  629. std::vector<unsigned> instPos;
  630. instPos.reserve(unsigned(spv.size()) / 16); // initial estimate; can grow if needed.
  631. // Build local table of instruction start positions
  632. process(
  633. [&](spv::Op, unsigned start) { instPos.push_back(start); return true; },
  634. op_fn_nop);
  635. if (errorLatch)
  636. return;
  637. // Window size for context-sensitive canonicalization values
  638. // Empirical best size from a single data set. TODO: Would be a good tunable.
  639. // We essentially perform a little convolution around each instruction,
  640. // to capture the flavor of nearby code, to hopefully match to similar
  641. // code in other modules.
  642. static const unsigned windowSize = 2;
  643. for (unsigned entry = 0; entry < unsigned(instPos.size()); ++entry) {
  644. const unsigned start = instPos[entry];
  645. const spv::Op opCode = asOpCode(start);
  646. if (opCode == spv::OpFunction)
  647. fnId = asId(start + 2);
  648. if (opCode == spv::OpFunctionEnd)
  649. fnId = spv::NoResult;
  650. if (fnId != spv::NoResult) { // if inside a function
  651. if (spv::InstructionDesc[opCode].hasResult()) {
  652. const unsigned word = start + (spv::InstructionDesc[opCode].hasType() ? 2 : 1);
  653. const spv::Id resId = asId(word);
  654. std::uint32_t hashval = fnId * 17; // small prime
  655. for (unsigned i = entry-1; i >= entry-windowSize; --i) {
  656. if (asOpCode(instPos[i]) == spv::OpFunction)
  657. break;
  658. hashval = hashval * 30103 + asOpCodeHash(instPos[i]); // 30103 = semiarbitrary prime
  659. }
  660. for (unsigned i = entry; i <= entry + windowSize; ++i) {
  661. if (asOpCode(instPos[i]) == spv::OpFunctionEnd)
  662. break;
  663. hashval = hashval * 30103 + asOpCodeHash(instPos[i]); // 30103 = semiarbitrary prime
  664. }
  665. if (isOldIdUnmapped(resId)) {
  666. localId(resId, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  667. if (errorLatch)
  668. return;
  669. }
  670. }
  671. }
  672. }
  673. spv::Op thisOpCode(spv::OpNop);
  674. std::unordered_map<int, int> opCounter;
  675. int idCounter(0);
  676. fnId = spv::NoResult;
  677. process(
  678. [&](spv::Op opCode, unsigned start) {
  679. switch (opCode) {
  680. case spv::OpFunction:
  681. // Reset counters at each function
  682. idCounter = 0;
  683. opCounter.clear();
  684. fnId = asId(start + 2);
  685. break;
  686. case spv::OpImageSampleImplicitLod:
  687. case spv::OpImageSampleExplicitLod:
  688. case spv::OpImageSampleDrefImplicitLod:
  689. case spv::OpImageSampleDrefExplicitLod:
  690. case spv::OpImageSampleProjImplicitLod:
  691. case spv::OpImageSampleProjExplicitLod:
  692. case spv::OpImageSampleProjDrefImplicitLod:
  693. case spv::OpImageSampleProjDrefExplicitLod:
  694. case spv::OpDot:
  695. case spv::OpCompositeExtract:
  696. case spv::OpCompositeInsert:
  697. case spv::OpVectorShuffle:
  698. case spv::OpLabel:
  699. case spv::OpVariable:
  700. case spv::OpAccessChain:
  701. case spv::OpLoad:
  702. case spv::OpStore:
  703. case spv::OpCompositeConstruct:
  704. case spv::OpFunctionCall:
  705. ++opCounter[opCode];
  706. idCounter = 0;
  707. thisOpCode = opCode;
  708. break;
  709. default:
  710. thisOpCode = spv::OpNop;
  711. }
  712. return false;
  713. },
  714. [&](spv::Id& id) {
  715. if (thisOpCode != spv::OpNop) {
  716. ++idCounter;
  717. const std::uint32_t hashval =
  718. // Explicitly cast operands to unsigned int to avoid integer
  719. // promotion to signed int followed by integer overflow,
  720. // which would result in undefined behavior.
  721. static_cast<unsigned int>(opCounter[thisOpCode])
  722. * thisOpCode
  723. * 50047
  724. + idCounter
  725. + static_cast<unsigned int>(fnId) * 117;
  726. if (isOldIdUnmapped(id))
  727. localId(id, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  728. }
  729. });
  730. }
  731. // EXPERIMENTAL: forward IO and uniform load/stores into operands
  732. // This produces invalid Schema-0 SPIRV
  733. void spirvbin_t::forwardLoadStores()
  734. {
  735. idset_t fnLocalVars; // set of function local vars
  736. idmap_t idMap; // Map of load result IDs to what they load
  737. // EXPERIMENTAL: Forward input and access chain loads into consumptions
  738. process(
  739. [&](spv::Op opCode, unsigned start) {
  740. // Add inputs and uniforms to the map
  741. if ((opCode == spv::OpVariable && asWordCount(start) == 4) &&
  742. (spv[start+3] == spv::StorageClassUniform ||
  743. spv[start+3] == spv::StorageClassUniformConstant ||
  744. spv[start+3] == spv::StorageClassInput))
  745. fnLocalVars.insert(asId(start+2));
  746. if (opCode == spv::OpAccessChain && fnLocalVars.count(asId(start+3)) > 0)
  747. fnLocalVars.insert(asId(start+2));
  748. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) {
  749. idMap[asId(start+2)] = asId(start+3);
  750. stripInst(start);
  751. }
  752. return false;
  753. },
  754. [&](spv::Id& id) { if (idMap.find(id) != idMap.end()) id = idMap[id]; }
  755. );
  756. if (errorLatch)
  757. return;
  758. // EXPERIMENTAL: Implicit output stores
  759. fnLocalVars.clear();
  760. idMap.clear();
  761. process(
  762. [&](spv::Op opCode, unsigned start) {
  763. // Add inputs and uniforms to the map
  764. if ((opCode == spv::OpVariable && asWordCount(start) == 4) &&
  765. (spv[start+3] == spv::StorageClassOutput))
  766. fnLocalVars.insert(asId(start+2));
  767. if (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) {
  768. idMap[asId(start+2)] = asId(start+1);
  769. stripInst(start);
  770. }
  771. return false;
  772. },
  773. op_fn_nop);
  774. if (errorLatch)
  775. return;
  776. process(
  777. inst_fn_nop,
  778. [&](spv::Id& id) { if (idMap.find(id) != idMap.end()) id = idMap[id]; }
  779. );
  780. if (errorLatch)
  781. return;
  782. strip(); // strip out data we decided to eliminate
  783. }
  784. // optimize loads and stores
  785. void spirvbin_t::optLoadStore()
  786. {
  787. idset_t fnLocalVars; // candidates for removal (only locals)
  788. idmap_t idMap; // Map of load result IDs to what they load
  789. blockmap_t blockMap; // Map of IDs to blocks they first appear in
  790. int blockNum = 0; // block count, to avoid crossing flow control
  791. // Find all the function local pointers stored at most once, and not via access chains
  792. process(
  793. [&](spv::Op opCode, unsigned start) {
  794. const int wordCount = asWordCount(start);
  795. // Count blocks, so we can avoid crossing flow control
  796. if (isFlowCtrl(opCode))
  797. ++blockNum;
  798. // Add local variables to the map
  799. if ((opCode == spv::OpVariable && spv[start+3] == spv::StorageClassFunction && asWordCount(start) == 4)) {
  800. fnLocalVars.insert(asId(start+2));
  801. return true;
  802. }
  803. // Ignore process vars referenced via access chain
  804. if ((opCode == spv::OpAccessChain || opCode == spv::OpInBoundsAccessChain) && fnLocalVars.count(asId(start+3)) > 0) {
  805. fnLocalVars.erase(asId(start+3));
  806. idMap.erase(asId(start+3));
  807. return true;
  808. }
  809. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) {
  810. const spv::Id varId = asId(start+3);
  811. // Avoid loads before stores
  812. if (idMap.find(varId) == idMap.end()) {
  813. fnLocalVars.erase(varId);
  814. idMap.erase(varId);
  815. }
  816. // don't do for volatile references
  817. if (wordCount > 4 && (spv[start+4] & spv::MemoryAccessVolatileMask)) {
  818. fnLocalVars.erase(varId);
  819. idMap.erase(varId);
  820. }
  821. // Handle flow control
  822. if (blockMap.find(varId) == blockMap.end()) {
  823. blockMap[varId] = blockNum; // track block we found it in.
  824. } else if (blockMap[varId] != blockNum) {
  825. fnLocalVars.erase(varId); // Ignore if crosses flow control
  826. idMap.erase(varId);
  827. }
  828. return true;
  829. }
  830. if (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) {
  831. const spv::Id varId = asId(start+1);
  832. if (idMap.find(varId) == idMap.end()) {
  833. idMap[varId] = asId(start+2);
  834. } else {
  835. // Remove if it has more than one store to the same pointer
  836. fnLocalVars.erase(varId);
  837. idMap.erase(varId);
  838. }
  839. // don't do for volatile references
  840. if (wordCount > 3 && (spv[start+3] & spv::MemoryAccessVolatileMask)) {
  841. fnLocalVars.erase(asId(start+3));
  842. idMap.erase(asId(start+3));
  843. }
  844. // Handle flow control
  845. if (blockMap.find(varId) == blockMap.end()) {
  846. blockMap[varId] = blockNum; // track block we found it in.
  847. } else if (blockMap[varId] != blockNum) {
  848. fnLocalVars.erase(varId); // Ignore if crosses flow control
  849. idMap.erase(varId);
  850. }
  851. return true;
  852. }
  853. return false;
  854. },
  855. // If local var id used anywhere else, don't eliminate
  856. [&](spv::Id& id) {
  857. if (fnLocalVars.count(id) > 0) {
  858. fnLocalVars.erase(id);
  859. idMap.erase(id);
  860. }
  861. }
  862. );
  863. if (errorLatch)
  864. return;
  865. process(
  866. [&](spv::Op opCode, unsigned start) {
  867. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0)
  868. idMap[asId(start+2)] = idMap[asId(start+3)];
  869. return false;
  870. },
  871. op_fn_nop);
  872. if (errorLatch)
  873. return;
  874. // Chase replacements to their origins, in case there is a chain such as:
  875. // 2 = store 1
  876. // 3 = load 2
  877. // 4 = store 3
  878. // 5 = load 4
  879. // We want to replace uses of 5 with 1.
  880. for (const auto& idPair : idMap) {
  881. spv::Id id = idPair.first;
  882. while (idMap.find(id) != idMap.end()) // Chase to end of chain
  883. id = idMap[id];
  884. idMap[idPair.first] = id; // replace with final result
  885. }
  886. // Remove the load/store/variables for the ones we've discovered
  887. process(
  888. [&](spv::Op opCode, unsigned start) {
  889. if ((opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) ||
  890. (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) ||
  891. (opCode == spv::OpVariable && fnLocalVars.count(asId(start+2)) > 0)) {
  892. stripInst(start);
  893. return true;
  894. }
  895. return false;
  896. },
  897. [&](spv::Id& id) {
  898. if (idMap.find(id) != idMap.end()) id = idMap[id];
  899. }
  900. );
  901. if (errorLatch)
  902. return;
  903. strip(); // strip out data we decided to eliminate
  904. }
  905. // remove bodies of uncalled functions
  906. void spirvbin_t::dceFuncs()
  907. {
  908. msg(3, 2, std::string("Removing Dead Functions: "));
  909. // TODO: There are more efficient ways to do this.
  910. bool changed = true;
  911. while (changed) {
  912. changed = false;
  913. for (auto fn = fnPos.begin(); fn != fnPos.end(); ) {
  914. if (fn->first == entryPoint) { // don't DCE away the entry point!
  915. ++fn;
  916. continue;
  917. }
  918. const auto call_it = fnCalls.find(fn->first);
  919. if (call_it == fnCalls.end() || call_it->second == 0) {
  920. changed = true;
  921. stripRange.push_back(fn->second);
  922. // decrease counts of called functions
  923. process(
  924. [&](spv::Op opCode, unsigned start) {
  925. if (opCode == spv::Op::OpFunctionCall) {
  926. const auto call_it = fnCalls.find(asId(start + 3));
  927. if (call_it != fnCalls.end()) {
  928. if (--call_it->second <= 0)
  929. fnCalls.erase(call_it);
  930. }
  931. }
  932. return true;
  933. },
  934. op_fn_nop,
  935. fn->second.first,
  936. fn->second.second);
  937. if (errorLatch)
  938. return;
  939. fn = fnPos.erase(fn);
  940. } else ++fn;
  941. }
  942. }
  943. }
  944. // remove unused function variables + decorations
  945. void spirvbin_t::dceVars()
  946. {
  947. msg(3, 2, std::string("DCE Vars: "));
  948. std::unordered_map<spv::Id, int> varUseCount;
  949. // Count function variable use
  950. process(
  951. [&](spv::Op opCode, unsigned start) {
  952. if (opCode == spv::OpVariable) {
  953. ++varUseCount[asId(start+2)];
  954. return true;
  955. } else if (opCode == spv::OpEntryPoint) {
  956. const int wordCount = asWordCount(start);
  957. for (int i = 4; i < wordCount; i++) {
  958. ++varUseCount[asId(start+i)];
  959. }
  960. return true;
  961. } else
  962. return false;
  963. },
  964. [&](spv::Id& id) { if (varUseCount[id]) ++varUseCount[id]; }
  965. );
  966. if (errorLatch)
  967. return;
  968. // Remove single-use function variables + associated decorations and names
  969. process(
  970. [&](spv::Op opCode, unsigned start) {
  971. spv::Id id = spv::NoResult;
  972. if (opCode == spv::OpVariable)
  973. id = asId(start+2);
  974. if (opCode == spv::OpDecorate || opCode == spv::OpName)
  975. id = asId(start+1);
  976. if (id != spv::NoResult && varUseCount[id] == 1)
  977. stripInst(start);
  978. return true;
  979. },
  980. op_fn_nop);
  981. }
  982. // remove unused types
  983. void spirvbin_t::dceTypes()
  984. {
  985. std::vector<bool> isType(bound(), false);
  986. // for speed, make O(1) way to get to type query (map is log(n))
  987. for (const auto typeStart : typeConstPos)
  988. isType[asTypeConstId(typeStart)] = true;
  989. std::unordered_map<spv::Id, int> typeUseCount;
  990. // This is not the most efficient algorithm, but this is an offline tool, and
  991. // it's easy to write this way. Can be improved opportunistically if needed.
  992. bool changed = true;
  993. while (changed) {
  994. changed = false;
  995. strip();
  996. typeUseCount.clear();
  997. // Count total type usage
  998. process(inst_fn_nop,
  999. [&](spv::Id& id) { if (isType[id]) ++typeUseCount[id]; }
  1000. );
  1001. if (errorLatch)
  1002. return;
  1003. // Remove single reference types
  1004. for (const auto typeStart : typeConstPos) {
  1005. const spv::Id typeId = asTypeConstId(typeStart);
  1006. if (typeUseCount[typeId] == 1) {
  1007. changed = true;
  1008. --typeUseCount[typeId];
  1009. stripInst(typeStart);
  1010. }
  1011. }
  1012. if (errorLatch)
  1013. return;
  1014. }
  1015. }
  1016. #ifdef NOTDEF
  1017. bool spirvbin_t::matchType(const spirvbin_t::globaltypes_t& globalTypes, spv::Id lt, spv::Id gt) const
  1018. {
  1019. // Find the local type id "lt" and global type id "gt"
  1020. const auto lt_it = typeConstPosR.find(lt);
  1021. if (lt_it == typeConstPosR.end())
  1022. return false;
  1023. const auto typeStart = lt_it->second;
  1024. // Search for entry in global table
  1025. const auto gtype = globalTypes.find(gt);
  1026. if (gtype == globalTypes.end())
  1027. return false;
  1028. const auto& gdata = gtype->second;
  1029. // local wordcount and opcode
  1030. const int wordCount = asWordCount(typeStart);
  1031. const spv::Op opCode = asOpCode(typeStart);
  1032. // no type match if opcodes don't match, or operand count doesn't match
  1033. if (opCode != opOpCode(gdata[0]) || wordCount != opWordCount(gdata[0]))
  1034. return false;
  1035. const unsigned numOperands = wordCount - 2; // all types have a result
  1036. const auto cmpIdRange = [&](range_t range) {
  1037. for (int x=range.first; x<std::min(range.second, wordCount); ++x)
  1038. if (!matchType(globalTypes, asId(typeStart+x), gdata[x]))
  1039. return false;
  1040. return true;
  1041. };
  1042. const auto cmpConst = [&]() { return cmpIdRange(constRange(opCode)); };
  1043. const auto cmpSubType = [&]() { return cmpIdRange(typeRange(opCode)); };
  1044. // Compare literals in range [start,end)
  1045. const auto cmpLiteral = [&]() {
  1046. const auto range = literalRange(opCode);
  1047. return std::equal(spir.begin() + typeStart + range.first,
  1048. spir.begin() + typeStart + std::min(range.second, wordCount),
  1049. gdata.begin() + range.first);
  1050. };
  1051. assert(isTypeOp(opCode) || isConstOp(opCode));
  1052. switch (opCode) {
  1053. case spv::OpTypeOpaque: // TODO: disable until we compare the literal strings.
  1054. case spv::OpTypeQueue: return false;
  1055. case spv::OpTypeEvent: // fall through...
  1056. case spv::OpTypeDeviceEvent: // ...
  1057. case spv::OpTypeReserveId: return false;
  1058. // for samplers, we don't handle the optional parameters yet
  1059. case spv::OpTypeSampler: return cmpLiteral() && cmpConst() && cmpSubType() && wordCount == 8;
  1060. default: return cmpLiteral() && cmpConst() && cmpSubType();
  1061. }
  1062. }
  1063. // Look for an equivalent type in the globalTypes map
  1064. spv::Id spirvbin_t::findType(const spirvbin_t::globaltypes_t& globalTypes, spv::Id lt) const
  1065. {
  1066. // Try a recursive type match on each in turn, and return a match if we find one
  1067. for (const auto& gt : globalTypes)
  1068. if (matchType(globalTypes, lt, gt.first))
  1069. return gt.first;
  1070. return spv::NoType;
  1071. }
  1072. #endif // NOTDEF
  1073. // Return start position in SPV of given Id. error if not found.
  1074. unsigned spirvbin_t::idPos(spv::Id id) const
  1075. {
  1076. const auto tid_it = idPosR.find(id);
  1077. if (tid_it == idPosR.end()) {
  1078. error("ID not found");
  1079. return 0;
  1080. }
  1081. return tid_it->second;
  1082. }
  1083. // Hash types to canonical values. This can return ID collisions (it's a bit
  1084. // inevitable): it's up to the caller to handle that gracefully.
  1085. std::uint32_t spirvbin_t::hashType(unsigned typeStart) const
  1086. {
  1087. const unsigned wordCount = asWordCount(typeStart);
  1088. const spv::Op opCode = asOpCode(typeStart);
  1089. switch (opCode) {
  1090. case spv::OpTypeVoid: return 0;
  1091. case spv::OpTypeBool: return 1;
  1092. case spv::OpTypeInt: return 3 + (spv[typeStart+3]);
  1093. case spv::OpTypeFloat: return 5;
  1094. case spv::OpTypeVector:
  1095. return 6 + hashType(idPos(spv[typeStart+2])) * (spv[typeStart+3] - 1);
  1096. case spv::OpTypeMatrix:
  1097. return 30 + hashType(idPos(spv[typeStart+2])) * (spv[typeStart+3] - 1);
  1098. case spv::OpTypeImage:
  1099. return 120 + hashType(idPos(spv[typeStart+2])) +
  1100. spv[typeStart+3] + // dimensionality
  1101. spv[typeStart+4] * 8 * 16 + // depth
  1102. spv[typeStart+5] * 4 * 16 + // arrayed
  1103. spv[typeStart+6] * 2 * 16 + // multisampled
  1104. spv[typeStart+7] * 1 * 16; // format
  1105. case spv::OpTypeSampler:
  1106. return 500;
  1107. case spv::OpTypeSampledImage:
  1108. return 502;
  1109. case spv::OpTypeArray:
  1110. return 501 + hashType(idPos(spv[typeStart+2])) * spv[typeStart+3];
  1111. case spv::OpTypeRuntimeArray:
  1112. return 5000 + hashType(idPos(spv[typeStart+2]));
  1113. case spv::OpTypeStruct:
  1114. {
  1115. std::uint32_t hash = 10000;
  1116. for (unsigned w=2; w < wordCount; ++w)
  1117. hash += w * hashType(idPos(spv[typeStart+w]));
  1118. return hash;
  1119. }
  1120. case spv::OpTypeOpaque: return 6000 + spv[typeStart+2];
  1121. case spv::OpTypePointer: return 100000 + hashType(idPos(spv[typeStart+3]));
  1122. case spv::OpTypeFunction:
  1123. {
  1124. std::uint32_t hash = 200000;
  1125. for (unsigned w=2; w < wordCount; ++w)
  1126. hash += w * hashType(idPos(spv[typeStart+w]));
  1127. return hash;
  1128. }
  1129. case spv::OpTypeEvent: return 300000;
  1130. case spv::OpTypeDeviceEvent: return 300001;
  1131. case spv::OpTypeReserveId: return 300002;
  1132. case spv::OpTypeQueue: return 300003;
  1133. case spv::OpTypePipe: return 300004;
  1134. case spv::OpConstantTrue: return 300007;
  1135. case spv::OpConstantFalse: return 300008;
  1136. case spv::OpConstantComposite:
  1137. {
  1138. std::uint32_t hash = 300011 + hashType(idPos(spv[typeStart+1]));
  1139. for (unsigned w=3; w < wordCount; ++w)
  1140. hash += w * hashType(idPos(spv[typeStart+w]));
  1141. return hash;
  1142. }
  1143. case spv::OpConstant:
  1144. {
  1145. std::uint32_t hash = 400011 + hashType(idPos(spv[typeStart+1]));
  1146. for (unsigned w=3; w < wordCount; ++w)
  1147. hash += w * spv[typeStart+w];
  1148. return hash;
  1149. }
  1150. case spv::OpConstantNull:
  1151. {
  1152. std::uint32_t hash = 500009 + hashType(idPos(spv[typeStart+1]));
  1153. return hash;
  1154. }
  1155. case spv::OpConstantSampler:
  1156. {
  1157. std::uint32_t hash = 600011 + hashType(idPos(spv[typeStart+1]));
  1158. for (unsigned w=3; w < wordCount; ++w)
  1159. hash += w * spv[typeStart+w];
  1160. return hash;
  1161. }
  1162. default:
  1163. error("unknown type opcode");
  1164. return 0;
  1165. }
  1166. }
  1167. void spirvbin_t::mapTypeConst()
  1168. {
  1169. globaltypes_t globalTypeMap;
  1170. msg(3, 2, std::string("Remapping Consts & Types: "));
  1171. static const std::uint32_t softTypeIdLimit = 3011; // small prime. TODO: get from options
  1172. static const std::uint32_t firstMappedID = 8; // offset into ID space
  1173. for (auto& typeStart : typeConstPos) {
  1174. const spv::Id resId = asTypeConstId(typeStart);
  1175. const std::uint32_t hashval = hashType(typeStart);
  1176. if (errorLatch)
  1177. return;
  1178. if (isOldIdUnmapped(resId)) {
  1179. localId(resId, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  1180. if (errorLatch)
  1181. return;
  1182. }
  1183. }
  1184. }
  1185. // Strip a single binary by removing ranges given in stripRange
  1186. void spirvbin_t::strip()
  1187. {
  1188. if (stripRange.empty()) // nothing to do
  1189. return;
  1190. // Sort strip ranges in order of traversal
  1191. std::sort(stripRange.begin(), stripRange.end());
  1192. // Allocate a new binary big enough to hold old binary
  1193. // We'll step this iterator through the strip ranges as we go through the binary
  1194. auto strip_it = stripRange.begin();
  1195. int strippedPos = 0;
  1196. for (unsigned word = 0; word < unsigned(spv.size()); ++word) {
  1197. while (strip_it != stripRange.end() && word >= strip_it->second)
  1198. ++strip_it;
  1199. if (strip_it == stripRange.end() || word < strip_it->first || word >= strip_it->second)
  1200. spv[strippedPos++] = spv[word];
  1201. }
  1202. spv.resize(strippedPos);
  1203. stripRange.clear();
  1204. buildLocalMaps();
  1205. }
  1206. // Strip a single binary by removing ranges given in stripRange
  1207. void spirvbin_t::remap(std::uint32_t opts)
  1208. {
  1209. options = opts;
  1210. // Set up opcode tables from SpvDoc
  1211. spv::Parameterize();
  1212. validate(); // validate header
  1213. buildLocalMaps(); // build ID maps
  1214. msg(3, 4, std::string("ID bound: ") + std::to_string(bound()));
  1215. if (options & STRIP) stripDebug();
  1216. if (errorLatch) return;
  1217. strip(); // strip out data we decided to eliminate
  1218. if (errorLatch) return;
  1219. if (options & OPT_LOADSTORE) optLoadStore();
  1220. if (errorLatch) return;
  1221. if (options & OPT_FWD_LS) forwardLoadStores();
  1222. if (errorLatch) return;
  1223. if (options & DCE_FUNCS) dceFuncs();
  1224. if (errorLatch) return;
  1225. if (options & DCE_VARS) dceVars();
  1226. if (errorLatch) return;
  1227. if (options & DCE_TYPES) dceTypes();
  1228. if (errorLatch) return;
  1229. strip(); // strip out data we decided to eliminate
  1230. if (errorLatch) return;
  1231. stripDeadRefs(); // remove references to things we DCEed
  1232. if (errorLatch) return;
  1233. // after the last strip, we must clean any debug info referring to now-deleted data
  1234. if (options & MAP_TYPES) mapTypeConst();
  1235. if (errorLatch) return;
  1236. if (options & MAP_NAMES) mapNames();
  1237. if (errorLatch) return;
  1238. if (options & MAP_FUNCS) mapFnBodies();
  1239. if (errorLatch) return;
  1240. if (options & MAP_ALL) {
  1241. mapRemainder(); // map any unmapped IDs
  1242. if (errorLatch) return;
  1243. applyMap(); // Now remap each shader to the new IDs we've come up with
  1244. if (errorLatch) return;
  1245. }
  1246. }
  1247. // remap from a memory image
  1248. void spirvbin_t::remap(std::vector<std::uint32_t>& in_spv, const std::vector<std::string>& whiteListStrings,
  1249. std::uint32_t opts)
  1250. {
  1251. stripWhiteList = whiteListStrings;
  1252. spv.swap(in_spv);
  1253. remap(opts);
  1254. spv.swap(in_spv);
  1255. }
  1256. // remap from a memory image - legacy interface without white list
  1257. void spirvbin_t::remap(std::vector<std::uint32_t>& in_spv, std::uint32_t opts)
  1258. {
  1259. stripWhiteList.clear();
  1260. spv.swap(in_spv);
  1261. remap(opts);
  1262. spv.swap(in_spv);
  1263. }
  1264. } // namespace SPV
  1265. #endif // defined (use_cpp11)