SPVRemapper.cpp 52 KB

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