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