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