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