Debian Codegraph @

thirdparty/spirv-cross/spirv_cross.cpp

raw symbols SCIP
1 /*
2 * Copyright 2015-2021 Arm Limited
3 * SPDX-License-Identifier: Apache-2.0 OR MIT
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 /*
19 * At your option, you may choose to accept this material under either:
20 * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
21 * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
22 */
23
24 #include "spirv_cross.hpp"
25 #include "GLSL.std.450.h"
26 #include "spirv_cfg.hpp"
27 #include "spirv_common.hpp"
28 #include "spirv_parser.hpp"
29 #include <algorithm>
30 #include <cstring>
31 #include <utility>
32
33 using namespace std;
34 using namespace spv;
35 using namespace SPIRV_CROSS_NAMESPACE;
36
37 Compiler::Compiler(vector<uint32_t> ir_)
38 {
39 Parser parser(std::move(ir_));
40 parser.parse();
41 set_ir(std::move(parser.get_parsed_ir()));
42 }
43
44 Compiler::Compiler(const uint32_t *ir_, size_t word_count)
45 {
46 Parser parser(ir_, word_count);
47 parser.parse();
48 set_ir(std::move(parser.get_parsed_ir()));
49 }
50
51 Compiler::Compiler(const ParsedIR &ir_)
52 {
53 set_ir(ir_);
54 }
55
56 Compiler::Compiler(ParsedIR &&ir_)
57 {
58 set_ir(std::move(ir_));
59 }
60
61 void Compiler::set_ir(ParsedIR &&ir_)
62 {
63 ir = std::move(ir_);
64 parse_fixup();
65 }
66
67 void Compiler::set_ir(const ParsedIR &ir_)
68 {
69 ir = ir_;
70 parse_fixup();
71 }
72
73 string Compiler::compile()
74 {
75 return "";
76 }
77
78 bool Compiler::variable_storage_is_aliased(const SPIRVariable &v)
79 {
80 auto &type = get<SPIRType>(v.basetype);
81 bool ssbo = v.storage == StorageClassStorageBuffer ||
82 ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
83 bool image = type.basetype == SPIRType::Image;
84 bool counter = type.basetype == SPIRType::AtomicCounter;
85 bool buffer_reference = type.storage == StorageClassPhysicalStorageBuffer;
86
87 bool is_restrict;
88 if (ssbo)
89 is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
90 else
91 is_restrict = has_decoration(v.self, DecorationRestrict);
92
93 return !is_restrict && (ssbo || image || counter || buffer_reference);
94 }
95
96 bool Compiler::block_is_control_dependent(const SPIRBlock &block)
97 {
98 for (auto &i : block.ops)
99 {
100 auto ops = stream(i);
101 auto op = static_cast<Op>(i.op);
102
103 switch (op)
104 {
105 case OpFunctionCall:
106 {
107 uint32_t func = ops[2];
108 if (function_is_control_dependent(get<SPIRFunction>(func)))
109 return true;
110 break;
111 }
112
113 // Derivatives
114 case OpDPdx:
115 case OpDPdxCoarse:
116 case OpDPdxFine:
117 case OpDPdy:
118 case OpDPdyCoarse:
119 case OpDPdyFine:
120 case OpFwidth:
121 case OpFwidthCoarse:
122 case OpFwidthFine:
123
124 // Anything implicit LOD
125 case OpImageSampleImplicitLod:
126 case OpImageSampleDrefImplicitLod:
127 case OpImageSampleProjImplicitLod:
128 case OpImageSampleProjDrefImplicitLod:
129 case OpImageSparseSampleImplicitLod:
130 case OpImageSparseSampleDrefImplicitLod:
131 case OpImageSparseSampleProjImplicitLod:
132 case OpImageSparseSampleProjDrefImplicitLod:
133 case OpImageQueryLod:
134 case OpImageDrefGather:
135 case OpImageGather:
136 case OpImageSparseDrefGather:
137 case OpImageSparseGather:
138
139 // Anything subgroups
140 case OpGroupNonUniformElect:
141 case OpGroupNonUniformAll:
142 case OpGroupNonUniformAny:
143 case OpGroupNonUniformAllEqual:
144 case OpGroupNonUniformBroadcast:
145 case OpGroupNonUniformBroadcastFirst:
146 case OpGroupNonUniformBallot:
147 case OpGroupNonUniformInverseBallot:
148 case OpGroupNonUniformBallotBitExtract:
149 case OpGroupNonUniformBallotBitCount:
150 case OpGroupNonUniformBallotFindLSB:
151 case OpGroupNonUniformBallotFindMSB:
152 case OpGroupNonUniformShuffle:
153 case OpGroupNonUniformShuffleXor:
154 case OpGroupNonUniformShuffleUp:
155 case OpGroupNonUniformShuffleDown:
156 case OpGroupNonUniformIAdd:
157 case OpGroupNonUniformFAdd:
158 case OpGroupNonUniformIMul:
159 case OpGroupNonUniformFMul:
160 case OpGroupNonUniformSMin:
161 case OpGroupNonUniformUMin:
162 case OpGroupNonUniformFMin:
163 case OpGroupNonUniformSMax:
164 case OpGroupNonUniformUMax:
165 case OpGroupNonUniformFMax:
166 case OpGroupNonUniformBitwiseAnd:
167 case OpGroupNonUniformBitwiseOr:
168 case OpGroupNonUniformBitwiseXor:
169 case OpGroupNonUniformLogicalAnd:
170 case OpGroupNonUniformLogicalOr:
171 case OpGroupNonUniformLogicalXor:
172 case OpGroupNonUniformQuadBroadcast:
173 case OpGroupNonUniformQuadSwap:
174 case OpGroupNonUniformRotateKHR:
175
176 // Control barriers
177 case OpControlBarrier:
178 return true;
179
180 default:
181 break;
182 }
183 }
184
185 return false;
186 }
187
188 bool Compiler::block_is_pure(const SPIRBlock &block)
189 {
190 // This is a global side effect of the function.
191 if (block.terminator == SPIRBlock::Kill ||
192 block.terminator == SPIRBlock::TerminateRay ||
193 block.terminator == SPIRBlock::IgnoreIntersection ||
194 block.terminator == SPIRBlock::EmitMeshTasks)
195 return false;
196
197 for (auto &i : block.ops)
198 {
199 auto ops = stream(i);
200 auto op = static_cast<Op>(i.op);
201
202 switch (op)
203 {
204 case OpFunctionCall:
205 {
206 uint32_t func = ops[2];
207 if (!function_is_pure(get<SPIRFunction>(func)))
208 return false;
209 break;
210 }
211
212 case OpCopyMemory:
213 case OpStore:
214 case OpCooperativeMatrixStoreKHR:
215 {
216 auto &type = expression_type(ops[0]);
217 if (type.storage != StorageClassFunction)
218 return false;
219 break;
220 }
221
222 case OpImageWrite:
223 return false;
224
225 // Atomics are impure.
226 case OpAtomicLoad:
227 case OpAtomicStore:
228 case OpAtomicExchange:
229 case OpAtomicCompareExchange:
230 case OpAtomicCompareExchangeWeak:
231 case OpAtomicIIncrement:
232 case OpAtomicIDecrement:
233 case OpAtomicIAdd:
234 case OpAtomicISub:
235 case OpAtomicSMin:
236 case OpAtomicUMin:
237 case OpAtomicSMax:
238 case OpAtomicUMax:
239 case OpAtomicAnd:
240 case OpAtomicOr:
241 case OpAtomicXor:
242 return false;
243
244 // Geometry shader builtins modify global state.
245 case OpEndPrimitive:
246 case OpEmitStreamVertex:
247 case OpEndStreamPrimitive:
248 case OpEmitVertex:
249 return false;
250
251 // Mesh shader functions modify global state.
252 // (EmitMeshTasks is a terminator).
253 case OpSetMeshOutputsEXT:
254 return false;
255
256 // Barriers disallow any reordering, so we should treat blocks with barrier as writing.
257 case OpControlBarrier:
258 case OpMemoryBarrier:
259 return false;
260
261 // Ray tracing builtins are impure.
262 case OpReportIntersectionKHR:
263 case OpIgnoreIntersectionNV:
264 case OpTerminateRayNV:
265 case OpTraceNV:
266 case OpTraceRayKHR:
267 case OpExecuteCallableNV:
268 case OpExecuteCallableKHR:
269 case OpRayQueryInitializeKHR:
270 case OpRayQueryTerminateKHR:
271 case OpRayQueryGenerateIntersectionKHR:
272 case OpRayQueryConfirmIntersectionKHR:
273 case OpRayQueryProceedKHR:
274 // There are various getters in ray query, but they are considered pure.
275 return false;
276
277 // OpExtInst is potentially impure depending on extension, but GLSL builtins are at least pure.
278
279 case OpDemoteToHelperInvocationEXT:
280 // This is a global side effect of the function.
281 return false;
282
283 case OpExtInst:
284 {
285 uint32_t extension_set = ops[2];
286 if (get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
287 {
288 auto op_450 = static_cast<GLSLstd450>(ops[3]);
289 switch (op_450)
290 {
291 case GLSLstd450Modf:
292 case GLSLstd450Frexp:
293 {
294 auto &type = expression_type(ops[5]);
295 if (type.storage != StorageClassFunction)
296 return false;
297 break;
298 }
299
300 default:
301 break;
302 }
303 }
304 break;
305 }
306
307 default:
308 break;
309 }
310 }
311
312 return true;
313 }
314
315 string Compiler::to_name(uint32_t id, bool allow_alias) const
316 {
317 if (allow_alias && ir.ids[id].get_type() == TypeType)
318 {
319 // If this type is a simple alias, emit the
320 // name of the original type instead.
321 // We don't want to override the meta alias
322 // as that can be overridden by the reflection APIs after parse.
323 auto &type = get<SPIRType>(id);
324 if (type.type_alias)
325 {
326 // If the alias master has been specially packed, we will have emitted a clean variant as well,
327 // so skip the name aliasing here.
328 if (!has_extended_decoration(type.type_alias, SPIRVCrossDecorationBufferBlockRepacked))
329 return to_name(type.type_alias);
330 }
331 }
332
333 auto &alias = ir.get_name(id);
334 if (alias.empty())
335 return join("_", id);
336 else
337 return alias;
338 }
339
340 bool Compiler::function_is_pure(const SPIRFunction &func)
341 {
342 for (auto block : func.blocks)
343 if (!block_is_pure(get<SPIRBlock>(block)))
344 return false;
345
346 return true;
347 }
348
349 bool Compiler::function_is_control_dependent(const SPIRFunction &func)
350 {
351 for (auto block : func.blocks)
352 if (block_is_control_dependent(get<SPIRBlock>(block)))
353 return true;
354
355 return false;
356 }
357
358 void Compiler::register_global_read_dependencies(const SPIRBlock &block, uint32_t id)
359 {
360 for (auto &i : block.ops)
361 {
362 auto ops = stream(i);
363 auto op = static_cast<Op>(i.op);
364
365 switch (op)
366 {
367 case OpFunctionCall:
368 {
369 uint32_t func = ops[2];
370 register_global_read_dependencies(get<SPIRFunction>(func), id);
371 break;
372 }
373
374 case OpLoad:
375 case OpCooperativeMatrixLoadKHR:
376 case OpImageRead:
377 {
378 // If we're in a storage class which does not get invalidated, adding dependencies here is no big deal.
379 auto *var = maybe_get_backing_variable(ops[2]);
380 if (var && var->storage != StorageClassFunction)
381 {
382 auto &type = get<SPIRType>(var->basetype);
383
384 // InputTargets are immutable.
385 if (type.basetype != SPIRType::Image && type.image.dim != DimSubpassData)
386 var->dependees.push_back(id);
387 }
388 break;
389 }
390
391 default:
392 break;
393 }
394 }
395 }
396
397 void Compiler::register_global_read_dependencies(const SPIRFunction &func, uint32_t id)
398 {
399 for (auto block : func.blocks)
400 register_global_read_dependencies(get<SPIRBlock>(block), id);
401 }
402
403 SPIRVariable *Compiler::maybe_get_backing_variable(uint32_t chain)
404 {
405 auto *var = maybe_get<SPIRVariable>(chain);
406 if (!var)
407 {
408 auto *cexpr = maybe_get<SPIRExpression>(chain);
409 if (cexpr)
410 var = maybe_get<SPIRVariable>(cexpr->loaded_from);
411
412 auto *access_chain = maybe_get<SPIRAccessChain>(chain);
413 if (access_chain)
414 var = maybe_get<SPIRVariable>(access_chain->loaded_from);
415 }
416
417 return var;
418 }
419
420 void Compiler::register_read(uint32_t expr, uint32_t chain, bool forwarded)
421 {
422 auto &e = get<SPIRExpression>(expr);
423 auto *var = maybe_get_backing_variable(chain);
424
425 if (var)
426 {
427 e.loaded_from = var->self;
428
429 // If the backing variable is immutable, we do not need to depend on the variable.
430 if (forwarded && !is_immutable(var->self))
431 var->dependees.push_back(e.self);
432
433 // If we load from a parameter, make sure we create "inout" if we also write to the parameter.
434 // The default is "in" however, so we never invalidate our compilation by reading.
435 if (var && var->parameter)
436 var->parameter->read_count++;
437 }
438 }
439
440 void Compiler::register_write(uint32_t chain)
441 {
442 auto *var = maybe_get<SPIRVariable>(chain);
443 if (!var)
444 {
445 // If we're storing through an access chain, invalidate the backing variable instead.
446 auto *expr = maybe_get<SPIRExpression>(chain);
447 if (expr && expr->loaded_from)
448 var = maybe_get<SPIRVariable>(expr->loaded_from);
449
450 auto *access_chain = maybe_get<SPIRAccessChain>(chain);
451 if (access_chain && access_chain->loaded_from)
452 var = maybe_get<SPIRVariable>(access_chain->loaded_from);
453 }
454
455 auto &chain_type = expression_type(chain);
456
457 if (var)
458 {
459 bool check_argument_storage_qualifier = true;
460 auto &type = expression_type(chain);
461
462 // If our variable is in a storage class which can alias with other buffers,
463 // invalidate all variables which depend on aliased variables. And if this is a
464 // variable pointer, then invalidate all variables regardless.
465 if (get_variable_data_type(*var).pointer)
466 {
467 flush_all_active_variables();
468
469 if (type.pointer_depth == 1)
470 {
471 // We have a backing variable which is a pointer-to-pointer type.
472 // We are storing some data through a pointer acquired through that variable,
473 // but we are not writing to the value of the variable itself,
474 // i.e., we are not modifying the pointer directly.
475 // If we are storing a non-pointer type (pointer_depth == 1),
476 // we know that we are storing some unrelated data.
477 // A case here would be
478 // void foo(Foo * const *arg) {
479 // Foo *bar = *arg;
480 // bar->unrelated = 42;
481 // }
482 // arg, the argument is constant.
483 check_argument_storage_qualifier = false;
484 }
485 }
486
487 if (type.storage == StorageClassPhysicalStorageBuffer || variable_storage_is_aliased(*var))
488 flush_all_aliased_variables();
489 else if (var)
490 flush_dependees(*var);
491
492 // We tried to write to a parameter which is not marked with out qualifier, force a recompile.
493 if (check_argument_storage_qualifier && var->parameter && var->parameter->write_count == 0)
494 {
495 var->parameter->write_count++;
496 force_recompile();
497 }
498 }
499 else if (chain_type.pointer)
500 {
501 // If we stored through a variable pointer, then we don't know which
502 // variable we stored to. So *all* expressions after this point need to
503 // be invalidated.
504 // FIXME: If we can prove that the variable pointer will point to
505 // only certain variables, we can invalidate only those.
506 flush_all_active_variables();
507 }
508
509 // If chain_type.pointer is false, we're not writing to memory backed variables, but temporaries instead.
510 // This can happen in copy_logical_type where we unroll complex reads and writes to temporaries.
511 }
512
513 void Compiler::flush_dependees(SPIRVariable &var)
514 {
515 for (auto expr : var.dependees)
516 invalid_expressions.insert(expr);
517 var.dependees.clear();
518 }
519
520 void Compiler::flush_all_aliased_variables()
521 {
522 for (auto aliased : aliased_variables)
523 flush_dependees(get<SPIRVariable>(aliased));
524 }
525
526 void Compiler::flush_all_atomic_capable_variables()
527 {
528 for (auto global : global_variables)
529 flush_dependees(get<SPIRVariable>(global));
530 flush_all_aliased_variables();
531 }
532
533 void Compiler::flush_control_dependent_expressions(uint32_t block_id)
534 {
535 auto &block = get<SPIRBlock>(block_id);
536 for (auto &expr : block.invalidate_expressions)
537 invalid_expressions.insert(expr);
538 block.invalidate_expressions.clear();
539 }
540
541 void Compiler::flush_all_active_variables()
542 {
543 // Invalidate all temporaries we read from variables in this block since they were forwarded.
544 // Invalidate all temporaries we read from globals.
545 for (auto &v : current_function->local_variables)
546 flush_dependees(get<SPIRVariable>(v));
547 for (auto &arg : current_function->arguments)
548 flush_dependees(get<SPIRVariable>(arg.id));
549 for (auto global : global_variables)
550 flush_dependees(get<SPIRVariable>(global));
551
552 flush_all_aliased_variables();
553 }
554
555 uint32_t Compiler::expression_type_id(uint32_t id) const
556 {
557 switch (ir.ids[id].get_type())
558 {
559 case TypeVariable:
560 return get<SPIRVariable>(id).basetype;
561
562 case TypeExpression:
563 return get<SPIRExpression>(id).expression_type;
564
565 case TypeConstant:
566 return get<SPIRConstant>(id).constant_type;
567
568 case TypeConstantOp:
569 return get<SPIRConstantOp>(id).basetype;
570
571 case TypeUndef:
572 return get<SPIRUndef>(id).basetype;
573
574 case TypeCombinedImageSampler:
575 return get<SPIRCombinedImageSampler>(id).combined_type;
576
577 case TypeAccessChain:
578 return get<SPIRAccessChain>(id).basetype;
579
580 default:
581 SPIRV_CROSS_THROW("Cannot resolve expression type.");
582 }
583 }
584
585 const SPIRType &Compiler::expression_type(uint32_t id) const
586 {
587 return get<SPIRType>(expression_type_id(id));
588 }
589
590 bool Compiler::expression_is_lvalue(uint32_t id) const
591 {
592 auto &type = expression_type(id);
593
594 switch (type.basetype)
595 {
596 case SPIRType::SampledImage:
597 case SPIRType::Image:
598 case SPIRType::Sampler:
599 return false;
600
601 default:
602 return true;
603 }
604 }
605
606 bool Compiler::is_immutable(uint32_t id) const
607 {
608 if (ir.ids[id].get_type() == TypeVariable)
609 {
610 auto &var = get<SPIRVariable>(id);
611
612 // Anything we load from the UniformConstant address space is guaranteed to be immutable.
613 bool pointer_to_const = var.storage == StorageClassUniformConstant;
614 return pointer_to_const || var.phi_variable || !expression_is_lvalue(id);
615 }
616 else if (ir.ids[id].get_type() == TypeAccessChain)
617 return get<SPIRAccessChain>(id).immutable;
618 else if (ir.ids[id].get_type() == TypeExpression)
619 return get<SPIRExpression>(id).immutable;
620 else if (ir.ids[id].get_type() == TypeConstant || ir.ids[id].get_type() == TypeConstantOp ||
621 ir.ids[id].get_type() == TypeUndef)
622 return true;
623 else
624 return false;
625 }
626
627 static inline bool storage_class_is_interface(spv::StorageClass storage)
628 {
629 switch (storage)
630 {
631 case StorageClassInput:
632 case StorageClassOutput:
633 case StorageClassUniform:
634 case StorageClassUniformConstant:
635 case StorageClassAtomicCounter:
636 case StorageClassPushConstant:
637 case StorageClassStorageBuffer:
638 return true;
639
640 default:
641 return false;
642 }
643 }
644
645 bool Compiler::is_hidden_variable(const SPIRVariable &var, bool include_builtins) const
646 {
647 if ((is_builtin_variable(var) && !include_builtins) || var.remapped_variable)
648 return true;
649
650 // Combined image samplers are always considered active as they are "magic" variables.
651 if (find_if(begin(combined_image_samplers), end(combined_image_samplers), [&var](const CombinedImageSampler &samp) {
652 return samp.combined_id == var.self;
653 }) != end(combined_image_samplers))
654 {
655 return false;
656 }
657
658 // In SPIR-V 1.4 and up we must also use the active variable interface to disable global variables
659 // which are not part of the entry point.
660 if (ir.get_spirv_version() >= 0x10400 && var.storage != spv::StorageClassGeneric &&
661 var.storage != spv::StorageClassFunction && !interface_variable_exists_in_entry_point(var.self))
662 {
663 return true;
664 }
665
666 return check_active_interface_variables && storage_class_is_interface(var.storage) &&
667 active_interface_variables.find(var.self) == end(active_interface_variables);
668 }
669
670 bool Compiler::is_builtin_type(const SPIRType &type) const
671 {
672 auto *type_meta = ir.find_meta(type.self);
673
674 // We can have builtin structs as well. If one member of a struct is builtin, the struct must also be builtin.
675 if (type_meta)
676 for (auto &m : type_meta->members)
677 if (m.builtin)
678 return true;
679
680 return false;
681 }
682
683 bool Compiler::is_builtin_variable(const SPIRVariable &var) const
684 {
685 auto *m = ir.find_meta(var.self);
686
687 if (var.compat_builtin || (m && m->decoration.builtin))
688 return true;
689 else
690 return is_builtin_type(get<SPIRType>(var.basetype));
691 }
692
693 bool Compiler::is_member_builtin(const SPIRType &type, uint32_t index, BuiltIn *builtin) const
694 {
695 auto *type_meta = ir.find_meta(type.self);
696
697 if (type_meta)
698 {
699 auto &memb = type_meta->members;
700 if (index < memb.size() && memb[index].builtin)
701 {
702 if (builtin)
703 *builtin = memb[index].builtin_type;
704 return true;
705 }
706 }
707
708 return false;
709 }
710
711 bool Compiler::is_scalar(const SPIRType &type) const
712 {
713 return type.basetype != SPIRType::Struct && type.vecsize == 1 && type.columns == 1;
714 }
715
716 bool Compiler::is_vector(const SPIRType &type) const
717 {
718 return type.vecsize > 1 && type.columns == 1;
719 }
720
721 bool Compiler::is_matrix(const SPIRType &type) const
722 {
723 return type.vecsize > 1 && type.columns > 1;
724 }
725
726 bool Compiler::is_array(const SPIRType &type) const
727 {
728 return type.op == OpTypeArray || type.op == OpTypeRuntimeArray;
729 }
730
731 bool Compiler::is_pointer(const SPIRType &type) const
732 {
733 return type.op == OpTypePointer && type.basetype != SPIRType::Unknown; // Ignore function pointers.
734 }
735
736 bool Compiler::is_physical_pointer(const SPIRType &type) const
737 {
738 return type.op == OpTypePointer && type.storage == StorageClassPhysicalStorageBuffer;
739 }
740
741 bool Compiler::is_physical_pointer_to_buffer_block(const SPIRType &type) const
742 {
743 return is_physical_pointer(type) && get_pointee_type(type).self == type.parent_type &&
744 (has_decoration(type.self, DecorationBlock) ||
745 has_decoration(type.self, DecorationBufferBlock));
746 }
747
748 bool Compiler::is_runtime_size_array(const SPIRType &type)
749 {
750 return type.op == OpTypeRuntimeArray;
751 }
752
753 ShaderResources Compiler::get_shader_resources() const
754 {
755 return get_shader_resources(nullptr);
756 }
757
758 ShaderResources Compiler::get_shader_resources(const unordered_set<VariableID> &active_variables) const
759 {
760 return get_shader_resources(&active_variables);
761 }
762
763 bool Compiler::InterfaceVariableAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
764 {
765 uint32_t variable = 0;
766 switch (opcode)
767 {
768 // Need this first, otherwise, GCC complains about unhandled switch statements.
769 default:
770 break;
771
772 case OpFunctionCall:
773 {
774 // Invalid SPIR-V.
775 if (length < 3)
776 return false;
777
778 uint32_t count = length - 3;
779 args += 3;
780 for (uint32_t i = 0; i < count; i++)
781 {
782 auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
783 if (var && storage_class_is_interface(var->storage))
784 variables.insert(args[i]);
785 }
786 break;
787 }
788
789 case OpSelect:
790 {
791 // Invalid SPIR-V.
792 if (length < 5)
793 return false;
794
795 uint32_t count = length - 3;
796 args += 3;
797 for (uint32_t i = 0; i < count; i++)
798 {
799 auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
800 if (var && storage_class_is_interface(var->storage))
801 variables.insert(args[i]);
802 }
803 break;
804 }
805
806 case OpPhi:
807 {
808 // Invalid SPIR-V.
809 if (length < 2)
810 return false;
811
812 uint32_t count = length - 2;
813 args += 2;
814 for (uint32_t i = 0; i < count; i += 2)
815 {
816 auto *var = compiler.maybe_get<SPIRVariable>(args[i]);
817 if (var && storage_class_is_interface(var->storage))
818 variables.insert(args[i]);
819 }
820 break;
821 }
822
823 case OpAtomicStore:
824 case OpStore:
825 case OpCooperativeMatrixStoreKHR:
826 // Invalid SPIR-V.
827 if (length < 1)
828 return false;
829 variable = args[0];
830 break;
831
832 case OpCopyMemory:
833 {
834 if (length < 2)
835 return false;
836
837 auto *var = compiler.maybe_get<SPIRVariable>(args[0]);
838 if (var && storage_class_is_interface(var->storage))
839 variables.insert(args[0]);
840
841 var = compiler.maybe_get<SPIRVariable>(args[1]);
842 if (var && storage_class_is_interface(var->storage))
843 variables.insert(args[1]);
844 break;
845 }
846
847 case OpExtInst:
848 {
849 if (length < 3)
850 return false;
851 auto &extension_set = compiler.get<SPIRExtension>(args[2]);
852 switch (extension_set.ext)
853 {
854 case SPIRExtension::GLSL:
855 {
856 auto op = static_cast<GLSLstd450>(args[3]);
857
858 switch (op)
859 {
860 case GLSLstd450InterpolateAtCentroid:
861 case GLSLstd450InterpolateAtSample:
862 case GLSLstd450InterpolateAtOffset:
863 {
864 auto *var = compiler.maybe_get<SPIRVariable>(args[4]);
865 if (var && storage_class_is_interface(var->storage))
866 variables.insert(args[4]);
867 break;
868 }
869
870 case GLSLstd450Modf:
871 case GLSLstd450Fract:
872 {
873 auto *var = compiler.maybe_get<SPIRVariable>(args[5]);
874 if (var && storage_class_is_interface(var->storage))
875 variables.insert(args[5]);
876 break;
877 }
878
879 default:
880 break;
881 }
882 break;
883 }
884 case SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter:
885 {
886 enum AMDShaderExplicitVertexParameter
887 {
888 InterpolateAtVertexAMD = 1
889 };
890
891 auto op = static_cast<AMDShaderExplicitVertexParameter>(args[3]);
892
893 switch (op)
894 {
895 case InterpolateAtVertexAMD:
896 {
897 auto *var = compiler.maybe_get<SPIRVariable>(args[4]);
898 if (var && storage_class_is_interface(var->storage))
899 variables.insert(args[4]);
900 break;
901 }
902
903 default:
904 break;
905 }
906 break;
907 }
908 default:
909 break;
910 }
911 break;
912 }
913
914 case OpAccessChain:
915 case OpInBoundsAccessChain:
916 case OpPtrAccessChain:
917 case OpLoad:
918 case OpCooperativeMatrixLoadKHR:
919 case OpCopyObject:
920 case OpImageTexelPointer:
921 case OpAtomicLoad:
922 case OpAtomicExchange:
923 case OpAtomicCompareExchange:
924 case OpAtomicCompareExchangeWeak:
925 case OpAtomicIIncrement:
926 case OpAtomicIDecrement:
927 case OpAtomicIAdd:
928 case OpAtomicISub:
929 case OpAtomicSMin:
930 case OpAtomicUMin:
931 case OpAtomicSMax:
932 case OpAtomicUMax:
933 case OpAtomicAnd:
934 case OpAtomicOr:
935 case OpAtomicXor:
936 case OpArrayLength:
937 // Invalid SPIR-V.
938 if (length < 3)
939 return false;
940 variable = args[2];
941 break;
942 }
943
944 if (variable)
945 {
946 auto *var = compiler.maybe_get<SPIRVariable>(variable);
947 if (var && storage_class_is_interface(var->storage))
948 variables.insert(variable);
949 }
950 return true;
951 }
952
953 unordered_set<VariableID> Compiler::get_active_interface_variables() const
954 {
955 // Traverse the call graph and find all interface variables which are in use.
956 unordered_set<VariableID> variables;
957 InterfaceVariableAccessHandler handler(*this, variables);
958 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
959
960 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
961 if (var.storage != StorageClassOutput)
962 return;
963 if (!interface_variable_exists_in_entry_point(var.self))
964 return;
965
966 // An output variable which is just declared (but uninitialized) might be read by subsequent stages
967 // so we should force-enable these outputs,
968 // since compilation will fail if a subsequent stage attempts to read from the variable in question.
969 // Also, make sure we preserve output variables which are only initialized, but never accessed by any code.
970 if (var.initializer != ID(0) || get_execution_model() != ExecutionModelFragment)
971 variables.insert(var.self);
972 });
973
974 // If we needed to create one, we'll need it.
975 if (dummy_sampler_id)
976 variables.insert(dummy_sampler_id);
977
978 return variables;
979 }
980
981 void Compiler::set_enabled_interface_variables(std::unordered_set<VariableID> active_variables)
982 {
983 active_interface_variables = std::move(active_variables);
984 check_active_interface_variables = true;
985 }
986
987 ShaderResources Compiler::get_shader_resources(const unordered_set<VariableID> *active_variables) const
988 {
989 ShaderResources res;
990
991 bool ssbo_instance_name = reflection_ssbo_instance_name_is_significant();
992
993 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
994 auto &type = this->get<SPIRType>(var.basetype);
995
996 // It is possible for uniform storage classes to be passed as function parameters, so detect
997 // that. To detect function parameters, check of StorageClass of variable is function scope.
998 if (var.storage == StorageClassFunction || !type.pointer)
999 return;
1000
1001 if (active_variables && active_variables->find(var.self) == end(*active_variables))
1002 return;
1003
1004 // In SPIR-V 1.4 and up, every global must be present in the entry point interface list,
1005 // not just IO variables.
1006 bool active_in_entry_point = true;
1007 if (ir.get_spirv_version() < 0x10400)
1008 {
1009 if (var.storage == StorageClassInput || var.storage == StorageClassOutput)
1010 active_in_entry_point = interface_variable_exists_in_entry_point(var.self);
1011 }
1012 else
1013 active_in_entry_point = interface_variable_exists_in_entry_point(var.self);
1014
1015 if (!active_in_entry_point)
1016 return;
1017
1018 bool is_builtin = is_builtin_variable(var);
1019
1020 if (is_builtin)
1021 {
1022 if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
1023 return;
1024
1025 auto &list = var.storage == StorageClassInput ? res.builtin_inputs : res.builtin_outputs;
1026 BuiltInResource resource;
1027
1028 if (has_decoration(type.self, DecorationBlock))
1029 {
1030 resource.resource = { var.self, var.basetype, type.self,
1031 get_remapped_declared_block_name(var.self, false) };
1032
1033 for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
1034 {
1035 resource.value_type_id = type.member_types[i];
1036 resource.builtin = BuiltIn(get_member_decoration(type.self, i, DecorationBuiltIn));
1037 list.push_back(resource);
1038 }
1039 }
1040 else
1041 {
1042 bool strip_array =
1043 !has_decoration(var.self, DecorationPatch) && (
1044 get_execution_model() == ExecutionModelTessellationControl ||
1045 (get_execution_model() == ExecutionModelTessellationEvaluation &&
1046 var.storage == StorageClassInput));
1047
1048 resource.resource = { var.self, var.basetype, type.self, get_name(var.self) };
1049
1050 if (strip_array && !type.array.empty())
1051 resource.value_type_id = get_variable_data_type(var).parent_type;
1052 else
1053 resource.value_type_id = get_variable_data_type_id(var);
1054
1055 assert(resource.value_type_id);
1056
1057 resource.builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
1058 list.push_back(std::move(resource));
1059 }
1060 return;
1061 }
1062
1063 // Input
1064 if (var.storage == StorageClassInput)
1065 {
1066 if (has_decoration(type.self, DecorationBlock))
1067 {
1068 res.stage_inputs.push_back(
1069 { var.self, var.basetype, type.self,
1070 get_remapped_declared_block_name(var.self, false) });
1071 }
1072 else
1073 res.stage_inputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1074 }
1075 // Subpass inputs
1076 else if (var.storage == StorageClassUniformConstant && type.image.dim == DimSubpassData)
1077 {
1078 res.subpass_inputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1079 }
1080 // Outputs
1081 else if (var.storage == StorageClassOutput)
1082 {
1083 if (has_decoration(type.self, DecorationBlock))
1084 {
1085 res.stage_outputs.push_back(
1086 { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, false) });
1087 }
1088 else
1089 res.stage_outputs.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1090 }
1091 // UBOs
1092 else if (type.storage == StorageClassUniform && has_decoration(type.self, DecorationBlock))
1093 {
1094 res.uniform_buffers.push_back(
1095 { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, false) });
1096 }
1097 // Old way to declare SSBOs.
1098 else if (type.storage == StorageClassUniform && has_decoration(type.self, DecorationBufferBlock))
1099 {
1100 res.storage_buffers.push_back(
1101 { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
1102 }
1103 // Modern way to declare SSBOs.
1104 else if (type.storage == StorageClassStorageBuffer)
1105 {
1106 res.storage_buffers.push_back(
1107 { var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
1108 }
1109 // Push constant blocks
1110 else if (type.storage == StorageClassPushConstant)
1111 {
1112 // There can only be one push constant block, but keep the vector in case this restriction is lifted
1113 // in the future.
1114 res.push_constant_buffers.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1115 }
1116 else if (type.storage == StorageClassShaderRecordBufferKHR)
1117 {
1118 res.shader_record_buffers.push_back({ var.self, var.basetype, type.self, get_remapped_declared_block_name(var.self, ssbo_instance_name) });
1119 }
1120 // Atomic counters
1121 else if (type.storage == StorageClassAtomicCounter)
1122 {
1123 res.atomic_counters.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1124 }
1125 else if (type.storage == StorageClassUniformConstant)
1126 {
1127 if (type.basetype == SPIRType::Image)
1128 {
1129 // Images
1130 if (type.image.sampled == 2)
1131 {
1132 res.storage_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1133 }
1134 // Separate images
1135 else if (type.image.sampled == 1)
1136 {
1137 res.separate_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1138 }
1139 }
1140 // Separate samplers
1141 else if (type.basetype == SPIRType::Sampler)
1142 {
1143 res.separate_samplers.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1144 }
1145 // Textures
1146 else if (type.basetype == SPIRType::SampledImage)
1147 {
1148 res.sampled_images.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1149 }
1150 // Acceleration structures
1151 else if (type.basetype == SPIRType::AccelerationStructure)
1152 {
1153 res.acceleration_structures.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1154 }
1155 else
1156 {
1157 res.gl_plain_uniforms.push_back({ var.self, var.basetype, type.self, get_name(var.self) });
1158 }
1159 }
1160 });
1161
1162 return res;
1163 }
1164
1165 bool Compiler::type_is_top_level_block(const SPIRType &type) const
1166 {
1167 if (type.basetype != SPIRType::Struct)
1168 return false;
1169 return has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
1170 }
1171
1172 bool Compiler::type_is_block_like(const SPIRType &type) const
1173 {
1174 if (type_is_top_level_block(type))
1175 return true;
1176
1177 if (type.basetype == SPIRType::Struct)
1178 {
1179 // Block-like types may have Offset decorations.
1180 for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
1181 if (has_member_decoration(type.self, i, DecorationOffset))
1182 return true;
1183 }
1184
1185 return false;
1186 }
1187
1188 void Compiler::parse_fixup()
1189 {
1190 // Figure out specialization constants for work group sizes.
1191 for (auto id_ : ir.ids_for_constant_or_variable)
1192 {
1193 auto &id = ir.ids[id_];
1194
1195 if (id.get_type() == TypeConstant)
1196 {
1197 auto &c = id.get<SPIRConstant>();
1198 if (has_decoration(c.self, DecorationBuiltIn) &&
1199 BuiltIn(get_decoration(c.self, DecorationBuiltIn)) == BuiltInWorkgroupSize)
1200 {
1201 // In current SPIR-V, there can be just one constant like this.
1202 // All entry points will receive the constant value.
1203 // WorkgroupSize take precedence over LocalSizeId.
1204 for (auto &entry : ir.entry_points)
1205 {
1206 entry.second.workgroup_size.constant = c.self;
1207 entry.second.workgroup_size.x = c.scalar(0, 0);
1208 entry.second.workgroup_size.y = c.scalar(0, 1);
1209 entry.second.workgroup_size.z = c.scalar(0, 2);
1210 }
1211 }
1212 }
1213 else if (id.get_type() == TypeVariable)
1214 {
1215 auto &var = id.get<SPIRVariable>();
1216 if (var.storage == StorageClassPrivate || var.storage == StorageClassWorkgroup ||
1217 var.storage == StorageClassTaskPayloadWorkgroupEXT ||
1218 var.storage == StorageClassOutput)
1219 {
1220 global_variables.push_back(var.self);
1221 }
1222 if (variable_storage_is_aliased(var))
1223 aliased_variables.push_back(var.self);
1224 }
1225 }
1226 }
1227
1228 void Compiler::update_name_cache(unordered_set<string> &cache_primary, const unordered_set<string> &cache_secondary,
1229 string &name)
1230 {
1231 if (name.empty())
1232 return;
1233
1234 const auto find_name = [&](const string &n) -> bool {
1235 if (cache_primary.find(n) != end(cache_primary))
1236 return true;
1237
1238 if (&cache_primary != &cache_secondary)
1239 if (cache_secondary.find(n) != end(cache_secondary))
1240 return true;
1241
1242 return false;
1243 };
1244
1245 const auto insert_name = [&](const string &n) { cache_primary.insert(n); };
1246
1247 if (!find_name(name))
1248 {
1249 insert_name(name);
1250 return;
1251 }
1252
1253 uint32_t counter = 0;
1254 auto tmpname = name;
1255
1256 bool use_linked_underscore = true;
1257
1258 if (tmpname == "_")
1259 {
1260 // We cannot just append numbers, as we will end up creating internally reserved names.
1261 // Make it like _0_<counter> instead.
1262 tmpname += "0";
1263 }
1264 else if (tmpname.back() == '_')
1265 {
1266 // The last_character is an underscore, so we don't need to link in underscore.
1267 // This would violate double underscore rules.
1268 use_linked_underscore = false;
1269 }
1270
1271 // If there is a collision (very rare),
1272 // keep tacking on extra identifier until it's unique.
1273 do
1274 {
1275 counter++;
1276 name = tmpname + (use_linked_underscore ? "_" : "") + convert_to_string(counter);
1277 } while (find_name(name));
1278 insert_name(name);
1279 }
1280
1281 void Compiler::update_name_cache(unordered_set<string> &cache, string &name)
1282 {
1283 update_name_cache(cache, cache, name);
1284 }
1285
1286 void Compiler::set_name(ID id, const std::string &name)
1287 {
1288 ir.set_name(id, name);
1289 }
1290
1291 const SPIRType &Compiler::get_type(TypeID id) const
1292 {
1293 return get<SPIRType>(id);
1294 }
1295
1296 const SPIRType &Compiler::get_type_from_variable(VariableID id) const
1297 {
1298 return get<SPIRType>(get<SPIRVariable>(id).basetype);
1299 }
1300
1301 uint32_t Compiler::get_pointee_type_id(uint32_t type_id) const
1302 {
1303 auto *p_type = &get<SPIRType>(type_id);
1304 if (p_type->pointer)
1305 {
1306 assert(p_type->parent_type);
1307 type_id = p_type->parent_type;
1308 }
1309 return type_id;
1310 }
1311
1312 const SPIRType &Compiler::get_pointee_type(const SPIRType &type) const
1313 {
1314 auto *p_type = &type;
1315 if (p_type->pointer)
1316 {
1317 assert(p_type->parent_type);
1318 p_type = &get<SPIRType>(p_type->parent_type);
1319 }
1320 return *p_type;
1321 }
1322
1323 const SPIRType &Compiler::get_pointee_type(uint32_t type_id) const
1324 {
1325 return get_pointee_type(get<SPIRType>(type_id));
1326 }
1327
1328 uint32_t Compiler::get_variable_data_type_id(const SPIRVariable &var) const
1329 {
1330 if (var.phi_variable || var.storage == spv::StorageClass::StorageClassAtomicCounter)
1331 return var.basetype;
1332 return get_pointee_type_id(var.basetype);
1333 }
1334
1335 SPIRType &Compiler::get_variable_data_type(const SPIRVariable &var)
1336 {
1337 return get<SPIRType>(get_variable_data_type_id(var));
1338 }
1339
1340 const SPIRType &Compiler::get_variable_data_type(const SPIRVariable &var) const
1341 {
1342 return get<SPIRType>(get_variable_data_type_id(var));
1343 }
1344
1345 SPIRType &Compiler::get_variable_element_type(const SPIRVariable &var)
1346 {
1347 SPIRType *type = &get_variable_data_type(var);
1348 if (is_array(*type))
1349 type = &get<SPIRType>(type->parent_type);
1350 return *type;
1351 }
1352
1353 const SPIRType &Compiler::get_variable_element_type(const SPIRVariable &var) const
1354 {
1355 const SPIRType *type = &get_variable_data_type(var);
1356 if (is_array(*type))
1357 type = &get<SPIRType>(type->parent_type);
1358 return *type;
1359 }
1360
1361 bool Compiler::is_sampled_image_type(const SPIRType &type)
1362 {
1363 return (type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage) && type.image.sampled == 1 &&
1364 type.image.dim != DimBuffer;
1365 }
1366
1367 void Compiler::set_member_decoration_string(TypeID id, uint32_t index, spv::Decoration decoration,
1368 const std::string &argument)
1369 {
1370 ir.set_member_decoration_string(id, index, decoration, argument);
1371 }
1372
1373 void Compiler::set_member_decoration(TypeID id, uint32_t index, Decoration decoration, uint32_t argument)
1374 {
1375 ir.set_member_decoration(id, index, decoration, argument);
1376 }
1377
1378 void Compiler::set_member_name(TypeID id, uint32_t index, const std::string &name)
1379 {
1380 ir.set_member_name(id, index, name);
1381 }
1382
1383 const std::string &Compiler::get_member_name(TypeID id, uint32_t index) const
1384 {
1385 return ir.get_member_name(id, index);
1386 }
1387
1388 void Compiler::set_qualified_name(uint32_t id, const string &name)
1389 {
1390 ir.meta[id].decoration.qualified_alias = name;
1391 }
1392
1393 void Compiler::set_member_qualified_name(uint32_t type_id, uint32_t index, const std::string &name)
1394 {
1395 ir.meta[type_id].members.resize(max(ir.meta[type_id].members.size(), size_t(index) + 1));
1396 ir.meta[type_id].members[index].qualified_alias = name;
1397 }
1398
1399 const string &Compiler::get_member_qualified_name(TypeID type_id, uint32_t index) const
1400 {
1401 auto *m = ir.find_meta(type_id);
1402 if (m && index < m->members.size())
1403 return m->members[index].qualified_alias;
1404 else
1405 return ir.get_empty_string();
1406 }
1407
1408 uint32_t Compiler::get_member_decoration(TypeID id, uint32_t index, Decoration decoration) const
1409 {
1410 return ir.get_member_decoration(id, index, decoration);
1411 }
1412
1413 const Bitset &Compiler::get_member_decoration_bitset(TypeID id, uint32_t index) const
1414 {
1415 return ir.get_member_decoration_bitset(id, index);
1416 }
1417
1418 bool Compiler::has_member_decoration(TypeID id, uint32_t index, Decoration decoration) const
1419 {
1420 return ir.has_member_decoration(id, index, decoration);
1421 }
1422
1423 void Compiler::unset_member_decoration(TypeID id, uint32_t index, Decoration decoration)
1424 {
1425 ir.unset_member_decoration(id, index, decoration);
1426 }
1427
1428 void Compiler::set_decoration_string(ID id, spv::Decoration decoration, const std::string &argument)
1429 {
1430 ir.set_decoration_string(id, decoration, argument);
1431 }
1432
1433 void Compiler::set_decoration(ID id, Decoration decoration, uint32_t argument)
1434 {
1435 ir.set_decoration(id, decoration, argument);
1436 }
1437
1438 void Compiler::set_extended_decoration(uint32_t id, ExtendedDecorations decoration, uint32_t value)
1439 {
1440 auto &dec = ir.meta[id].decoration;
1441 dec.extended.flags.set(decoration);
1442 dec.extended.values[decoration] = value;
1443 }
1444
1445 void Compiler::set_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration,
1446 uint32_t value)
1447 {
1448 ir.meta[type].members.resize(max(ir.meta[type].members.size(), size_t(index) + 1));
1449 auto &dec = ir.meta[type].members[index];
1450 dec.extended.flags.set(decoration);
1451 dec.extended.values[decoration] = value;
1452 }
1453
1454 static uint32_t get_default_extended_decoration(ExtendedDecorations decoration)
1455 {
1456 switch (decoration)
1457 {
1458 case SPIRVCrossDecorationResourceIndexPrimary:
1459 case SPIRVCrossDecorationResourceIndexSecondary:
1460 case SPIRVCrossDecorationResourceIndexTertiary:
1461 case SPIRVCrossDecorationResourceIndexQuaternary:
1462 case SPIRVCrossDecorationInterfaceMemberIndex:
1463 return ~(0u);
1464
1465 default:
1466 return 0;
1467 }
1468 }
1469
1470 uint32_t Compiler::get_extended_decoration(uint32_t id, ExtendedDecorations decoration) const
1471 {
1472 auto *m = ir.find_meta(id);
1473 if (!m)
1474 return 0;
1475
1476 auto &dec = m->decoration;
1477
1478 if (!dec.extended.flags.get(decoration))
1479 return get_default_extended_decoration(decoration);
1480
1481 return dec.extended.values[decoration];
1482 }
1483
1484 uint32_t Compiler::get_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration) const
1485 {
1486 auto *m = ir.find_meta(type);
1487 if (!m)
1488 return 0;
1489
1490 if (index >= m->members.size())
1491 return 0;
1492
1493 auto &dec = m->members[index];
1494 if (!dec.extended.flags.get(decoration))
1495 return get_default_extended_decoration(decoration);
1496 return dec.extended.values[decoration];
1497 }
1498
1499 bool Compiler::has_extended_decoration(uint32_t id, ExtendedDecorations decoration) const
1500 {
1501 auto *m = ir.find_meta(id);
1502 if (!m)
1503 return false;
1504
1505 auto &dec = m->decoration;
1506 return dec.extended.flags.get(decoration);
1507 }
1508
1509 bool Compiler::has_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration) const
1510 {
1511 auto *m = ir.find_meta(type);
1512 if (!m)
1513 return false;
1514
1515 if (index >= m->members.size())
1516 return false;
1517
1518 auto &dec = m->members[index];
1519 return dec.extended.flags.get(decoration);
1520 }
1521
1522 void Compiler::unset_extended_decoration(uint32_t id, ExtendedDecorations decoration)
1523 {
1524 auto &dec = ir.meta[id].decoration;
1525 dec.extended.flags.clear(decoration);
1526 dec.extended.values[decoration] = 0;
1527 }
1528
1529 void Compiler::unset_extended_member_decoration(uint32_t type, uint32_t index, ExtendedDecorations decoration)
1530 {
1531 ir.meta[type].members.resize(max(ir.meta[type].members.size(), size_t(index) + 1));
1532 auto &dec = ir.meta[type].members[index];
1533 dec.extended.flags.clear(decoration);
1534 dec.extended.values[decoration] = 0;
1535 }
1536
1537 StorageClass Compiler::get_storage_class(VariableID id) const
1538 {
1539 return get<SPIRVariable>(id).storage;
1540 }
1541
1542 const std::string &Compiler::get_name(ID id) const
1543 {
1544 return ir.get_name(id);
1545 }
1546
1547 const std::string Compiler::get_fallback_name(ID id) const
1548 {
1549 return join("_", id);
1550 }
1551
1552 const std::string Compiler::get_block_fallback_name(VariableID id) const
1553 {
1554 auto &var = get<SPIRVariable>(id);
1555 if (get_name(id).empty())
1556 return join("_", get<SPIRType>(var.basetype).self, "_", id);
1557 else
1558 return get_name(id);
1559 }
1560
1561 const Bitset &Compiler::get_decoration_bitset(ID id) const
1562 {
1563 return ir.get_decoration_bitset(id);
1564 }
1565
1566 bool Compiler::has_decoration(ID id, Decoration decoration) const
1567 {
1568 return ir.has_decoration(id, decoration);
1569 }
1570
1571 const string &Compiler::get_decoration_string(ID id, Decoration decoration) const
1572 {
1573 return ir.get_decoration_string(id, decoration);
1574 }
1575
1576 const string &Compiler::get_member_decoration_string(TypeID id, uint32_t index, Decoration decoration) const
1577 {
1578 return ir.get_member_decoration_string(id, index, decoration);
1579 }
1580
1581 uint32_t Compiler::get_decoration(ID id, Decoration decoration) const
1582 {
1583 return ir.get_decoration(id, decoration);
1584 }
1585
1586 void Compiler::unset_decoration(ID id, Decoration decoration)
1587 {
1588 ir.unset_decoration(id, decoration);
1589 }
1590
1591 bool Compiler::get_binary_offset_for_decoration(VariableID id, spv::Decoration decoration, uint32_t &word_offset) const
1592 {
1593 auto *m = ir.find_meta(id);
1594 if (!m)
1595 return false;
1596
1597 auto &word_offsets = m->decoration_word_offset;
1598 auto itr = word_offsets.find(decoration);
1599 if (itr == end(word_offsets))
1600 return false;
1601
1602 word_offset = itr->second;
1603 return true;
1604 }
1605
1606 bool Compiler::block_is_noop(const SPIRBlock &block) const
1607 {
1608 if (block.terminator != SPIRBlock::Direct)
1609 return false;
1610
1611 auto &child = get<SPIRBlock>(block.next_block);
1612
1613 // If this block participates in PHI, the block isn't really noop.
1614 for (auto &phi : block.phi_variables)
1615 if (phi.parent == block.self || phi.parent == child.self)
1616 return false;
1617
1618 for (auto &phi : child.phi_variables)
1619 if (phi.parent == block.self)
1620 return false;
1621
1622 // Verify all instructions have no semantic impact.
1623 for (auto &i : block.ops)
1624 {
1625 auto op = static_cast<Op>(i.op);
1626
1627 switch (op)
1628 {
1629 // Non-Semantic instructions.
1630 case OpLine:
1631 case OpNoLine:
1632 break;
1633
1634 case OpExtInst:
1635 {
1636 auto *ops = stream(i);
1637 auto ext = get<SPIRExtension>(ops[2]).ext;
1638
1639 bool ext_is_nonsemantic_only =
1640 ext == SPIRExtension::NonSemanticShaderDebugInfo ||
1641 ext == SPIRExtension::SPV_debug_info ||
1642 ext == SPIRExtension::NonSemanticGeneric;
1643
1644 if (!ext_is_nonsemantic_only)
1645 return false;
1646
1647 break;
1648 }
1649
1650 default:
1651 return false;
1652 }
1653 }
1654
1655 return true;
1656 }
1657
1658 bool Compiler::block_is_loop_candidate(const SPIRBlock &block, SPIRBlock::Method method) const
1659 {
1660 // Tried and failed.
1661 if (block.disable_block_optimization || block.complex_continue)
1662 return false;
1663
1664 if (method == SPIRBlock::MergeToSelectForLoop || method == SPIRBlock::MergeToSelectContinueForLoop)
1665 {
1666 // Try to detect common for loop pattern
1667 // which the code backend can use to create cleaner code.
1668 // for(;;) { if (cond) { some_body; } else { break; } }
1669 // is the pattern we're looking for.
1670 const auto *false_block = maybe_get<SPIRBlock>(block.false_block);
1671 const auto *true_block = maybe_get<SPIRBlock>(block.true_block);
1672 const auto *merge_block = maybe_get<SPIRBlock>(block.merge_block);
1673
1674 bool false_block_is_merge = block.false_block == block.merge_block ||
1675 (false_block && merge_block && execution_is_noop(*false_block, *merge_block));
1676
1677 bool true_block_is_merge = block.true_block == block.merge_block ||
1678 (true_block && merge_block && execution_is_noop(*true_block, *merge_block));
1679
1680 bool positive_candidate =
1681 block.true_block != block.merge_block && block.true_block != block.self && false_block_is_merge;
1682
1683 bool negative_candidate =
1684 block.false_block != block.merge_block && block.false_block != block.self && true_block_is_merge;
1685
1686 bool ret = block.terminator == SPIRBlock::Select && block.merge == SPIRBlock::MergeLoop &&
1687 (positive_candidate || negative_candidate);
1688
1689 if (ret && positive_candidate && method == SPIRBlock::MergeToSelectContinueForLoop)
1690 ret = block.true_block == block.continue_block;
1691 else if (ret && negative_candidate && method == SPIRBlock::MergeToSelectContinueForLoop)
1692 ret = block.false_block == block.continue_block;
1693
1694 // If we have OpPhi which depends on branches which came from our own block,
1695 // we need to flush phi variables in else block instead of a trivial break,
1696 // so we cannot assume this is a for loop candidate.
1697 if (ret)
1698 {
1699 for (auto &phi : block.phi_variables)
1700 if (phi.parent == block.self)
1701 return false;
1702
1703 auto *merge = maybe_get<SPIRBlock>(block.merge_block);
1704 if (merge)
1705 for (auto &phi : merge->phi_variables)
1706 if (phi.parent == block.self)
1707 return false;
1708 }
1709 return ret;
1710 }
1711 else if (method == SPIRBlock::MergeToDirectForLoop)
1712 {
1713 // Empty loop header that just sets up merge target
1714 // and branches to loop body.
1715 bool ret = block.terminator == SPIRBlock::Direct && block.merge == SPIRBlock::MergeLoop && block_is_noop(block);
1716
1717 if (!ret)
1718 return false;
1719
1720 auto &child = get<SPIRBlock>(block.next_block);
1721
1722 const auto *false_block = maybe_get<SPIRBlock>(child.false_block);
1723 const auto *true_block = maybe_get<SPIRBlock>(child.true_block);
1724 const auto *merge_block = maybe_get<SPIRBlock>(block.merge_block);
1725
1726 bool false_block_is_merge = child.false_block == block.merge_block ||
1727 (false_block && merge_block && execution_is_noop(*false_block, *merge_block));
1728
1729 bool true_block_is_merge = child.true_block == block.merge_block ||
1730 (true_block && merge_block && execution_is_noop(*true_block, *merge_block));
1731
1732 bool positive_candidate =
1733 child.true_block != block.merge_block && child.true_block != block.self && false_block_is_merge;
1734
1735 bool negative_candidate =
1736 child.false_block != block.merge_block && child.false_block != block.self && true_block_is_merge;
1737
1738 ret = child.terminator == SPIRBlock::Select && child.merge == SPIRBlock::MergeNone &&
1739 (positive_candidate || negative_candidate);
1740
1741 if (ret)
1742 {
1743 auto *merge = maybe_get<SPIRBlock>(block.merge_block);
1744 if (merge)
1745 for (auto &phi : merge->phi_variables)
1746 if (phi.parent == block.self || phi.parent == child.false_block)
1747 return false;
1748 }
1749
1750 return ret;
1751 }
1752 else
1753 return false;
1754 }
1755
1756 bool Compiler::execution_is_noop(const SPIRBlock &from, const SPIRBlock &to) const
1757 {
1758 if (!execution_is_branchless(from, to))
1759 return false;
1760
1761 auto *start = &from;
1762 for (;;)
1763 {
1764 if (start->self == to.self)
1765 return true;
1766
1767 if (!block_is_noop(*start))
1768 return false;
1769
1770 auto &next = get<SPIRBlock>(start->next_block);
1771 start = &next;
1772 }
1773 }
1774
1775 bool Compiler::execution_is_branchless(const SPIRBlock &from, const SPIRBlock &to) const
1776 {
1777 auto *start = &from;
1778 for (;;)
1779 {
1780 if (start->self == to.self)
1781 return true;
1782
1783 if (start->terminator == SPIRBlock::Direct && start->merge == SPIRBlock::MergeNone)
1784 start = &get<SPIRBlock>(start->next_block);
1785 else
1786 return false;
1787 }
1788 }
1789
1790 bool Compiler::execution_is_direct_branch(const SPIRBlock &from, const SPIRBlock &to) const
1791 {
1792 return from.terminator == SPIRBlock::Direct && from.merge == SPIRBlock::MergeNone && from.next_block == to.self;
1793 }
1794
1795 SPIRBlock::ContinueBlockType Compiler::continue_block_type(const SPIRBlock &block) const
1796 {
1797 // The block was deemed too complex during code emit, pick conservative fallback paths.
1798 if (block.complex_continue)
1799 return SPIRBlock::ComplexLoop;
1800
1801 // In older glslang output continue block can be equal to the loop header.
1802 // In this case, execution is clearly branchless, so just assume a while loop header here.
1803 if (block.merge == SPIRBlock::MergeLoop)
1804 return SPIRBlock::WhileLoop;
1805
1806 if (block.loop_dominator == BlockID(SPIRBlock::NoDominator))
1807 {
1808 // Continue block is never reached from CFG.
1809 return SPIRBlock::ComplexLoop;
1810 }
1811
1812 auto &dominator = get<SPIRBlock>(block.loop_dominator);
1813
1814 if (execution_is_noop(block, dominator))
1815 return SPIRBlock::WhileLoop;
1816 else if (execution_is_branchless(block, dominator))
1817 return SPIRBlock::ForLoop;
1818 else
1819 {
1820 const auto *false_block = maybe_get<SPIRBlock>(block.false_block);
1821 const auto *true_block = maybe_get<SPIRBlock>(block.true_block);
1822 const auto *merge_block = maybe_get<SPIRBlock>(dominator.merge_block);
1823
1824 // If we need to flush Phi in this block, we cannot have a DoWhile loop.
1825 bool flush_phi_to_false = false_block && flush_phi_required(block.self, block.false_block);
1826 bool flush_phi_to_true = true_block && flush_phi_required(block.self, block.true_block);
1827 if (flush_phi_to_false || flush_phi_to_true)
1828 return SPIRBlock::ComplexLoop;
1829
1830 bool positive_do_while = block.true_block == dominator.self &&
1831 (block.false_block == dominator.merge_block ||
1832 (false_block && merge_block && execution_is_noop(*false_block, *merge_block)));
1833
1834 bool negative_do_while = block.false_block == dominator.self &&
1835 (block.true_block == dominator.merge_block ||
1836 (true_block && merge_block && execution_is_noop(*true_block, *merge_block)));
1837
1838 if (block.merge == SPIRBlock::MergeNone && block.terminator == SPIRBlock::Select &&
1839 (positive_do_while || negative_do_while))
1840 {
1841 return SPIRBlock::DoWhileLoop;
1842 }
1843 else
1844 return SPIRBlock::ComplexLoop;
1845 }
1846 }
1847
1848 const SmallVector<SPIRBlock::Case> &Compiler::get_case_list(const SPIRBlock &block) const
1849 {
1850 uint32_t width = 0;
1851
1852 // First we check if we can get the type directly from the block.condition
1853 // since it can be a SPIRConstant or a SPIRVariable.
1854 if (const auto *constant = maybe_get<SPIRConstant>(block.condition))
1855 {
1856 const auto &type = get<SPIRType>(constant->constant_type);
1857 width = type.width;
1858 }
1859 else if (const auto *op = maybe_get<SPIRConstantOp>(block.condition))
1860 {
1861 const auto &type = get<SPIRType>(op->basetype);
1862 width = type.width;
1863 }
1864 else if (const auto *var = maybe_get<SPIRVariable>(block.condition))
1865 {
1866 const auto &type = get<SPIRType>(var->basetype);
1867 width = type.width;
1868 }
1869 else if (const auto *undef = maybe_get<SPIRUndef>(block.condition))
1870 {
1871 const auto &type = get<SPIRType>(undef->basetype);
1872 width = type.width;
1873 }
1874 else
1875 {
1876 auto search = ir.load_type_width.find(block.condition);
1877 if (search == ir.load_type_width.end())
1878 {
1879 SPIRV_CROSS_THROW("Use of undeclared variable on a switch statement.");
1880 }
1881
1882 width = search->second;
1883 }
1884
1885 if (width > 32)
1886 return block.cases_64bit;
1887
1888 return block.cases_32bit;
1889 }
1890
1891 bool Compiler::traverse_all_reachable_opcodes(const SPIRBlock &block, OpcodeHandler &handler) const
1892 {
1893 handler.set_current_block(block);
1894 handler.rearm_current_block(block);
1895
1896 // Ideally, perhaps traverse the CFG instead of all blocks in order to eliminate dead blocks,
1897 // but this shouldn't be a problem in practice unless the SPIR-V is doing insane things like recursing
1898 // inside dead blocks ...
1899 for (auto &i : block.ops)
1900 {
1901 auto ops = stream(i);
1902 auto op = static_cast<Op>(i.op);
1903
1904 if (!handler.handle(op, ops, i.length))
1905 return false;
1906
1907 if (op == OpFunctionCall)
1908 {
1909 auto &func = get<SPIRFunction>(ops[2]);
1910 if (handler.follow_function_call(func))
1911 {
1912 if (!handler.begin_function_scope(ops, i.length))
1913 return false;
1914 if (!traverse_all_reachable_opcodes(get<SPIRFunction>(ops[2]), handler))
1915 return false;
1916 if (!handler.end_function_scope(ops, i.length))
1917 return false;
1918
1919 handler.rearm_current_block(block);
1920 }
1921 }
1922 }
1923
1924 if (!handler.handle_terminator(block))
1925 return false;
1926
1927 return true;
1928 }
1929
1930 bool Compiler::traverse_all_reachable_opcodes(const SPIRFunction &func, OpcodeHandler &handler) const
1931 {
1932 for (auto block : func.blocks)
1933 if (!traverse_all_reachable_opcodes(get<SPIRBlock>(block), handler))
1934 return false;
1935
1936 return true;
1937 }
1938
1939 uint32_t Compiler::type_struct_member_offset(const SPIRType &type, uint32_t index) const
1940 {
1941 auto *type_meta = ir.find_meta(type.self);
1942 if (type_meta)
1943 {
1944 // Decoration must be set in valid SPIR-V, otherwise throw.
1945 auto &dec = type_meta->members[index];
1946 if (dec.decoration_flags.get(DecorationOffset))
1947 return dec.offset;
1948 else
1949 SPIRV_CROSS_THROW("Struct member does not have Offset set.");
1950 }
1951 else
1952 SPIRV_CROSS_THROW("Struct member does not have Offset set.");
1953 }
1954
1955 uint32_t Compiler::type_struct_member_array_stride(const SPIRType &type, uint32_t index) const
1956 {
1957 auto *type_meta = ir.find_meta(type.member_types[index]);
1958 if (type_meta)
1959 {
1960 // Decoration must be set in valid SPIR-V, otherwise throw.
1961 // ArrayStride is part of the array type not OpMemberDecorate.
1962 auto &dec = type_meta->decoration;
1963 if (dec.decoration_flags.get(DecorationArrayStride))
1964 return dec.array_stride;
1965 else
1966 SPIRV_CROSS_THROW("Struct member does not have ArrayStride set.");
1967 }
1968 else
1969 SPIRV_CROSS_THROW("Struct member does not have ArrayStride set.");
1970 }
1971
1972 uint32_t Compiler::type_struct_member_matrix_stride(const SPIRType &type, uint32_t index) const
1973 {
1974 auto *type_meta = ir.find_meta(type.self);
1975 if (type_meta)
1976 {
1977 // Decoration must be set in valid SPIR-V, otherwise throw.
1978 // MatrixStride is part of OpMemberDecorate.
1979 auto &dec = type_meta->members[index];
1980 if (dec.decoration_flags.get(DecorationMatrixStride))
1981 return dec.matrix_stride;
1982 else
1983 SPIRV_CROSS_THROW("Struct member does not have MatrixStride set.");
1984 }
1985 else
1986 SPIRV_CROSS_THROW("Struct member does not have MatrixStride set.");
1987 }
1988
1989 size_t Compiler::get_declared_struct_size(const SPIRType &type) const
1990 {
1991 if (type.member_types.empty())
1992 SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
1993
1994 // Offsets can be declared out of order, so we need to deduce the actual size
1995 // based on last member instead.
1996 uint32_t member_index = 0;
1997 size_t highest_offset = 0;
1998 for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
1999 {
2000 size_t offset = type_struct_member_offset(type, i);
2001 if (offset > highest_offset)
2002 {
2003 highest_offset = offset;
2004 member_index = i;
2005 }
2006 }
2007
2008 size_t size = get_declared_struct_member_size(type, member_index);
2009 return highest_offset + size;
2010 }
2011
2012 size_t Compiler::get_declared_struct_size_runtime_array(const SPIRType &type, size_t array_size) const
2013 {
2014 if (type.member_types.empty())
2015 SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
2016
2017 size_t size = get_declared_struct_size(type);
2018 auto &last_type = get<SPIRType>(type.member_types.back());
2019 if (!last_type.array.empty() && last_type.array_size_literal[0] && last_type.array[0] == 0) // Runtime array
2020 size += array_size * type_struct_member_array_stride(type, uint32_t(type.member_types.size() - 1));
2021
2022 return size;
2023 }
2024
2025 uint32_t Compiler::evaluate_spec_constant_u32(const SPIRConstantOp &spec) const
2026 {
2027 auto &result_type = get<SPIRType>(spec.basetype);
2028 if (result_type.basetype != SPIRType::UInt && result_type.basetype != SPIRType::Int &&
2029 result_type.basetype != SPIRType::Boolean)
2030 {
2031 SPIRV_CROSS_THROW(
2032 "Only 32-bit integers and booleans are currently supported when evaluating specialization constants.\n");
2033 }
2034
2035 if (!is_scalar(result_type))
2036 SPIRV_CROSS_THROW("Spec constant evaluation must be a scalar.\n");
2037
2038 uint32_t value = 0;
2039
2040 const auto eval_u32 = [&](uint32_t id) -> uint32_t {
2041 auto &type = expression_type(id);
2042 if (type.basetype != SPIRType::UInt && type.basetype != SPIRType::Int && type.basetype != SPIRType::Boolean)
2043 {
2044 SPIRV_CROSS_THROW("Only 32-bit integers and booleans are currently supported when evaluating "
2045 "specialization constants.\n");
2046 }
2047
2048 if (!is_scalar(type))
2049 SPIRV_CROSS_THROW("Spec constant evaluation must be a scalar.\n");
2050 if (const auto *c = this->maybe_get<SPIRConstant>(id))
2051 return c->scalar();
2052 else
2053 return evaluate_spec_constant_u32(this->get<SPIRConstantOp>(id));
2054 };
2055
2056 #define binary_spec_op(op, binary_op) \
2057 case Op##op: \
2058 value = eval_u32(spec.arguments[0]) binary_op eval_u32(spec.arguments[1]); \
2059 break
2060 #define binary_spec_op_cast(op, binary_op, type) \
2061 case Op##op: \
2062 value = uint32_t(type(eval_u32(spec.arguments[0])) binary_op type(eval_u32(spec.arguments[1]))); \
2063 break
2064
2065 // Support the basic opcodes which are typically used when computing array sizes.
2066 switch (spec.opcode)
2067 {
2068 binary_spec_op(IAdd, +);
2069 binary_spec_op(ISub, -);
2070 binary_spec_op(IMul, *);
2071 binary_spec_op(BitwiseAnd, &);
2072 binary_spec_op(BitwiseOr, |);
2073 binary_spec_op(BitwiseXor, ^);
2074 binary_spec_op(LogicalAnd, &);
2075 binary_spec_op(LogicalOr, |);
2076 binary_spec_op(ShiftLeftLogical, <<);
2077 binary_spec_op(ShiftRightLogical, >>);
2078 binary_spec_op_cast(ShiftRightArithmetic, >>, int32_t);
2079 binary_spec_op(LogicalEqual, ==);
2080 binary_spec_op(LogicalNotEqual, !=);
2081 binary_spec_op(IEqual, ==);
2082 binary_spec_op(INotEqual, !=);
2083 binary_spec_op(ULessThan, <);
2084 binary_spec_op(ULessThanEqual, <=);
2085 binary_spec_op(UGreaterThan, >);
2086 binary_spec_op(UGreaterThanEqual, >=);
2087 binary_spec_op_cast(SLessThan, <, int32_t);
2088 binary_spec_op_cast(SLessThanEqual, <=, int32_t);
2089 binary_spec_op_cast(SGreaterThan, >, int32_t);
2090 binary_spec_op_cast(SGreaterThanEqual, >=, int32_t);
2091 #undef binary_spec_op
2092 #undef binary_spec_op_cast
2093
2094 case OpLogicalNot:
2095 value = uint32_t(!eval_u32(spec.arguments[0]));
2096 break;
2097
2098 case OpNot:
2099 value = ~eval_u32(spec.arguments[0]);
2100 break;
2101
2102 case OpSNegate:
2103 value = uint32_t(-int32_t(eval_u32(spec.arguments[0])));
2104 break;
2105
2106 case OpSelect:
2107 value = eval_u32(spec.arguments[0]) ? eval_u32(spec.arguments[1]) : eval_u32(spec.arguments[2]);
2108 break;
2109
2110 case OpUMod:
2111 {
2112 uint32_t a = eval_u32(spec.arguments[0]);
2113 uint32_t b = eval_u32(spec.arguments[1]);
2114 if (b == 0)
2115 SPIRV_CROSS_THROW("Undefined behavior in UMod, b == 0.\n");
2116 value = a % b;
2117 break;
2118 }
2119
2120 case OpSRem:
2121 {
2122 auto a = int32_t(eval_u32(spec.arguments[0]));
2123 auto b = int32_t(eval_u32(spec.arguments[1]));
2124 if (b == 0)
2125 SPIRV_CROSS_THROW("Undefined behavior in SRem, b == 0.\n");
2126 value = a % b;
2127 break;
2128 }
2129
2130 case OpSMod:
2131 {
2132 auto a = int32_t(eval_u32(spec.arguments[0]));
2133 auto b = int32_t(eval_u32(spec.arguments[1]));
2134 if (b == 0)
2135 SPIRV_CROSS_THROW("Undefined behavior in SMod, b == 0.\n");
2136 auto v = a % b;
2137
2138 // Makes sure we match the sign of b, not a.
2139 if ((b < 0 && v > 0) || (b > 0 && v < 0))
2140 v += b;
2141 value = v;
2142 break;
2143 }
2144
2145 case OpUDiv:
2146 {
2147 uint32_t a = eval_u32(spec.arguments[0]);
2148 uint32_t b = eval_u32(spec.arguments[1]);
2149 if (b == 0)
2150 SPIRV_CROSS_THROW("Undefined behavior in UDiv, b == 0.\n");
2151 value = a / b;
2152 break;
2153 }
2154
2155 case OpSDiv:
2156 {
2157 auto a = int32_t(eval_u32(spec.arguments[0]));
2158 auto b = int32_t(eval_u32(spec.arguments[1]));
2159 if (b == 0)
2160 SPIRV_CROSS_THROW("Undefined behavior in SDiv, b == 0.\n");
2161 value = a / b;
2162 break;
2163 }
2164
2165 default:
2166 SPIRV_CROSS_THROW("Unsupported spec constant opcode for evaluation.\n");
2167 }
2168
2169 return value;
2170 }
2171
2172 uint32_t Compiler::evaluate_constant_u32(uint32_t id) const
2173 {
2174 if (const auto *c = maybe_get<SPIRConstant>(id))
2175 return c->scalar();
2176 else
2177 return evaluate_spec_constant_u32(get<SPIRConstantOp>(id));
2178 }
2179
2180 size_t Compiler::get_declared_struct_member_size(const SPIRType &struct_type, uint32_t index) const
2181 {
2182 if (struct_type.member_types.empty())
2183 SPIRV_CROSS_THROW("Declared struct in block cannot be empty.");
2184
2185 auto &flags = get_member_decoration_bitset(struct_type.self, index);
2186 auto &type = get<SPIRType>(struct_type.member_types[index]);
2187
2188 switch (type.basetype)
2189 {
2190 case SPIRType::Unknown:
2191 case SPIRType::Void:
2192 case SPIRType::Boolean: // Bools are purely logical, and cannot be used for externally visible types.
2193 case SPIRType::AtomicCounter:
2194 case SPIRType::Image:
2195 case SPIRType::SampledImage:
2196 case SPIRType::Sampler:
2197 SPIRV_CROSS_THROW("Querying size for object with opaque size.");
2198
2199 default:
2200 break;
2201 }
2202
2203 if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer)
2204 {
2205 // Check if this is a top-level pointer type, and not an array of pointers.
2206 if (type.pointer_depth > get<SPIRType>(type.parent_type).pointer_depth)
2207 return 8;
2208 }
2209
2210 if (!type.array.empty())
2211 {
2212 // For arrays, we can use ArrayStride to get an easy check.
2213 bool array_size_literal = type.array_size_literal.back();
2214 uint32_t array_size = array_size_literal ? type.array.back() : evaluate_constant_u32(type.array.back());
2215 return type_struct_member_array_stride(struct_type, index) * array_size;
2216 }
2217 else if (type.basetype == SPIRType::Struct)
2218 {
2219 return get_declared_struct_size(type);
2220 }
2221 else
2222 {
2223 unsigned vecsize = type.vecsize;
2224 unsigned columns = type.columns;
2225
2226 // Vectors.
2227 if (columns == 1)
2228 {
2229 size_t component_size = type.width / 8;
2230 return vecsize * component_size;
2231 }
2232 else
2233 {
2234 uint32_t matrix_stride = type_struct_member_matrix_stride(struct_type, index);
2235
2236 // Per SPIR-V spec, matrices must be tightly packed and aligned up for vec3 accesses.
2237 if (flags.get(DecorationRowMajor))
2238 return matrix_stride * vecsize;
2239 else if (flags.get(DecorationColMajor))
2240 return matrix_stride * columns;
2241 else
2242 SPIRV_CROSS_THROW("Either row-major or column-major must be declared for matrices.");
2243 }
2244 }
2245 }
2246
2247 bool Compiler::BufferAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
2248 {
2249 if (opcode != OpAccessChain && opcode != OpInBoundsAccessChain && opcode != OpPtrAccessChain)
2250 return true;
2251
2252 bool ptr_chain = (opcode == OpPtrAccessChain);
2253
2254 // Invalid SPIR-V.
2255 if (length < (ptr_chain ? 5u : 4u))
2256 return false;
2257
2258 if (args[2] != id)
2259 return true;
2260
2261 // Don't bother traversing the entire access chain tree yet.
2262 // If we access a struct member, assume we access the entire member.
2263 uint32_t index = compiler.get<SPIRConstant>(args[ptr_chain ? 4 : 3]).scalar();
2264
2265 // Seen this index already.
2266 if (seen.find(index) != end(seen))
2267 return true;
2268 seen.insert(index);
2269
2270 auto &type = compiler.expression_type(id);
2271 uint32_t offset = compiler.type_struct_member_offset(type, index);
2272
2273 size_t range;
2274 // If we have another member in the struct, deduce the range by looking at the next member.
2275 // This is okay since structs in SPIR-V can have padding, but Offset decoration must be
2276 // monotonically increasing.
2277 // Of course, this doesn't take into account if the SPIR-V for some reason decided to add
2278 // very large amounts of padding, but that's not really a big deal.
2279 if (index + 1 < type.member_types.size())
2280 {
2281 range = compiler.type_struct_member_offset(type, index + 1) - offset;
2282 }
2283 else
2284 {
2285 // No padding, so just deduce it from the size of the member directly.
2286 range = compiler.get_declared_struct_member_size(type, index);
2287 }
2288
2289 ranges.push_back({ index, offset, range });
2290 return true;
2291 }
2292
2293 SmallVector<BufferRange> Compiler::get_active_buffer_ranges(VariableID id) const
2294 {
2295 SmallVector<BufferRange> ranges;
2296 BufferAccessHandler handler(*this, ranges, id);
2297 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
2298 return ranges;
2299 }
2300
2301 bool Compiler::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
2302 {
2303 if (a.basetype != b.basetype)
2304 return false;
2305 if (a.width != b.width)
2306 return false;
2307 if (a.vecsize != b.vecsize)
2308 return false;
2309 if (a.columns != b.columns)
2310 return false;
2311 if (a.array.size() != b.array.size())
2312 return false;
2313
2314 size_t array_count = a.array.size();
2315 if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
2316 return false;
2317
2318 if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
2319 {
2320 if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
2321 return false;
2322 }
2323
2324 if (a.member_types.size() != b.member_types.size())
2325 return false;
2326
2327 size_t member_types = a.member_types.size();
2328 for (size_t i = 0; i < member_types; i++)
2329 {
2330 if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
2331 return false;
2332 }
2333
2334 return true;
2335 }
2336
2337 const Bitset &Compiler::get_execution_mode_bitset() const
2338 {
2339 return get_entry_point().flags;
2340 }
2341
2342 void Compiler::set_execution_mode(ExecutionMode mode, uint32_t arg0, uint32_t arg1, uint32_t arg2)
2343 {
2344 auto &execution = get_entry_point();
2345
2346 execution.flags.set(mode);
2347 switch (mode)
2348 {
2349 case ExecutionModeLocalSize:
2350 execution.workgroup_size.x = arg0;
2351 execution.workgroup_size.y = arg1;
2352 execution.workgroup_size.z = arg2;
2353 break;
2354
2355 case ExecutionModeLocalSizeId:
2356 execution.workgroup_size.id_x = arg0;
2357 execution.workgroup_size.id_y = arg1;
2358 execution.workgroup_size.id_z = arg2;
2359 break;
2360
2361 case ExecutionModeInvocations:
2362 execution.invocations = arg0;
2363 break;
2364
2365 case ExecutionModeOutputVertices:
2366 execution.output_vertices = arg0;
2367 break;
2368
2369 case ExecutionModeOutputPrimitivesEXT:
2370 execution.output_primitives = arg0;
2371 break;
2372
2373 case ExecutionModeFPFastMathDefault:
2374 execution.fp_fast_math_defaults[arg0] = arg1;
2375 break;
2376
2377 default:
2378 break;
2379 }
2380 }
2381
2382 void Compiler::unset_execution_mode(ExecutionMode mode)
2383 {
2384 auto &execution = get_entry_point();
2385 execution.flags.clear(mode);
2386 }
2387
2388 uint32_t Compiler::get_work_group_size_specialization_constants(SpecializationConstant &x, SpecializationConstant &y,
2389 SpecializationConstant &z) const
2390 {
2391 auto &execution = get_entry_point();
2392 x = { 0, 0 };
2393 y = { 0, 0 };
2394 z = { 0, 0 };
2395
2396 // WorkgroupSize builtin takes precedence over LocalSize / LocalSizeId.
2397 if (execution.workgroup_size.constant != 0)
2398 {
2399 auto &c = get<SPIRConstant>(execution.workgroup_size.constant);
2400
2401 if (c.m.c[0].id[0] != ID(0))
2402 {
2403 x.id = c.m.c[0].id[0];
2404 x.constant_id = get_decoration(c.m.c[0].id[0], DecorationSpecId);
2405 }
2406
2407 if (c.m.c[0].id[1] != ID(0))
2408 {
2409 y.id = c.m.c[0].id[1];
2410 y.constant_id = get_decoration(c.m.c[0].id[1], DecorationSpecId);
2411 }
2412
2413 if (c.m.c[0].id[2] != ID(0))
2414 {
2415 z.id = c.m.c[0].id[2];
2416 z.constant_id = get_decoration(c.m.c[0].id[2], DecorationSpecId);
2417 }
2418 }
2419 else if (execution.flags.get(ExecutionModeLocalSizeId))
2420 {
2421 auto &cx = get<SPIRConstant>(execution.workgroup_size.id_x);
2422 if (cx.specialization)
2423 {
2424 x.id = execution.workgroup_size.id_x;
2425 x.constant_id = get_decoration(execution.workgroup_size.id_x, DecorationSpecId);
2426 }
2427
2428 auto &cy = get<SPIRConstant>(execution.workgroup_size.id_y);
2429 if (cy.specialization)
2430 {
2431 y.id = execution.workgroup_size.id_y;
2432 y.constant_id = get_decoration(execution.workgroup_size.id_y, DecorationSpecId);
2433 }
2434
2435 auto &cz = get<SPIRConstant>(execution.workgroup_size.id_z);
2436 if (cz.specialization)
2437 {
2438 z.id = execution.workgroup_size.id_z;
2439 z.constant_id = get_decoration(execution.workgroup_size.id_z, DecorationSpecId);
2440 }
2441 }
2442
2443 return execution.workgroup_size.constant;
2444 }
2445
2446 uint32_t Compiler::get_execution_mode_argument(spv::ExecutionMode mode, uint32_t index) const
2447 {
2448 auto &execution = get_entry_point();
2449 switch (mode)
2450 {
2451 case ExecutionModeLocalSizeId:
2452 if (execution.flags.get(ExecutionModeLocalSizeId))
2453 {
2454 switch (index)
2455 {
2456 case 0:
2457 return execution.workgroup_size.id_x;
2458 case 1:
2459 return execution.workgroup_size.id_y;
2460 case 2:
2461 return execution.workgroup_size.id_z;
2462 default:
2463 return 0;
2464 }
2465 }
2466 else
2467 return 0;
2468
2469 case ExecutionModeLocalSize:
2470 switch (index)
2471 {
2472 case 0:
2473 if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_x != 0)
2474 return get<SPIRConstant>(execution.workgroup_size.id_x).scalar();
2475 else
2476 return execution.workgroup_size.x;
2477 case 1:
2478 if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_y != 0)
2479 return get<SPIRConstant>(execution.workgroup_size.id_y).scalar();
2480 else
2481 return execution.workgroup_size.y;
2482 case 2:
2483 if (execution.flags.get(ExecutionModeLocalSizeId) && execution.workgroup_size.id_z != 0)
2484 return get<SPIRConstant>(execution.workgroup_size.id_z).scalar();
2485 else
2486 return execution.workgroup_size.z;
2487 default:
2488 return 0;
2489 }
2490
2491 case ExecutionModeInvocations:
2492 return execution.invocations;
2493
2494 case ExecutionModeOutputVertices:
2495 return execution.output_vertices;
2496
2497 case ExecutionModeOutputPrimitivesEXT:
2498 return execution.output_primitives;
2499
2500 default:
2501 return 0;
2502 }
2503 }
2504
2505 ExecutionModel Compiler::get_execution_model() const
2506 {
2507 auto &execution = get_entry_point();
2508 return execution.model;
2509 }
2510
2511 bool Compiler::is_tessellation_shader(ExecutionModel model)
2512 {
2513 return model == ExecutionModelTessellationControl || model == ExecutionModelTessellationEvaluation;
2514 }
2515
2516 bool Compiler::is_vertex_like_shader() const
2517 {
2518 auto model = get_execution_model();
2519 return model == ExecutionModelVertex || model == ExecutionModelGeometry ||
2520 model == ExecutionModelTessellationControl || model == ExecutionModelTessellationEvaluation;
2521 }
2522
2523 bool Compiler::is_tessellation_shader() const
2524 {
2525 return is_tessellation_shader(get_execution_model());
2526 }
2527
2528 bool Compiler::is_tessellating_triangles() const
2529 {
2530 return get_execution_mode_bitset().get(ExecutionModeTriangles);
2531 }
2532
2533 void Compiler::set_remapped_variable_state(VariableID id, bool remap_enable)
2534 {
2535 get<SPIRVariable>(id).remapped_variable = remap_enable;
2536 }
2537
2538 bool Compiler::get_remapped_variable_state(VariableID id) const
2539 {
2540 return get<SPIRVariable>(id).remapped_variable;
2541 }
2542
2543 void Compiler::set_subpass_input_remapped_components(VariableID id, uint32_t components)
2544 {
2545 get<SPIRVariable>(id).remapped_components = components;
2546 }
2547
2548 uint32_t Compiler::get_subpass_input_remapped_components(VariableID id) const
2549 {
2550 return get<SPIRVariable>(id).remapped_components;
2551 }
2552
2553 void Compiler::add_implied_read_expression(SPIRExpression &e, uint32_t source)
2554 {
2555 auto itr = find(begin(e.implied_read_expressions), end(e.implied_read_expressions), ID(source));
2556 if (itr == end(e.implied_read_expressions))
2557 e.implied_read_expressions.push_back(source);
2558 }
2559
2560 void Compiler::add_implied_read_expression(SPIRAccessChain &e, uint32_t source)
2561 {
2562 auto itr = find(begin(e.implied_read_expressions), end(e.implied_read_expressions), ID(source));
2563 if (itr == end(e.implied_read_expressions))
2564 e.implied_read_expressions.push_back(source);
2565 }
2566
2567 void Compiler::add_active_interface_variable(uint32_t var_id)
2568 {
2569 active_interface_variables.insert(var_id);
2570
2571 // In SPIR-V 1.4 and up we must also track the interface variable in the entry point.
2572 if (ir.get_spirv_version() >= 0x10400)
2573 {
2574 auto &vars = get_entry_point().interface_variables;
2575 if (find(begin(vars), end(vars), VariableID(var_id)) == end(vars))
2576 vars.push_back(var_id);
2577 }
2578 }
2579
2580 void Compiler::inherit_expression_dependencies(uint32_t dst, uint32_t source_expression)
2581 {
2582 auto *ptr_e = maybe_get<SPIRExpression>(dst);
2583
2584 if (is_position_invariant() && ptr_e && maybe_get<SPIRExpression>(source_expression))
2585 {
2586 auto &deps = ptr_e->invariance_dependencies;
2587 if (std::find(deps.begin(), deps.end(), source_expression) == deps.end())
2588 deps.push_back(source_expression);
2589 }
2590
2591 // Don't inherit any expression dependencies if the expression in dst
2592 // is not a forwarded temporary.
2593 if (forwarded_temporaries.find(dst) == end(forwarded_temporaries) ||
2594 forced_temporaries.find(dst) != end(forced_temporaries))
2595 {
2596 return;
2597 }
2598
2599 auto &e = *ptr_e;
2600 auto *phi = maybe_get<SPIRVariable>(source_expression);
2601 if (phi && phi->phi_variable)
2602 {
2603 // We have used a phi variable, which can change at the end of the block,
2604 // so make sure we take a dependency on this phi variable.
2605 phi->dependees.push_back(dst);
2606 }
2607
2608 auto *s = maybe_get<SPIRExpression>(source_expression);
2609 if (!s)
2610 return;
2611
2612 auto &e_deps = e.expression_dependencies;
2613 auto &s_deps = s->expression_dependencies;
2614
2615 // If we depend on a expression, we also depend on all sub-dependencies from source.
2616 e_deps.push_back(source_expression);
2617 e_deps.insert(end(e_deps), begin(s_deps), end(s_deps));
2618
2619 // Eliminate duplicated dependencies.
2620 sort(begin(e_deps), end(e_deps));
2621 e_deps.erase(unique(begin(e_deps), end(e_deps)), end(e_deps));
2622 }
2623
2624 SmallVector<EntryPoint> Compiler::get_entry_points_and_stages() const
2625 {
2626 SmallVector<EntryPoint> entries;
2627 for (auto &entry : ir.entry_points)
2628 entries.push_back({ entry.second.orig_name, entry.second.model });
2629 return entries;
2630 }
2631
2632 void Compiler::rename_entry_point(const std::string &old_name, const std::string &new_name, spv::ExecutionModel model)
2633 {
2634 auto &entry = get_entry_point(old_name, model);
2635 entry.orig_name = new_name;
2636 entry.name = new_name;
2637 }
2638
2639 void Compiler::set_entry_point(const std::string &name, spv::ExecutionModel model)
2640 {
2641 auto &entry = get_entry_point(name, model);
2642 ir.default_entry_point = entry.self;
2643 }
2644
2645 SPIREntryPoint &Compiler::get_first_entry_point(const std::string &name)
2646 {
2647 auto itr = find_if(
2648 begin(ir.entry_points), end(ir.entry_points),
2649 [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool { return entry.second.orig_name == name; });
2650
2651 if (itr == end(ir.entry_points))
2652 SPIRV_CROSS_THROW("Entry point does not exist.");
2653
2654 return itr->second;
2655 }
2656
2657 const SPIREntryPoint &Compiler::get_first_entry_point(const std::string &name) const
2658 {
2659 auto itr = find_if(
2660 begin(ir.entry_points), end(ir.entry_points),
2661 [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool { return entry.second.orig_name == name; });
2662
2663 if (itr == end(ir.entry_points))
2664 SPIRV_CROSS_THROW("Entry point does not exist.");
2665
2666 return itr->second;
2667 }
2668
2669 SPIREntryPoint &Compiler::get_entry_point(const std::string &name, ExecutionModel model)
2670 {
2671 auto itr = find_if(begin(ir.entry_points), end(ir.entry_points),
2672 [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool {
2673 return entry.second.orig_name == name && entry.second.model == model;
2674 });
2675
2676 if (itr == end(ir.entry_points))
2677 SPIRV_CROSS_THROW("Entry point does not exist.");
2678
2679 return itr->second;
2680 }
2681
2682 const SPIREntryPoint &Compiler::get_entry_point(const std::string &name, ExecutionModel model) const
2683 {
2684 auto itr = find_if(begin(ir.entry_points), end(ir.entry_points),
2685 [&](const std::pair<uint32_t, SPIREntryPoint> &entry) -> bool {
2686 return entry.second.orig_name == name && entry.second.model == model;
2687 });
2688
2689 if (itr == end(ir.entry_points))
2690 SPIRV_CROSS_THROW("Entry point does not exist.");
2691
2692 return itr->second;
2693 }
2694
2695 const string &Compiler::get_cleansed_entry_point_name(const std::string &name, ExecutionModel model) const
2696 {
2697 return get_entry_point(name, model).name;
2698 }
2699
2700 const SPIREntryPoint &Compiler::get_entry_point() const
2701 {
2702 return ir.entry_points.find(ir.default_entry_point)->second;
2703 }
2704
2705 SPIREntryPoint &Compiler::get_entry_point()
2706 {
2707 return ir.entry_points.find(ir.default_entry_point)->second;
2708 }
2709
2710 bool Compiler::interface_variable_exists_in_entry_point(uint32_t id) const
2711 {
2712 auto &var = get<SPIRVariable>(id);
2713
2714 if (ir.get_spirv_version() < 0x10400)
2715 {
2716 if (var.storage != StorageClassInput && var.storage != StorageClassOutput &&
2717 var.storage != StorageClassUniformConstant)
2718 SPIRV_CROSS_THROW("Only Input, Output variables and Uniform constants are part of a shader linking interface.");
2719
2720 // This is to avoid potential problems with very old glslang versions which did
2721 // not emit input/output interfaces properly.
2722 // We can assume they only had a single entry point, and single entry point
2723 // shaders could easily be assumed to use every interface variable anyways.
2724 if (ir.entry_points.size() <= 1)
2725 return true;
2726 }
2727
2728 // In SPIR-V 1.4 and later, all global resource variables must be present.
2729
2730 auto &execution = get_entry_point();
2731 return find(begin(execution.interface_variables), end(execution.interface_variables), VariableID(id)) !=
2732 end(execution.interface_variables);
2733 }
2734
2735 void Compiler::CombinedImageSamplerHandler::push_remap_parameters(const SPIRFunction &func, const uint32_t *args,
2736 uint32_t length)
2737 {
2738 // If possible, pipe through a remapping table so that parameters know
2739 // which variables they actually bind to in this scope.
2740 unordered_map<uint32_t, uint32_t> remapping;
2741 for (uint32_t i = 0; i < length; i++)
2742 remapping[func.arguments[i].id] = remap_parameter(args[i]);
2743 parameter_remapping.push(std::move(remapping));
2744 }
2745
2746 void Compiler::CombinedImageSamplerHandler::pop_remap_parameters()
2747 {
2748 parameter_remapping.pop();
2749 }
2750
2751 uint32_t Compiler::CombinedImageSamplerHandler::remap_parameter(uint32_t id)
2752 {
2753 auto *var = compiler.maybe_get_backing_variable(id);
2754 if (var)
2755 id = var->self;
2756
2757 if (parameter_remapping.empty())
2758 return id;
2759
2760 auto &remapping = parameter_remapping.top();
2761 auto itr = remapping.find(id);
2762 if (itr != end(remapping))
2763 return itr->second;
2764 else
2765 return id;
2766 }
2767
2768 bool Compiler::CombinedImageSamplerHandler::begin_function_scope(const uint32_t *args, uint32_t length)
2769 {
2770 if (length < 3)
2771 return false;
2772
2773 auto &callee = compiler.get<SPIRFunction>(args[2]);
2774 args += 3;
2775 length -= 3;
2776 push_remap_parameters(callee, args, length);
2777 functions.push(&callee);
2778 return true;
2779 }
2780
2781 bool Compiler::CombinedImageSamplerHandler::end_function_scope(const uint32_t *args, uint32_t length)
2782 {
2783 if (length < 3)
2784 return false;
2785
2786 auto &callee = compiler.get<SPIRFunction>(args[2]);
2787 args += 3;
2788
2789 // There are two types of cases we have to handle,
2790 // a callee might call sampler2D(texture2D, sampler) directly where
2791 // one or more parameters originate from parameters.
2792 // Alternatively, we need to provide combined image samplers to our callees,
2793 // and in this case we need to add those as well.
2794
2795 pop_remap_parameters();
2796
2797 // Our callee has now been processed at least once.
2798 // No point in doing it again.
2799 callee.do_combined_parameters = false;
2800
2801 auto &params = functions.top()->combined_parameters;
2802 functions.pop();
2803 if (functions.empty())
2804 return true;
2805
2806 auto &caller = *functions.top();
2807 if (caller.do_combined_parameters)
2808 {
2809 for (auto &param : params)
2810 {
2811 VariableID image_id = param.global_image ? param.image_id : VariableID(args[param.image_id]);
2812 VariableID sampler_id = param.global_sampler ? param.sampler_id : VariableID(args[param.sampler_id]);
2813
2814 auto *i = compiler.maybe_get_backing_variable(image_id);
2815 auto *s = compiler.maybe_get_backing_variable(sampler_id);
2816 if (i)
2817 image_id = i->self;
2818 if (s)
2819 sampler_id = s->self;
2820
2821 register_combined_image_sampler(caller, 0, image_id, sampler_id, param.depth);
2822 }
2823 }
2824
2825 return true;
2826 }
2827
2828 void Compiler::CombinedImageSamplerHandler::register_combined_image_sampler(SPIRFunction &caller,
2829 VariableID combined_module_id,
2830 VariableID image_id, VariableID sampler_id,
2831 bool depth)
2832 {
2833 // We now have a texture ID and a sampler ID which will either be found as a global
2834 // or a parameter in our own function. If both are global, they will not need a parameter,
2835 // otherwise, add it to our list.
2836 SPIRFunction::CombinedImageSamplerParameter param = {
2837 0u, image_id, sampler_id, true, true, depth,
2838 };
2839
2840 auto texture_itr = find_if(begin(caller.arguments), end(caller.arguments),
2841 [image_id](const SPIRFunction::Parameter &p) { return p.id == image_id; });
2842 auto sampler_itr = find_if(begin(caller.arguments), end(caller.arguments),
2843 [sampler_id](const SPIRFunction::Parameter &p) { return p.id == sampler_id; });
2844
2845 if (texture_itr != end(caller.arguments))
2846 {
2847 param.global_image = false;
2848 param.image_id = uint32_t(texture_itr - begin(caller.arguments));
2849 }
2850
2851 if (sampler_itr != end(caller.arguments))
2852 {
2853 param.global_sampler = false;
2854 param.sampler_id = uint32_t(sampler_itr - begin(caller.arguments));
2855 }
2856
2857 if (param.global_image && param.global_sampler)
2858 return;
2859
2860 auto itr = find_if(begin(caller.combined_parameters), end(caller.combined_parameters),
2861 [&param](const SPIRFunction::CombinedImageSamplerParameter &p) {
2862 return param.image_id == p.image_id && param.sampler_id == p.sampler_id &&
2863 param.global_image == p.global_image && param.global_sampler == p.global_sampler;
2864 });
2865
2866 if (itr == end(caller.combined_parameters))
2867 {
2868 uint32_t id = compiler.ir.increase_bound_by(3);
2869 auto type_id = id + 0;
2870 auto ptr_type_id = id + 1;
2871 auto combined_id = id + 2;
2872 auto &base = compiler.expression_type(image_id);
2873 auto &type = compiler.set<SPIRType>(type_id, OpTypeSampledImage);
2874 auto &ptr_type = compiler.set<SPIRType>(ptr_type_id, OpTypePointer);
2875
2876 type = base;
2877 type.self = type_id;
2878 type.basetype = SPIRType::SampledImage;
2879 type.pointer = false;
2880 type.storage = StorageClassGeneric;
2881 type.image.depth = depth;
2882
2883 ptr_type = type;
2884 ptr_type.pointer = true;
2885 ptr_type.storage = StorageClassUniformConstant;
2886 ptr_type.parent_type = type_id;
2887
2888 // Build new variable.
2889 compiler.set<SPIRVariable>(combined_id, ptr_type_id, StorageClassFunction, 0);
2890
2891 // Inherit RelaxedPrecision.
2892 // If any of OpSampledImage, underlying image or sampler are marked, inherit the decoration.
2893 bool relaxed_precision =
2894 compiler.has_decoration(sampler_id, DecorationRelaxedPrecision) ||
2895 compiler.has_decoration(image_id, DecorationRelaxedPrecision) ||
2896 (combined_module_id && compiler.has_decoration(combined_module_id, DecorationRelaxedPrecision));
2897
2898 if (relaxed_precision)
2899 compiler.set_decoration(combined_id, DecorationRelaxedPrecision);
2900
2901 param.id = combined_id;
2902
2903 compiler.set_name(combined_id,
2904 join("SPIRV_Cross_Combined", compiler.to_name(image_id), compiler.to_name(sampler_id)));
2905
2906 caller.combined_parameters.push_back(param);
2907 caller.shadow_arguments.push_back({ ptr_type_id, combined_id, 0u, 0u, true });
2908 }
2909 }
2910
2911 bool Compiler::DummySamplerForCombinedImageHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
2912 {
2913 if (need_dummy_sampler)
2914 {
2915 // No need to traverse further, we know the result.
2916 return false;
2917 }
2918
2919 switch (opcode)
2920 {
2921 case OpLoad:
2922 {
2923 if (length < 3)
2924 return false;
2925
2926 uint32_t result_type = args[0];
2927
2928 auto &type = compiler.get<SPIRType>(result_type);
2929 bool separate_image =
2930 type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer;
2931
2932 // If not separate image, don't bother.
2933 if (!separate_image)
2934 return true;
2935
2936 uint32_t id = args[1];
2937 uint32_t ptr = args[2];
2938 compiler.set<SPIRExpression>(id, "", result_type, true);
2939 compiler.register_read(id, ptr, true);
2940 break;
2941 }
2942
2943 case OpImageFetch:
2944 case OpImageQuerySizeLod:
2945 case OpImageQuerySize:
2946 case OpImageQueryLevels:
2947 case OpImageQuerySamples:
2948 {
2949 // If we are fetching or querying LOD from a plain OpTypeImage, we must pre-combine with our dummy sampler.
2950 auto *var = compiler.maybe_get_backing_variable(args[2]);
2951 if (var)
2952 {
2953 auto &type = compiler.get<SPIRType>(var->basetype);
2954 if (type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer)
2955 need_dummy_sampler = true;
2956 }
2957
2958 break;
2959 }
2960
2961 case OpInBoundsAccessChain:
2962 case OpAccessChain:
2963 case OpPtrAccessChain:
2964 {
2965 if (length < 3)
2966 return false;
2967
2968 uint32_t result_type = args[0];
2969 auto &type = compiler.get<SPIRType>(result_type);
2970 bool separate_image =
2971 type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer;
2972 if (!separate_image)
2973 return true;
2974
2975 uint32_t id = args[1];
2976 uint32_t ptr = args[2];
2977 compiler.set<SPIRExpression>(id, "", result_type, true);
2978 compiler.register_read(id, ptr, true);
2979
2980 // Other backends might use SPIRAccessChain for this later.
2981 compiler.ir.ids[id].set_allow_type_rewrite();
2982 break;
2983 }
2984
2985 default:
2986 break;
2987 }
2988
2989 return true;
2990 }
2991
2992 bool Compiler::CombinedImageSamplerHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
2993 {
2994 // We need to figure out where samplers and images are loaded from, so do only the bare bones compilation we need.
2995 bool is_fetch = false;
2996
2997 switch (opcode)
2998 {
2999 case OpLoad:
3000 {
3001 if (length < 3)
3002 return false;
3003
3004 uint32_t result_type = args[0];
3005
3006 auto &type = compiler.get<SPIRType>(result_type);
3007 bool separate_image = type.basetype == SPIRType::Image && type.image.sampled == 1;
3008 bool separate_sampler = type.basetype == SPIRType::Sampler;
3009
3010 // If not separate image or sampler, don't bother.
3011 if (!separate_image && !separate_sampler)
3012 return true;
3013
3014 uint32_t id = args[1];
3015 uint32_t ptr = args[2];
3016 compiler.set<SPIRExpression>(id, "", result_type, true);
3017 compiler.register_read(id, ptr, true);
3018 return true;
3019 }
3020
3021 case OpInBoundsAccessChain:
3022 case OpAccessChain:
3023 case OpPtrAccessChain:
3024 {
3025 if (length < 3)
3026 return false;
3027
3028 // Technically, it is possible to have arrays of textures and arrays of samplers and combine them, but this becomes essentially
3029 // impossible to implement, since we don't know which concrete sampler we are accessing.
3030 // One potential way is to create a combinatorial explosion where N textures and M samplers are combined into N * M sampler2Ds,
3031 // but this seems ridiculously complicated for a problem which is easy to work around.
3032 // Checking access chains like this assumes we don't have samplers or textures inside uniform structs, but this makes no sense.
3033
3034 uint32_t result_type = args[0];
3035
3036 auto &type = compiler.get<SPIRType>(result_type);
3037 bool separate_image = type.basetype == SPIRType::Image && type.image.sampled == 1;
3038 bool separate_sampler = type.basetype == SPIRType::Sampler;
3039 if (separate_sampler)
3040 SPIRV_CROSS_THROW(
3041 "Attempting to use arrays or structs of separate samplers. This is not possible to statically "
3042 "remap to plain GLSL.");
3043
3044 if (separate_image)
3045 {
3046 uint32_t id = args[1];
3047 uint32_t ptr = args[2];
3048 compiler.set<SPIRExpression>(id, "", result_type, true);
3049 compiler.register_read(id, ptr, true);
3050 }
3051 return true;
3052 }
3053
3054 case OpImageFetch:
3055 case OpImageQuerySizeLod:
3056 case OpImageQuerySize:
3057 case OpImageQueryLevels:
3058 case OpImageQuerySamples:
3059 {
3060 // If we are fetching from a plain OpTypeImage or querying LOD, we must pre-combine with our dummy sampler.
3061 auto *var = compiler.maybe_get_backing_variable(args[2]);
3062 if (!var)
3063 return true;
3064
3065 auto &type = compiler.get<SPIRType>(var->basetype);
3066 if (type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer)
3067 {
3068 if (compiler.dummy_sampler_id == 0)
3069 SPIRV_CROSS_THROW("texelFetch without sampler was found, but no dummy sampler has been created with "
3070 "build_dummy_sampler_for_combined_images().");
3071
3072 // Do it outside.
3073 is_fetch = true;
3074 break;
3075 }
3076
3077 return true;
3078 }
3079
3080 case OpSampledImage:
3081 // Do it outside.
3082 break;
3083
3084 default:
3085 return true;
3086 }
3087
3088 // Registers sampler2D calls used in case they are parameters so
3089 // that their callees know which combined image samplers to propagate down the call stack.
3090 if (!functions.empty())
3091 {
3092 auto &callee = *functions.top();
3093 if (callee.do_combined_parameters)
3094 {
3095 uint32_t image_id = args[2];
3096
3097 auto *image = compiler.maybe_get_backing_variable(image_id);
3098 if (image)
3099 image_id = image->self;
3100
3101 uint32_t sampler_id = is_fetch ? compiler.dummy_sampler_id : args[3];
3102 auto *sampler = compiler.maybe_get_backing_variable(sampler_id);
3103 if (sampler)
3104 sampler_id = sampler->self;
3105
3106 uint32_t combined_id = args[1];
3107
3108 auto &combined_type = compiler.get<SPIRType>(args[0]);
3109 register_combined_image_sampler(callee, combined_id, image_id, sampler_id, combined_type.image.depth);
3110 }
3111 }
3112
3113 // For function calls, we need to remap IDs which are function parameters into global variables.
3114 // This information is statically known from the current place in the call stack.
3115 // Function parameters are not necessarily pointers, so if we don't have a backing variable, remapping will know
3116 // which backing variable the image/sample came from.
3117 VariableID image_id = remap_parameter(args[2]);
3118 VariableID sampler_id = is_fetch ? compiler.dummy_sampler_id : remap_parameter(args[3]);
3119
3120 auto itr = find_if(begin(compiler.combined_image_samplers), end(compiler.combined_image_samplers),
3121 [image_id, sampler_id](const CombinedImageSampler &combined) {
3122 return combined.image_id == image_id && combined.sampler_id == sampler_id;
3123 });
3124
3125 if (itr == end(compiler.combined_image_samplers))
3126 {
3127 uint32_t sampled_type;
3128 uint32_t combined_module_id;
3129 if (is_fetch)
3130 {
3131 // Have to invent the sampled image type.
3132 sampled_type = compiler.ir.increase_bound_by(1);
3133 auto &type = compiler.set<SPIRType>(sampled_type, OpTypeSampledImage);
3134 type = compiler.expression_type(args[2]);
3135 type.self = sampled_type;
3136 type.basetype = SPIRType::SampledImage;
3137 type.image.depth = false;
3138 combined_module_id = 0;
3139 }
3140 else
3141 {
3142 sampled_type = args[0];
3143 combined_module_id = args[1];
3144 }
3145
3146 auto id = compiler.ir.increase_bound_by(2);
3147 auto type_id = id + 0;
3148 auto combined_id = id + 1;
3149
3150 // Make a new type, pointer to OpTypeSampledImage, so we can make a variable of this type.
3151 // We will probably have this type lying around, but it doesn't hurt to make duplicates for internal purposes.
3152 auto &type = compiler.set<SPIRType>(type_id, OpTypePointer);
3153 auto &base = compiler.get<SPIRType>(sampled_type);
3154 type = base;
3155 type.pointer = true;
3156 type.storage = StorageClassUniformConstant;
3157 type.parent_type = type_id;
3158
3159 // Build new variable.
3160 compiler.set<SPIRVariable>(combined_id, type_id, StorageClassUniformConstant, 0);
3161
3162 // Inherit RelaxedPrecision (and potentially other useful flags if deemed relevant).
3163 // If any of OpSampledImage, underlying image or sampler are marked, inherit the decoration.
3164 bool relaxed_precision =
3165 (sampler_id && compiler.has_decoration(sampler_id, DecorationRelaxedPrecision)) ||
3166 (image_id && compiler.has_decoration(image_id, DecorationRelaxedPrecision)) ||
3167 (combined_module_id && compiler.has_decoration(combined_module_id, DecorationRelaxedPrecision));
3168
3169 if (relaxed_precision)
3170 compiler.set_decoration(combined_id, DecorationRelaxedPrecision);
3171
3172 // Propagate the array type for the original image as well.
3173 auto *var = compiler.maybe_get_backing_variable(image_id);
3174 if (var)
3175 {
3176 auto &parent_type = compiler.get<SPIRType>(var->basetype);
3177 type.array = parent_type.array;
3178 type.array_size_literal = parent_type.array_size_literal;
3179 }
3180
3181 compiler.combined_image_samplers.push_back({ combined_id, image_id, sampler_id });
3182 }
3183
3184 return true;
3185 }
3186
3187 VariableID Compiler::build_dummy_sampler_for_combined_images()
3188 {
3189 DummySamplerForCombinedImageHandler handler(*this);
3190 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
3191 if (handler.need_dummy_sampler)
3192 {
3193 uint32_t offset = ir.increase_bound_by(3);
3194 auto type_id = offset + 0;
3195 auto ptr_type_id = offset + 1;
3196 auto var_id = offset + 2;
3197
3198 auto &sampler = set<SPIRType>(type_id, OpTypeSampler);
3199 sampler.basetype = SPIRType::Sampler;
3200
3201 auto &ptr_sampler = set<SPIRType>(ptr_type_id, OpTypePointer);
3202 ptr_sampler = sampler;
3203 ptr_sampler.self = type_id;
3204 ptr_sampler.storage = StorageClassUniformConstant;
3205 ptr_sampler.pointer = true;
3206 ptr_sampler.parent_type = type_id;
3207
3208 set<SPIRVariable>(var_id, ptr_type_id, StorageClassUniformConstant, 0);
3209 set_name(var_id, "SPIRV_Cross_DummySampler");
3210 dummy_sampler_id = var_id;
3211 return var_id;
3212 }
3213 else
3214 return 0;
3215 }
3216
3217 void Compiler::build_combined_image_samplers()
3218 {
3219 ir.for_each_typed_id<SPIRFunction>([&](uint32_t, SPIRFunction &func) {
3220 func.combined_parameters.clear();
3221 func.shadow_arguments.clear();
3222 func.do_combined_parameters = true;
3223 });
3224
3225 combined_image_samplers.clear();
3226 CombinedImageSamplerHandler handler(*this);
3227 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
3228 }
3229
3230 SmallVector<SpecializationConstant> Compiler::get_specialization_constants() const
3231 {
3232 SmallVector<SpecializationConstant> spec_consts;
3233 ir.for_each_typed_id<SPIRConstant>([&](uint32_t, const SPIRConstant &c) {
3234 if (c.specialization && has_decoration(c.self, DecorationSpecId))
3235 spec_consts.push_back({ c.self, get_decoration(c.self, DecorationSpecId) });
3236 });
3237 return spec_consts;
3238 }
3239
3240 SPIRConstant &Compiler::get_constant(ConstantID id)
3241 {
3242 return get<SPIRConstant>(id);
3243 }
3244
3245 const SPIRConstant &Compiler::get_constant(ConstantID id) const
3246 {
3247 return get<SPIRConstant>(id);
3248 }
3249
3250 static bool exists_unaccessed_path_to_return(const CFG &cfg, uint32_t block, const unordered_set<uint32_t> &blocks,
3251 unordered_set<uint32_t> &visit_cache)
3252 {
3253 // This block accesses the variable.
3254 if (blocks.find(block) != end(blocks))
3255 return false;
3256
3257 // We are at the end of the CFG.
3258 if (cfg.get_succeeding_edges(block).empty())
3259 return true;
3260
3261 // If any of our successors have a path to the end, there exists a path from block.
3262 for (auto &succ : cfg.get_succeeding_edges(block))
3263 {
3264 if (visit_cache.count(succ) == 0)
3265 {
3266 if (exists_unaccessed_path_to_return(cfg, succ, blocks, visit_cache))
3267 return true;
3268 visit_cache.insert(succ);
3269 }
3270 }
3271
3272 return false;
3273 }
3274
3275 void Compiler::analyze_parameter_preservation(
3276 SPIRFunction &entry, const CFG &cfg, const unordered_map<uint32_t, unordered_set<uint32_t>> &variable_to_blocks,
3277 const unordered_map<uint32_t, unordered_set<uint32_t>> &complete_write_blocks)
3278 {
3279 for (auto &arg : entry.arguments)
3280 {
3281 // Non-pointers are always inputs.
3282 auto &type = get<SPIRType>(arg.type);
3283 if (!type.pointer)
3284 continue;
3285
3286 // Opaque argument types are always in
3287 bool potential_preserve;
3288 switch (type.basetype)
3289 {
3290 case SPIRType::Sampler:
3291 case SPIRType::Image:
3292 case SPIRType::SampledImage:
3293 case SPIRType::AtomicCounter:
3294 potential_preserve = false;
3295 break;
3296
3297 default:
3298 potential_preserve = true;
3299 break;
3300 }
3301
3302 if (!potential_preserve)
3303 continue;
3304
3305 auto itr = variable_to_blocks.find(arg.id);
3306 if (itr == end(variable_to_blocks))
3307 {
3308 // Variable is never accessed.
3309 continue;
3310 }
3311
3312 // We have accessed a variable, but there was no complete writes to that variable.
3313 // We deduce that we must preserve the argument.
3314 itr = complete_write_blocks.find(arg.id);
3315 if (itr == end(complete_write_blocks))
3316 {
3317 arg.read_count++;
3318 continue;
3319 }
3320
3321 // If there is a path through the CFG where no block completely writes to the variable, the variable will be in an undefined state
3322 // when the function returns. We therefore need to implicitly preserve the variable in case there are writers in the function.
3323 // Major case here is if a function is
3324 // void foo(int &var) { if (cond) var = 10; }
3325 // Using read/write counts, we will think it's just an out variable, but it really needs to be inout,
3326 // because if we don't write anything whatever we put into the function must return back to the caller.
3327 unordered_set<uint32_t> visit_cache;
3328 if (exists_unaccessed_path_to_return(cfg, entry.entry_block, itr->second, visit_cache))
3329 arg.read_count++;
3330 }
3331 }
3332
3333 Compiler::AnalyzeVariableScopeAccessHandler::AnalyzeVariableScopeAccessHandler(Compiler &compiler_,
3334 SPIRFunction &entry_)
3335 : compiler(compiler_)
3336 , entry(entry_)
3337 {
3338 }
3339
3340 bool Compiler::AnalyzeVariableScopeAccessHandler::follow_function_call(const SPIRFunction &)
3341 {
3342 // Only analyze within this function.
3343 return false;
3344 }
3345
3346 void Compiler::AnalyzeVariableScopeAccessHandler::set_current_block(const SPIRBlock &block)
3347 {
3348 current_block = &block;
3349
3350 // If we're branching to a block which uses OpPhi, in GLSL
3351 // this will be a variable write when we branch,
3352 // so we need to track access to these variables as well to
3353 // have a complete picture.
3354 const auto test_phi = [this, &block](uint32_t to) {
3355 auto &next = compiler.get<SPIRBlock>(to);
3356 for (auto &phi : next.phi_variables)
3357 {
3358 if (phi.parent == block.self)
3359 {
3360 accessed_variables_to_block[phi.function_variable].insert(block.self);
3361 // Phi variables are also accessed in our target branch block.
3362 accessed_variables_to_block[phi.function_variable].insert(next.self);
3363
3364 notify_variable_access(phi.local_variable, block.self);
3365 }
3366 }
3367 };
3368
3369 switch (block.terminator)
3370 {
3371 case SPIRBlock::Direct:
3372 notify_variable_access(block.condition, block.self);
3373 test_phi(block.next_block);
3374 break;
3375
3376 case SPIRBlock::Select:
3377 notify_variable_access(block.condition, block.self);
3378 test_phi(block.true_block);
3379 test_phi(block.false_block);
3380 break;
3381
3382 case SPIRBlock::MultiSelect:
3383 {
3384 notify_variable_access(block.condition, block.self);
3385 auto &cases = compiler.get_case_list(block);
3386 for (auto &target : cases)
3387 test_phi(target.block);
3388 if (block.default_block)
3389 test_phi(block.default_block);
3390 break;
3391 }
3392
3393 default:
3394 break;
3395 }
3396 }
3397
3398 void Compiler::AnalyzeVariableScopeAccessHandler::notify_variable_access(uint32_t id, uint32_t block)
3399 {
3400 if (id == 0)
3401 return;
3402
3403 // Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
3404 auto itr = rvalue_forward_children.find(id);
3405 if (itr != end(rvalue_forward_children))
3406 for (auto child_id : itr->second)
3407 notify_variable_access(child_id, block);
3408
3409 if (id_is_phi_variable(id))
3410 accessed_variables_to_block[id].insert(block);
3411 else if (id_is_potential_temporary(id))
3412 accessed_temporaries_to_block[id].insert(block);
3413 }
3414
3415 bool Compiler::AnalyzeVariableScopeAccessHandler::id_is_phi_variable(uint32_t id) const
3416 {
3417 if (id >= compiler.get_current_id_bound())
3418 return false;
3419 auto *var = compiler.maybe_get<SPIRVariable>(id);
3420 return var && var->phi_variable;
3421 }
3422
3423 bool Compiler::AnalyzeVariableScopeAccessHandler::id_is_potential_temporary(uint32_t id) const
3424 {
3425 if (id >= compiler.get_current_id_bound())
3426 return false;
3427
3428 // Temporaries are not created before we start emitting code.
3429 return compiler.ir.ids[id].empty() || (compiler.ir.ids[id].get_type() == TypeExpression);
3430 }
3431
3432 bool Compiler::AnalyzeVariableScopeAccessHandler::handle_terminator(const SPIRBlock &block)
3433 {
3434 switch (block.terminator)
3435 {
3436 case SPIRBlock::Return:
3437 if (block.return_value)
3438 notify_variable_access(block.return_value, block.self);
3439 break;
3440
3441 case SPIRBlock::Select:
3442 case SPIRBlock::MultiSelect:
3443 notify_variable_access(block.condition, block.self);
3444 break;
3445
3446 default:
3447 break;
3448 }
3449
3450 return true;
3451 }
3452
3453 bool Compiler::AnalyzeVariableScopeAccessHandler::handle(spv::Op op, const uint32_t *args, uint32_t length)
3454 {
3455 // Keep track of the types of temporaries, so we can hoist them out as necessary.
3456 uint32_t result_type = 0, result_id = 0;
3457 if (compiler.instruction_to_result_type(result_type, result_id, op, args, length))
3458 {
3459 // For some opcodes, we will need to override the result id.
3460 // If we need to hoist the temporary, the temporary type is the input, not the result.
3461 if (op == OpConvertUToAccelerationStructureKHR)
3462 {
3463 auto itr = result_id_to_type.find(args[2]);
3464 if (itr != result_id_to_type.end())
3465 result_type = itr->second;
3466 }
3467
3468 result_id_to_type[result_id] = result_type;
3469 }
3470
3471 switch (op)
3472 {
3473 case OpStore:
3474 case OpCooperativeMatrixStoreKHR:
3475 {
3476 if (length < 2)
3477 return false;
3478
3479 ID ptr = args[0];
3480 auto *var = compiler.maybe_get_backing_variable(ptr);
3481
3482 // If we store through an access chain, we have a partial write.
3483 if (var)
3484 {
3485 accessed_variables_to_block[var->self].insert(current_block->self);
3486 if (var->self == ptr)
3487 complete_write_variables_to_block[var->self].insert(current_block->self);
3488 else
3489 partial_write_variables_to_block[var->self].insert(current_block->self);
3490 }
3491
3492 // args[0] might be an access chain we have to track use of.
3493 notify_variable_access(args[0], current_block->self);
3494 // Might try to store a Phi variable here.
3495 notify_variable_access(args[1], current_block->self);
3496 break;
3497 }
3498
3499 case OpAccessChain:
3500 case OpInBoundsAccessChain:
3501 case OpPtrAccessChain:
3502 {
3503 if (length < 3)
3504 return false;
3505
3506 // Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
3507 uint32_t ptr = args[2];
3508 auto *var = compiler.maybe_get<SPIRVariable>(ptr);
3509 if (var)
3510 {
3511 accessed_variables_to_block[var->self].insert(current_block->self);
3512 rvalue_forward_children[args[1]].insert(var->self);
3513 }
3514
3515 // args[2] might be another access chain we have to track use of.
3516 for (uint32_t i = 2; i < length; i++)
3517 {
3518 notify_variable_access(args[i], current_block->self);
3519 rvalue_forward_children[args[1]].insert(args[i]);
3520 }
3521
3522 // Also keep track of the access chain pointer itself.
3523 // In exceptionally rare cases, we can end up with a case where
3524 // the access chain is generated in the loop body, but is consumed in continue block.
3525 // This means we need complex loop workarounds, and we must detect this via CFG analysis.
3526 notify_variable_access(args[1], current_block->self);
3527
3528 // The result of an access chain is a fixed expression and is not really considered a temporary.
3529 auto &e = compiler.set<SPIRExpression>(args[1], "", args[0], true);
3530 auto *backing_variable = compiler.maybe_get_backing_variable(ptr);
3531 e.loaded_from = backing_variable ? VariableID(backing_variable->self) : VariableID(0);
3532
3533 // Other backends might use SPIRAccessChain for this later.
3534 compiler.ir.ids[args[1]].set_allow_type_rewrite();
3535 access_chain_expressions.insert(args[1]);
3536 break;
3537 }
3538
3539 case OpCopyMemory:
3540 {
3541 if (length < 2)
3542 return false;
3543
3544 ID lhs = args[0];
3545 ID rhs = args[1];
3546 auto *var = compiler.maybe_get_backing_variable(lhs);
3547
3548 // If we store through an access chain, we have a partial write.
3549 if (var)
3550 {
3551 accessed_variables_to_block[var->self].insert(current_block->self);
3552 if (var->self == lhs)
3553 complete_write_variables_to_block[var->self].insert(current_block->self);
3554 else
3555 partial_write_variables_to_block[var->self].insert(current_block->self);
3556 }
3557
3558 // args[0:1] might be access chains we have to track use of.
3559 for (uint32_t i = 0; i < 2; i++)
3560 notify_variable_access(args[i], current_block->self);
3561
3562 var = compiler.maybe_get_backing_variable(rhs);
3563 if (var)
3564 accessed_variables_to_block[var->self].insert(current_block->self);
3565 break;
3566 }
3567
3568 case OpCopyObject:
3569 {
3570 // OpCopyObject copies the underlying non-pointer type,
3571 // so any temp variable should be declared using the underlying type.
3572 // If the type is a pointer, get its base type and overwrite the result type mapping.
3573 auto &type = compiler.get<SPIRType>(result_type);
3574 if (type.pointer)
3575 result_id_to_type[result_id] = type.parent_type;
3576
3577 if (length < 3)
3578 return false;
3579
3580 auto *var = compiler.maybe_get_backing_variable(args[2]);
3581 if (var)
3582 accessed_variables_to_block[var->self].insert(current_block->self);
3583
3584 // Might be an access chain which we have to keep track of.
3585 notify_variable_access(args[1], current_block->self);
3586 if (access_chain_expressions.count(args[2]))
3587 access_chain_expressions.insert(args[1]);
3588
3589 // Might try to copy a Phi variable here.
3590 notify_variable_access(args[2], current_block->self);
3591 break;
3592 }
3593
3594 case OpLoad:
3595 case OpCooperativeMatrixLoadKHR:
3596 {
3597 if (length < 3)
3598 return false;
3599 uint32_t ptr = args[2];
3600 auto *var = compiler.maybe_get_backing_variable(ptr);
3601 if (var)
3602 accessed_variables_to_block[var->self].insert(current_block->self);
3603
3604 // Loaded value is a temporary.
3605 notify_variable_access(args[1], current_block->self);
3606
3607 // Might be an access chain we have to track use of.
3608 notify_variable_access(args[2], current_block->self);
3609
3610 // If we're loading an opaque type we cannot lower it to a temporary,
3611 // we must defer access of args[2] until it's used.
3612 auto &type = compiler.get<SPIRType>(args[0]);
3613 if (compiler.type_is_opaque_value(type))
3614 rvalue_forward_children[args[1]].insert(args[2]);
3615 break;
3616 }
3617
3618 case OpFunctionCall:
3619 {
3620 if (length < 3)
3621 return false;
3622
3623 // Return value may be a temporary.
3624 if (compiler.get_type(args[0]).basetype != SPIRType::Void)
3625 notify_variable_access(args[1], current_block->self);
3626
3627 length -= 3;
3628 args += 3;
3629
3630 for (uint32_t i = 0; i < length; i++)
3631 {
3632 auto *var = compiler.maybe_get_backing_variable(args[i]);
3633 if (var)
3634 {
3635 accessed_variables_to_block[var->self].insert(current_block->self);
3636 // Assume we can get partial writes to this variable.
3637 partial_write_variables_to_block[var->self].insert(current_block->self);
3638 }
3639
3640 // Cannot easily prove if argument we pass to a function is completely written.
3641 // Usually, functions write to a dummy variable,
3642 // which is then copied to in full to the real argument.
3643
3644 // Might try to copy a Phi variable here.
3645 notify_variable_access(args[i], current_block->self);
3646 }
3647 break;
3648 }
3649
3650 case OpSelect:
3651 {
3652 // In case of variable pointers, we might access a variable here.
3653 // We cannot prove anything about these accesses however.
3654 for (uint32_t i = 1; i < length; i++)
3655 {
3656 if (i >= 3)
3657 {
3658 auto *var = compiler.maybe_get_backing_variable(args[i]);
3659 if (var)
3660 {
3661 accessed_variables_to_block[var->self].insert(current_block->self);
3662 // Assume we can get partial writes to this variable.
3663 partial_write_variables_to_block[var->self].insert(current_block->self);
3664 }
3665 }
3666
3667 // Might try to copy a Phi variable here.
3668 notify_variable_access(args[i], current_block->self);
3669 }
3670 break;
3671 }
3672
3673 case OpExtInst:
3674 {
3675 for (uint32_t i = 4; i < length; i++)
3676 notify_variable_access(args[i], current_block->self);
3677 notify_variable_access(args[1], current_block->self);
3678
3679 uint32_t extension_set = args[2];
3680 if (compiler.get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
3681 {
3682 auto op_450 = static_cast<GLSLstd450>(args[3]);
3683 switch (op_450)
3684 {
3685 case GLSLstd450Modf:
3686 case GLSLstd450Frexp:
3687 {
3688 uint32_t ptr = args[5];
3689 auto *var = compiler.maybe_get_backing_variable(ptr);
3690 if (var)
3691 {
3692 accessed_variables_to_block[var->self].insert(current_block->self);
3693 if (var->self == ptr)
3694 complete_write_variables_to_block[var->self].insert(current_block->self);
3695 else
3696 partial_write_variables_to_block[var->self].insert(current_block->self);
3697 }
3698 break;
3699 }
3700
3701 default:
3702 break;
3703 }
3704 }
3705 break;
3706 }
3707
3708 case OpArrayLength:
3709 // Only result is a temporary.
3710 notify_variable_access(args[1], current_block->self);
3711 break;
3712
3713 case OpLine:
3714 case OpNoLine:
3715 // Uses literals, but cannot be a phi variable or temporary, so ignore.
3716 break;
3717
3718 // Atomics shouldn't be able to access function-local variables.
3719 // Some GLSL builtins access a pointer.
3720
3721 case OpCompositeInsert:
3722 case OpVectorShuffle:
3723 // Specialize for opcode which contains literals.
3724 for (uint32_t i = 1; i < 4; i++)
3725 notify_variable_access(args[i], current_block->self);
3726 break;
3727
3728 case OpCompositeExtract:
3729 // Specialize for opcode which contains literals.
3730 for (uint32_t i = 1; i < 3; i++)
3731 notify_variable_access(args[i], current_block->self);
3732 break;
3733
3734 case OpImageWrite:
3735 for (uint32_t i = 0; i < length; i++)
3736 {
3737 // Argument 3 is a literal.
3738 if (i != 3)
3739 notify_variable_access(args[i], current_block->self);
3740 }
3741 break;
3742
3743 case OpImageSampleImplicitLod:
3744 case OpImageSampleExplicitLod:
3745 case OpImageSparseSampleImplicitLod:
3746 case OpImageSparseSampleExplicitLod:
3747 case OpImageSampleProjImplicitLod:
3748 case OpImageSampleProjExplicitLod:
3749 case OpImageSparseSampleProjImplicitLod:
3750 case OpImageSparseSampleProjExplicitLod:
3751 case OpImageFetch:
3752 case OpImageSparseFetch:
3753 case OpImageRead:
3754 case OpImageSparseRead:
3755 for (uint32_t i = 1; i < length; i++)
3756 {
3757 // Argument 4 is a literal.
3758 if (i != 4)
3759 notify_variable_access(args[i], current_block->self);
3760 }
3761 break;
3762
3763 case OpImageSampleDrefImplicitLod:
3764 case OpImageSampleDrefExplicitLod:
3765 case OpImageSparseSampleDrefImplicitLod:
3766 case OpImageSparseSampleDrefExplicitLod:
3767 case OpImageSampleProjDrefImplicitLod:
3768 case OpImageSampleProjDrefExplicitLod:
3769 case OpImageSparseSampleProjDrefImplicitLod:
3770 case OpImageSparseSampleProjDrefExplicitLod:
3771 case OpImageGather:
3772 case OpImageSparseGather:
3773 case OpImageDrefGather:
3774 case OpImageSparseDrefGather:
3775 for (uint32_t i = 1; i < length; i++)
3776 {
3777 // Argument 5 is a literal.
3778 if (i != 5)
3779 notify_variable_access(args[i], current_block->self);
3780 }
3781 break;
3782
3783 default:
3784 {
3785 // Rather dirty way of figuring out where Phi variables are used.
3786 // As long as only IDs are used, we can scan through instructions and try to find any evidence that
3787 // the ID of a variable has been used.
3788 // There are potential false positives here where a literal is used in-place of an ID,
3789 // but worst case, it does not affect the correctness of the compile.
3790 // Exhaustive analysis would be better here, but it's not worth it for now.
3791 for (uint32_t i = 0; i < length; i++)
3792 notify_variable_access(args[i], current_block->self);
3793 break;
3794 }
3795 }
3796 return true;
3797 }
3798
3799 Compiler::StaticExpressionAccessHandler::StaticExpressionAccessHandler(Compiler &compiler_, uint32_t variable_id_)
3800 : compiler(compiler_)
3801 , variable_id(variable_id_)
3802 {
3803 }
3804
3805 bool Compiler::StaticExpressionAccessHandler::follow_function_call(const SPIRFunction &)
3806 {
3807 return false;
3808 }
3809
3810 bool Compiler::StaticExpressionAccessHandler::handle(spv::Op op, const uint32_t *args, uint32_t length)
3811 {
3812 switch (op)
3813 {
3814 case OpStore:
3815 case OpCooperativeMatrixStoreKHR:
3816 if (length < 2)
3817 return false;
3818 if (args[0] == variable_id)
3819 {
3820 static_expression = args[1];
3821 write_count++;
3822 }
3823 break;
3824
3825 case OpLoad:
3826 case OpCooperativeMatrixLoadKHR:
3827 if (length < 3)
3828 return false;
3829 if (args[2] == variable_id && static_expression == 0) // Tried to read from variable before it was initialized.
3830 return false;
3831 break;
3832
3833 case OpAccessChain:
3834 case OpInBoundsAccessChain:
3835 case OpPtrAccessChain:
3836 if (length < 3)
3837 return false;
3838 if (args[2] == variable_id) // If we try to access chain our candidate variable before we store to it, bail.
3839 return false;
3840 break;
3841
3842 default:
3843 break;
3844 }
3845
3846 return true;
3847 }
3848
3849 void Compiler::find_function_local_luts(SPIRFunction &entry, const AnalyzeVariableScopeAccessHandler &handler,
3850 bool single_function)
3851 {
3852 auto &cfg = *function_cfgs.find(entry.self)->second;
3853
3854 // For each variable which is statically accessed.
3855 for (auto &accessed_var : handler.accessed_variables_to_block)
3856 {
3857 auto &blocks = accessed_var.second;
3858 auto &var = get<SPIRVariable>(accessed_var.first);
3859 auto &type = expression_type(accessed_var.first);
3860
3861 // First check if there are writes to the variable. Later, if there are none, we'll
3862 // reconsider it as globally accessed LUT.
3863 if (!var.is_written_to)
3864 {
3865 var.is_written_to = handler.complete_write_variables_to_block.count(var.self) != 0 ||
3866 handler.partial_write_variables_to_block.count(var.self) != 0;
3867 }
3868
3869 // Only consider function local variables here.
3870 // If we only have a single function in our CFG, private storage is also fine,
3871 // since it behaves like a function local variable.
3872 bool allow_lut = var.storage == StorageClassFunction || (single_function && var.storage == StorageClassPrivate);
3873 if (!allow_lut)
3874 continue;
3875
3876 // We cannot be a phi variable.
3877 if (var.phi_variable)
3878 continue;
3879
3880 // Only consider arrays here.
3881 if (type.array.empty())
3882 continue;
3883
3884 // If the variable has an initializer, make sure it is a constant expression.
3885 uint32_t static_constant_expression = 0;
3886 if (var.initializer)
3887 {
3888 if (ir.ids[var.initializer].get_type() != TypeConstant)
3889 continue;
3890 static_constant_expression = var.initializer;
3891
3892 // There can be no stores to this variable, we have now proved we have a LUT.
3893 if (var.is_written_to)
3894 continue;
3895 }
3896 else
3897 {
3898 // We can have one, and only one write to the variable, and that write needs to be a constant.
3899
3900 // No partial writes allowed.
3901 if (handler.partial_write_variables_to_block.count(var.self) != 0)
3902 continue;
3903
3904 auto itr = handler.complete_write_variables_to_block.find(var.self);
3905
3906 // No writes?
3907 if (itr == end(handler.complete_write_variables_to_block))
3908 continue;
3909
3910 // We write to the variable in more than one block.
3911 auto &write_blocks = itr->second;
3912 if (write_blocks.size() != 1)
3913 continue;
3914
3915 // The write needs to happen in the dominating block.
3916 DominatorBuilder builder(cfg);
3917 for (auto &block : blocks)
3918 builder.add_block(block);
3919 uint32_t dominator = builder.get_dominator();
3920
3921 // The complete write happened in a branch or similar, cannot deduce static expression.
3922 if (write_blocks.count(dominator) == 0)
3923 continue;
3924
3925 // Find the static expression for this variable.
3926 StaticExpressionAccessHandler static_expression_handler(*this, var.self);
3927 traverse_all_reachable_opcodes(get<SPIRBlock>(dominator), static_expression_handler);
3928
3929 // We want one, and exactly one write
3930 if (static_expression_handler.write_count != 1 || static_expression_handler.static_expression == 0)
3931 continue;
3932
3933 // Is it a constant expression?
3934 if (ir.ids[static_expression_handler.static_expression].get_type() != TypeConstant)
3935 continue;
3936
3937 // We found a LUT!
3938 static_constant_expression = static_expression_handler.static_expression;
3939 }
3940
3941 get<SPIRConstant>(static_constant_expression).is_used_as_lut = true;
3942 var.static_expression = static_constant_expression;
3943 var.statically_assigned = true;
3944 var.remapped_variable = true;
3945 }
3946 }
3947
3948 void Compiler::analyze_variable_scope(SPIRFunction &entry, AnalyzeVariableScopeAccessHandler &handler)
3949 {
3950 // First, we map out all variable access within a function.
3951 // Essentially a map of block -> { variables accessed in the basic block }
3952 traverse_all_reachable_opcodes(entry, handler);
3953
3954 auto &cfg = *function_cfgs.find(entry.self)->second;
3955
3956 // Analyze if there are parameters which need to be implicitly preserved with an "in" qualifier.
3957 analyze_parameter_preservation(entry, cfg, handler.accessed_variables_to_block,
3958 handler.complete_write_variables_to_block);
3959
3960 unordered_map<uint32_t, uint32_t> potential_loop_variables;
3961
3962 // Find the loop dominator block for each block.
3963 for (auto &block_id : entry.blocks)
3964 {
3965 auto &block = get<SPIRBlock>(block_id);
3966
3967 auto itr = ir.continue_block_to_loop_header.find(block_id);
3968 if (itr != end(ir.continue_block_to_loop_header) && itr->second != block_id)
3969 {
3970 // Continue block might be unreachable in the CFG, but we still like to know the loop dominator.
3971 // Edge case is when continue block is also the loop header, don't set the dominator in this case.
3972 block.loop_dominator = itr->second;
3973 }
3974 else
3975 {
3976 uint32_t loop_dominator = cfg.find_loop_dominator(block_id);
3977 if (loop_dominator != block_id)
3978 block.loop_dominator = loop_dominator;
3979 else
3980 block.loop_dominator = SPIRBlock::NoDominator;
3981 }
3982 }
3983
3984 // For each variable which is statically accessed.
3985 for (auto &var : handler.accessed_variables_to_block)
3986 {
3987 // Only deal with variables which are considered local variables in this function.
3988 if (find(begin(entry.local_variables), end(entry.local_variables), VariableID(var.first)) ==
3989 end(entry.local_variables))
3990 continue;
3991
3992 DominatorBuilder builder(cfg);
3993 auto &blocks = var.second;
3994 auto &type = expression_type(var.first);
3995 BlockID potential_continue_block = 0;
3996
3997 // Figure out which block is dominating all accesses of those variables.
3998 for (auto &block : blocks)
3999 {
4000 // If we're accessing a variable inside a continue block, this variable might be a loop variable.
4001 // We can only use loop variables with scalars, as we cannot track static expressions for vectors.
4002 if (is_continue(block))
4003 {
4004 // Potentially awkward case to check for.
4005 // We might have a variable inside a loop, which is touched by the continue block,
4006 // but is not actually a loop variable.
4007 // The continue block is dominated by the inner part of the loop, which does not make sense in high-level
4008 // language output because it will be declared before the body,
4009 // so we will have to lift the dominator up to the relevant loop header instead.
4010 builder.add_block(ir.continue_block_to_loop_header[block]);
4011
4012 // Arrays or structs cannot be loop variables.
4013 if (type.vecsize == 1 && type.columns == 1 && type.basetype != SPIRType::Struct && type.array.empty())
4014 {
4015 // The variable is used in multiple continue blocks, this is not a loop
4016 // candidate, signal that by setting block to -1u.
4017 if (potential_continue_block == 0)
4018 potential_continue_block = block;
4019 else
4020 potential_continue_block = ~(0u);
4021 }
4022 }
4023
4024 builder.add_block(block);
4025 }
4026
4027 builder.lift_continue_block_dominator();
4028
4029 // Add it to a per-block list of variables.
4030 BlockID dominating_block = builder.get_dominator();
4031
4032 if (dominating_block && potential_continue_block != 0 && potential_continue_block != ~0u)
4033 {
4034 auto &inner_block = get<SPIRBlock>(dominating_block);
4035
4036 BlockID merge_candidate = 0;
4037
4038 // Analyze the dominator. If it lives in a different loop scope than the candidate continue
4039 // block, reject the loop variable candidate.
4040 if (inner_block.merge == SPIRBlock::MergeLoop)
4041 merge_candidate = inner_block.merge_block;
4042 else if (inner_block.loop_dominator != SPIRBlock::NoDominator)
4043 merge_candidate = get<SPIRBlock>(inner_block.loop_dominator).merge_block;
4044
4045 if (merge_candidate != 0 && cfg.is_reachable(merge_candidate))
4046 {
4047 // If the merge block has a higher post-visit order, we know that continue candidate
4048 // cannot reach the merge block, and we have two separate scopes.
4049 if (!cfg.is_reachable(potential_continue_block) ||
4050 cfg.get_visit_order(merge_candidate) > cfg.get_visit_order(potential_continue_block))
4051 {
4052 potential_continue_block = 0;
4053 }
4054 }
4055 }
4056
4057 if (potential_continue_block != 0 && potential_continue_block != ~0u)
4058 potential_loop_variables[var.first] = potential_continue_block;
4059
4060 // For variables whose dominating block is inside a loop, there is a risk that these variables
4061 // actually need to be preserved across loop iterations. We can express this by adding
4062 // a "read" access to the loop header.
4063 // In the dominating block, we must see an OpStore or equivalent as the first access of an OpVariable.
4064 // Should that fail, we look for the outermost loop header and tack on an access there.
4065 // Phi nodes cannot have this problem.
4066 if (dominating_block)
4067 {
4068 auto &variable = get<SPIRVariable>(var.first);
4069 if (!variable.phi_variable)
4070 {
4071 auto *block = &get<SPIRBlock>(dominating_block);
4072 bool preserve = may_read_undefined_variable_in_block(*block, var.first);
4073 if (preserve)
4074 {
4075 // Find the outermost loop scope.
4076 while (block->loop_dominator != BlockID(SPIRBlock::NoDominator))
4077 block = &get<SPIRBlock>(block->loop_dominator);
4078
4079 if (block->self != dominating_block)
4080 {
4081 builder.add_block(block->self);
4082 dominating_block = builder.get_dominator();
4083 }
4084 }
4085 }
4086 }
4087
4088 // If all blocks here are dead code, this will be 0, so the variable in question
4089 // will be completely eliminated.
4090 if (dominating_block)
4091 {
4092 auto &block = get<SPIRBlock>(dominating_block);
4093 block.dominated_variables.push_back(var.first);
4094 get<SPIRVariable>(var.first).dominator = dominating_block;
4095 }
4096 }
4097
4098 for (auto &var : handler.accessed_temporaries_to_block)
4099 {
4100 auto itr = handler.result_id_to_type.find(var.first);
4101
4102 if (itr == end(handler.result_id_to_type))
4103 {
4104 // We found a false positive ID being used, ignore.
4105 // This should probably be an assert.
4106 continue;
4107 }
4108
4109 // There is no point in doing domination analysis for opaque types.
4110 auto &type = get<SPIRType>(itr->second);
4111 if (type_is_opaque_value(type))
4112 continue;
4113
4114 DominatorBuilder builder(cfg);
4115 bool force_temporary = false;
4116 bool used_in_header_hoisted_continue_block = false;
4117
4118 // Figure out which block is dominating all accesses of those temporaries.
4119 auto &blocks = var.second;
4120 for (auto &block : blocks)
4121 {
4122 builder.add_block(block);
4123
4124 if (blocks.size() != 1 && is_continue(block))
4125 {
4126 // The risk here is that inner loop can dominate the continue block.
4127 // Any temporary we access in the continue block must be declared before the loop.
4128 // This is moot for complex loops however.
4129 auto &loop_header_block = get<SPIRBlock>(ir.continue_block_to_loop_header[block]);
4130 assert(loop_header_block.merge == SPIRBlock::MergeLoop);
4131 builder.add_block(loop_header_block.self);
4132 used_in_header_hoisted_continue_block = true;
4133 }
4134 }
4135
4136 uint32_t dominating_block = builder.get_dominator();
4137
4138 if (blocks.size() != 1 && is_single_block_loop(dominating_block))
4139 {
4140 // Awkward case, because the loop header is also the continue block,
4141 // so hoisting to loop header does not help.
4142 force_temporary = true;
4143 }
4144
4145 if (dominating_block)
4146 {
4147 // If we touch a variable in the dominating block, this is the expected setup.
4148 // SPIR-V normally mandates this, but we have extra cases for temporary use inside loops.
4149 bool first_use_is_dominator = blocks.count(dominating_block) != 0;
4150
4151 if (!first_use_is_dominator || force_temporary)
4152 {
4153 if (handler.access_chain_expressions.count(var.first))
4154 {
4155 // Exceptionally rare case.
4156 // We cannot declare temporaries of access chains (except on MSL perhaps with pointers).
4157 // Rather than do that, we force the indexing expressions to be declared in the right scope by
4158 // tracking their usage to that end. There is no temporary to hoist.
4159 // However, we still need to observe declaration order of the access chain.
4160
4161 if (used_in_header_hoisted_continue_block)
4162 {
4163 // For this scenario, we used an access chain inside a continue block where we also registered an access to header block.
4164 // This is a problem as we need to declare an access chain properly first with full definition.
4165 // We cannot use temporaries for these expressions,
4166 // so we must make sure the access chain is declared ahead of time.
4167 // Force a complex for loop to deal with this.
4168 // TODO: Out-of-order declaring for loops where continue blocks are emitted last might be another option.
4169 auto &loop_header_block = get<SPIRBlock>(dominating_block);
4170 assert(loop_header_block.merge == SPIRBlock::MergeLoop);
4171 loop_header_block.complex_continue = true;
4172 }
4173 }
4174 else
4175 {
4176 // This should be very rare, but if we try to declare a temporary inside a loop,
4177 // and that temporary is used outside the loop as well (spirv-opt inliner likes this)
4178 // we should actually emit the temporary outside the loop.
4179 hoisted_temporaries.insert(var.first);
4180 forced_temporaries.insert(var.first);
4181
4182 auto &block_temporaries = get<SPIRBlock>(dominating_block).declare_temporary;
4183 block_temporaries.emplace_back(handler.result_id_to_type[var.first], var.first);
4184 }
4185 }
4186 else if (blocks.size() > 1)
4187 {
4188 // Keep track of the temporary as we might have to declare this temporary.
4189 // This can happen if the loop header dominates a temporary, but we have a complex fallback loop.
4190 // In this case, the header is actually inside the for (;;) {} block, and we have problems.
4191 // What we need to do is hoist the temporaries outside the for (;;) {} block in case the header block
4192 // declares the temporary.
4193 auto &block_temporaries = get<SPIRBlock>(dominating_block).potential_declare_temporary;
4194 block_temporaries.emplace_back(handler.result_id_to_type[var.first], var.first);
4195 }
4196 }
4197 }
4198
4199 unordered_set<uint32_t> seen_blocks;
4200
4201 // Now, try to analyze whether or not these variables are actually loop variables.
4202 for (auto &loop_variable : potential_loop_variables)
4203 {
4204 auto &var = get<SPIRVariable>(loop_variable.first);
4205 auto dominator = var.dominator;
4206 BlockID block = loop_variable.second;
4207
4208 // The variable was accessed in multiple continue blocks, ignore.
4209 if (block == BlockID(~(0u)) || block == BlockID(0))
4210 continue;
4211
4212 // Dead code.
4213 if (dominator == ID(0))
4214 continue;
4215
4216 BlockID header = 0;
4217
4218 // Find the loop header for this block if we are a continue block.
4219 {
4220 auto itr = ir.continue_block_to_loop_header.find(block);
4221 if (itr != end(ir.continue_block_to_loop_header))
4222 {
4223 header = itr->second;
4224 }
4225 else if (get<SPIRBlock>(block).continue_block == block)
4226 {
4227 // Also check for self-referential continue block.
4228 header = block;
4229 }
4230 }
4231
4232 assert(header);
4233 auto &header_block = get<SPIRBlock>(header);
4234 auto &blocks = handler.accessed_variables_to_block[loop_variable.first];
4235
4236 // If a loop variable is not used before the loop, it's probably not a loop variable.
4237 bool has_accessed_variable = blocks.count(header) != 0;
4238
4239 // Now, there are two conditions we need to meet for the variable to be a loop variable.
4240 // 1. The dominating block must have a branch-free path to the loop header,
4241 // this way we statically know which expression should be part of the loop variable initializer.
4242
4243 // Walk from the dominator, if there is one straight edge connecting
4244 // dominator and loop header, we statically know the loop initializer.
4245 bool static_loop_init = true;
4246 while (dominator != header)
4247 {
4248 if (blocks.count(dominator) != 0)
4249 has_accessed_variable = true;
4250
4251 auto &succ = cfg.get_succeeding_edges(dominator);
4252 if (succ.size() != 1)
4253 {
4254 static_loop_init = false;
4255 break;
4256 }
4257
4258 auto &pred = cfg.get_preceding_edges(succ.front());
4259 if (pred.size() != 1 || pred.front() != dominator)
4260 {
4261 static_loop_init = false;
4262 break;
4263 }
4264
4265 dominator = succ.front();
4266 }
4267
4268 if (!static_loop_init || !has_accessed_variable)
4269 continue;
4270
4271 // The second condition we need to meet is that no access after the loop
4272 // merge can occur. Walk the CFG to see if we find anything.
4273
4274 seen_blocks.clear();
4275 cfg.walk_from(seen_blocks, header_block.merge_block, [&](uint32_t walk_block) -> bool {
4276 // We found a block which accesses the variable outside the loop.
4277 if (blocks.find(walk_block) != end(blocks))
4278 static_loop_init = false;
4279 return true;
4280 });
4281
4282 if (!static_loop_init)
4283 continue;
4284
4285 // We have a loop variable.
4286 header_block.loop_variables.push_back(loop_variable.first);
4287 // Need to sort here as variables come from an unordered container, and pushing stuff in wrong order
4288 // will break reproducability in regression runs.
4289 sort(begin(header_block.loop_variables), end(header_block.loop_variables));
4290 get<SPIRVariable>(loop_variable.first).loop_variable = true;
4291 }
4292 }
4293
4294 bool Compiler::may_read_undefined_variable_in_block(const SPIRBlock &block, uint32_t var)
4295 {
4296 for (auto &op : block.ops)
4297 {
4298 auto *ops = stream(op);
4299 switch (op.op)
4300 {
4301 case OpStore:
4302 case OpCooperativeMatrixStoreKHR:
4303 case OpCopyMemory:
4304 if (ops[0] == var)
4305 return false;
4306 break;
4307
4308 case OpAccessChain:
4309 case OpInBoundsAccessChain:
4310 case OpPtrAccessChain:
4311 // Access chains are generally used to partially read and write. It's too hard to analyze
4312 // if all constituents are written fully before continuing, so just assume it's preserved.
4313 // This is the same as the parameter preservation analysis.
4314 if (ops[2] == var)
4315 return true;
4316 break;
4317
4318 case OpSelect:
4319 // Variable pointers.
4320 // We might read before writing.
4321 if (ops[3] == var || ops[4] == var)
4322 return true;
4323 break;
4324
4325 case OpPhi:
4326 {
4327 // Variable pointers.
4328 // We might read before writing.
4329 if (op.length < 2)
4330 break;
4331
4332 uint32_t count = op.length - 2;
4333 for (uint32_t i = 0; i < count; i += 2)
4334 if (ops[i + 2] == var)
4335 return true;
4336 break;
4337 }
4338
4339 case OpCopyObject:
4340 case OpLoad:
4341 case OpCooperativeMatrixLoadKHR:
4342 if (ops[2] == var)
4343 return true;
4344 break;
4345
4346 case OpFunctionCall:
4347 {
4348 if (op.length < 3)
4349 break;
4350
4351 // May read before writing.
4352 uint32_t count = op.length - 3;
4353 for (uint32_t i = 0; i < count; i++)
4354 if (ops[i + 3] == var)
4355 return true;
4356 break;
4357 }
4358
4359 default:
4360 break;
4361 }
4362 }
4363
4364 // Not accessed somehow, at least not in a usual fashion.
4365 // It's likely accessed in a branch, so assume we must preserve.
4366 return true;
4367 }
4368
4369 bool Compiler::GeometryEmitDisocveryHandler::handle(spv::Op opcode, const uint32_t *, uint32_t)
4370 {
4371 if (opcode == OpEmitVertex || opcode == OpEndPrimitive)
4372 {
4373 for (auto *func : function_stack)
4374 func->emits_geometry = true;
4375 }
4376
4377 return true;
4378 }
4379
4380 bool Compiler::GeometryEmitDisocveryHandler::begin_function_scope(const uint32_t *stream, uint32_t)
4381 {
4382 auto &callee = compiler.get<SPIRFunction>(stream[2]);
4383 function_stack.push_back(&callee);
4384 return true;
4385 }
4386
4387 bool Compiler::GeometryEmitDisocveryHandler::end_function_scope([[maybe_unused]] const uint32_t *stream, uint32_t)
4388 {
4389 assert(function_stack.back() == &compiler.get<SPIRFunction>(stream[2]));
4390 function_stack.pop_back();
4391
4392 return true;
4393 }
4394
4395 void Compiler::discover_geometry_emitters()
4396 {
4397 GeometryEmitDisocveryHandler handler(*this);
4398
4399 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
4400 }
4401
4402 Bitset Compiler::get_buffer_block_flags(VariableID id) const
4403 {
4404 return ir.get_buffer_block_flags(get<SPIRVariable>(id));
4405 }
4406
4407 bool Compiler::get_common_basic_type(const SPIRType &type, SPIRType::BaseType &base_type)
4408 {
4409 if (type.basetype == SPIRType::Struct)
4410 {
4411 base_type = SPIRType::Unknown;
4412 for (auto &member_type : type.member_types)
4413 {
4414 SPIRType::BaseType member_base;
4415 if (!get_common_basic_type(get<SPIRType>(member_type), member_base))
4416 return false;
4417
4418 if (base_type == SPIRType::Unknown)
4419 base_type = member_base;
4420 else if (base_type != member_base)
4421 return false;
4422 }
4423 return true;
4424 }
4425 else
4426 {
4427 base_type = type.basetype;
4428 return true;
4429 }
4430 }
4431
4432 void Compiler::ActiveBuiltinHandler::handle_builtin(const SPIRType &type, BuiltIn builtin,
4433 const Bitset &decoration_flags)
4434 {
4435 // If used, we will need to explicitly declare a new array size for these builtins.
4436
4437 if (builtin == BuiltInClipDistance)
4438 {
4439 if (!type.array_size_literal[0])
4440 SPIRV_CROSS_THROW("Array size for ClipDistance must be a literal.");
4441 uint32_t array_size = type.array[0];
4442 if (array_size == 0)
4443 SPIRV_CROSS_THROW("Array size for ClipDistance must not be unsized.");
4444 compiler.clip_distance_count = array_size;
4445 }
4446 else if (builtin == BuiltInCullDistance)
4447 {
4448 if (!type.array_size_literal[0])
4449 SPIRV_CROSS_THROW("Array size for CullDistance must be a literal.");
4450 uint32_t array_size = type.array[0];
4451 if (array_size == 0)
4452 SPIRV_CROSS_THROW("Array size for CullDistance must not be unsized.");
4453 compiler.cull_distance_count = array_size;
4454 }
4455 else if (builtin == BuiltInPosition)
4456 {
4457 if (decoration_flags.get(DecorationInvariant))
4458 compiler.position_invariant = true;
4459 }
4460 }
4461
4462 void Compiler::ActiveBuiltinHandler::add_if_builtin(uint32_t id, bool allow_blocks)
4463 {
4464 // Only handle plain variables here.
4465 // Builtins which are part of a block are handled in AccessChain.
4466 // If allow_blocks is used however, this is to handle initializers of blocks,
4467 // which implies that all members are written to.
4468
4469 auto *var = compiler.maybe_get<SPIRVariable>(id);
4470 auto *m = compiler.ir.find_meta(id);
4471 if (var && m)
4472 {
4473 auto &type = compiler.get<SPIRType>(var->basetype);
4474 auto &decorations = m->decoration;
4475 auto &flags = type.storage == StorageClassInput ?
4476 compiler.active_input_builtins : compiler.active_output_builtins;
4477 if (decorations.builtin)
4478 {
4479 flags.set(decorations.builtin_type);
4480 handle_builtin(type, decorations.builtin_type, decorations.decoration_flags);
4481 }
4482 else if (allow_blocks && compiler.has_decoration(type.self, DecorationBlock))
4483 {
4484 uint32_t member_count = uint32_t(type.member_types.size());
4485 for (uint32_t i = 0; i < member_count; i++)
4486 {
4487 if (compiler.has_member_decoration(type.self, i, DecorationBuiltIn))
4488 {
4489 auto &member_type = compiler.get<SPIRType>(type.member_types[i]);
4490 BuiltIn builtin = BuiltIn(compiler.get_member_decoration(type.self, i, DecorationBuiltIn));
4491 flags.set(builtin);
4492 handle_builtin(member_type, builtin, compiler.get_member_decoration_bitset(type.self, i));
4493 }
4494 }
4495 }
4496 }
4497 }
4498
4499 void Compiler::ActiveBuiltinHandler::add_if_builtin(uint32_t id)
4500 {
4501 add_if_builtin(id, false);
4502 }
4503
4504 void Compiler::ActiveBuiltinHandler::add_if_builtin_or_block(uint32_t id)
4505 {
4506 add_if_builtin(id, true);
4507 }
4508
4509 bool Compiler::ActiveBuiltinHandler::handle(spv::Op opcode, const uint32_t *args, uint32_t length)
4510 {
4511 switch (opcode)
4512 {
4513 case OpStore:
4514 case OpCooperativeMatrixStoreKHR:
4515 if (length < 1)
4516 return false;
4517
4518 add_if_builtin(args[0]);
4519 break;
4520
4521 case OpCopyMemory:
4522 if (length < 2)
4523 return false;
4524
4525 add_if_builtin(args[0]);
4526 add_if_builtin(args[1]);
4527 break;
4528
4529 case OpCopyObject:
4530 case OpLoad:
4531 case OpCooperativeMatrixLoadKHR:
4532 if (length < 3)
4533 return false;
4534
4535 add_if_builtin(args[2]);
4536 break;
4537
4538 case OpSelect:
4539 if (length < 5)
4540 return false;
4541
4542 add_if_builtin(args[3]);
4543 add_if_builtin(args[4]);
4544 break;
4545
4546 case OpPhi:
4547 {
4548 if (length < 2)
4549 return false;
4550
4551 uint32_t count = length - 2;
4552 args += 2;
4553 for (uint32_t i = 0; i < count; i += 2)
4554 add_if_builtin(args[i]);
4555 break;
4556 }
4557
4558 case OpFunctionCall:
4559 {
4560 if (length < 3)
4561 return false;
4562
4563 uint32_t count = length - 3;
4564 args += 3;
4565 for (uint32_t i = 0; i < count; i++)
4566 add_if_builtin(args[i]);
4567 break;
4568 }
4569
4570 case OpAccessChain:
4571 case OpInBoundsAccessChain:
4572 case OpPtrAccessChain:
4573 {
4574 if (length < 4)
4575 return false;
4576
4577 // Only consider global variables, cannot consider variables in functions yet, or other
4578 // access chains as they have not been created yet.
4579 auto *var = compiler.maybe_get<SPIRVariable>(args[2]);
4580 if (!var)
4581 break;
4582
4583 // Required if we access chain into builtins like gl_GlobalInvocationID.
4584 add_if_builtin(args[2]);
4585
4586 // Start traversing type hierarchy at the proper non-pointer types.
4587 auto *type = &compiler.get_variable_data_type(*var);
4588
4589 auto &flags =
4590 var->storage == StorageClassInput ? compiler.active_input_builtins : compiler.active_output_builtins;
4591
4592 uint32_t count = length - 3;
4593 args += 3;
4594 for (uint32_t i = 0; i < count; i++)
4595 {
4596 // Pointers
4597 // PtrAccessChain functions more like a pointer offset. Type remains the same.
4598 if (opcode == OpPtrAccessChain && i == 0)
4599 continue;
4600
4601 // Arrays
4602 if (!type->array.empty())
4603 {
4604 type = &compiler.get<SPIRType>(type->parent_type);
4605 }
4606 // Structs
4607 else if (type->basetype == SPIRType::Struct)
4608 {
4609 uint32_t index = compiler.get<SPIRConstant>(args[i]).scalar();
4610
4611 if (index < uint32_t(compiler.ir.meta[type->self].members.size()))
4612 {
4613 auto &decorations = compiler.ir.meta[type->self].members[index];
4614 if (decorations.builtin)
4615 {
4616 flags.set(decorations.builtin_type);
4617 handle_builtin(compiler.get<SPIRType>(type->member_types[index]), decorations.builtin_type,
4618 decorations.decoration_flags);
4619 }
4620 }
4621
4622 type = &compiler.get<SPIRType>(type->member_types[index]);
4623 }
4624 else
4625 {
4626 // No point in traversing further. We won't find any extra builtins.
4627 break;
4628 }
4629 }
4630 break;
4631 }
4632
4633 default:
4634 break;
4635 }
4636
4637 return true;
4638 }
4639
4640 void Compiler::update_active_builtins()
4641 {
4642 active_input_builtins.reset();
4643 active_output_builtins.reset();
4644 cull_distance_count = 0;
4645 clip_distance_count = 0;
4646 ActiveBuiltinHandler handler(*this);
4647 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
4648
4649 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
4650 if (var.storage != StorageClassOutput)
4651 return;
4652 if (!interface_variable_exists_in_entry_point(var.self))
4653 return;
4654
4655 // Also, make sure we preserve output variables which are only initialized, but never accessed by any code.
4656 if (var.initializer != ID(0))
4657 handler.add_if_builtin_or_block(var.self);
4658 });
4659 }
4660
4661 // Returns whether this shader uses a builtin of the storage class
4662 bool Compiler::has_active_builtin(BuiltIn builtin, StorageClass storage) const
4663 {
4664 const Bitset *flags;
4665 switch (storage)
4666 {
4667 case StorageClassInput:
4668 flags = &active_input_builtins;
4669 break;
4670 case StorageClassOutput:
4671 flags = &active_output_builtins;
4672 break;
4673
4674 default:
4675 return false;
4676 }
4677 return flags->get(builtin);
4678 }
4679
4680 void Compiler::analyze_image_and_sampler_usage()
4681 {
4682 CombinedImageSamplerDrefHandler dref_handler(*this);
4683 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), dref_handler);
4684
4685 CombinedImageSamplerUsageHandler handler(*this, dref_handler.dref_combined_samplers);
4686 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
4687
4688 // Need to run this traversal twice. First time, we propagate any comparison sampler usage from leaf functions
4689 // down to main().
4690 // In the second pass, we can propagate up forced depth state coming from main() up into leaf functions.
4691 handler.dependency_hierarchy.clear();
4692 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
4693
4694 comparison_ids = std::move(handler.comparison_ids);
4695 need_subpass_input = handler.need_subpass_input;
4696 need_subpass_input_ms = handler.need_subpass_input_ms;
4697
4698 // Forward information from separate images and samplers into combined image samplers.
4699 for (auto &combined : combined_image_samplers)
4700 if (comparison_ids.count(combined.sampler_id))
4701 comparison_ids.insert(combined.combined_id);
4702 }
4703
4704 bool Compiler::CombinedImageSamplerDrefHandler::handle(spv::Op opcode, const uint32_t *args, uint32_t)
4705 {
4706 // Mark all sampled images which are used with Dref.
4707 switch (opcode)
4708 {
4709 case OpImageSampleDrefExplicitLod:
4710 case OpImageSampleDrefImplicitLod:
4711 case OpImageSampleProjDrefExplicitLod:
4712 case OpImageSampleProjDrefImplicitLod:
4713 case OpImageSparseSampleProjDrefImplicitLod:
4714 case OpImageSparseSampleDrefImplicitLod:
4715 case OpImageSparseSampleProjDrefExplicitLod:
4716 case OpImageSparseSampleDrefExplicitLod:
4717 case OpImageDrefGather:
4718 case OpImageSparseDrefGather:
4719 dref_combined_samplers.insert(args[2]);
4720 return true;
4721
4722 default:
4723 break;
4724 }
4725
4726 return true;
4727 }
4728
4729 const CFG &Compiler::get_cfg_for_current_function() const
4730 {
4731 assert(current_function);
4732 return get_cfg_for_function(current_function->self);
4733 }
4734
4735 const CFG &Compiler::get_cfg_for_function(uint32_t id) const
4736 {
4737 auto cfg_itr = function_cfgs.find(id);
4738 assert(cfg_itr != end(function_cfgs));
4739 assert(cfg_itr->second);
4740 return *cfg_itr->second;
4741 }
4742
4743 void Compiler::build_function_control_flow_graphs_and_analyze()
4744 {
4745 CFGBuilder handler(*this);
4746 handler.function_cfgs[ir.default_entry_point].reset(new CFG(*this, get<SPIRFunction>(ir.default_entry_point)));
4747 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
4748 function_cfgs = std::move(handler.function_cfgs);
4749 bool single_function = function_cfgs.size() <= 1;
4750
4751 for (auto &f : function_cfgs)
4752 {
4753 auto &func = get<SPIRFunction>(f.first);
4754 AnalyzeVariableScopeAccessHandler scope_handler(*this, func);
4755 analyze_variable_scope(func, scope_handler);
4756 find_function_local_luts(func, scope_handler, single_function);
4757
4758 // Check if we can actually use the loop variables we found in analyze_variable_scope.
4759 // To use multiple initializers, we need the same type and qualifiers.
4760 for (auto block : func.blocks)
4761 {
4762 auto &b = get<SPIRBlock>(block);
4763 if (b.loop_variables.size() < 2)
4764 continue;
4765
4766 auto &flags = get_decoration_bitset(b.loop_variables.front());
4767 uint32_t type = get<SPIRVariable>(b.loop_variables.front()).basetype;
4768 bool invalid_initializers = false;
4769 for (auto loop_variable : b.loop_variables)
4770 {
4771 if (flags != get_decoration_bitset(loop_variable) ||
4772 type != get<SPIRVariable>(b.loop_variables.front()).basetype)
4773 {
4774 invalid_initializers = true;
4775 break;
4776 }
4777 }
4778
4779 if (invalid_initializers)
4780 {
4781 for (auto loop_variable : b.loop_variables)
4782 get<SPIRVariable>(loop_variable).loop_variable = false;
4783 b.loop_variables.clear();
4784 }
4785 }
4786 }
4787
4788 // Find LUTs which are not function local. Only consider this case if the CFG is multi-function,
4789 // otherwise we treat Private as Function trivially.
4790 // Needs to be analyzed from the outside since we have to block the LUT optimization if at least
4791 // one function writes to it.
4792 if (!single_function)
4793 {
4794 for (auto &id : global_variables)
4795 {
4796 auto &var = get<SPIRVariable>(id);
4797 auto &type = get_variable_data_type(var);
4798
4799 if (is_array(type) && var.storage == StorageClassPrivate &&
4800 var.initializer && !var.is_written_to &&
4801 ir.ids[var.initializer].get_type() == TypeConstant)
4802 {
4803 get<SPIRConstant>(var.initializer).is_used_as_lut = true;
4804 var.static_expression = var.initializer;
4805 var.statically_assigned = true;
4806 var.remapped_variable = true;
4807 }
4808 }
4809 }
4810 }
4811
4812 Compiler::CFGBuilder::CFGBuilder(Compiler &compiler_)
4813 : compiler(compiler_)
4814 {
4815 }
4816
4817 bool Compiler::CFGBuilder::handle(spv::Op, const uint32_t *, uint32_t)
4818 {
4819 return true;
4820 }
4821
4822 bool Compiler::CFGBuilder::follow_function_call(const SPIRFunction &func)
4823 {
4824 if (function_cfgs.find(func.self) == end(function_cfgs))
4825 {
4826 function_cfgs[func.self].reset(new CFG(compiler, func));
4827 return true;
4828 }
4829 else
4830 return false;
4831 }
4832
4833 void Compiler::CombinedImageSamplerUsageHandler::add_dependency(uint32_t dst, uint32_t src)
4834 {
4835 dependency_hierarchy[dst].insert(src);
4836 // Propagate up any comparison state if we're loading from one such variable.
4837 if (comparison_ids.count(src))
4838 comparison_ids.insert(dst);
4839 }
4840
4841 bool Compiler::CombinedImageSamplerUsageHandler::begin_function_scope(const uint32_t *args, uint32_t length)
4842 {
4843 if (length < 3)
4844 return false;
4845
4846 auto &func = compiler.get<SPIRFunction>(args[2]);
4847 const auto *arg = &args[3];
4848 length -= 3;
4849
4850 for (uint32_t i = 0; i < length; i++)
4851 {
4852 auto &argument = func.arguments[i];
4853 add_dependency(argument.id, arg[i]);
4854 }
4855
4856 return true;
4857 }
4858
4859 void Compiler::CombinedImageSamplerUsageHandler::add_hierarchy_to_comparison_ids(uint32_t id)
4860 {
4861 // Traverse the variable dependency hierarchy and tag everything in its path with comparison ids.
4862 comparison_ids.insert(id);
4863
4864 for (auto &dep_id : dependency_hierarchy[id])
4865 add_hierarchy_to_comparison_ids(dep_id);
4866 }
4867
4868 bool Compiler::CombinedImageSamplerUsageHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
4869 {
4870 switch (opcode)
4871 {
4872 case OpAccessChain:
4873 case OpInBoundsAccessChain:
4874 case OpPtrAccessChain:
4875 case OpLoad:
4876 {
4877 if (length < 3)
4878 return false;
4879
4880 add_dependency(args[1], args[2]);
4881
4882 // Ideally defer this to OpImageRead, but then we'd need to track loaded IDs.
4883 // If we load an image, we're going to use it and there is little harm in declaring an unused gl_FragCoord.
4884 auto &type = compiler.get<SPIRType>(args[0]);
4885 if (type.image.dim == DimSubpassData)
4886 {
4887 need_subpass_input = true;
4888 if (type.image.ms)
4889 need_subpass_input_ms = true;
4890 }
4891
4892 // If we load a SampledImage and it will be used with Dref, propagate the state up.
4893 if (dref_combined_samplers.count(args[1]) != 0)
4894 add_hierarchy_to_comparison_ids(args[1]);
4895 break;
4896 }
4897
4898 case OpSampledImage:
4899 {
4900 if (length < 4)
4901 return false;
4902
4903 // If the underlying resource has been used for comparison then duplicate loads of that resource must be too.
4904 // This image must be a depth image.
4905 uint32_t result_id = args[1];
4906 uint32_t image = args[2];
4907 uint32_t sampler = args[3];
4908
4909 if (dref_combined_samplers.count(result_id) != 0)
4910 {
4911 add_hierarchy_to_comparison_ids(image);
4912
4913 // This sampler must be a SamplerComparisonState, and not a regular SamplerState.
4914 add_hierarchy_to_comparison_ids(sampler);
4915
4916 // Mark the OpSampledImage itself as being comparison state.
4917 comparison_ids.insert(result_id);
4918 }
4919 return true;
4920 }
4921
4922 default:
4923 break;
4924 }
4925
4926 return true;
4927 }
4928
4929 bool Compiler::buffer_is_hlsl_counter_buffer(VariableID id) const
4930 {
4931 auto *m = ir.find_meta(id);
4932 return m && m->hlsl_is_magic_counter_buffer;
4933 }
4934
4935 bool Compiler::buffer_get_hlsl_counter_buffer(VariableID id, uint32_t &counter_id) const
4936 {
4937 auto *m = ir.find_meta(id);
4938
4939 // First, check for the proper decoration.
4940 if (m && m->hlsl_magic_counter_buffer != 0)
4941 {
4942 counter_id = m->hlsl_magic_counter_buffer;
4943 return true;
4944 }
4945 else
4946 return false;
4947 }
4948
4949 void Compiler::make_constant_null(uint32_t id, uint32_t type)
4950 {
4951 auto &constant_type = get<SPIRType>(type);
4952
4953 if (constant_type.pointer)
4954 {
4955 auto &constant = set<SPIRConstant>(id, type);
4956 constant.make_null(constant_type);
4957 }
4958 else if (!constant_type.array.empty())
4959 {
4960 assert(constant_type.parent_type);
4961 uint32_t parent_id = ir.increase_bound_by(1);
4962 make_constant_null(parent_id, constant_type.parent_type);
4963
4964 // The array size of OpConstantNull can be either literal or specialization constant.
4965 // In the latter case, we cannot take the value as-is, as it can be changed to anything.
4966 // Rather, we assume it to be *one* for the sake of initializer.
4967 bool is_literal_array_size = constant_type.array_size_literal.back();
4968 uint32_t count = is_literal_array_size ? constant_type.array.back() : 1;
4969 SmallVector<uint32_t> elements(count);
4970 for (uint32_t i = 0; i < count; i++)
4971 elements[i] = parent_id;
4972 auto &constant = set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
4973 constant.is_null_array_specialized_length = !is_literal_array_size;
4974 }
4975 else if (!constant_type.member_types.empty())
4976 {
4977 uint32_t member_ids = ir.increase_bound_by(uint32_t(constant_type.member_types.size()));
4978 SmallVector<uint32_t> elements(constant_type.member_types.size());
4979 for (uint32_t i = 0; i < constant_type.member_types.size(); i++)
4980 {
4981 make_constant_null(member_ids + i, constant_type.member_types[i]);
4982 elements[i] = member_ids + i;
4983 }
4984 set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
4985 }
4986 else
4987 {
4988 auto &constant = set<SPIRConstant>(id, type);
4989 constant.make_null(constant_type);
4990 }
4991 }
4992
4993 const SmallVector<spv::Capability> &Compiler::get_declared_capabilities() const
4994 {
4995 return ir.declared_capabilities;
4996 }
4997
4998 const SmallVector<std::string> &Compiler::get_declared_extensions() const
4999 {
5000 return ir.declared_extensions;
5001 }
5002
5003 std::string Compiler::get_remapped_declared_block_name(VariableID id) const
5004 {
5005 return get_remapped_declared_block_name(id, false);
5006 }
5007
5008 std::string Compiler::get_remapped_declared_block_name(uint32_t id, bool fallback_prefer_instance_name) const
5009 {
5010 auto itr = declared_block_names.find(id);
5011 if (itr != end(declared_block_names))
5012 {
5013 return itr->second;
5014 }
5015 else
5016 {
5017 auto &var = get<SPIRVariable>(id);
5018
5019 if (fallback_prefer_instance_name)
5020 {
5021 return to_name(var.self);
5022 }
5023 else
5024 {
5025 auto &type = get<SPIRType>(var.basetype);
5026 auto *type_meta = ir.find_meta(type.self);
5027 auto *block_name = type_meta ? &type_meta->decoration.alias : nullptr;
5028 return (!block_name || block_name->empty()) ? get_block_fallback_name(id) : *block_name;
5029 }
5030 }
5031 }
5032
5033 bool Compiler::reflection_ssbo_instance_name_is_significant() const
5034 {
5035 if (ir.source.known)
5036 {
5037 // UAVs from HLSL source tend to be declared in a way where the type is reused
5038 // but the instance name is significant, and that's the name we should report.
5039 // For GLSL, SSBOs each have their own block type as that's how GLSL is written.
5040 return ir.source.hlsl;
5041 }
5042
5043 unordered_set<uint32_t> ssbo_type_ids;
5044 bool aliased_ssbo_types = false;
5045
5046 // If we don't have any OpSource information, we need to perform some shaky heuristics.
5047 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
5048 auto &type = this->get<SPIRType>(var.basetype);
5049 if (!type.pointer || var.storage == StorageClassFunction)
5050 return;
5051
5052 bool ssbo = var.storage == StorageClassStorageBuffer ||
5053 (var.storage == StorageClassUniform && has_decoration(type.self, DecorationBufferBlock));
5054
5055 if (ssbo)
5056 {
5057 if (ssbo_type_ids.count(type.self))
5058 aliased_ssbo_types = true;
5059 else
5060 ssbo_type_ids.insert(type.self);
5061 }
5062 });
5063
5064 // If the block name is aliased, assume we have HLSL-style UAV declarations.
5065 return aliased_ssbo_types;
5066 }
5067
5068 bool Compiler::instruction_to_result_type(uint32_t &result_type, uint32_t &result_id, spv::Op op,
5069 const uint32_t *args, uint32_t length)
5070 {
5071 if (length < 2)
5072 return false;
5073
5074 bool has_result_id = false, has_result_type = false;
5075 HasResultAndType(op, &has_result_id, &has_result_type);
5076 if (has_result_id && has_result_type)
5077 {
5078 result_type = args[0];
5079 result_id = args[1];
5080 return true;
5081 }
5082 else
5083 return false;
5084 }
5085
5086 Bitset Compiler::combined_decoration_for_member(const SPIRType &type, uint32_t index) const
5087 {
5088 Bitset flags;
5089 auto *type_meta = ir.find_meta(type.self);
5090
5091 if (type_meta)
5092 {
5093 auto &members = type_meta->members;
5094 if (index >= members.size())
5095 return flags;
5096 auto &dec = members[index];
5097
5098 flags.merge_or(dec.decoration_flags);
5099
5100 auto &member_type = get<SPIRType>(type.member_types[index]);
5101
5102 // If our member type is a struct, traverse all the child members as well recursively.
5103 auto &member_childs = member_type.member_types;
5104 for (uint32_t i = 0; i < member_childs.size(); i++)
5105 {
5106 auto &child_member_type = get<SPIRType>(member_childs[i]);
5107 if (!child_member_type.pointer)
5108 flags.merge_or(combined_decoration_for_member(member_type, i));
5109 }
5110 }
5111
5112 return flags;
5113 }
5114
5115 bool Compiler::is_desktop_only_format(spv::ImageFormat format)
5116 {
5117 switch (format)
5118 {
5119 // Desktop-only formats
5120 case ImageFormatR11fG11fB10f:
5121 case ImageFormatR16f:
5122 case ImageFormatRgb10A2:
5123 case ImageFormatR8:
5124 case ImageFormatRg8:
5125 case ImageFormatR16:
5126 case ImageFormatRg16:
5127 case ImageFormatRgba16:
5128 case ImageFormatR16Snorm:
5129 case ImageFormatRg16Snorm:
5130 case ImageFormatRgba16Snorm:
5131 case ImageFormatR8Snorm:
5132 case ImageFormatRg8Snorm:
5133 case ImageFormatR8ui:
5134 case ImageFormatRg8ui:
5135 case ImageFormatR16ui:
5136 case ImageFormatRgb10a2ui:
5137 case ImageFormatR8i:
5138 case ImageFormatRg8i:
5139 case ImageFormatR16i:
5140 return true;
5141 default:
5142 break;
5143 }
5144
5145 return false;
5146 }
5147
5148 // An image is determined to be a depth image if it is marked as a depth image and is not also
5149 // explicitly marked with a color format, or if there are any sample/gather compare operations on it.
5150 bool Compiler::is_depth_image(const SPIRType &type, uint32_t id) const
5151 {
5152 return (type.image.depth && type.image.format == ImageFormatUnknown) || comparison_ids.count(id);
5153 }
5154
5155 bool Compiler::type_is_opaque_value(const SPIRType &type) const
5156 {
5157 return !type.pointer && (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Image ||
5158 type.basetype == SPIRType::Sampler);
5159 }
5160
5161 // Make these member functions so we can easily break on any force_recompile events.
5162 void Compiler::force_recompile()
5163 {
5164 is_force_recompile = true;
5165 }
5166
5167 void Compiler::force_recompile_guarantee_forward_progress()
5168 {
5169 force_recompile();
5170 is_force_recompile_forward_progress = true;
5171 }
5172
5173 bool Compiler::is_forcing_recompilation() const
5174 {
5175 return is_force_recompile;
5176 }
5177
5178 void Compiler::clear_force_recompile()
5179 {
5180 is_force_recompile = false;
5181 is_force_recompile_forward_progress = false;
5182 }
5183
5184 Compiler::PhysicalStorageBufferPointerHandler::PhysicalStorageBufferPointerHandler(Compiler &compiler_)
5185 : compiler(compiler_)
5186 {
5187 }
5188
5189 Compiler::PhysicalBlockMeta *Compiler::PhysicalStorageBufferPointerHandler::find_block_meta(uint32_t id) const
5190 {
5191 auto chain_itr = access_chain_to_physical_block.find(id);
5192 if (chain_itr != access_chain_to_physical_block.end())
5193 return chain_itr->second;
5194 else
5195 return nullptr;
5196 }
5197
5198 void Compiler::PhysicalStorageBufferPointerHandler::mark_aligned_access(uint32_t id, const uint32_t *args, uint32_t length)
5199 {
5200 uint32_t mask = *args;
5201 args++;
5202 length--;
5203 if (length && (mask & MemoryAccessVolatileMask) != 0)
5204 {
5205 args++;
5206 length--;
5207 }
5208
5209 if (length && (mask & MemoryAccessAlignedMask) != 0)
5210 {
5211 uint32_t alignment = *args;
5212 auto *meta = find_block_meta(id);
5213
5214 // This makes the assumption that the application does not rely on insane edge cases like:
5215 // Bind buffer with ADDR = 8, use block offset of 8 bytes, load/store with 16 byte alignment.
5216 // If we emit the buffer with alignment = 16 here, the first element at offset = 0 should
5217 // actually have alignment of 8 bytes, but this is too theoretical and awkward to support.
5218 // We could potentially keep track of any offset in the access chain, but it's
5219 // practically impossible for high level compilers to emit code like that,
5220 // so deducing overall alignment requirement based on maximum observed Alignment value is probably fine.
5221 if (meta && alignment > meta->alignment)
5222 meta->alignment = alignment;
5223 }
5224 }
5225
5226 bool Compiler::PhysicalStorageBufferPointerHandler::type_is_bda_block_entry(uint32_t type_id) const
5227 {
5228 auto &type = compiler.get<SPIRType>(type_id);
5229 return compiler.is_physical_pointer(type);
5230 }
5231
5232 uint32_t Compiler::PhysicalStorageBufferPointerHandler::get_minimum_scalar_alignment(const SPIRType &type) const
5233 {
5234 if (type.storage == spv::StorageClassPhysicalStorageBuffer)
5235 return 8;
5236 else if (type.basetype == SPIRType::Struct)
5237 {
5238 uint32_t alignment = 0;
5239 for (auto &member_type : type.member_types)
5240 {
5241 uint32_t member_align = get_minimum_scalar_alignment(compiler.get<SPIRType>(member_type));
5242 if (member_align > alignment)
5243 alignment = member_align;
5244 }
5245 return alignment;
5246 }
5247 else
5248 return type.width / 8;
5249 }
5250
5251 void Compiler::PhysicalStorageBufferPointerHandler::setup_meta_chain(uint32_t type_id, uint32_t var_id)
5252 {
5253 if (type_is_bda_block_entry(type_id))
5254 {
5255 auto &meta = physical_block_type_meta[type_id];
5256 access_chain_to_physical_block[var_id] = &meta;
5257
5258 auto &type = compiler.get<SPIRType>(type_id);
5259
5260 if (!compiler.is_physical_pointer_to_buffer_block(type))
5261 non_block_types.insert(type_id);
5262
5263 if (meta.alignment == 0)
5264 meta.alignment = get_minimum_scalar_alignment(compiler.get_pointee_type(type));
5265 }
5266 }
5267
5268 bool Compiler::PhysicalStorageBufferPointerHandler::handle(Op op, const uint32_t *args, uint32_t length)
5269 {
5270 // When a BDA pointer comes to life, we need to keep a mapping of SSA ID -> type ID for the pointer type.
5271 // For every load and store, we'll need to be able to look up the type ID being accessed and mark any alignment
5272 // requirements.
5273 switch (op)
5274 {
5275 case OpConvertUToPtr:
5276 case OpBitcast:
5277 case OpCompositeExtract:
5278 // Extract can begin a new chain if we had a struct or array of pointers as input.
5279 // We don't begin chains before we have a pure scalar pointer.
5280 setup_meta_chain(args[0], args[1]);
5281 break;
5282
5283 case OpAccessChain:
5284 case OpInBoundsAccessChain:
5285 case OpPtrAccessChain:
5286 case OpCopyObject:
5287 {
5288 auto itr = access_chain_to_physical_block.find(args[2]);
5289 if (itr != access_chain_to_physical_block.end())
5290 access_chain_to_physical_block[args[1]] = itr->second;
5291 break;
5292 }
5293
5294 case OpLoad:
5295 {
5296 setup_meta_chain(args[0], args[1]);
5297 if (length >= 4)
5298 mark_aligned_access(args[2], args + 3, length - 3);
5299 break;
5300 }
5301
5302 case OpStore:
5303 {
5304 if (length >= 3)
5305 mark_aligned_access(args[0], args + 2, length - 2);
5306 break;
5307 }
5308
5309 case OpCooperativeMatrixLoadKHR:
5310 case OpCooperativeMatrixStoreKHR:
5311 {
5312 // TODO: Can we meaningfully deal with this?
5313 break;
5314 }
5315
5316 default:
5317 break;
5318 }
5319
5320 return true;
5321 }
5322
5323 uint32_t Compiler::PhysicalStorageBufferPointerHandler::get_base_non_block_type_id(uint32_t type_id) const
5324 {
5325 auto *type = &compiler.get<SPIRType>(type_id);
5326 while (compiler.is_physical_pointer(*type) && !type_is_bda_block_entry(type_id))
5327 {
5328 type_id = type->parent_type;
5329 type = &compiler.get<SPIRType>(type_id);
5330 }
5331
5332 assert(type_is_bda_block_entry(type_id));
5333 return type_id;
5334 }
5335
5336 void Compiler::PhysicalStorageBufferPointerHandler::analyze_non_block_types_from_block(const SPIRType &type)
5337 {
5338 if (analyzed_type_ids.count(type.self))
5339 return;
5340 analyzed_type_ids.insert(type.self);
5341
5342 for (auto &member : type.member_types)
5343 {
5344 auto &subtype = compiler.get<SPIRType>(member);
5345
5346 if (compiler.is_physical_pointer(subtype) && !compiler.is_physical_pointer_to_buffer_block(subtype))
5347 non_block_types.insert(get_base_non_block_type_id(member));
5348 else if (subtype.basetype == SPIRType::Struct && !compiler.is_pointer(subtype))
5349 analyze_non_block_types_from_block(subtype);
5350 }
5351 }
5352
5353 void Compiler::analyze_non_block_pointer_types()
5354 {
5355 PhysicalStorageBufferPointerHandler handler(*this);
5356 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
5357
5358 // Analyze any block declaration we have to make. It might contain
5359 // physical pointers to POD types which we never used, and thus never added to the list.
5360 // We'll need to add those pointer types to the set of types we declare.
5361 ir.for_each_typed_id<SPIRType>([&](uint32_t id, SPIRType &type) {
5362 // Only analyze the raw block struct, not any pointer-to-struct, since that's just redundant.
5363 if (type.self == id &&
5364 (has_decoration(type.self, DecorationBlock) ||
5365 has_decoration(type.self, DecorationBufferBlock)))
5366 {
5367 handler.analyze_non_block_types_from_block(type);
5368 }
5369 });
5370
5371 physical_storage_non_block_pointer_types.reserve(handler.non_block_types.size());
5372 for (auto type : handler.non_block_types)
5373 physical_storage_non_block_pointer_types.push_back(type);
5374 sort(begin(physical_storage_non_block_pointer_types), end(physical_storage_non_block_pointer_types));
5375 physical_storage_type_to_alignment = std::move(handler.physical_block_type_meta);
5376 }
5377
5378 bool Compiler::InterlockedResourceAccessPrepassHandler::handle(Op op, const uint32_t *, uint32_t)
5379 {
5380 if (op == OpBeginInvocationInterlockEXT || op == OpEndInvocationInterlockEXT)
5381 {
5382 if (interlock_function_id != 0 && interlock_function_id != call_stack.back())
5383 {
5384 // Most complex case, we have no sensible way of dealing with this
5385 // other than taking the 100% conservative approach, exit early.
5386 split_function_case = true;
5387 return false;
5388 }
5389 else
5390 {
5391 interlock_function_id = call_stack.back();
5392 // If this call is performed inside control flow we have a problem.
5393 auto &cfg = compiler.get_cfg_for_function(interlock_function_id);
5394
5395 uint32_t from_block_id = compiler.get<SPIRFunction>(interlock_function_id).entry_block;
5396 bool outside_control_flow = cfg.node_terminates_control_flow_in_sub_graph(from_block_id, current_block_id);
5397 if (!outside_control_flow)
5398 control_flow_interlock = true;
5399 }
5400 }
5401 return true;
5402 }
5403
5404 void Compiler::InterlockedResourceAccessPrepassHandler::rearm_current_block(const SPIRBlock &block)
5405 {
5406 current_block_id = block.self;
5407 }
5408
5409 bool Compiler::InterlockedResourceAccessPrepassHandler::begin_function_scope(const uint32_t *args, uint32_t length)
5410 {
5411 if (length < 3)
5412 return false;
5413 call_stack.push_back(args[2]);
5414 return true;
5415 }
5416
5417 bool Compiler::InterlockedResourceAccessPrepassHandler::end_function_scope(const uint32_t *, uint32_t)
5418 {
5419 call_stack.pop_back();
5420 return true;
5421 }
5422
5423 bool Compiler::InterlockedResourceAccessHandler::begin_function_scope(const uint32_t *args, uint32_t length)
5424 {
5425 if (length < 3)
5426 return false;
5427
5428 if (args[2] == interlock_function_id)
5429 call_stack_is_interlocked = true;
5430
5431 call_stack.push_back(args[2]);
5432 return true;
5433 }
5434
5435 bool Compiler::InterlockedResourceAccessHandler::end_function_scope(const uint32_t *, uint32_t)
5436 {
5437 if (call_stack.back() == interlock_function_id)
5438 call_stack_is_interlocked = false;
5439
5440 call_stack.pop_back();
5441 return true;
5442 }
5443
5444 void Compiler::InterlockedResourceAccessHandler::access_potential_resource(uint32_t id)
5445 {
5446 if ((use_critical_section && in_crit_sec) || (control_flow_interlock && call_stack_is_interlocked) ||
5447 split_function_case)
5448 {
5449 compiler.interlocked_resources.insert(id);
5450 }
5451 }
5452
5453 bool Compiler::InterlockedResourceAccessHandler::handle(Op opcode, const uint32_t *args, uint32_t length)
5454 {
5455 // Only care about critical section analysis if we have simple case.
5456 if (use_critical_section)
5457 {
5458 if (opcode == OpBeginInvocationInterlockEXT)
5459 {
5460 in_crit_sec = true;
5461 return true;
5462 }
5463
5464 if (opcode == OpEndInvocationInterlockEXT)
5465 {
5466 // End critical section--nothing more to do.
5467 return false;
5468 }
5469 }
5470
5471 // We need to figure out where images and buffers are loaded from, so do only the bare bones compilation we need.
5472 switch (opcode)
5473 {
5474 case OpLoad:
5475 case OpCooperativeMatrixLoadKHR:
5476 {
5477 if (length < 3)
5478 return false;
5479
5480 uint32_t ptr = args[2];
5481 auto *var = compiler.maybe_get_backing_variable(ptr);
5482
5483 // We're only concerned with buffer and image memory here.
5484 if (!var)
5485 break;
5486
5487 switch (var->storage)
5488 {
5489 default:
5490 break;
5491
5492 case StorageClassUniformConstant:
5493 {
5494 uint32_t result_type = args[0];
5495 uint32_t id = args[1];
5496 compiler.set<SPIRExpression>(id, "", result_type, true);
5497 compiler.register_read(id, ptr, true);
5498 break;
5499 }
5500
5501 case StorageClassUniform:
5502 // Must have BufferBlock; we only care about SSBOs.
5503 if (!compiler.has_decoration(compiler.get<SPIRType>(var->basetype).self, DecorationBufferBlock))
5504 break;
5505 // fallthrough
5506 case StorageClassStorageBuffer:
5507 access_potential_resource(var->self);
5508 break;
5509 }
5510 break;
5511 }
5512
5513 case OpInBoundsAccessChain:
5514 case OpAccessChain:
5515 case OpPtrAccessChain:
5516 {
5517 if (length < 3)
5518 return false;
5519
5520 uint32_t result_type = args[0];
5521
5522 auto &type = compiler.get<SPIRType>(result_type);
5523 if (type.storage == StorageClassUniform || type.storage == StorageClassUniformConstant ||
5524 type.storage == StorageClassStorageBuffer)
5525 {
5526 uint32_t id = args[1];
5527 uint32_t ptr = args[2];
5528 compiler.set<SPIRExpression>(id, "", result_type, true);
5529 compiler.register_read(id, ptr, true);
5530 compiler.ir.ids[id].set_allow_type_rewrite();
5531 }
5532 break;
5533 }
5534
5535 case OpImageTexelPointer:
5536 {
5537 if (length < 3)
5538 return false;
5539
5540 uint32_t result_type = args[0];
5541 uint32_t id = args[1];
5542 uint32_t ptr = args[2];
5543 auto &e = compiler.set<SPIRExpression>(id, "", result_type, true);
5544 auto *var = compiler.maybe_get_backing_variable(ptr);
5545 if (var)
5546 e.loaded_from = var->self;
5547 break;
5548 }
5549
5550 case OpStore:
5551 case OpImageWrite:
5552 case OpAtomicStore:
5553 case OpCooperativeMatrixStoreKHR:
5554 {
5555 if (length < 1)
5556 return false;
5557
5558 uint32_t ptr = args[0];
5559 auto *var = compiler.maybe_get_backing_variable(ptr);
5560 if (var && (var->storage == StorageClassUniform || var->storage == StorageClassUniformConstant ||
5561 var->storage == StorageClassStorageBuffer))
5562 {
5563 access_potential_resource(var->self);
5564 }
5565
5566 break;
5567 }
5568
5569 case OpCopyMemory:
5570 {
5571 if (length < 2)
5572 return false;
5573
5574 uint32_t dst = args[0];
5575 uint32_t src = args[1];
5576 auto *dst_var = compiler.maybe_get_backing_variable(dst);
5577 auto *src_var = compiler.maybe_get_backing_variable(src);
5578
5579 if (dst_var && (dst_var->storage == StorageClassUniform || dst_var->storage == StorageClassStorageBuffer))
5580 access_potential_resource(dst_var->self);
5581
5582 if (src_var)
5583 {
5584 if (src_var->storage != StorageClassUniform && src_var->storage != StorageClassStorageBuffer)
5585 break;
5586
5587 if (src_var->storage == StorageClassUniform &&
5588 !compiler.has_decoration(compiler.get<SPIRType>(src_var->basetype).self, DecorationBufferBlock))
5589 {
5590 break;
5591 }
5592
5593 access_potential_resource(src_var->self);
5594 }
5595
5596 break;
5597 }
5598
5599 case OpImageRead:
5600 case OpAtomicLoad:
5601 {
5602 if (length < 3)
5603 return false;
5604
5605 uint32_t ptr = args[2];
5606 auto *var = compiler.maybe_get_backing_variable(ptr);
5607
5608 // We're only concerned with buffer and image memory here.
5609 if (!var)
5610 break;
5611
5612 switch (var->storage)
5613 {
5614 default:
5615 break;
5616
5617 case StorageClassUniform:
5618 // Must have BufferBlock; we only care about SSBOs.
5619 if (!compiler.has_decoration(compiler.get<SPIRType>(var->basetype).self, DecorationBufferBlock))
5620 break;
5621 // fallthrough
5622 case StorageClassUniformConstant:
5623 case StorageClassStorageBuffer:
5624 access_potential_resource(var->self);
5625 break;
5626 }
5627 break;
5628 }
5629
5630 case OpAtomicExchange:
5631 case OpAtomicCompareExchange:
5632 case OpAtomicIIncrement:
5633 case OpAtomicIDecrement:
5634 case OpAtomicIAdd:
5635 case OpAtomicISub:
5636 case OpAtomicSMin:
5637 case OpAtomicUMin:
5638 case OpAtomicSMax:
5639 case OpAtomicUMax:
5640 case OpAtomicAnd:
5641 case OpAtomicOr:
5642 case OpAtomicXor:
5643 {
5644 if (length < 3)
5645 return false;
5646
5647 uint32_t ptr = args[2];
5648 auto *var = compiler.maybe_get_backing_variable(ptr);
5649 if (var && (var->storage == StorageClassUniform || var->storage == StorageClassUniformConstant ||
5650 var->storage == StorageClassStorageBuffer))
5651 {
5652 access_potential_resource(var->self);
5653 }
5654
5655 break;
5656 }
5657
5658 default:
5659 break;
5660 }
5661
5662 return true;
5663 }
5664
5665 void Compiler::analyze_interlocked_resource_usage()
5666 {
5667 if (get_execution_model() == ExecutionModelFragment &&
5668 (get_entry_point().flags.get(ExecutionModePixelInterlockOrderedEXT) ||
5669 get_entry_point().flags.get(ExecutionModePixelInterlockUnorderedEXT) ||
5670 get_entry_point().flags.get(ExecutionModeSampleInterlockOrderedEXT) ||
5671 get_entry_point().flags.get(ExecutionModeSampleInterlockUnorderedEXT)))
5672 {
5673 InterlockedResourceAccessPrepassHandler prepass_handler(*this, ir.default_entry_point);
5674 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), prepass_handler);
5675
5676 InterlockedResourceAccessHandler handler(*this, ir.default_entry_point);
5677 handler.interlock_function_id = prepass_handler.interlock_function_id;
5678 handler.split_function_case = prepass_handler.split_function_case;
5679 handler.control_flow_interlock = prepass_handler.control_flow_interlock;
5680 handler.use_critical_section = !handler.split_function_case && !handler.control_flow_interlock;
5681
5682 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), handler);
5683
5684 // For GLSL. If we hit any of these cases, we have to fall back to conservative approach.
5685 interlocked_is_complex =
5686 !handler.use_critical_section || handler.interlock_function_id != ir.default_entry_point;
5687 }
5688 }
5689
5690 // Helper function
5691 bool Compiler::check_internal_recursion(const SPIRType &type, std::unordered_set<uint32_t> &checked_ids)
5692 {
5693 if (type.basetype != SPIRType::Struct)
5694 return false;
5695
5696 if (checked_ids.count(type.self))
5697 return true;
5698
5699 // Recurse into struct members
5700 bool is_recursive = false;
5701 checked_ids.insert(type.self);
5702 uint32_t mbr_cnt = uint32_t(type.member_types.size());
5703 for (uint32_t mbr_idx = 0; !is_recursive && mbr_idx < mbr_cnt; mbr_idx++)
5704 {
5705 uint32_t mbr_type_id = type.member_types[mbr_idx];
5706 auto &mbr_type = get<SPIRType>(mbr_type_id);
5707 is_recursive |= check_internal_recursion(mbr_type, checked_ids);
5708 }
5709 checked_ids.erase(type.self);
5710 return is_recursive;
5711 }
5712
5713 // Return whether the struct type contains a structural recursion nested somewhere within its content.
5714 bool Compiler::type_contains_recursion(const SPIRType &type)
5715 {
5716 std::unordered_set<uint32_t> checked_ids;
5717 return check_internal_recursion(type, checked_ids);
5718 }
5719
5720 bool Compiler::type_is_array_of_pointers(const SPIRType &type) const
5721 {
5722 if (!is_array(type))
5723 return false;
5724
5725 // BDA types must have parent type hierarchy.
5726 if (!type.parent_type)
5727 return false;
5728
5729 // Punch through all array layers.
5730 auto *parent = &get<SPIRType>(type.parent_type);
5731 while (is_array(*parent))
5732 parent = &get<SPIRType>(parent->parent_type);
5733
5734 return is_pointer(*parent);
5735 }
5736
5737 bool Compiler::flush_phi_required(BlockID from, BlockID to) const
5738 {
5739 auto &child = get<SPIRBlock>(to);
5740 for (auto &phi : child.phi_variables)
5741 if (phi.parent == from)
5742 return true;
5743 return false;
5744 }
5745
5746 void Compiler::add_loop_level()
5747 {
5748 current_loop_level++;
5749 }