blob: 49c429cd1cad96685bca75d3ac4f3085995676f8 [file] [log] [blame]
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001/*
Hans-Kristian Arntzenf9818f02020-01-16 15:24:37 +01002 * Copyright 2018-2020 Arm Limited
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02003 *
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
17#include "spirv_parser.hpp"
18#include <assert.h>
19
20using namespace std;
21using namespace spv;
22
Hans-Kristian Arntzen9b92e682019-03-29 10:29:44 +010023namespace SPIRV_CROSS_NAMESPACE
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020024{
Hans-Kristian Arntzen3fe57d32019-04-09 12:46:23 +020025Parser::Parser(vector<uint32_t> spirv)
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020026{
27 ir.spirv = move(spirv);
28}
29
30Parser::Parser(const uint32_t *spirv_data, size_t word_count)
31{
Hans-Kristian Arntzen3fe57d32019-04-09 12:46:23 +020032 ir.spirv = vector<uint32_t>(spirv_data, spirv_data + word_count);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020033}
34
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +010035static bool decoration_is_string(Decoration decoration)
36{
37 switch (decoration)
38 {
39 case DecorationHlslSemanticGOOGLE:
40 return true;
41
42 default:
43 return false;
44 }
45}
46
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020047static inline uint32_t swap_endian(uint32_t v)
48{
49 return ((v >> 24) & 0x000000ffu) | ((v >> 8) & 0x0000ff00u) | ((v << 8) & 0x00ff0000u) | ((v << 24) & 0xff000000u);
50}
51
52static bool is_valid_spirv_version(uint32_t version)
53{
54 switch (version)
55 {
56 // Allow v99 since it tends to just work.
57 case 99:
58 case 0x10000: // SPIR-V 1.0
59 case 0x10100: // SPIR-V 1.1
60 case 0x10200: // SPIR-V 1.2
61 case 0x10300: // SPIR-V 1.3
Hans-Kristian Arntzenab1fa902019-05-07 09:53:40 +020062 case 0x10400: // SPIR-V 1.4
Hans-Kristian Arntzen02c34fe2019-09-19 10:26:04 +020063 case 0x10500: // SPIR-V 1.5
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020064 return true;
65
66 default:
67 return false;
68 }
69}
70
71void Parser::parse()
72{
73 auto &spirv = ir.spirv;
74
75 auto len = spirv.size();
76 if (len < 5)
77 SPIRV_CROSS_THROW("SPIRV file too small.");
78
79 auto s = spirv.data();
80
81 // Endian-swap if we need to.
82 if (s[0] == swap_endian(MagicNumber))
83 transform(begin(spirv), end(spirv), begin(spirv), [](uint32_t c) { return swap_endian(c); });
84
85 if (s[0] != MagicNumber || !is_valid_spirv_version(s[1]))
86 SPIRV_CROSS_THROW("Invalid SPIRV format.");
87
88 uint32_t bound = s[3];
Hans-Kristian Arntzen92a42942020-02-14 12:57:01 +010089
90 const uint32_t MaximumNumberOfIDs = 0x3fffff;
91 if (bound > MaximumNumberOfIDs)
92 SPIRV_CROSS_THROW("ID bound exceeds limit of 0x3fffff.\n");
93
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020094 ir.set_id_bounds(bound);
95
96 uint32_t offset = 5;
97
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +020098 SmallVector<Instruction> instructions;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020099 while (offset < len)
100 {
101 Instruction instr = {};
102 instr.op = spirv[offset] & 0xffff;
103 instr.count = (spirv[offset] >> 16) & 0xffff;
104
105 if (instr.count == 0)
106 SPIRV_CROSS_THROW("SPIR-V instructions cannot consume 0 words. Invalid SPIR-V file.");
107
108 instr.offset = offset + 1;
109 instr.length = instr.count - 1;
110
111 offset += instr.count;
112
113 if (offset > spirv.size())
114 SPIRV_CROSS_THROW("SPIR-V instruction goes out of bounds.");
115
116 instructions.push_back(instr);
117 }
118
119 for (auto &i : instructions)
120 parse(i);
121
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200122 for (auto &fixup : forward_pointer_fixups)
123 {
124 auto &target = get<SPIRType>(fixup.first);
125 auto &source = get<SPIRType>(fixup.second);
126 target.member_types = source.member_types;
127 target.basetype = source.basetype;
128 target.self = source.self;
129 }
130 forward_pointer_fixups.clear();
131
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200132 if (current_function)
133 SPIRV_CROSS_THROW("Function was not terminated.");
134 if (current_block)
135 SPIRV_CROSS_THROW("Block was not terminated.");
136}
137
138const uint32_t *Parser::stream(const Instruction &instr) const
139{
140 // If we're not going to use any arguments, just return nullptr.
141 // We want to avoid case where we return an out of range pointer
142 // that trips debug assertions on some platforms.
143 if (!instr.length)
144 return nullptr;
145
146 if (instr.offset + instr.length > ir.spirv.size())
147 SPIRV_CROSS_THROW("Compiler::stream() out of range.");
148 return &ir.spirv[instr.offset];
149}
150
Hans-Kristian Arntzen3fe57d32019-04-09 12:46:23 +0200151static string extract_string(const vector<uint32_t> &spirv, uint32_t offset)
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200152{
153 string ret;
154 for (uint32_t i = offset; i < spirv.size(); i++)
155 {
156 uint32_t w = spirv[i];
157
158 for (uint32_t j = 0; j < 4; j++, w >>= 8)
159 {
160 char c = w & 0xff;
161 if (c == '\0')
162 return ret;
163 ret += c;
164 }
165 }
166
167 SPIRV_CROSS_THROW("String was not terminated before EOF");
168}
169
170void Parser::parse(const Instruction &instruction)
171{
172 auto *ops = stream(instruction);
173 auto op = static_cast<Op>(instruction.op);
174 uint32_t length = instruction.length;
175
176 switch (op)
177 {
lifpan00a765e2018-11-15 09:04:36 +0800178 case OpSourceContinued:
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200179 case OpSourceExtension:
180 case OpNop:
lifpan91610962018-11-13 14:28:38 +0800181 case OpModuleProcessed:
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200182 break;
183
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +0200184 case OpString:
185 {
186 set<SPIRString>(ops[0], extract_string(ir.spirv, instruction.offset + 1));
187 break;
188 }
189
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200190 case OpMemoryModel:
191 ir.addressing_model = static_cast<AddressingModel>(ops[0]);
192 ir.memory_model = static_cast<MemoryModel>(ops[1]);
193 break;
194
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200195 case OpSource:
196 {
197 auto lang = static_cast<SourceLanguage>(ops[0]);
198 switch (lang)
199 {
200 case SourceLanguageESSL:
201 ir.source.es = true;
202 ir.source.version = ops[1];
203 ir.source.known = true;
204 ir.source.hlsl = false;
205 break;
206
207 case SourceLanguageGLSL:
208 ir.source.es = false;
209 ir.source.version = ops[1];
210 ir.source.known = true;
211 ir.source.hlsl = false;
212 break;
213
214 case SourceLanguageHLSL:
215 // For purposes of cross-compiling, this is GLSL 450.
216 ir.source.es = false;
217 ir.source.version = 450;
218 ir.source.known = true;
219 ir.source.hlsl = true;
220 break;
221
222 default:
223 ir.source.known = false;
224 break;
225 }
226 break;
227 }
228
229 case OpUndef:
230 {
231 uint32_t result_type = ops[0];
232 uint32_t id = ops[1];
233 set<SPIRUndef>(id, result_type);
lifpan876627d2019-04-08 19:45:31 +0800234 if (current_block)
235 current_block->ops.push_back(instruction);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200236 break;
237 }
238
239 case OpCapability:
240 {
241 uint32_t cap = ops[0];
242 if (cap == CapabilityKernel)
243 SPIRV_CROSS_THROW("Kernel capability not supported.");
244
245 ir.declared_capabilities.push_back(static_cast<Capability>(ops[0]));
246 break;
247 }
248
249 case OpExtension:
250 {
251 auto ext = extract_string(ir.spirv, instruction.offset);
252 ir.declared_extensions.push_back(move(ext));
253 break;
254 }
255
256 case OpExtInstImport:
257 {
258 uint32_t id = ops[0];
259 auto ext = extract_string(ir.spirv, instruction.offset + 1);
260 if (ext == "GLSL.std.450")
261 set<SPIRExtension>(id, SPIRExtension::GLSL);
Lifeng Pan5ca87792019-07-04 16:03:06 +0800262 else if (ext == "DebugInfo")
263 set<SPIRExtension>(id, SPIRExtension::SPV_debug_info);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200264 else if (ext == "SPV_AMD_shader_ballot")
265 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_ballot);
266 else if (ext == "SPV_AMD_shader_explicit_vertex_parameter")
267 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter);
268 else if (ext == "SPV_AMD_shader_trinary_minmax")
269 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_trinary_minmax);
270 else if (ext == "SPV_AMD_gcn_shader")
271 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_gcn_shader);
272 else
273 set<SPIRExtension>(id, SPIRExtension::Unsupported);
274
275 // Other SPIR-V extensions which have ExtInstrs are currently not supported.
276
277 break;
278 }
279
Lifeng Pan5ca87792019-07-04 16:03:06 +0800280 case OpExtInst:
281 {
282 // The SPIR-V debug information extended instructions might come at global scope.
283 if (current_block)
284 current_block->ops.push_back(instruction);
285 break;
286 }
287
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200288 case OpEntryPoint:
289 {
290 auto itr =
291 ir.entry_points.insert(make_pair(ops[1], SPIREntryPoint(ops[1], static_cast<ExecutionModel>(ops[0]),
292 extract_string(ir.spirv, instruction.offset + 2))));
293 auto &e = itr.first->second;
294
295 // Strings need nul-terminator and consume the whole word.
296 uint32_t strlen_words = uint32_t((e.name.size() + 1 + 3) >> 2);
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +0200297
298 for (uint32_t i = strlen_words + 2; i < instruction.length; i++)
299 e.interface_variables.push_back(ops[i]);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200300
301 // Set the name of the entry point in case OpName is not provided later.
302 ir.set_name(ops[1], e.name);
303
304 // If we don't have an entry, make the first one our "default".
305 if (!ir.default_entry_point)
306 ir.default_entry_point = ops[1];
307 break;
308 }
309
310 case OpExecutionMode:
311 {
312 auto &execution = ir.entry_points[ops[0]];
313 auto mode = static_cast<ExecutionMode>(ops[1]);
314 execution.flags.set(mode);
315
316 switch (mode)
317 {
318 case ExecutionModeInvocations:
319 execution.invocations = ops[2];
320 break;
321
322 case ExecutionModeLocalSize:
323 execution.workgroup_size.x = ops[2];
324 execution.workgroup_size.y = ops[3];
325 execution.workgroup_size.z = ops[4];
326 break;
327
328 case ExecutionModeOutputVertices:
329 execution.output_vertices = ops[2];
330 break;
331
332 default:
333 break;
334 }
335 break;
336 }
337
338 case OpName:
339 {
340 uint32_t id = ops[0];
341 ir.set_name(id, extract_string(ir.spirv, instruction.offset + 1));
342 break;
343 }
344
345 case OpMemberName:
346 {
347 uint32_t id = ops[0];
348 uint32_t member = ops[1];
349 ir.set_member_name(id, member, extract_string(ir.spirv, instruction.offset + 2));
350 break;
351 }
352
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +0100353 case OpDecorationGroup:
354 {
355 // Noop, this simply means an ID should be a collector of decorations.
356 // The meta array is already a flat array of decorations which will contain the relevant decorations.
357 break;
358 }
359
360 case OpGroupDecorate:
361 {
362 uint32_t group_id = ops[0];
363 auto &decorations = ir.meta[group_id].decoration;
364 auto &flags = decorations.decoration_flags;
365
366 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
367 // i.e., we cannot just copy the meta structure directly.
368 for (uint32_t i = 1; i < length; i++)
369 {
370 uint32_t target = ops[i];
371 flags.for_each_bit([&](uint32_t bit) {
372 auto decoration = static_cast<Decoration>(bit);
373
374 if (decoration_is_string(decoration))
375 {
376 ir.set_decoration_string(target, decoration, ir.get_decoration_string(group_id, decoration));
377 }
378 else
379 {
380 ir.meta[target].decoration_word_offset[decoration] =
381 ir.meta[group_id].decoration_word_offset[decoration];
382 ir.set_decoration(target, decoration, ir.get_decoration(group_id, decoration));
383 }
384 });
385 }
386 break;
387 }
388
389 case OpGroupMemberDecorate:
390 {
391 uint32_t group_id = ops[0];
392 auto &flags = ir.meta[group_id].decoration.decoration_flags;
393
394 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
395 // i.e., we cannot just copy the meta structure directly.
396 for (uint32_t i = 1; i + 1 < length; i += 2)
397 {
398 uint32_t target = ops[i + 0];
399 uint32_t index = ops[i + 1];
400 flags.for_each_bit([&](uint32_t bit) {
401 auto decoration = static_cast<Decoration>(bit);
402
403 if (decoration_is_string(decoration))
404 ir.set_member_decoration_string(target, index, decoration,
405 ir.get_decoration_string(group_id, decoration));
406 else
407 ir.set_member_decoration(target, index, decoration, ir.get_decoration(group_id, decoration));
408 });
409 }
410 break;
411 }
412
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200413 case OpDecorate:
414 case OpDecorateId:
415 {
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +0100416 // OpDecorateId technically supports an array of arguments, but our only supported decorations are single uint,
417 // so merge decorate and decorate-id here.
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200418 uint32_t id = ops[0];
419
420 auto decoration = static_cast<Decoration>(ops[1]);
421 if (length >= 3)
422 {
423 ir.meta[id].decoration_word_offset[decoration] = uint32_t(&ops[2] - ir.spirv.data());
424 ir.set_decoration(id, decoration, ops[2]);
425 }
426 else
427 ir.set_decoration(id, decoration);
428
429 break;
430 }
431
432 case OpDecorateStringGOOGLE:
433 {
434 uint32_t id = ops[0];
435 auto decoration = static_cast<Decoration>(ops[1]);
436 ir.set_decoration_string(id, decoration, extract_string(ir.spirv, instruction.offset + 2));
437 break;
438 }
439
440 case OpMemberDecorate:
441 {
442 uint32_t id = ops[0];
443 uint32_t member = ops[1];
444 auto decoration = static_cast<Decoration>(ops[2]);
445 if (length >= 4)
446 ir.set_member_decoration(id, member, decoration, ops[3]);
447 else
448 ir.set_member_decoration(id, member, decoration);
449 break;
450 }
451
452 case OpMemberDecorateStringGOOGLE:
453 {
454 uint32_t id = ops[0];
455 uint32_t member = ops[1];
456 auto decoration = static_cast<Decoration>(ops[2]);
457 ir.set_member_decoration_string(id, member, decoration, extract_string(ir.spirv, instruction.offset + 3));
458 break;
459 }
460
461 // Build up basic types.
462 case OpTypeVoid:
463 {
464 uint32_t id = ops[0];
465 auto &type = set<SPIRType>(id);
466 type.basetype = SPIRType::Void;
467 break;
468 }
469
470 case OpTypeBool:
471 {
472 uint32_t id = ops[0];
473 auto &type = set<SPIRType>(id);
474 type.basetype = SPIRType::Boolean;
475 type.width = 1;
476 break;
477 }
478
479 case OpTypeFloat:
480 {
481 uint32_t id = ops[0];
482 uint32_t width = ops[1];
483 auto &type = set<SPIRType>(id);
484 if (width == 64)
485 type.basetype = SPIRType::Double;
486 else if (width == 32)
487 type.basetype = SPIRType::Float;
488 else if (width == 16)
489 type.basetype = SPIRType::Half;
490 else
491 SPIRV_CROSS_THROW("Unrecognized bit-width of floating point type.");
492 type.width = width;
493 break;
494 }
495
496 case OpTypeInt:
497 {
498 uint32_t id = ops[0];
499 uint32_t width = ops[1];
lifpanb21525b2018-11-28 14:20:24 +0800500 bool signedness = ops[2] != 0;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200501 auto &type = set<SPIRType>(id);
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +0100502 type.basetype = signedness ? to_signed_basetype(width) : to_unsigned_basetype(width);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200503 type.width = width;
504 break;
505 }
506
507 // Build composite types by "inheriting".
508 // NOTE: The self member is also copied! For pointers and array modifiers this is a good thing
509 // since we can refer to decorations on pointee classes which is needed for UBO/SSBO, I/O blocks in geometry/tess etc.
510 case OpTypeVector:
511 {
512 uint32_t id = ops[0];
513 uint32_t vecsize = ops[2];
514
515 auto &base = get<SPIRType>(ops[1]);
516 auto &vecbase = set<SPIRType>(id);
517
518 vecbase = base;
519 vecbase.vecsize = vecsize;
520 vecbase.self = id;
521 vecbase.parent_type = ops[1];
522 break;
523 }
524
525 case OpTypeMatrix:
526 {
527 uint32_t id = ops[0];
528 uint32_t colcount = ops[2];
529
530 auto &base = get<SPIRType>(ops[1]);
531 auto &matrixbase = set<SPIRType>(id);
532
533 matrixbase = base;
534 matrixbase.columns = colcount;
535 matrixbase.self = id;
536 matrixbase.parent_type = ops[1];
537 break;
538 }
539
540 case OpTypeArray:
541 {
542 uint32_t id = ops[0];
543 auto &arraybase = set<SPIRType>(id);
544
545 uint32_t tid = ops[1];
546 auto &base = get<SPIRType>(tid);
547
548 arraybase = base;
549 arraybase.parent_type = tid;
550
551 uint32_t cid = ops[2];
552 ir.mark_used_as_array_length(cid);
553 auto *c = maybe_get<SPIRConstant>(cid);
554 bool literal = c && !c->specialization;
555
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200556 // We're copying type information into Array types, so we'll need a fixup for any physical pointer
557 // references.
558 if (base.forward_pointer)
559 forward_pointer_fixups.push_back({ id, tid });
560
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200561 arraybase.array_size_literal.push_back(literal);
562 arraybase.array.push_back(literal ? c->scalar() : cid);
563 // Do NOT set arraybase.self!
564 break;
565 }
566
567 case OpTypeRuntimeArray:
568 {
569 uint32_t id = ops[0];
570
571 auto &base = get<SPIRType>(ops[1]);
572 auto &arraybase = set<SPIRType>(id);
573
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200574 // We're copying type information into Array types, so we'll need a fixup for any physical pointer
575 // references.
576 if (base.forward_pointer)
577 forward_pointer_fixups.push_back({ id, ops[1] });
578
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200579 arraybase = base;
580 arraybase.array.push_back(0);
581 arraybase.array_size_literal.push_back(true);
582 arraybase.parent_type = ops[1];
583 // Do NOT set arraybase.self!
584 break;
585 }
586
587 case OpTypeImage:
588 {
589 uint32_t id = ops[0];
590 auto &type = set<SPIRType>(id);
591 type.basetype = SPIRType::Image;
592 type.image.type = ops[1];
593 type.image.dim = static_cast<Dim>(ops[2]);
594 type.image.depth = ops[3] == 1;
595 type.image.arrayed = ops[4] != 0;
596 type.image.ms = ops[5] != 0;
597 type.image.sampled = ops[6];
598 type.image.format = static_cast<ImageFormat>(ops[7]);
599 type.image.access = (length >= 9) ? static_cast<AccessQualifier>(ops[8]) : AccessQualifierMax;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200600 break;
601 }
602
603 case OpTypeSampledImage:
604 {
605 uint32_t id = ops[0];
606 uint32_t imagetype = ops[1];
607 auto &type = set<SPIRType>(id);
608 type = get<SPIRType>(imagetype);
609 type.basetype = SPIRType::SampledImage;
610 type.self = id;
611 break;
612 }
613
614 case OpTypeSampler:
615 {
616 uint32_t id = ops[0];
617 auto &type = set<SPIRType>(id);
618 type.basetype = SPIRType::Sampler;
619 break;
620 }
621
622 case OpTypePointer:
623 {
624 uint32_t id = ops[0];
625
626 auto &base = get<SPIRType>(ops[2]);
627 auto &ptrbase = set<SPIRType>(id);
628
629 ptrbase = base;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200630 ptrbase.pointer = true;
Hans-Kristian Arntzend0b93722018-11-26 12:23:28 +0100631 ptrbase.pointer_depth++;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200632 ptrbase.storage = static_cast<StorageClass>(ops[1]);
633
634 if (ptrbase.storage == StorageClassAtomicCounter)
635 ptrbase.basetype = SPIRType::AtomicCounter;
636
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200637 if (base.forward_pointer)
638 forward_pointer_fixups.push_back({ id, ops[2] });
639
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200640 ptrbase.parent_type = ops[2];
641
642 // Do NOT set ptrbase.self!
643 break;
644 }
645
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200646 case OpTypeForwardPointer:
647 {
648 uint32_t id = ops[0];
649 auto &ptrbase = set<SPIRType>(id);
650 ptrbase.pointer = true;
651 ptrbase.pointer_depth++;
652 ptrbase.storage = static_cast<StorageClass>(ops[1]);
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200653 ptrbase.forward_pointer = true;
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200654
655 if (ptrbase.storage == StorageClassAtomicCounter)
656 ptrbase.basetype = SPIRType::AtomicCounter;
657
658 break;
659 }
660
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200661 case OpTypeStruct:
662 {
663 uint32_t id = ops[0];
664 auto &type = set<SPIRType>(id);
665 type.basetype = SPIRType::Struct;
666 for (uint32_t i = 1; i < length; i++)
667 type.member_types.push_back(ops[i]);
668
669 // Check if we have seen this struct type before, with just different
670 // decorations.
671 //
672 // Add workaround for issue #17 as well by looking at OpName for the struct
673 // types, which we shouldn't normally do.
674 // We should not normally have to consider type aliases like this to begin with
675 // however ... glslang issues #304, #307 cover this.
676
677 // For stripped names, never consider struct type aliasing.
678 // We risk declaring the same struct multiple times, but type-punning is not allowed
679 // so this is safe.
680 bool consider_aliasing = !ir.get_name(type.self).empty();
681 if (consider_aliasing)
682 {
683 for (auto &other : global_struct_cache)
684 {
685 if (ir.get_name(type.self) == ir.get_name(other) &&
686 types_are_logically_equivalent(type, get<SPIRType>(other)))
687 {
688 type.type_alias = other;
689 break;
690 }
691 }
692
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +0200693 if (type.type_alias == TypeID(0))
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200694 global_struct_cache.push_back(id);
695 }
696 break;
697 }
698
699 case OpTypeFunction:
700 {
701 uint32_t id = ops[0];
702 uint32_t ret = ops[1];
703
704 auto &func = set<SPIRFunctionPrototype>(id, ret);
705 for (uint32_t i = 2; i < length; i++)
706 func.parameter_types.push_back(ops[i]);
707 break;
708 }
709
Hans-Kristian Arntzen6b0e5582020-04-21 14:25:18 +0200710 case OpTypeAccelerationStructureKHR:
Patrick Moursda39a7b2019-02-26 15:43:03 +0100711 {
712 uint32_t id = ops[0];
713 auto &type = set<SPIRType>(id);
Hans-Kristian Arntzen6b0e5582020-04-21 14:25:18 +0200714 type.basetype = SPIRType::AccelerationStructure;
715 break;
716 }
717
718 case OpTypeRayQueryProvisionalKHR:
719 {
720 uint32_t id = ops[0];
721 auto &type = set<SPIRType>(id);
722 type.basetype = SPIRType::RayQuery;
Patrick Moursda39a7b2019-02-26 15:43:03 +0100723 break;
724 }
725
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200726 // Variable declaration
727 // All variables are essentially pointers with a storage qualifier.
728 case OpVariable:
729 {
730 uint32_t type = ops[0];
731 uint32_t id = ops[1];
732 auto storage = static_cast<StorageClass>(ops[2]);
733 uint32_t initializer = length == 4 ? ops[3] : 0;
734
735 if (storage == StorageClassFunction)
736 {
737 if (!current_function)
738 SPIRV_CROSS_THROW("No function currently in scope");
739 current_function->add_local_variable(id);
740 }
741
742 set<SPIRVariable>(id, type, storage, initializer);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200743 break;
744 }
745
746 // OpPhi
747 // OpPhi is a fairly magical opcode.
748 // It selects temporary variables based on which parent block we *came from*.
749 // In high-level languages we can "de-SSA" by creating a function local, and flush out temporaries to this function-local
750 // variable to emulate SSA Phi.
751 case OpPhi:
752 {
753 if (!current_function)
754 SPIRV_CROSS_THROW("No function currently in scope");
755 if (!current_block)
756 SPIRV_CROSS_THROW("No block currently in scope");
757
758 uint32_t result_type = ops[0];
759 uint32_t id = ops[1];
760
761 // Instead of a temporary, create a new function-wide temporary with this ID instead.
762 auto &var = set<SPIRVariable>(id, result_type, spv::StorageClassFunction);
763 var.phi_variable = true;
764
765 current_function->add_local_variable(id);
766
767 for (uint32_t i = 2; i + 2 <= length; i += 2)
768 current_block->phi_variables.push_back({ ops[i], ops[i + 1], id });
769 break;
770 }
771
772 // Constants
773 case OpSpecConstant:
774 case OpConstant:
775 {
776 uint32_t id = ops[1];
777 auto &type = get<SPIRType>(ops[0]);
778
779 if (type.width > 32)
780 set<SPIRConstant>(id, ops[0], ops[2] | (uint64_t(ops[3]) << 32), op == OpSpecConstant);
781 else
782 set<SPIRConstant>(id, ops[0], ops[2], op == OpSpecConstant);
783 break;
784 }
785
786 case OpSpecConstantFalse:
787 case OpConstantFalse:
788 {
789 uint32_t id = ops[1];
790 set<SPIRConstant>(id, ops[0], uint32_t(0), op == OpSpecConstantFalse);
791 break;
792 }
793
794 case OpSpecConstantTrue:
795 case OpConstantTrue:
796 {
797 uint32_t id = ops[1];
798 set<SPIRConstant>(id, ops[0], uint32_t(1), op == OpSpecConstantTrue);
799 break;
800 }
801
802 case OpConstantNull:
803 {
804 uint32_t id = ops[1];
805 uint32_t type = ops[0];
Hans-Kristian Arntzenb8905bb2020-03-26 11:21:23 +0100806 ir.make_constant_null(id, type, true);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200807 break;
808 }
809
810 case OpSpecConstantComposite:
811 case OpConstantComposite:
812 {
813 uint32_t id = ops[1];
814 uint32_t type = ops[0];
815
816 auto &ctype = get<SPIRType>(type);
817
818 // We can have constants which are structs and arrays.
819 // In this case, our SPIRConstant will be a list of other SPIRConstant ids which we
820 // can refer to.
821 if (ctype.basetype == SPIRType::Struct || !ctype.array.empty())
822 {
823 set<SPIRConstant>(id, type, ops + 2, length - 2, op == OpSpecConstantComposite);
824 }
825 else
826 {
827 uint32_t elements = length - 2;
828 if (elements > 4)
829 SPIRV_CROSS_THROW("OpConstantComposite only supports 1, 2, 3 and 4 elements.");
830
831 SPIRConstant remapped_constant_ops[4];
832 const SPIRConstant *c[4];
833 for (uint32_t i = 0; i < elements; i++)
834 {
835 // Specialization constants operations can also be part of this.
836 // We do not know their value, so any attempt to query SPIRConstant later
837 // will fail. We can only propagate the ID of the expression and use to_expression on it.
838 auto *constant_op = maybe_get<SPIRConstantOp>(ops[2 + i]);
Hans-Kristian Arntzendf3e21a2019-03-27 10:51:23 +0100839 auto *undef_op = maybe_get<SPIRUndef>(ops[2 + i]);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200840 if (constant_op)
841 {
842 if (op == OpConstantComposite)
843 SPIRV_CROSS_THROW("Specialization constant operation used in OpConstantComposite.");
844
845 remapped_constant_ops[i].make_null(get<SPIRType>(constant_op->basetype));
846 remapped_constant_ops[i].self = constant_op->self;
847 remapped_constant_ops[i].constant_type = constant_op->basetype;
848 remapped_constant_ops[i].specialization = true;
849 c[i] = &remapped_constant_ops[i];
850 }
Hans-Kristian Arntzendf3e21a2019-03-27 10:51:23 +0100851 else if (undef_op)
852 {
853 // Undefined, just pick 0.
854 remapped_constant_ops[i].make_null(get<SPIRType>(undef_op->basetype));
855 remapped_constant_ops[i].constant_type = undef_op->basetype;
856 c[i] = &remapped_constant_ops[i];
857 }
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200858 else
859 c[i] = &get<SPIRConstant>(ops[2 + i]);
860 }
861 set<SPIRConstant>(id, type, c, elements, op == OpSpecConstantComposite);
862 }
863 break;
864 }
865
866 // Functions
867 case OpFunction:
868 {
869 uint32_t res = ops[0];
870 uint32_t id = ops[1];
871 // Control
872 uint32_t type = ops[3];
873
874 if (current_function)
875 SPIRV_CROSS_THROW("Must end a function before starting a new one!");
876
877 current_function = &set<SPIRFunction>(id, res, type);
878 break;
879 }
880
881 case OpFunctionParameter:
882 {
883 uint32_t type = ops[0];
884 uint32_t id = ops[1];
885
886 if (!current_function)
887 SPIRV_CROSS_THROW("Must be in a function!");
888
889 current_function->add_parameter(type, id);
890 set<SPIRVariable>(id, type, StorageClassFunction);
891 break;
892 }
893
894 case OpFunctionEnd:
895 {
896 if (current_block)
897 {
898 // Very specific error message, but seems to come up quite often.
899 SPIRV_CROSS_THROW(
900 "Cannot end a function before ending the current block.\n"
901 "Likely cause: If this SPIR-V was created from glslang HLSL, make sure the entry point is valid.");
902 }
903 current_function = nullptr;
904 break;
905 }
906
907 // Blocks
908 case OpLabel:
909 {
910 // OpLabel always starts a block.
911 if (!current_function)
912 SPIRV_CROSS_THROW("Blocks cannot exist outside functions!");
913
914 uint32_t id = ops[0];
915
916 current_function->blocks.push_back(id);
917 if (!current_function->entry_block)
918 current_function->entry_block = id;
919
920 if (current_block)
921 SPIRV_CROSS_THROW("Cannot start a block before ending the current block.");
922
923 current_block = &set<SPIRBlock>(id);
924 break;
925 }
926
927 // Branch instructions end blocks.
928 case OpBranch:
929 {
930 if (!current_block)
931 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
932
933 uint32_t target = ops[0];
934 current_block->terminator = SPIRBlock::Direct;
935 current_block->next_block = target;
936 current_block = nullptr;
937 break;
938 }
939
940 case OpBranchConditional:
941 {
942 if (!current_block)
943 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
944
945 current_block->condition = ops[0];
946 current_block->true_block = ops[1];
947 current_block->false_block = ops[2];
948
949 current_block->terminator = SPIRBlock::Select;
950 current_block = nullptr;
951 break;
952 }
953
954 case OpSwitch:
955 {
956 if (!current_block)
957 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
958
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200959 current_block->terminator = SPIRBlock::MultiSelect;
960
961 current_block->condition = ops[0];
962 current_block->default_block = ops[1];
963
964 for (uint32_t i = 2; i + 2 <= length; i += 2)
965 current_block->cases.push_back({ ops[i], ops[i + 1] });
966
967 // If we jump to next block, make it break instead since we're inside a switch case block at that point.
968 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
969
970 current_block = nullptr;
971 break;
972 }
973
974 case OpKill:
975 {
976 if (!current_block)
977 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
978 current_block->terminator = SPIRBlock::Kill;
979 current_block = nullptr;
980 break;
981 }
982
983 case OpReturn:
984 {
985 if (!current_block)
986 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
987 current_block->terminator = SPIRBlock::Return;
988 current_block = nullptr;
989 break;
990 }
991
992 case OpReturnValue:
993 {
994 if (!current_block)
995 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
996 current_block->terminator = SPIRBlock::Return;
997 current_block->return_value = ops[0];
998 current_block = nullptr;
999 break;
1000 }
1001
1002 case OpUnreachable:
1003 {
1004 if (!current_block)
1005 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1006 current_block->terminator = SPIRBlock::Unreachable;
1007 current_block = nullptr;
1008 break;
1009 }
1010
1011 case OpSelectionMerge:
1012 {
1013 if (!current_block)
1014 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
1015
1016 current_block->next_block = ops[0];
1017 current_block->merge = SPIRBlock::MergeSelection;
1018 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
1019
1020 if (length >= 2)
1021 {
1022 if (ops[1] & SelectionControlFlattenMask)
1023 current_block->hint = SPIRBlock::HintFlatten;
1024 else if (ops[1] & SelectionControlDontFlattenMask)
1025 current_block->hint = SPIRBlock::HintDontFlatten;
1026 }
1027 break;
1028 }
1029
1030 case OpLoopMerge:
1031 {
1032 if (!current_block)
1033 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
1034
1035 current_block->merge_block = ops[0];
1036 current_block->continue_block = ops[1];
1037 current_block->merge = SPIRBlock::MergeLoop;
1038
1039 ir.block_meta[current_block->self] |= ParsedIR::BLOCK_META_LOOP_HEADER_BIT;
1040 ir.block_meta[current_block->merge_block] |= ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
1041
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02001042 ir.continue_block_to_loop_header[current_block->continue_block] = BlockID(current_block->self);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001043
1044 // Don't add loop headers to continue blocks,
1045 // which would make it impossible branch into the loop header since
1046 // they are treated as continues.
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02001047 if (current_block->continue_block != BlockID(current_block->self))
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001048 ir.block_meta[current_block->continue_block] |= ParsedIR::BLOCK_META_CONTINUE_BIT;
1049
1050 if (length >= 3)
1051 {
1052 if (ops[2] & LoopControlUnrollMask)
1053 current_block->hint = SPIRBlock::HintUnroll;
1054 else if (ops[2] & LoopControlDontUnrollMask)
1055 current_block->hint = SPIRBlock::HintDontUnroll;
1056 }
1057 break;
1058 }
1059
1060 case OpSpecConstantOp:
1061 {
1062 if (length < 3)
1063 SPIRV_CROSS_THROW("OpSpecConstantOp not enough arguments.");
1064
1065 uint32_t result_type = ops[0];
1066 uint32_t id = ops[1];
1067 auto spec_op = static_cast<Op>(ops[2]);
1068
1069 set<SPIRConstantOp>(id, result_type, spec_op, ops + 3, length - 3);
1070 break;
1071 }
1072
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001073 case OpLine:
1074 {
1075 // OpLine might come at global scope, but we don't care about those since they will not be declared in any
1076 // meaningful correct order.
Hans-Kristian Arntzen48a7da42019-05-28 15:51:42 +02001077 // Ignore all OpLine directives which live outside a function.
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001078 if (current_block)
1079 current_block->ops.push_back(instruction);
1080
Hans-Kristian Arntzen48a7da42019-05-28 15:51:42 +02001081 // Line directives may arrive before first OpLabel.
1082 // Treat this as the line of the function declaration,
1083 // so warnings for arguments can propagate properly.
1084 if (current_function)
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001085 {
1086 // Store the first one we find and emit it before creating the function prototype.
1087 if (current_function->entry_line.file_id == 0)
1088 {
1089 current_function->entry_line.file_id = ops[0];
1090 current_function->entry_line.line_literal = ops[1];
1091 }
1092 }
1093 break;
1094 }
1095
Lifeng Pan5ca87792019-07-04 16:03:06 +08001096 case OpNoLine:
1097 {
1098 // OpNoLine might come at global scope.
1099 if (current_block)
1100 current_block->ops.push_back(instruction);
Hans-Kristian Arntzen13378ad2019-07-05 10:25:18 +02001101 break;
Lifeng Pan5ca87792019-07-04 16:03:06 +08001102 }
1103
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001104 // Actual opcodes.
1105 default:
1106 {
1107 if (!current_block)
1108 SPIRV_CROSS_THROW("Currently no block to insert opcode.");
1109
1110 current_block->ops.push_back(instruction);
1111 break;
1112 }
1113 }
1114}
1115
1116bool Parser::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
1117{
1118 if (a.basetype != b.basetype)
1119 return false;
1120 if (a.width != b.width)
1121 return false;
1122 if (a.vecsize != b.vecsize)
1123 return false;
1124 if (a.columns != b.columns)
1125 return false;
1126 if (a.array.size() != b.array.size())
1127 return false;
1128
1129 size_t array_count = a.array.size();
1130 if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
1131 return false;
1132
1133 if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
1134 {
1135 if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
1136 return false;
1137 }
1138
1139 if (a.member_types.size() != b.member_types.size())
1140 return false;
1141
1142 size_t member_types = a.member_types.size();
1143 for (size_t i = 0; i < member_types; i++)
1144 {
1145 if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
1146 return false;
1147 }
1148
1149 return true;
1150}
1151
1152bool Parser::variable_storage_is_aliased(const SPIRVariable &v) const
1153{
1154 auto &type = get<SPIRType>(v.basetype);
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +01001155
1156 auto *type_meta = ir.find_meta(type.self);
1157
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001158 bool ssbo = v.storage == StorageClassStorageBuffer ||
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +01001159 (type_meta && type_meta->decoration.decoration_flags.get(DecorationBufferBlock));
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001160 bool image = type.basetype == SPIRType::Image;
1161 bool counter = type.basetype == SPIRType::AtomicCounter;
1162
1163 bool is_restrict;
1164 if (ssbo)
1165 is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
1166 else
1167 is_restrict = ir.has_decoration(v.self, DecorationRestrict);
1168
1169 return !is_restrict && (ssbo || image || counter);
1170}
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001171} // namespace SPIRV_CROSS_NAMESPACE