spirv_parser.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. /*
  2. * Copyright 2018-2019 Arm Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "spirv_parser.hpp"
  17. #include <assert.h>
  18. using namespace std;
  19. using namespace spv;
  20. namespace SPIRV_CROSS_NAMESPACE
  21. {
  22. Parser::Parser(vector<uint32_t> spirv)
  23. {
  24. ir.spirv = move(spirv);
  25. }
  26. Parser::Parser(const uint32_t *spirv_data, size_t word_count)
  27. {
  28. ir.spirv = vector<uint32_t>(spirv_data, spirv_data + word_count);
  29. }
  30. static bool decoration_is_string(Decoration decoration)
  31. {
  32. switch (decoration)
  33. {
  34. case DecorationHlslSemanticGOOGLE:
  35. return true;
  36. default:
  37. return false;
  38. }
  39. }
  40. static inline uint32_t swap_endian(uint32_t v)
  41. {
  42. return ((v >> 24) & 0x000000ffu) | ((v >> 8) & 0x0000ff00u) | ((v << 8) & 0x00ff0000u) | ((v << 24) & 0xff000000u);
  43. }
  44. static bool is_valid_spirv_version(uint32_t version)
  45. {
  46. switch (version)
  47. {
  48. // Allow v99 since it tends to just work.
  49. case 99:
  50. case 0x10000: // SPIR-V 1.0
  51. case 0x10100: // SPIR-V 1.1
  52. case 0x10200: // SPIR-V 1.2
  53. case 0x10300: // SPIR-V 1.3
  54. case 0x10400: // SPIR-V 1.4
  55. return true;
  56. default:
  57. return false;
  58. }
  59. }
  60. void Parser::parse()
  61. {
  62. auto &spirv = ir.spirv;
  63. auto len = spirv.size();
  64. if (len < 5)
  65. SPIRV_CROSS_THROW("SPIRV file too small.");
  66. auto s = spirv.data();
  67. // Endian-swap if we need to.
  68. if (s[0] == swap_endian(MagicNumber))
  69. transform(begin(spirv), end(spirv), begin(spirv), [](uint32_t c) { return swap_endian(c); });
  70. if (s[0] != MagicNumber || !is_valid_spirv_version(s[1]))
  71. SPIRV_CROSS_THROW("Invalid SPIRV format.");
  72. uint32_t bound = s[3];
  73. ir.set_id_bounds(bound);
  74. uint32_t offset = 5;
  75. SmallVector<Instruction> instructions;
  76. while (offset < len)
  77. {
  78. Instruction instr = {};
  79. instr.op = spirv[offset] & 0xffff;
  80. instr.count = (spirv[offset] >> 16) & 0xffff;
  81. if (instr.count == 0)
  82. SPIRV_CROSS_THROW("SPIR-V instructions cannot consume 0 words. Invalid SPIR-V file.");
  83. instr.offset = offset + 1;
  84. instr.length = instr.count - 1;
  85. offset += instr.count;
  86. if (offset > spirv.size())
  87. SPIRV_CROSS_THROW("SPIR-V instruction goes out of bounds.");
  88. instructions.push_back(instr);
  89. }
  90. for (auto &i : instructions)
  91. parse(i);
  92. if (current_function)
  93. SPIRV_CROSS_THROW("Function was not terminated.");
  94. if (current_block)
  95. SPIRV_CROSS_THROW("Block was not terminated.");
  96. }
  97. const uint32_t *Parser::stream(const Instruction &instr) const
  98. {
  99. // If we're not going to use any arguments, just return nullptr.
  100. // We want to avoid case where we return an out of range pointer
  101. // that trips debug assertions on some platforms.
  102. if (!instr.length)
  103. return nullptr;
  104. if (instr.offset + instr.length > ir.spirv.size())
  105. SPIRV_CROSS_THROW("Compiler::stream() out of range.");
  106. return &ir.spirv[instr.offset];
  107. }
  108. static string extract_string(const vector<uint32_t> &spirv, uint32_t offset)
  109. {
  110. string ret;
  111. for (uint32_t i = offset; i < spirv.size(); i++)
  112. {
  113. uint32_t w = spirv[i];
  114. for (uint32_t j = 0; j < 4; j++, w >>= 8)
  115. {
  116. char c = w & 0xff;
  117. if (c == '\0')
  118. return ret;
  119. ret += c;
  120. }
  121. }
  122. SPIRV_CROSS_THROW("String was not terminated before EOF");
  123. }
  124. void Parser::parse(const Instruction &instruction)
  125. {
  126. auto *ops = stream(instruction);
  127. auto op = static_cast<Op>(instruction.op);
  128. uint32_t length = instruction.length;
  129. switch (op)
  130. {
  131. case OpSourceContinued:
  132. case OpSourceExtension:
  133. case OpNop:
  134. case OpLine:
  135. case OpNoLine:
  136. case OpString:
  137. case OpModuleProcessed:
  138. break;
  139. case OpMemoryModel:
  140. ir.addressing_model = static_cast<AddressingModel>(ops[0]);
  141. ir.memory_model = static_cast<MemoryModel>(ops[1]);
  142. break;
  143. case OpSource:
  144. {
  145. auto lang = static_cast<SourceLanguage>(ops[0]);
  146. switch (lang)
  147. {
  148. case SourceLanguageESSL:
  149. ir.source.es = true;
  150. ir.source.version = ops[1];
  151. ir.source.known = true;
  152. ir.source.hlsl = false;
  153. break;
  154. case SourceLanguageGLSL:
  155. ir.source.es = false;
  156. ir.source.version = ops[1];
  157. ir.source.known = true;
  158. ir.source.hlsl = false;
  159. break;
  160. case SourceLanguageHLSL:
  161. // For purposes of cross-compiling, this is GLSL 450.
  162. ir.source.es = false;
  163. ir.source.version = 450;
  164. ir.source.known = true;
  165. ir.source.hlsl = true;
  166. break;
  167. default:
  168. ir.source.known = false;
  169. break;
  170. }
  171. break;
  172. }
  173. case OpUndef:
  174. {
  175. uint32_t result_type = ops[0];
  176. uint32_t id = ops[1];
  177. set<SPIRUndef>(id, result_type);
  178. if (current_block)
  179. current_block->ops.push_back(instruction);
  180. break;
  181. }
  182. case OpCapability:
  183. {
  184. uint32_t cap = ops[0];
  185. if (cap == CapabilityKernel)
  186. SPIRV_CROSS_THROW("Kernel capability not supported.");
  187. ir.declared_capabilities.push_back(static_cast<Capability>(ops[0]));
  188. break;
  189. }
  190. case OpExtension:
  191. {
  192. auto ext = extract_string(ir.spirv, instruction.offset);
  193. ir.declared_extensions.push_back(move(ext));
  194. break;
  195. }
  196. case OpExtInstImport:
  197. {
  198. uint32_t id = ops[0];
  199. auto ext = extract_string(ir.spirv, instruction.offset + 1);
  200. if (ext == "GLSL.std.450")
  201. set<SPIRExtension>(id, SPIRExtension::GLSL);
  202. else if (ext == "SPV_AMD_shader_ballot")
  203. set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_ballot);
  204. else if (ext == "SPV_AMD_shader_explicit_vertex_parameter")
  205. set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter);
  206. else if (ext == "SPV_AMD_shader_trinary_minmax")
  207. set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_trinary_minmax);
  208. else if (ext == "SPV_AMD_gcn_shader")
  209. set<SPIRExtension>(id, SPIRExtension::SPV_AMD_gcn_shader);
  210. else
  211. set<SPIRExtension>(id, SPIRExtension::Unsupported);
  212. // Other SPIR-V extensions which have ExtInstrs are currently not supported.
  213. break;
  214. }
  215. case OpEntryPoint:
  216. {
  217. auto itr =
  218. ir.entry_points.insert(make_pair(ops[1], SPIREntryPoint(ops[1], static_cast<ExecutionModel>(ops[0]),
  219. extract_string(ir.spirv, instruction.offset + 2))));
  220. auto &e = itr.first->second;
  221. // Strings need nul-terminator and consume the whole word.
  222. uint32_t strlen_words = uint32_t((e.name.size() + 1 + 3) >> 2);
  223. e.interface_variables.insert(end(e.interface_variables), ops + strlen_words + 2, ops + instruction.length);
  224. // Set the name of the entry point in case OpName is not provided later.
  225. ir.set_name(ops[1], e.name);
  226. // If we don't have an entry, make the first one our "default".
  227. if (!ir.default_entry_point)
  228. ir.default_entry_point = ops[1];
  229. break;
  230. }
  231. case OpExecutionMode:
  232. {
  233. auto &execution = ir.entry_points[ops[0]];
  234. auto mode = static_cast<ExecutionMode>(ops[1]);
  235. execution.flags.set(mode);
  236. switch (mode)
  237. {
  238. case ExecutionModeInvocations:
  239. execution.invocations = ops[2];
  240. break;
  241. case ExecutionModeLocalSize:
  242. execution.workgroup_size.x = ops[2];
  243. execution.workgroup_size.y = ops[3];
  244. execution.workgroup_size.z = ops[4];
  245. break;
  246. case ExecutionModeOutputVertices:
  247. execution.output_vertices = ops[2];
  248. break;
  249. default:
  250. break;
  251. }
  252. break;
  253. }
  254. case OpName:
  255. {
  256. uint32_t id = ops[0];
  257. ir.set_name(id, extract_string(ir.spirv, instruction.offset + 1));
  258. break;
  259. }
  260. case OpMemberName:
  261. {
  262. uint32_t id = ops[0];
  263. uint32_t member = ops[1];
  264. ir.set_member_name(id, member, extract_string(ir.spirv, instruction.offset + 2));
  265. break;
  266. }
  267. case OpDecorationGroup:
  268. {
  269. // Noop, this simply means an ID should be a collector of decorations.
  270. // The meta array is already a flat array of decorations which will contain the relevant decorations.
  271. break;
  272. }
  273. case OpGroupDecorate:
  274. {
  275. uint32_t group_id = ops[0];
  276. auto &decorations = ir.meta[group_id].decoration;
  277. auto &flags = decorations.decoration_flags;
  278. // Copies decorations from one ID to another. Only copy decorations which are set in the group,
  279. // i.e., we cannot just copy the meta structure directly.
  280. for (uint32_t i = 1; i < length; i++)
  281. {
  282. uint32_t target = ops[i];
  283. flags.for_each_bit([&](uint32_t bit) {
  284. auto decoration = static_cast<Decoration>(bit);
  285. if (decoration_is_string(decoration))
  286. {
  287. ir.set_decoration_string(target, decoration, ir.get_decoration_string(group_id, decoration));
  288. }
  289. else
  290. {
  291. ir.meta[target].decoration_word_offset[decoration] =
  292. ir.meta[group_id].decoration_word_offset[decoration];
  293. ir.set_decoration(target, decoration, ir.get_decoration(group_id, decoration));
  294. }
  295. });
  296. }
  297. break;
  298. }
  299. case OpGroupMemberDecorate:
  300. {
  301. uint32_t group_id = ops[0];
  302. auto &flags = ir.meta[group_id].decoration.decoration_flags;
  303. // Copies decorations from one ID to another. Only copy decorations which are set in the group,
  304. // i.e., we cannot just copy the meta structure directly.
  305. for (uint32_t i = 1; i + 1 < length; i += 2)
  306. {
  307. uint32_t target = ops[i + 0];
  308. uint32_t index = ops[i + 1];
  309. flags.for_each_bit([&](uint32_t bit) {
  310. auto decoration = static_cast<Decoration>(bit);
  311. if (decoration_is_string(decoration))
  312. ir.set_member_decoration_string(target, index, decoration,
  313. ir.get_decoration_string(group_id, decoration));
  314. else
  315. ir.set_member_decoration(target, index, decoration, ir.get_decoration(group_id, decoration));
  316. });
  317. }
  318. break;
  319. }
  320. case OpDecorate:
  321. case OpDecorateId:
  322. {
  323. // OpDecorateId technically supports an array of arguments, but our only supported decorations are single uint,
  324. // so merge decorate and decorate-id here.
  325. uint32_t id = ops[0];
  326. auto decoration = static_cast<Decoration>(ops[1]);
  327. if (length >= 3)
  328. {
  329. ir.meta[id].decoration_word_offset[decoration] = uint32_t(&ops[2] - ir.spirv.data());
  330. ir.set_decoration(id, decoration, ops[2]);
  331. }
  332. else
  333. ir.set_decoration(id, decoration);
  334. break;
  335. }
  336. case OpDecorateStringGOOGLE:
  337. {
  338. uint32_t id = ops[0];
  339. auto decoration = static_cast<Decoration>(ops[1]);
  340. ir.set_decoration_string(id, decoration, extract_string(ir.spirv, instruction.offset + 2));
  341. break;
  342. }
  343. case OpMemberDecorate:
  344. {
  345. uint32_t id = ops[0];
  346. uint32_t member = ops[1];
  347. auto decoration = static_cast<Decoration>(ops[2]);
  348. if (length >= 4)
  349. ir.set_member_decoration(id, member, decoration, ops[3]);
  350. else
  351. ir.set_member_decoration(id, member, decoration);
  352. break;
  353. }
  354. case OpMemberDecorateStringGOOGLE:
  355. {
  356. uint32_t id = ops[0];
  357. uint32_t member = ops[1];
  358. auto decoration = static_cast<Decoration>(ops[2]);
  359. ir.set_member_decoration_string(id, member, decoration, extract_string(ir.spirv, instruction.offset + 3));
  360. break;
  361. }
  362. // Build up basic types.
  363. case OpTypeVoid:
  364. {
  365. uint32_t id = ops[0];
  366. auto &type = set<SPIRType>(id);
  367. type.basetype = SPIRType::Void;
  368. break;
  369. }
  370. case OpTypeBool:
  371. {
  372. uint32_t id = ops[0];
  373. auto &type = set<SPIRType>(id);
  374. type.basetype = SPIRType::Boolean;
  375. type.width = 1;
  376. break;
  377. }
  378. case OpTypeFloat:
  379. {
  380. uint32_t id = ops[0];
  381. uint32_t width = ops[1];
  382. auto &type = set<SPIRType>(id);
  383. if (width == 64)
  384. type.basetype = SPIRType::Double;
  385. else if (width == 32)
  386. type.basetype = SPIRType::Float;
  387. else if (width == 16)
  388. type.basetype = SPIRType::Half;
  389. else
  390. SPIRV_CROSS_THROW("Unrecognized bit-width of floating point type.");
  391. type.width = width;
  392. break;
  393. }
  394. case OpTypeInt:
  395. {
  396. uint32_t id = ops[0];
  397. uint32_t width = ops[1];
  398. bool signedness = ops[2] != 0;
  399. auto &type = set<SPIRType>(id);
  400. type.basetype = signedness ? to_signed_basetype(width) : to_unsigned_basetype(width);
  401. type.width = width;
  402. break;
  403. }
  404. // Build composite types by "inheriting".
  405. // NOTE: The self member is also copied! For pointers and array modifiers this is a good thing
  406. // since we can refer to decorations on pointee classes which is needed for UBO/SSBO, I/O blocks in geometry/tess etc.
  407. case OpTypeVector:
  408. {
  409. uint32_t id = ops[0];
  410. uint32_t vecsize = ops[2];
  411. auto &base = get<SPIRType>(ops[1]);
  412. auto &vecbase = set<SPIRType>(id);
  413. vecbase = base;
  414. vecbase.vecsize = vecsize;
  415. vecbase.self = id;
  416. vecbase.parent_type = ops[1];
  417. break;
  418. }
  419. case OpTypeMatrix:
  420. {
  421. uint32_t id = ops[0];
  422. uint32_t colcount = ops[2];
  423. auto &base = get<SPIRType>(ops[1]);
  424. auto &matrixbase = set<SPIRType>(id);
  425. matrixbase = base;
  426. matrixbase.columns = colcount;
  427. matrixbase.self = id;
  428. matrixbase.parent_type = ops[1];
  429. break;
  430. }
  431. case OpTypeArray:
  432. {
  433. uint32_t id = ops[0];
  434. auto &arraybase = set<SPIRType>(id);
  435. uint32_t tid = ops[1];
  436. auto &base = get<SPIRType>(tid);
  437. arraybase = base;
  438. arraybase.parent_type = tid;
  439. uint32_t cid = ops[2];
  440. ir.mark_used_as_array_length(cid);
  441. auto *c = maybe_get<SPIRConstant>(cid);
  442. bool literal = c && !c->specialization;
  443. arraybase.array_size_literal.push_back(literal);
  444. arraybase.array.push_back(literal ? c->scalar() : cid);
  445. // Do NOT set arraybase.self!
  446. break;
  447. }
  448. case OpTypeRuntimeArray:
  449. {
  450. uint32_t id = ops[0];
  451. auto &base = get<SPIRType>(ops[1]);
  452. auto &arraybase = set<SPIRType>(id);
  453. arraybase = base;
  454. arraybase.array.push_back(0);
  455. arraybase.array_size_literal.push_back(true);
  456. arraybase.parent_type = ops[1];
  457. // Do NOT set arraybase.self!
  458. break;
  459. }
  460. case OpTypeImage:
  461. {
  462. uint32_t id = ops[0];
  463. auto &type = set<SPIRType>(id);
  464. type.basetype = SPIRType::Image;
  465. type.image.type = ops[1];
  466. type.image.dim = static_cast<Dim>(ops[2]);
  467. type.image.depth = ops[3] == 1;
  468. type.image.arrayed = ops[4] != 0;
  469. type.image.ms = ops[5] != 0;
  470. type.image.sampled = ops[6];
  471. type.image.format = static_cast<ImageFormat>(ops[7]);
  472. type.image.access = (length >= 9) ? static_cast<AccessQualifier>(ops[8]) : AccessQualifierMax;
  473. if (type.image.sampled == 0)
  474. SPIRV_CROSS_THROW("OpTypeImage Sampled parameter must not be zero.");
  475. break;
  476. }
  477. case OpTypeSampledImage:
  478. {
  479. uint32_t id = ops[0];
  480. uint32_t imagetype = ops[1];
  481. auto &type = set<SPIRType>(id);
  482. type = get<SPIRType>(imagetype);
  483. type.basetype = SPIRType::SampledImage;
  484. type.self = id;
  485. break;
  486. }
  487. case OpTypeSampler:
  488. {
  489. uint32_t id = ops[0];
  490. auto &type = set<SPIRType>(id);
  491. type.basetype = SPIRType::Sampler;
  492. break;
  493. }
  494. case OpTypePointer:
  495. {
  496. uint32_t id = ops[0];
  497. auto &base = get<SPIRType>(ops[2]);
  498. auto &ptrbase = set<SPIRType>(id);
  499. ptrbase = base;
  500. ptrbase.pointer = true;
  501. ptrbase.pointer_depth++;
  502. ptrbase.storage = static_cast<StorageClass>(ops[1]);
  503. if (ptrbase.storage == StorageClassAtomicCounter)
  504. ptrbase.basetype = SPIRType::AtomicCounter;
  505. ptrbase.parent_type = ops[2];
  506. // Do NOT set ptrbase.self!
  507. break;
  508. }
  509. case OpTypeForwardPointer:
  510. {
  511. uint32_t id = ops[0];
  512. auto &ptrbase = set<SPIRType>(id);
  513. ptrbase.pointer = true;
  514. ptrbase.pointer_depth++;
  515. ptrbase.storage = static_cast<StorageClass>(ops[1]);
  516. if (ptrbase.storage == StorageClassAtomicCounter)
  517. ptrbase.basetype = SPIRType::AtomicCounter;
  518. break;
  519. }
  520. case OpTypeStruct:
  521. {
  522. uint32_t id = ops[0];
  523. auto &type = set<SPIRType>(id);
  524. type.basetype = SPIRType::Struct;
  525. for (uint32_t i = 1; i < length; i++)
  526. type.member_types.push_back(ops[i]);
  527. // Check if we have seen this struct type before, with just different
  528. // decorations.
  529. //
  530. // Add workaround for issue #17 as well by looking at OpName for the struct
  531. // types, which we shouldn't normally do.
  532. // We should not normally have to consider type aliases like this to begin with
  533. // however ... glslang issues #304, #307 cover this.
  534. // For stripped names, never consider struct type aliasing.
  535. // We risk declaring the same struct multiple times, but type-punning is not allowed
  536. // so this is safe.
  537. bool consider_aliasing = !ir.get_name(type.self).empty();
  538. if (consider_aliasing)
  539. {
  540. for (auto &other : global_struct_cache)
  541. {
  542. if (ir.get_name(type.self) == ir.get_name(other) &&
  543. types_are_logically_equivalent(type, get<SPIRType>(other)))
  544. {
  545. type.type_alias = other;
  546. break;
  547. }
  548. }
  549. if (type.type_alias == 0)
  550. global_struct_cache.push_back(id);
  551. }
  552. break;
  553. }
  554. case OpTypeFunction:
  555. {
  556. uint32_t id = ops[0];
  557. uint32_t ret = ops[1];
  558. auto &func = set<SPIRFunctionPrototype>(id, ret);
  559. for (uint32_t i = 2; i < length; i++)
  560. func.parameter_types.push_back(ops[i]);
  561. break;
  562. }
  563. case OpTypeAccelerationStructureNV:
  564. {
  565. uint32_t id = ops[0];
  566. auto &type = set<SPIRType>(id);
  567. type.basetype = SPIRType::AccelerationStructureNV;
  568. break;
  569. }
  570. // Variable declaration
  571. // All variables are essentially pointers with a storage qualifier.
  572. case OpVariable:
  573. {
  574. uint32_t type = ops[0];
  575. uint32_t id = ops[1];
  576. auto storage = static_cast<StorageClass>(ops[2]);
  577. uint32_t initializer = length == 4 ? ops[3] : 0;
  578. if (storage == StorageClassFunction)
  579. {
  580. if (!current_function)
  581. SPIRV_CROSS_THROW("No function currently in scope");
  582. current_function->add_local_variable(id);
  583. }
  584. set<SPIRVariable>(id, type, storage, initializer);
  585. // hlsl based shaders don't have those decorations. force them and then reset when reading/writing images
  586. auto &ttype = get<SPIRType>(type);
  587. if (ttype.basetype == SPIRType::BaseType::Image)
  588. {
  589. ir.set_decoration(id, DecorationNonWritable);
  590. ir.set_decoration(id, DecorationNonReadable);
  591. }
  592. break;
  593. }
  594. // OpPhi
  595. // OpPhi is a fairly magical opcode.
  596. // It selects temporary variables based on which parent block we *came from*.
  597. // In high-level languages we can "de-SSA" by creating a function local, and flush out temporaries to this function-local
  598. // variable to emulate SSA Phi.
  599. case OpPhi:
  600. {
  601. if (!current_function)
  602. SPIRV_CROSS_THROW("No function currently in scope");
  603. if (!current_block)
  604. SPIRV_CROSS_THROW("No block currently in scope");
  605. uint32_t result_type = ops[0];
  606. uint32_t id = ops[1];
  607. // Instead of a temporary, create a new function-wide temporary with this ID instead.
  608. auto &var = set<SPIRVariable>(id, result_type, spv::StorageClassFunction);
  609. var.phi_variable = true;
  610. current_function->add_local_variable(id);
  611. for (uint32_t i = 2; i + 2 <= length; i += 2)
  612. current_block->phi_variables.push_back({ ops[i], ops[i + 1], id });
  613. break;
  614. }
  615. // Constants
  616. case OpSpecConstant:
  617. case OpConstant:
  618. {
  619. uint32_t id = ops[1];
  620. auto &type = get<SPIRType>(ops[0]);
  621. if (type.width > 32)
  622. set<SPIRConstant>(id, ops[0], ops[2] | (uint64_t(ops[3]) << 32), op == OpSpecConstant);
  623. else
  624. set<SPIRConstant>(id, ops[0], ops[2], op == OpSpecConstant);
  625. break;
  626. }
  627. case OpSpecConstantFalse:
  628. case OpConstantFalse:
  629. {
  630. uint32_t id = ops[1];
  631. set<SPIRConstant>(id, ops[0], uint32_t(0), op == OpSpecConstantFalse);
  632. break;
  633. }
  634. case OpSpecConstantTrue:
  635. case OpConstantTrue:
  636. {
  637. uint32_t id = ops[1];
  638. set<SPIRConstant>(id, ops[0], uint32_t(1), op == OpSpecConstantTrue);
  639. break;
  640. }
  641. case OpConstantNull:
  642. {
  643. uint32_t id = ops[1];
  644. uint32_t type = ops[0];
  645. make_constant_null(id, type);
  646. break;
  647. }
  648. case OpSpecConstantComposite:
  649. case OpConstantComposite:
  650. {
  651. uint32_t id = ops[1];
  652. uint32_t type = ops[0];
  653. auto &ctype = get<SPIRType>(type);
  654. // We can have constants which are structs and arrays.
  655. // In this case, our SPIRConstant will be a list of other SPIRConstant ids which we
  656. // can refer to.
  657. if (ctype.basetype == SPIRType::Struct || !ctype.array.empty())
  658. {
  659. set<SPIRConstant>(id, type, ops + 2, length - 2, op == OpSpecConstantComposite);
  660. }
  661. else
  662. {
  663. uint32_t elements = length - 2;
  664. if (elements > 4)
  665. SPIRV_CROSS_THROW("OpConstantComposite only supports 1, 2, 3 and 4 elements.");
  666. SPIRConstant remapped_constant_ops[4];
  667. const SPIRConstant *c[4];
  668. for (uint32_t i = 0; i < elements; i++)
  669. {
  670. // Specialization constants operations can also be part of this.
  671. // We do not know their value, so any attempt to query SPIRConstant later
  672. // will fail. We can only propagate the ID of the expression and use to_expression on it.
  673. auto *constant_op = maybe_get<SPIRConstantOp>(ops[2 + i]);
  674. auto *undef_op = maybe_get<SPIRUndef>(ops[2 + i]);
  675. if (constant_op)
  676. {
  677. if (op == OpConstantComposite)
  678. SPIRV_CROSS_THROW("Specialization constant operation used in OpConstantComposite.");
  679. remapped_constant_ops[i].make_null(get<SPIRType>(constant_op->basetype));
  680. remapped_constant_ops[i].self = constant_op->self;
  681. remapped_constant_ops[i].constant_type = constant_op->basetype;
  682. remapped_constant_ops[i].specialization = true;
  683. c[i] = &remapped_constant_ops[i];
  684. }
  685. else if (undef_op)
  686. {
  687. // Undefined, just pick 0.
  688. remapped_constant_ops[i].make_null(get<SPIRType>(undef_op->basetype));
  689. remapped_constant_ops[i].constant_type = undef_op->basetype;
  690. c[i] = &remapped_constant_ops[i];
  691. }
  692. else
  693. c[i] = &get<SPIRConstant>(ops[2 + i]);
  694. }
  695. set<SPIRConstant>(id, type, c, elements, op == OpSpecConstantComposite);
  696. }
  697. break;
  698. }
  699. // Functions
  700. case OpFunction:
  701. {
  702. uint32_t res = ops[0];
  703. uint32_t id = ops[1];
  704. // Control
  705. uint32_t type = ops[3];
  706. if (current_function)
  707. SPIRV_CROSS_THROW("Must end a function before starting a new one!");
  708. current_function = &set<SPIRFunction>(id, res, type);
  709. break;
  710. }
  711. case OpFunctionParameter:
  712. {
  713. uint32_t type = ops[0];
  714. uint32_t id = ops[1];
  715. if (!current_function)
  716. SPIRV_CROSS_THROW("Must be in a function!");
  717. current_function->add_parameter(type, id);
  718. set<SPIRVariable>(id, type, StorageClassFunction);
  719. break;
  720. }
  721. case OpFunctionEnd:
  722. {
  723. if (current_block)
  724. {
  725. // Very specific error message, but seems to come up quite often.
  726. SPIRV_CROSS_THROW(
  727. "Cannot end a function before ending the current block.\n"
  728. "Likely cause: If this SPIR-V was created from glslang HLSL, make sure the entry point is valid.");
  729. }
  730. current_function = nullptr;
  731. break;
  732. }
  733. // Blocks
  734. case OpLabel:
  735. {
  736. // OpLabel always starts a block.
  737. if (!current_function)
  738. SPIRV_CROSS_THROW("Blocks cannot exist outside functions!");
  739. uint32_t id = ops[0];
  740. current_function->blocks.push_back(id);
  741. if (!current_function->entry_block)
  742. current_function->entry_block = id;
  743. if (current_block)
  744. SPIRV_CROSS_THROW("Cannot start a block before ending the current block.");
  745. current_block = &set<SPIRBlock>(id);
  746. break;
  747. }
  748. // Branch instructions end blocks.
  749. case OpBranch:
  750. {
  751. if (!current_block)
  752. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  753. uint32_t target = ops[0];
  754. current_block->terminator = SPIRBlock::Direct;
  755. current_block->next_block = target;
  756. current_block = nullptr;
  757. break;
  758. }
  759. case OpBranchConditional:
  760. {
  761. if (!current_block)
  762. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  763. current_block->condition = ops[0];
  764. current_block->true_block = ops[1];
  765. current_block->false_block = ops[2];
  766. current_block->terminator = SPIRBlock::Select;
  767. current_block = nullptr;
  768. break;
  769. }
  770. case OpSwitch:
  771. {
  772. if (!current_block)
  773. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  774. current_block->terminator = SPIRBlock::MultiSelect;
  775. current_block->condition = ops[0];
  776. current_block->default_block = ops[1];
  777. for (uint32_t i = 2; i + 2 <= length; i += 2)
  778. current_block->cases.push_back({ ops[i], ops[i + 1] });
  779. // If we jump to next block, make it break instead since we're inside a switch case block at that point.
  780. ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
  781. current_block = nullptr;
  782. break;
  783. }
  784. case OpKill:
  785. {
  786. if (!current_block)
  787. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  788. current_block->terminator = SPIRBlock::Kill;
  789. current_block = nullptr;
  790. break;
  791. }
  792. case OpReturn:
  793. {
  794. if (!current_block)
  795. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  796. current_block->terminator = SPIRBlock::Return;
  797. current_block = nullptr;
  798. break;
  799. }
  800. case OpReturnValue:
  801. {
  802. if (!current_block)
  803. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  804. current_block->terminator = SPIRBlock::Return;
  805. current_block->return_value = ops[0];
  806. current_block = nullptr;
  807. break;
  808. }
  809. case OpUnreachable:
  810. {
  811. if (!current_block)
  812. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  813. current_block->terminator = SPIRBlock::Unreachable;
  814. current_block = nullptr;
  815. break;
  816. }
  817. case OpSelectionMerge:
  818. {
  819. if (!current_block)
  820. SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
  821. current_block->next_block = ops[0];
  822. current_block->merge = SPIRBlock::MergeSelection;
  823. ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
  824. if (length >= 2)
  825. {
  826. if (ops[1] & SelectionControlFlattenMask)
  827. current_block->hint = SPIRBlock::HintFlatten;
  828. else if (ops[1] & SelectionControlDontFlattenMask)
  829. current_block->hint = SPIRBlock::HintDontFlatten;
  830. }
  831. break;
  832. }
  833. case OpLoopMerge:
  834. {
  835. if (!current_block)
  836. SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
  837. current_block->merge_block = ops[0];
  838. current_block->continue_block = ops[1];
  839. current_block->merge = SPIRBlock::MergeLoop;
  840. ir.block_meta[current_block->self] |= ParsedIR::BLOCK_META_LOOP_HEADER_BIT;
  841. ir.block_meta[current_block->merge_block] |= ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
  842. ir.continue_block_to_loop_header[current_block->continue_block] = current_block->self;
  843. // Don't add loop headers to continue blocks,
  844. // which would make it impossible branch into the loop header since
  845. // they are treated as continues.
  846. if (current_block->continue_block != current_block->self)
  847. ir.block_meta[current_block->continue_block] |= ParsedIR::BLOCK_META_CONTINUE_BIT;
  848. if (length >= 3)
  849. {
  850. if (ops[2] & LoopControlUnrollMask)
  851. current_block->hint = SPIRBlock::HintUnroll;
  852. else if (ops[2] & LoopControlDontUnrollMask)
  853. current_block->hint = SPIRBlock::HintDontUnroll;
  854. }
  855. break;
  856. }
  857. case OpSpecConstantOp:
  858. {
  859. if (length < 3)
  860. SPIRV_CROSS_THROW("OpSpecConstantOp not enough arguments.");
  861. uint32_t result_type = ops[0];
  862. uint32_t id = ops[1];
  863. auto spec_op = static_cast<Op>(ops[2]);
  864. set<SPIRConstantOp>(id, result_type, spec_op, ops + 3, length - 3);
  865. break;
  866. }
  867. // Actual opcodes.
  868. default:
  869. {
  870. if (!current_block)
  871. SPIRV_CROSS_THROW("Currently no block to insert opcode.");
  872. current_block->ops.push_back(instruction);
  873. break;
  874. }
  875. }
  876. }
  877. bool Parser::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
  878. {
  879. if (a.basetype != b.basetype)
  880. return false;
  881. if (a.width != b.width)
  882. return false;
  883. if (a.vecsize != b.vecsize)
  884. return false;
  885. if (a.columns != b.columns)
  886. return false;
  887. if (a.array.size() != b.array.size())
  888. return false;
  889. size_t array_count = a.array.size();
  890. if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
  891. return false;
  892. if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
  893. {
  894. if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
  895. return false;
  896. }
  897. if (a.member_types.size() != b.member_types.size())
  898. return false;
  899. size_t member_types = a.member_types.size();
  900. for (size_t i = 0; i < member_types; i++)
  901. {
  902. if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
  903. return false;
  904. }
  905. return true;
  906. }
  907. bool Parser::variable_storage_is_aliased(const SPIRVariable &v) const
  908. {
  909. auto &type = get<SPIRType>(v.basetype);
  910. auto *type_meta = ir.find_meta(type.self);
  911. bool ssbo = v.storage == StorageClassStorageBuffer ||
  912. (type_meta && type_meta->decoration.decoration_flags.get(DecorationBufferBlock));
  913. bool image = type.basetype == SPIRType::Image;
  914. bool counter = type.basetype == SPIRType::AtomicCounter;
  915. bool is_restrict;
  916. if (ssbo)
  917. is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
  918. else
  919. is_restrict = ir.has_decoration(v.self, DecorationRestrict);
  920. return !is_restrict && (ssbo || image || counter);
  921. }
  922. void Parser::make_constant_null(uint32_t id, uint32_t type)
  923. {
  924. auto &constant_type = get<SPIRType>(type);
  925. if (constant_type.pointer)
  926. {
  927. auto &constant = set<SPIRConstant>(id, type);
  928. constant.make_null(constant_type);
  929. }
  930. else if (!constant_type.array.empty())
  931. {
  932. assert(constant_type.parent_type);
  933. uint32_t parent_id = ir.increase_bound_by(1);
  934. make_constant_null(parent_id, constant_type.parent_type);
  935. if (!constant_type.array_size_literal.back())
  936. SPIRV_CROSS_THROW("Array size of OpConstantNull must be a literal.");
  937. SmallVector<uint32_t> elements(constant_type.array.back());
  938. for (uint32_t i = 0; i < constant_type.array.back(); i++)
  939. elements[i] = parent_id;
  940. set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
  941. }
  942. else if (!constant_type.member_types.empty())
  943. {
  944. uint32_t member_ids = ir.increase_bound_by(uint32_t(constant_type.member_types.size()));
  945. SmallVector<uint32_t> elements(constant_type.member_types.size());
  946. for (uint32_t i = 0; i < constant_type.member_types.size(); i++)
  947. {
  948. make_constant_null(member_ids + i, constant_type.member_types[i]);
  949. elements[i] = member_ids + i;
  950. }
  951. set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
  952. }
  953. else
  954. {
  955. auto &constant = set<SPIRConstant>(id, type);
  956. constant.make_null(constant_type);
  957. }
  958. }
  959. } // namespace SPIRV_CROSS_NAMESPACE