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