Debian Codegraph @

thirdparty/spirv-cross/spirv_glsl.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_glsl.hpp"
25 #include "GLSL.std.450.h"
26 #include "spirv_common.hpp"
27 #include <algorithm>
28 #include <assert.h>
29 #include <cmath>
30 #include <limits>
31 #include <locale.h>
32 #include <utility>
33 #include <array>
34
35 #ifndef _WIN32
36 #include <langinfo.h>
37 #endif
38 #include <locale.h>
39
40 using namespace spv;
41 using namespace SPIRV_CROSS_NAMESPACE;
42 using namespace std;
43
44 enum ExtraSubExpressionType
45 {
46 // Create masks above any legal ID range to allow multiple address spaces into the extra_sub_expressions map.
47 EXTRA_SUB_EXPRESSION_TYPE_STREAM_OFFSET = 0x10000000,
48 EXTRA_SUB_EXPRESSION_TYPE_AUX = 0x20000000
49 };
50
51 static bool is_unsigned_opcode(Op op)
52 {
53 // Don't have to be exhaustive, only relevant for legacy target checking ...
54 switch (op)
55 {
56 case OpShiftRightLogical:
57 case OpUGreaterThan:
58 case OpUGreaterThanEqual:
59 case OpULessThan:
60 case OpULessThanEqual:
61 case OpUConvert:
62 case OpUDiv:
63 case OpUMod:
64 case OpUMulExtended:
65 case OpConvertUToF:
66 case OpConvertFToU:
67 return true;
68
69 default:
70 return false;
71 }
72 }
73
74 static bool is_unsigned_glsl_opcode(GLSLstd450 op)
75 {
76 // Don't have to be exhaustive, only relevant for legacy target checking ...
77 switch (op)
78 {
79 case GLSLstd450UClamp:
80 case GLSLstd450UMin:
81 case GLSLstd450UMax:
82 case GLSLstd450FindUMsb:
83 return true;
84
85 default:
86 return false;
87 }
88 }
89
90 static bool packing_is_vec4_padded(BufferPackingStandard packing)
91 {
92 switch (packing)
93 {
94 case BufferPackingHLSLCbuffer:
95 case BufferPackingHLSLCbufferPackOffset:
96 case BufferPackingStd140:
97 case BufferPackingStd140EnhancedLayout:
98 return true;
99
100 default:
101 return false;
102 }
103 }
104
105 static bool packing_is_hlsl(BufferPackingStandard packing)
106 {
107 switch (packing)
108 {
109 case BufferPackingHLSLCbuffer:
110 case BufferPackingHLSLCbufferPackOffset:
111 return true;
112
113 default:
114 return false;
115 }
116 }
117
118 static bool packing_has_flexible_offset(BufferPackingStandard packing)
119 {
120 switch (packing)
121 {
122 case BufferPackingStd140:
123 case BufferPackingStd430:
124 case BufferPackingScalar:
125 case BufferPackingHLSLCbuffer:
126 return false;
127
128 default:
129 return true;
130 }
131 }
132
133 static bool packing_is_scalar(BufferPackingStandard packing)
134 {
135 switch (packing)
136 {
137 case BufferPackingScalar:
138 case BufferPackingScalarEnhancedLayout:
139 return true;
140
141 default:
142 return false;
143 }
144 }
145
146 static BufferPackingStandard packing_to_substruct_packing(BufferPackingStandard packing)
147 {
148 switch (packing)
149 {
150 case BufferPackingStd140EnhancedLayout:
151 return BufferPackingStd140;
152 case BufferPackingStd430EnhancedLayout:
153 return BufferPackingStd430;
154 case BufferPackingHLSLCbufferPackOffset:
155 return BufferPackingHLSLCbuffer;
156 case BufferPackingScalarEnhancedLayout:
157 return BufferPackingScalar;
158 default:
159 return packing;
160 }
161 }
162
163 void CompilerGLSL::init()
164 {
165 if (ir.source.known)
166 {
167 options.es = ir.source.es;
168 options.version = ir.source.version;
169 }
170
171 // Query the locale to see what the decimal point is.
172 // We'll rely on fixing it up ourselves in the rare case we have a comma-as-decimal locale
173 // rather than setting locales ourselves. Settings locales in a safe and isolated way is rather
174 // tricky.
175 #ifdef _WIN32
176 // On Windows, localeconv uses thread-local storage, so it should be fine.
177 const struct lconv *conv = localeconv();
178 if (conv && conv->decimal_point)
179 current_locale_radix_character = *conv->decimal_point;
180 #elif defined(__ANDROID__) && __ANDROID_API__ < 26
181 // nl_langinfo is not supported on this platform, fall back to the worse alternative.
182 const struct lconv *conv = localeconv();
183 if (conv && conv->decimal_point)
184 current_locale_radix_character = *conv->decimal_point;
185 #else
186 // localeconv, the portable function is not MT safe ...
187 const char *decimal_point = nl_langinfo(RADIXCHAR);
188 if (decimal_point && *decimal_point != '\0')
189 current_locale_radix_character = *decimal_point;
190 #endif
191 }
192
193 static const char *to_pls_layout(PlsFormat format)
194 {
195 switch (format)
196 {
197 case PlsR11FG11FB10F:
198 return "layout(r11f_g11f_b10f) ";
199 case PlsR32F:
200 return "layout(r32f) ";
201 case PlsRG16F:
202 return "layout(rg16f) ";
203 case PlsRGB10A2:
204 return "layout(rgb10_a2) ";
205 case PlsRGBA8:
206 return "layout(rgba8) ";
207 case PlsRG16:
208 return "layout(rg16) ";
209 case PlsRGBA8I:
210 return "layout(rgba8i)";
211 case PlsRG16I:
212 return "layout(rg16i) ";
213 case PlsRGB10A2UI:
214 return "layout(rgb10_a2ui) ";
215 case PlsRGBA8UI:
216 return "layout(rgba8ui) ";
217 case PlsRG16UI:
218 return "layout(rg16ui) ";
219 case PlsR32UI:
220 return "layout(r32ui) ";
221 default:
222 return "";
223 }
224 }
225
226 static std::pair<spv::Op, SPIRType::BaseType> pls_format_to_basetype(PlsFormat format)
227 {
228 switch (format)
229 {
230 default:
231 case PlsR11FG11FB10F:
232 case PlsR32F:
233 case PlsRG16F:
234 case PlsRGB10A2:
235 case PlsRGBA8:
236 case PlsRG16:
237 return std::make_pair(spv::OpTypeFloat, SPIRType::Float);
238
239 case PlsRGBA8I:
240 case PlsRG16I:
241 return std::make_pair(spv::OpTypeInt, SPIRType::Int);
242
243 case PlsRGB10A2UI:
244 case PlsRGBA8UI:
245 case PlsRG16UI:
246 case PlsR32UI:
247 return std::make_pair(spv::OpTypeInt, SPIRType::UInt);
248 }
249 }
250
251 static uint32_t pls_format_to_components(PlsFormat format)
252 {
253 switch (format)
254 {
255 default:
256 case PlsR32F:
257 case PlsR32UI:
258 return 1;
259
260 case PlsRG16F:
261 case PlsRG16:
262 case PlsRG16UI:
263 case PlsRG16I:
264 return 2;
265
266 case PlsR11FG11FB10F:
267 return 3;
268
269 case PlsRGB10A2:
270 case PlsRGBA8:
271 case PlsRGBA8I:
272 case PlsRGB10A2UI:
273 case PlsRGBA8UI:
274 return 4;
275 }
276 }
277
278 const char *CompilerGLSL::vector_swizzle(int vecsize, int index)
279 {
280 static const char *const swizzle[4][4] = {
281 { ".x", ".y", ".z", ".w" },
282 { ".xy", ".yz", ".zw", nullptr },
283 { ".xyz", ".yzw", nullptr, nullptr },
284 #if defined(__GNUC__) && (__GNUC__ == 9)
285 // This works around a GCC 9 bug, see details in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90947.
286 // This array ends up being compiled as all nullptrs, tripping the assertions below.
287 { "", nullptr, nullptr, "$" },
288 #else
289 { "", nullptr, nullptr, nullptr },
290 #endif
291 };
292
293 assert(vecsize >= 1 && vecsize <= 4);
294 assert(index >= 0 && index < 4);
295 assert(swizzle[vecsize - 1][index]);
296
297 return swizzle[vecsize - 1][index];
298 }
299
300 void CompilerGLSL::reset(uint32_t iteration_count)
301 {
302 // Sanity check the iteration count to be robust against a certain class of bugs where
303 // we keep forcing recompilations without making clear forward progress.
304 // In buggy situations we will loop forever, or loop for an unbounded number of iterations.
305 // Certain types of recompilations are considered to make forward progress,
306 // but in almost all situations, we'll never see more than 3 iterations.
307 // It is highly context-sensitive when we need to force recompilation,
308 // and it is not practical with the current architecture
309 // to resolve everything up front.
310 if (iteration_count >= options.force_recompile_max_debug_iterations && !is_force_recompile_forward_progress)
311 SPIRV_CROSS_THROW("Maximum compilation loops detected and no forward progress was made. Must be a SPIRV-Cross bug!");
312
313 // We do some speculative optimizations which should pretty much always work out,
314 // but just in case the SPIR-V is rather weird, recompile until it's happy.
315 // This typically only means one extra pass.
316 clear_force_recompile();
317
318 // Clear invalid expression tracking.
319 invalid_expressions.clear();
320 composite_insert_overwritten.clear();
321 current_function = nullptr;
322
323 // Clear temporary usage tracking.
324 expression_usage_counts.clear();
325 forwarded_temporaries.clear();
326 suppressed_usage_tracking.clear();
327
328 // Ensure that we declare phi-variable copies even if the original declaration isn't deferred
329 flushed_phi_variables.clear();
330
331 current_emitting_switch_stack.clear();
332
333 reset_name_caches();
334
335 ir.for_each_typed_id<SPIRFunction>([&](uint32_t, SPIRFunction &func) {
336 func.active = false;
337 func.flush_undeclared = true;
338 });
339
340 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) { var.dependees.clear(); });
341
342 ir.reset_all_of_type<SPIRExpression>();
343 ir.reset_all_of_type<SPIRAccessChain>();
344
345 statement_count = 0;
346 indent = 0;
347 current_loop_level = 0;
348 }
349
350 void CompilerGLSL::remap_pls_variables()
351 {
352 for (auto &input : pls_inputs)
353 {
354 auto &var = get<SPIRVariable>(input.id);
355
356 bool input_is_target = false;
357 if (var.storage == StorageClassUniformConstant)
358 {
359 auto &type = get<SPIRType>(var.basetype);
360 input_is_target = type.image.dim == DimSubpassData;
361 }
362
363 if (var.storage != StorageClassInput && !input_is_target)
364 SPIRV_CROSS_THROW("Can only use in and target variables for PLS inputs.");
365 var.remapped_variable = true;
366 }
367
368 for (auto &output : pls_outputs)
369 {
370 auto &var = get<SPIRVariable>(output.id);
371 if (var.storage != StorageClassOutput)
372 SPIRV_CROSS_THROW("Can only use out variables for PLS outputs.");
373 var.remapped_variable = true;
374 }
375 }
376
377 void CompilerGLSL::remap_ext_framebuffer_fetch(uint32_t input_attachment_index, uint32_t color_location, bool coherent)
378 {
379 subpass_to_framebuffer_fetch_attachment.push_back({ input_attachment_index, color_location });
380 inout_color_attachments.push_back({ color_location, coherent });
381 }
382
383 bool CompilerGLSL::location_is_framebuffer_fetch(uint32_t location) const
384 {
385 return std::find_if(begin(inout_color_attachments), end(inout_color_attachments),
386 [&](const std::pair<uint32_t, bool> &elem) {
387 return elem.first == location;
388 }) != end(inout_color_attachments);
389 }
390
391 bool CompilerGLSL::location_is_non_coherent_framebuffer_fetch(uint32_t location) const
392 {
393 return std::find_if(begin(inout_color_attachments), end(inout_color_attachments),
394 [&](const std::pair<uint32_t, bool> &elem) {
395 return elem.first == location && !elem.second;
396 }) != end(inout_color_attachments);
397 }
398
399 void CompilerGLSL::find_static_extensions()
400 {
401 ir.for_each_typed_id<SPIRType>([&](uint32_t, const SPIRType &type) {
402 if (type.basetype == SPIRType::Double)
403 {
404 if (options.es)
405 SPIRV_CROSS_THROW("FP64 not supported in ES profile.");
406 if (!options.es && options.version < 400)
407 require_extension_internal("GL_ARB_gpu_shader_fp64");
408 }
409 else if (type.basetype == SPIRType::Int64 || type.basetype == SPIRType::UInt64)
410 {
411 if (options.es && options.version < 310) // GL_NV_gpu_shader5 fallback requires 310.
412 SPIRV_CROSS_THROW("64-bit integers not supported in ES profile before version 310.");
413 require_extension_internal("GL_ARB_gpu_shader_int64");
414 }
415 else if (type.basetype == SPIRType::Half)
416 {
417 require_extension_internal("GL_EXT_shader_explicit_arithmetic_types_float16");
418 if (options.vulkan_semantics)
419 require_extension_internal("GL_EXT_shader_16bit_storage");
420 }
421 else if (type.basetype == SPIRType::SByte || type.basetype == SPIRType::UByte)
422 {
423 require_extension_internal("GL_EXT_shader_explicit_arithmetic_types_int8");
424 if (options.vulkan_semantics)
425 require_extension_internal("GL_EXT_shader_8bit_storage");
426 }
427 else if (type.basetype == SPIRType::Short || type.basetype == SPIRType::UShort)
428 {
429 require_extension_internal("GL_EXT_shader_explicit_arithmetic_types_int16");
430 if (options.vulkan_semantics)
431 require_extension_internal("GL_EXT_shader_16bit_storage");
432 }
433 });
434
435 auto &execution = get_entry_point();
436 switch (execution.model)
437 {
438 case ExecutionModelGLCompute:
439 if (!options.es && options.version < 430)
440 require_extension_internal("GL_ARB_compute_shader");
441 if (options.es && options.version < 310)
442 SPIRV_CROSS_THROW("At least ESSL 3.10 required for compute shaders.");
443 break;
444
445 case ExecutionModelGeometry:
446 if (options.es && options.version < 320)
447 require_extension_internal("GL_EXT_geometry_shader");
448 if (!options.es && options.version < 150)
449 require_extension_internal("GL_ARB_geometry_shader4");
450
451 if (execution.flags.get(ExecutionModeInvocations) && execution.invocations != 1)
452 {
453 // Instanced GS is part of 400 core or this extension.
454 if (!options.es && options.version < 400)
455 require_extension_internal("GL_ARB_gpu_shader5");
456 }
457 break;
458
459 case ExecutionModelTessellationEvaluation:
460 case ExecutionModelTessellationControl:
461 if (options.es && options.version < 320)
462 require_extension_internal("GL_EXT_tessellation_shader");
463 if (!options.es && options.version < 400)
464 require_extension_internal("GL_ARB_tessellation_shader");
465 break;
466
467 case ExecutionModelRayGenerationKHR:
468 case ExecutionModelIntersectionKHR:
469 case ExecutionModelAnyHitKHR:
470 case ExecutionModelClosestHitKHR:
471 case ExecutionModelMissKHR:
472 case ExecutionModelCallableKHR:
473 // NV enums are aliases.
474 if (options.es || options.version < 460)
475 SPIRV_CROSS_THROW("Ray tracing shaders require non-es profile with version 460 or above.");
476 if (!options.vulkan_semantics)
477 SPIRV_CROSS_THROW("Ray tracing requires Vulkan semantics.");
478
479 // Need to figure out if we should target KHR or NV extension based on capabilities.
480 for (auto &cap : ir.declared_capabilities)
481 {
482 if (cap == CapabilityRayTracingKHR || cap == CapabilityRayQueryKHR ||
483 cap == CapabilityRayTraversalPrimitiveCullingKHR)
484 {
485 ray_tracing_is_khr = true;
486 break;
487 }
488 }
489
490 if (ray_tracing_is_khr)
491 {
492 // In KHR ray tracing we pass payloads by pointer instead of location,
493 // so make sure we assign locations properly.
494 ray_tracing_khr_fixup_locations();
495 require_extension_internal("GL_EXT_ray_tracing");
496 }
497 else
498 require_extension_internal("GL_NV_ray_tracing");
499 break;
500
501 case ExecutionModelMeshEXT:
502 case ExecutionModelTaskEXT:
503 if (options.es || options.version < 450)
504 SPIRV_CROSS_THROW("Mesh shaders require GLSL 450 or above.");
505 if (!options.vulkan_semantics)
506 SPIRV_CROSS_THROW("Mesh shaders require Vulkan semantics.");
507 require_extension_internal("GL_EXT_mesh_shader");
508 break;
509
510 default:
511 break;
512 }
513
514 if (!pls_inputs.empty() || !pls_outputs.empty())
515 {
516 if (execution.model != ExecutionModelFragment)
517 SPIRV_CROSS_THROW("Can only use GL_EXT_shader_pixel_local_storage in fragment shaders.");
518 require_extension_internal("GL_EXT_shader_pixel_local_storage");
519 }
520
521 if (!inout_color_attachments.empty())
522 {
523 if (execution.model != ExecutionModelFragment)
524 SPIRV_CROSS_THROW("Can only use GL_EXT_shader_framebuffer_fetch in fragment shaders.");
525 if (options.vulkan_semantics)
526 SPIRV_CROSS_THROW("Cannot use EXT_shader_framebuffer_fetch in Vulkan GLSL.");
527
528 bool has_coherent = false;
529 bool has_incoherent = false;
530
531 for (auto &att : inout_color_attachments)
532 {
533 if (att.second)
534 has_coherent = true;
535 else
536 has_incoherent = true;
537 }
538
539 if (has_coherent)
540 require_extension_internal("GL_EXT_shader_framebuffer_fetch");
541 if (has_incoherent)
542 require_extension_internal("GL_EXT_shader_framebuffer_fetch_non_coherent");
543 }
544
545 if (options.separate_shader_objects && !options.es && options.version < 410)
546 require_extension_internal("GL_ARB_separate_shader_objects");
547
548 if (ir.addressing_model == AddressingModelPhysicalStorageBuffer64)
549 {
550 if (!options.vulkan_semantics)
551 SPIRV_CROSS_THROW("GL_EXT_buffer_reference is only supported in Vulkan GLSL.");
552 if (options.es && options.version < 320)
553 SPIRV_CROSS_THROW("GL_EXT_buffer_reference requires ESSL 320.");
554 else if (!options.es && options.version < 450)
555 SPIRV_CROSS_THROW("GL_EXT_buffer_reference requires GLSL 450.");
556 require_extension_internal("GL_EXT_buffer_reference2");
557 }
558 else if (ir.addressing_model != AddressingModelLogical)
559 {
560 SPIRV_CROSS_THROW("Only Logical and PhysicalStorageBuffer64 addressing models are supported.");
561 }
562
563 // Check for nonuniform qualifier and passthrough.
564 // Instead of looping over all decorations to find this, just look at capabilities.
565 for (auto &cap : ir.declared_capabilities)
566 {
567 switch (cap)
568 {
569 case CapabilityShaderNonUniformEXT:
570 if (!options.vulkan_semantics)
571 require_extension_internal("GL_NV_gpu_shader5");
572 else
573 require_extension_internal("GL_EXT_nonuniform_qualifier");
574 break;
575 case CapabilityRuntimeDescriptorArrayEXT:
576 if (!options.vulkan_semantics)
577 SPIRV_CROSS_THROW("GL_EXT_nonuniform_qualifier is only supported in Vulkan GLSL.");
578 require_extension_internal("GL_EXT_nonuniform_qualifier");
579 break;
580
581 case CapabilityGeometryShaderPassthroughNV:
582 if (execution.model == ExecutionModelGeometry)
583 {
584 require_extension_internal("GL_NV_geometry_shader_passthrough");
585 execution.geometry_passthrough = true;
586 }
587 break;
588
589 case CapabilityVariablePointers:
590 case CapabilityVariablePointersStorageBuffer:
591 SPIRV_CROSS_THROW("VariablePointers capability is not supported in GLSL.");
592
593 case CapabilityMultiView:
594 if (options.vulkan_semantics)
595 require_extension_internal("GL_EXT_multiview");
596 else
597 {
598 require_extension_internal("GL_OVR_multiview2");
599 if (options.ovr_multiview_view_count == 0)
600 SPIRV_CROSS_THROW("ovr_multiview_view_count must be non-zero when using GL_OVR_multiview2.");
601 if (get_execution_model() != ExecutionModelVertex)
602 SPIRV_CROSS_THROW("OVR_multiview2 can only be used with Vertex shaders.");
603 }
604 break;
605
606 case CapabilityRayQueryKHR:
607 if (options.es || options.version < 460 || !options.vulkan_semantics)
608 SPIRV_CROSS_THROW("RayQuery requires Vulkan GLSL 460.");
609 require_extension_internal("GL_EXT_ray_query");
610 ray_tracing_is_khr = true;
611 break;
612
613 case CapabilityRayTraversalPrimitiveCullingKHR:
614 if (options.es || options.version < 460 || !options.vulkan_semantics)
615 SPIRV_CROSS_THROW("RayQuery requires Vulkan GLSL 460.");
616 require_extension_internal("GL_EXT_ray_flags_primitive_culling");
617 ray_tracing_is_khr = true;
618 break;
619
620 default:
621 break;
622 }
623 }
624
625 if (options.ovr_multiview_view_count)
626 {
627 if (options.vulkan_semantics)
628 SPIRV_CROSS_THROW("OVR_multiview2 cannot be used with Vulkan semantics.");
629 if (get_execution_model() != ExecutionModelVertex)
630 SPIRV_CROSS_THROW("OVR_multiview2 can only be used with Vertex shaders.");
631 require_extension_internal("GL_OVR_multiview2");
632 }
633
634 if (execution.flags.get(ExecutionModeQuadDerivativesKHR) ||
635 (execution.flags.get(ExecutionModeRequireFullQuadsKHR) && get_execution_model() == ExecutionModelFragment))
636 {
637 require_extension_internal("GL_EXT_shader_quad_control");
638 }
639
640 // KHR one is likely to get promoted at some point, so if we don't see an explicit SPIR-V extension, assume KHR.
641 for (auto &ext : ir.declared_extensions)
642 if (ext == "SPV_NV_fragment_shader_barycentric")
643 barycentric_is_nv = true;
644 }
645
646 void CompilerGLSL::require_polyfill(Polyfill polyfill, bool relaxed)
647 {
648 uint32_t &polyfills = (relaxed && (options.es || options.vulkan_semantics)) ?
649 required_polyfills_relaxed : required_polyfills;
650
651 if ((polyfills & polyfill) == 0)
652 {
653 polyfills |= polyfill;
654 force_recompile();
655 }
656 }
657
658 void CompilerGLSL::ray_tracing_khr_fixup_locations()
659 {
660 uint32_t location = 0;
661 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
662 // Incoming payload storage can also be used for tracing.
663 if (var.storage != StorageClassRayPayloadKHR && var.storage != StorageClassCallableDataKHR &&
664 var.storage != StorageClassIncomingRayPayloadKHR && var.storage != StorageClassIncomingCallableDataKHR)
665 return;
666 if (is_hidden_variable(var))
667 return;
668 set_decoration(var.self, DecorationLocation, location++);
669 });
670 }
671
672 string CompilerGLSL::compile()
673 {
674 ir.fixup_reserved_names();
675
676 if (!options.vulkan_semantics)
677 {
678 // only NV_gpu_shader5 supports divergent indexing on OpenGL, and it does so without extra qualifiers
679 backend.nonuniform_qualifier = "";
680 backend.needs_row_major_load_workaround = options.enable_row_major_load_workaround;
681 }
682 backend.allow_precision_qualifiers = options.vulkan_semantics || options.es;
683 backend.force_gl_in_out_block = true;
684 backend.supports_extensions = true;
685 backend.use_array_constructor = true;
686 backend.workgroup_size_is_hidden = true;
687 backend.requires_relaxed_precision_analysis = options.es || options.vulkan_semantics;
688 backend.support_precise_qualifier =
689 (!options.es && options.version >= 400) || (options.es && options.version >= 320);
690 backend.constant_null_initializer = "{ }";
691 backend.requires_matching_array_initializer = true;
692
693 if (is_legacy_es())
694 backend.support_case_fallthrough = false;
695
696 // Scan the SPIR-V to find trivial uses of extensions.
697 fixup_anonymous_struct_names();
698 fixup_type_alias();
699 reorder_type_alias();
700 build_function_control_flow_graphs_and_analyze();
701 find_static_extensions();
702 fixup_image_load_store_access();
703 update_active_builtins();
704 analyze_image_and_sampler_usage();
705 analyze_interlocked_resource_usage();
706 if (!inout_color_attachments.empty())
707 emit_inout_fragment_outputs_copy_to_subpass_inputs();
708
709 // Shaders might cast unrelated data to pointers of non-block types.
710 // Find all such instances and make sure we can cast the pointers to a synthesized block type.
711 if (ir.addressing_model == AddressingModelPhysicalStorageBuffer64)
712 analyze_non_block_pointer_types();
713
714 uint32_t pass_count = 0;
715 do
716 {
717 reset(pass_count);
718
719 buffer.reset();
720
721 emit_header();
722 emit_resources();
723 emit_extension_workarounds(get_execution_model());
724
725 if (required_polyfills != 0)
726 emit_polyfills(required_polyfills, false);
727 if ((options.es || options.vulkan_semantics) && required_polyfills_relaxed != 0)
728 emit_polyfills(required_polyfills_relaxed, true);
729
730 emit_function(get<SPIRFunction>(ir.default_entry_point), Bitset());
731
732 pass_count++;
733 } while (is_forcing_recompilation());
734
735 // Implement the interlocked wrapper function at the end.
736 // The body was implemented in lieu of main().
737 if (interlocked_is_complex)
738 {
739 statement("void main()");
740 begin_scope();
741 statement("// Interlocks were used in a way not compatible with GLSL, this is very slow.");
742 statement("SPIRV_Cross_beginInvocationInterlock();");
743 statement("spvMainInterlockedBody();");
744 statement("SPIRV_Cross_endInvocationInterlock();");
745 end_scope();
746 }
747
748 // Entry point in GLSL is always main().
749 get_entry_point().name = "main";
750
751 return buffer.str();
752 }
753
754 std::string CompilerGLSL::get_partial_source()
755 {
756 return buffer.str();
757 }
758
759 void CompilerGLSL::build_workgroup_size(SmallVector<string> &arguments, const SpecializationConstant &wg_x,
760 const SpecializationConstant &wg_y, const SpecializationConstant &wg_z)
761 {
762 auto &execution = get_entry_point();
763 bool builtin_workgroup = execution.workgroup_size.constant != 0;
764 bool use_local_size_id = !builtin_workgroup && execution.flags.get(ExecutionModeLocalSizeId);
765
766 if (wg_x.id)
767 {
768 if (options.vulkan_semantics)
769 arguments.push_back(join("local_size_x_id = ", wg_x.constant_id));
770 else
771 arguments.push_back(join("local_size_x = ", get<SPIRConstant>(wg_x.id).specialization_constant_macro_name));
772 }
773 else if (use_local_size_id && execution.workgroup_size.id_x)
774 arguments.push_back(join("local_size_x = ", get<SPIRConstant>(execution.workgroup_size.id_x).scalar()));
775 else
776 arguments.push_back(join("local_size_x = ", execution.workgroup_size.x));
777
778 if (wg_y.id)
779 {
780 if (options.vulkan_semantics)
781 arguments.push_back(join("local_size_y_id = ", wg_y.constant_id));
782 else
783 arguments.push_back(join("local_size_y = ", get<SPIRConstant>(wg_y.id).specialization_constant_macro_name));
784 }
785 else if (use_local_size_id && execution.workgroup_size.id_y)
786 arguments.push_back(join("local_size_y = ", get<SPIRConstant>(execution.workgroup_size.id_y).scalar()));
787 else
788 arguments.push_back(join("local_size_y = ", execution.workgroup_size.y));
789
790 if (wg_z.id)
791 {
792 if (options.vulkan_semantics)
793 arguments.push_back(join("local_size_z_id = ", wg_z.constant_id));
794 else
795 arguments.push_back(join("local_size_z = ", get<SPIRConstant>(wg_z.id).specialization_constant_macro_name));
796 }
797 else if (use_local_size_id && execution.workgroup_size.id_z)
798 arguments.push_back(join("local_size_z = ", get<SPIRConstant>(execution.workgroup_size.id_z).scalar()));
799 else
800 arguments.push_back(join("local_size_z = ", execution.workgroup_size.z));
801 }
802
803 void CompilerGLSL::request_subgroup_feature(ShaderSubgroupSupportHelper::Feature feature)
804 {
805 if (options.vulkan_semantics)
806 {
807 auto khr_extension = ShaderSubgroupSupportHelper::get_KHR_extension_for_feature(feature);
808 require_extension_internal(ShaderSubgroupSupportHelper::get_extension_name(khr_extension));
809 }
810 else
811 {
812 if (!shader_subgroup_supporter.is_feature_requested(feature))
813 force_recompile();
814 shader_subgroup_supporter.request_feature(feature);
815 }
816 }
817
818 void CompilerGLSL::emit_header()
819 {
820 auto &execution = get_entry_point();
821 statement("#version ", options.version, options.es && options.version > 100 ? " es" : "");
822
823 if (!options.es && options.version < 420)
824 {
825 // Needed for binding = # on UBOs, etc.
826 if (options.enable_420pack_extension)
827 {
828 statement("#ifdef GL_ARB_shading_language_420pack");
829 statement("#extension GL_ARB_shading_language_420pack : require");
830 statement("#endif");
831 }
832 // Needed for: layout(early_fragment_tests) in;
833 if (execution.flags.get(ExecutionModeEarlyFragmentTests))
834 require_extension_internal("GL_ARB_shader_image_load_store");
835 }
836
837 // Needed for: layout(post_depth_coverage) in;
838 if (execution.flags.get(ExecutionModePostDepthCoverage))
839 require_extension_internal("GL_ARB_post_depth_coverage");
840
841 // Needed for: layout({pixel,sample}_interlock_[un]ordered) in;
842 bool interlock_used = execution.flags.get(ExecutionModePixelInterlockOrderedEXT) ||
843 execution.flags.get(ExecutionModePixelInterlockUnorderedEXT) ||
844 execution.flags.get(ExecutionModeSampleInterlockOrderedEXT) ||
845 execution.flags.get(ExecutionModeSampleInterlockUnorderedEXT);
846
847 if (interlock_used)
848 {
849 if (options.es)
850 {
851 if (options.version < 310)
852 SPIRV_CROSS_THROW("At least ESSL 3.10 required for fragment shader interlock.");
853 require_extension_internal("GL_NV_fragment_shader_interlock");
854 }
855 else
856 {
857 if (options.version < 420)
858 require_extension_internal("GL_ARB_shader_image_load_store");
859 require_extension_internal("GL_ARB_fragment_shader_interlock");
860 }
861 }
862
863 for (auto &ext : forced_extensions)
864 {
865 if (ext == "GL_ARB_gpu_shader_int64")
866 {
867 statement("#if defined(GL_ARB_gpu_shader_int64)");
868 statement("#extension GL_ARB_gpu_shader_int64 : require");
869 if (!options.vulkan_semantics || options.es)
870 {
871 statement("#elif defined(GL_NV_gpu_shader5)");
872 statement("#extension GL_NV_gpu_shader5 : require");
873 }
874 statement("#else");
875 statement("#error No extension available for 64-bit integers.");
876 statement("#endif");
877 }
878 else if (ext == "GL_EXT_shader_explicit_arithmetic_types_float16")
879 {
880 // Special case, this extension has a potential fallback to another vendor extension in normal GLSL.
881 // GL_AMD_gpu_shader_half_float is a superset, so try that first.
882 statement("#if defined(GL_AMD_gpu_shader_half_float)");
883 statement("#extension GL_AMD_gpu_shader_half_float : require");
884 if (!options.vulkan_semantics)
885 {
886 statement("#elif defined(GL_NV_gpu_shader5)");
887 statement("#extension GL_NV_gpu_shader5 : require");
888 }
889 else
890 {
891 statement("#elif defined(GL_EXT_shader_explicit_arithmetic_types_float16)");
892 statement("#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require");
893 }
894 statement("#else");
895 statement("#error No extension available for FP16.");
896 statement("#endif");
897 }
898 else if (ext == "GL_EXT_shader_explicit_arithmetic_types_int8")
899 {
900 if (options.vulkan_semantics)
901 statement("#extension GL_EXT_shader_explicit_arithmetic_types_int8 : require");
902 else
903 {
904 statement("#if defined(GL_EXT_shader_explicit_arithmetic_types_int8)");
905 statement("#extension GL_EXT_shader_explicit_arithmetic_types_int8 : require");
906 statement("#elif defined(GL_NV_gpu_shader5)");
907 statement("#extension GL_NV_gpu_shader5 : require");
908 statement("#else");
909 statement("#error No extension available for Int8.");
910 statement("#endif");
911 }
912 }
913 else if (ext == "GL_EXT_shader_explicit_arithmetic_types_int16")
914 {
915 if (options.vulkan_semantics)
916 statement("#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require");
917 else
918 {
919 statement("#if defined(GL_EXT_shader_explicit_arithmetic_types_int16)");
920 statement("#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require");
921 statement("#elif defined(GL_AMD_gpu_shader_int16)");
922 statement("#extension GL_AMD_gpu_shader_int16 : require");
923 statement("#elif defined(GL_NV_gpu_shader5)");
924 statement("#extension GL_NV_gpu_shader5 : require");
925 statement("#else");
926 statement("#error No extension available for Int16.");
927 statement("#endif");
928 }
929 }
930 else if (ext == "GL_ARB_post_depth_coverage")
931 {
932 if (options.es)
933 statement("#extension GL_EXT_post_depth_coverage : require");
934 else
935 {
936 statement("#if defined(GL_ARB_post_depth_coverge)");
937 statement("#extension GL_ARB_post_depth_coverage : require");
938 statement("#else");
939 statement("#extension GL_EXT_post_depth_coverage : require");
940 statement("#endif");
941 }
942 }
943 else if (!options.vulkan_semantics && ext == "GL_ARB_shader_draw_parameters")
944 {
945 // Soft-enable this extension on plain GLSL.
946 statement("#ifdef ", ext);
947 statement("#extension ", ext, " : enable");
948 statement("#endif");
949 }
950 else if (ext == "GL_EXT_control_flow_attributes")
951 {
952 // These are just hints so we can conditionally enable and fallback in the shader.
953 statement("#if defined(GL_EXT_control_flow_attributes)");
954 statement("#extension GL_EXT_control_flow_attributes : require");
955 statement("#define SPIRV_CROSS_FLATTEN [[flatten]]");
956 statement("#define SPIRV_CROSS_BRANCH [[dont_flatten]]");
957 statement("#define SPIRV_CROSS_UNROLL [[unroll]]");
958 statement("#define SPIRV_CROSS_LOOP [[dont_unroll]]");
959 statement("#else");
960 statement("#define SPIRV_CROSS_FLATTEN");
961 statement("#define SPIRV_CROSS_BRANCH");
962 statement("#define SPIRV_CROSS_UNROLL");
963 statement("#define SPIRV_CROSS_LOOP");
964 statement("#endif");
965 }
966 else if (ext == "GL_NV_fragment_shader_interlock")
967 {
968 statement("#extension GL_NV_fragment_shader_interlock : require");
969 statement("#define SPIRV_Cross_beginInvocationInterlock() beginInvocationInterlockNV()");
970 statement("#define SPIRV_Cross_endInvocationInterlock() endInvocationInterlockNV()");
971 }
972 else if (ext == "GL_ARB_fragment_shader_interlock")
973 {
974 statement("#ifdef GL_ARB_fragment_shader_interlock");
975 statement("#extension GL_ARB_fragment_shader_interlock : enable");
976 statement("#define SPIRV_Cross_beginInvocationInterlock() beginInvocationInterlockARB()");
977 statement("#define SPIRV_Cross_endInvocationInterlock() endInvocationInterlockARB()");
978 statement("#elif defined(GL_INTEL_fragment_shader_ordering)");
979 statement("#extension GL_INTEL_fragment_shader_ordering : enable");
980 statement("#define SPIRV_Cross_beginInvocationInterlock() beginFragmentShaderOrderingINTEL()");
981 statement("#define SPIRV_Cross_endInvocationInterlock()");
982 statement("#endif");
983 }
984 else
985 statement("#extension ", ext, " : require");
986 }
987
988 if (!options.vulkan_semantics)
989 {
990 using Supp = ShaderSubgroupSupportHelper;
991 auto result = shader_subgroup_supporter.resolve();
992
993 for (uint32_t feature_index = 0; feature_index < Supp::FeatureCount; feature_index++)
994 {
995 auto feature = static_cast<Supp::Feature>(feature_index);
996 if (!shader_subgroup_supporter.is_feature_requested(feature))
997 continue;
998
999 auto exts = Supp::get_candidates_for_feature(feature, result);
1000 if (exts.empty())
1001 continue;
1002
1003 statement("");
1004
1005 for (auto &ext : exts)
1006 {
1007 const char *name = Supp::get_extension_name(ext);
1008 const char *extra_predicate = Supp::get_extra_required_extension_predicate(ext);
1009 auto extra_names = Supp::get_extra_required_extension_names(ext);
1010 statement(&ext != &exts.front() ? "#elif" : "#if", " defined(", name, ")",
1011 (*extra_predicate != '\0' ? " && " : ""), extra_predicate);
1012 for (const auto &e : extra_names)
1013 statement("#extension ", e, " : enable");
1014 statement("#extension ", name, " : require");
1015 }
1016
1017 if (!Supp::can_feature_be_implemented_without_extensions(feature))
1018 {
1019 statement("#else");
1020 statement("#error No extensions available to emulate requested subgroup feature.");
1021 }
1022
1023 statement("#endif");
1024 }
1025 }
1026
1027 for (auto &header : header_lines)
1028 statement(header);
1029
1030 SmallVector<string> inputs;
1031 SmallVector<string> outputs;
1032
1033 switch (execution.model)
1034 {
1035 case ExecutionModelVertex:
1036 if (options.ovr_multiview_view_count)
1037 inputs.push_back(join("num_views = ", options.ovr_multiview_view_count));
1038 break;
1039 case ExecutionModelGeometry:
1040 if ((execution.flags.get(ExecutionModeInvocations)) && execution.invocations != 1)
1041 inputs.push_back(join("invocations = ", execution.invocations));
1042 if (execution.flags.get(ExecutionModeInputPoints))
1043 inputs.push_back("points");
1044 if (execution.flags.get(ExecutionModeInputLines))
1045 inputs.push_back("lines");
1046 if (execution.flags.get(ExecutionModeInputLinesAdjacency))
1047 inputs.push_back("lines_adjacency");
1048 if (execution.flags.get(ExecutionModeTriangles))
1049 inputs.push_back("triangles");
1050 if (execution.flags.get(ExecutionModeInputTrianglesAdjacency))
1051 inputs.push_back("triangles_adjacency");
1052
1053 if (!execution.geometry_passthrough)
1054 {
1055 // For passthrough, these are implies and cannot be declared in shader.
1056 outputs.push_back(join("max_vertices = ", execution.output_vertices));
1057 if (execution.flags.get(ExecutionModeOutputTriangleStrip))
1058 outputs.push_back("triangle_strip");
1059 if (execution.flags.get(ExecutionModeOutputPoints))
1060 outputs.push_back("points");
1061 if (execution.flags.get(ExecutionModeOutputLineStrip))
1062 outputs.push_back("line_strip");
1063 }
1064 break;
1065
1066 case ExecutionModelTessellationControl:
1067 if (execution.flags.get(ExecutionModeOutputVertices))
1068 outputs.push_back(join("vertices = ", execution.output_vertices));
1069 break;
1070
1071 case ExecutionModelTessellationEvaluation:
1072 if (execution.flags.get(ExecutionModeQuads))
1073 inputs.push_back("quads");
1074 if (execution.flags.get(ExecutionModeTriangles))
1075 inputs.push_back("triangles");
1076 if (execution.flags.get(ExecutionModeIsolines))
1077 inputs.push_back("isolines");
1078 if (execution.flags.get(ExecutionModePointMode))
1079 inputs.push_back("point_mode");
1080
1081 if (!execution.flags.get(ExecutionModeIsolines))
1082 {
1083 if (execution.flags.get(ExecutionModeVertexOrderCw))
1084 inputs.push_back("cw");
1085 if (execution.flags.get(ExecutionModeVertexOrderCcw))
1086 inputs.push_back("ccw");
1087 }
1088
1089 if (execution.flags.get(ExecutionModeSpacingFractionalEven))
1090 inputs.push_back("fractional_even_spacing");
1091 if (execution.flags.get(ExecutionModeSpacingFractionalOdd))
1092 inputs.push_back("fractional_odd_spacing");
1093 if (execution.flags.get(ExecutionModeSpacingEqual))
1094 inputs.push_back("equal_spacing");
1095 break;
1096
1097 case ExecutionModelGLCompute:
1098 case ExecutionModelTaskEXT:
1099 case ExecutionModelMeshEXT:
1100 {
1101 if (execution.workgroup_size.constant != 0 || execution.flags.get(ExecutionModeLocalSizeId))
1102 {
1103 SpecializationConstant wg_x, wg_y, wg_z;
1104 get_work_group_size_specialization_constants(wg_x, wg_y, wg_z);
1105
1106 // If there are any spec constants on legacy GLSL, defer declaration, we need to set up macro
1107 // declarations before we can emit the work group size.
1108 if (options.vulkan_semantics ||
1109 ((wg_x.id == ConstantID(0)) && (wg_y.id == ConstantID(0)) && (wg_z.id == ConstantID(0))))
1110 build_workgroup_size(inputs, wg_x, wg_y, wg_z);
1111 }
1112 else
1113 {
1114 inputs.push_back(join("local_size_x = ", execution.workgroup_size.x));
1115 inputs.push_back(join("local_size_y = ", execution.workgroup_size.y));
1116 inputs.push_back(join("local_size_z = ", execution.workgroup_size.z));
1117 }
1118
1119 if (execution.model == ExecutionModelMeshEXT)
1120 {
1121 outputs.push_back(join("max_vertices = ", execution.output_vertices));
1122 outputs.push_back(join("max_primitives = ", execution.output_primitives));
1123 if (execution.flags.get(ExecutionModeOutputTrianglesEXT))
1124 outputs.push_back("triangles");
1125 else if (execution.flags.get(ExecutionModeOutputLinesEXT))
1126 outputs.push_back("lines");
1127 else if (execution.flags.get(ExecutionModeOutputPoints))
1128 outputs.push_back("points");
1129 }
1130 break;
1131 }
1132
1133 case ExecutionModelFragment:
1134 if (options.es)
1135 {
1136 switch (options.fragment.default_float_precision)
1137 {
1138 case Options::Lowp:
1139 statement("precision lowp float;");
1140 break;
1141
1142 case Options::Mediump:
1143 statement("precision mediump float;");
1144 break;
1145
1146 case Options::Highp:
1147 statement("precision highp float;");
1148 break;
1149
1150 default:
1151 break;
1152 }
1153
1154 switch (options.fragment.default_int_precision)
1155 {
1156 case Options::Lowp:
1157 statement("precision lowp int;");
1158 break;
1159
1160 case Options::Mediump:
1161 statement("precision mediump int;");
1162 break;
1163
1164 case Options::Highp:
1165 statement("precision highp int;");
1166 break;
1167
1168 default:
1169 break;
1170 }
1171 }
1172
1173 if (execution.flags.get(ExecutionModeEarlyFragmentTests))
1174 inputs.push_back("early_fragment_tests");
1175 if (execution.flags.get(ExecutionModePostDepthCoverage))
1176 inputs.push_back("post_depth_coverage");
1177
1178 if (interlock_used)
1179 statement("#if defined(GL_ARB_fragment_shader_interlock)");
1180
1181 if (execution.flags.get(ExecutionModePixelInterlockOrderedEXT))
1182 statement("layout(pixel_interlock_ordered) in;");
1183 else if (execution.flags.get(ExecutionModePixelInterlockUnorderedEXT))
1184 statement("layout(pixel_interlock_unordered) in;");
1185 else if (execution.flags.get(ExecutionModeSampleInterlockOrderedEXT))
1186 statement("layout(sample_interlock_ordered) in;");
1187 else if (execution.flags.get(ExecutionModeSampleInterlockUnorderedEXT))
1188 statement("layout(sample_interlock_unordered) in;");
1189
1190 if (interlock_used)
1191 {
1192 statement("#elif !defined(GL_INTEL_fragment_shader_ordering)");
1193 statement("#error Fragment Shader Interlock/Ordering extension missing!");
1194 statement("#endif");
1195 }
1196
1197 if (!options.es && execution.flags.get(ExecutionModeDepthGreater))
1198 statement("layout(depth_greater) out float gl_FragDepth;");
1199 else if (!options.es && execution.flags.get(ExecutionModeDepthLess))
1200 statement("layout(depth_less) out float gl_FragDepth;");
1201
1202 if (execution.flags.get(ExecutionModeRequireFullQuadsKHR))
1203 statement("layout(full_quads) in;");
1204
1205 break;
1206
1207 default:
1208 break;
1209 }
1210
1211 for (auto &cap : ir.declared_capabilities)
1212 if (cap == CapabilityRayTraversalPrimitiveCullingKHR)
1213 statement("layout(primitive_culling);");
1214
1215 if (execution.flags.get(ExecutionModeQuadDerivativesKHR))
1216 statement("layout(quad_derivatives) in;");
1217
1218 if (!inputs.empty())
1219 statement("layout(", merge(inputs), ") in;");
1220 if (!outputs.empty())
1221 statement("layout(", merge(outputs), ") out;");
1222
1223 statement("");
1224 }
1225
1226 bool CompilerGLSL::type_is_empty(const SPIRType &type)
1227 {
1228 return type.basetype == SPIRType::Struct && type.member_types.empty();
1229 }
1230
1231 void CompilerGLSL::emit_struct(SPIRType &type)
1232 {
1233 // Struct types can be stamped out multiple times
1234 // with just different offsets, matrix layouts, etc ...
1235 // Type-punning with these types is legal, which complicates things
1236 // when we are storing struct and array types in an SSBO for example.
1237 // If the type master is packed however, we can no longer assume that the struct declaration will be redundant.
1238 if (type.type_alias != TypeID(0) &&
1239 !has_extended_decoration(type.type_alias, SPIRVCrossDecorationBufferBlockRepacked))
1240 return;
1241
1242 add_resource_name(type.self);
1243 auto name = type_to_glsl(type);
1244
1245 statement(!backend.explicit_struct_type ? "struct " : "", name);
1246 begin_scope();
1247
1248 type.member_name_cache.clear();
1249
1250 uint32_t i = 0;
1251 bool emitted = false;
1252 for (auto &member : type.member_types)
1253 {
1254 add_member_name(type, i);
1255 emit_struct_member(type, member, i);
1256 i++;
1257 emitted = true;
1258 }
1259
1260 // Don't declare empty structs in GLSL, this is not allowed.
1261 if (type_is_empty(type) && !backend.supports_empty_struct)
1262 {
1263 statement("int empty_struct_member;");
1264 emitted = true;
1265 }
1266
1267 if (has_extended_decoration(type.self, SPIRVCrossDecorationPaddingTarget))
1268 emit_struct_padding_target(type);
1269
1270 end_scope_decl();
1271
1272 if (emitted)
1273 statement("");
1274 }
1275
1276 string CompilerGLSL::to_interpolation_qualifiers(const Bitset &flags)
1277 {
1278 string res;
1279 //if (flags & (1ull << DecorationSmooth))
1280 // res += "smooth ";
1281 if (flags.get(DecorationFlat))
1282 res += "flat ";
1283 if (flags.get(DecorationNoPerspective))
1284 {
1285 if (options.es)
1286 {
1287 if (options.version < 300)
1288 SPIRV_CROSS_THROW("noperspective requires ESSL 300.");
1289 require_extension_internal("GL_NV_shader_noperspective_interpolation");
1290 }
1291 else if (is_legacy_desktop())
1292 require_extension_internal("GL_EXT_gpu_shader4");
1293 res += "noperspective ";
1294 }
1295 if (flags.get(DecorationCentroid))
1296 res += "centroid ";
1297 if (flags.get(DecorationPatch))
1298 res += "patch ";
1299 if (flags.get(DecorationSample))
1300 {
1301 if (options.es)
1302 {
1303 if (options.version < 300)
1304 SPIRV_CROSS_THROW("sample requires ESSL 300.");
1305 else if (options.version < 320)
1306 require_extension_internal("GL_OES_shader_multisample_interpolation");
1307 }
1308 res += "sample ";
1309 }
1310 if (flags.get(DecorationInvariant) && (options.es || options.version >= 120))
1311 res += "invariant ";
1312 if (flags.get(DecorationPerPrimitiveEXT))
1313 {
1314 res += "perprimitiveEXT ";
1315 require_extension_internal("GL_EXT_mesh_shader");
1316 }
1317
1318 if (flags.get(DecorationExplicitInterpAMD))
1319 {
1320 require_extension_internal("GL_AMD_shader_explicit_vertex_parameter");
1321 res += "__explicitInterpAMD ";
1322 }
1323
1324 if (flags.get(DecorationPerVertexKHR))
1325 {
1326 if (options.es && options.version < 320)
1327 SPIRV_CROSS_THROW("pervertexEXT requires ESSL 320.");
1328 else if (!options.es && options.version < 450)
1329 SPIRV_CROSS_THROW("pervertexEXT requires GLSL 450.");
1330
1331 if (barycentric_is_nv)
1332 {
1333 require_extension_internal("GL_NV_fragment_shader_barycentric");
1334 res += "pervertexNV ";
1335 }
1336 else
1337 {
1338 require_extension_internal("GL_EXT_fragment_shader_barycentric");
1339 res += "pervertexEXT ";
1340 }
1341 }
1342
1343 return res;
1344 }
1345
1346 string CompilerGLSL::layout_for_member(const SPIRType &type, uint32_t index)
1347 {
1348 if (is_legacy())
1349 return "";
1350
1351 bool is_block = has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
1352 if (!is_block)
1353 return "";
1354
1355 auto &memb = ir.meta[type.self].members;
1356 if (index >= memb.size())
1357 return "";
1358 auto &dec = memb[index];
1359
1360 SmallVector<string> attr;
1361
1362 if (has_member_decoration(type.self, index, DecorationPassthroughNV))
1363 attr.push_back("passthrough");
1364
1365 // We can only apply layouts on members in block interfaces.
1366 // This is a bit problematic because in SPIR-V decorations are applied on the struct types directly.
1367 // This is not supported on GLSL, so we have to make the assumption that if a struct within our buffer block struct
1368 // has a decoration, it was originally caused by a top-level layout() qualifier in GLSL.
1369 //
1370 // We would like to go from (SPIR-V style):
1371 //
1372 // struct Foo { layout(row_major) mat4 matrix; };
1373 // buffer UBO { Foo foo; };
1374 //
1375 // to
1376 //
1377 // struct Foo { mat4 matrix; }; // GLSL doesn't support any layout shenanigans in raw struct declarations.
1378 // buffer UBO { layout(row_major) Foo foo; }; // Apply the layout on top-level.
1379 auto flags = combined_decoration_for_member(type, index);
1380
1381 if (flags.get(DecorationRowMajor))
1382 attr.push_back("row_major");
1383 // We don't emit any global layouts, so column_major is default.
1384 //if (flags & (1ull << DecorationColMajor))
1385 // attr.push_back("column_major");
1386
1387 if (dec.decoration_flags.get(DecorationLocation) && can_use_io_location(type.storage, true))
1388 attr.push_back(join("location = ", dec.location));
1389
1390 // Can only declare component if we can declare location.
1391 if (dec.decoration_flags.get(DecorationComponent) && can_use_io_location(type.storage, true))
1392 {
1393 if (!options.es)
1394 {
1395 if (options.version < 440 && options.version >= 140)
1396 require_extension_internal("GL_ARB_enhanced_layouts");
1397 else if (options.version < 140)
1398 SPIRV_CROSS_THROW("Component decoration is not supported in targets below GLSL 1.40.");
1399 attr.push_back(join("component = ", dec.component));
1400 }
1401 else
1402 SPIRV_CROSS_THROW("Component decoration is not supported in ES targets.");
1403 }
1404
1405 // SPIRVCrossDecorationPacked is set by layout_for_variable earlier to mark that we need to emit offset qualifiers.
1406 // This is only done selectively in GLSL as needed.
1407 if (has_extended_decoration(type.self, SPIRVCrossDecorationExplicitOffset) &&
1408 dec.decoration_flags.get(DecorationOffset))
1409 attr.push_back(join("offset = ", dec.offset));
1410 else if (type.storage == StorageClassOutput && dec.decoration_flags.get(DecorationOffset))
1411 attr.push_back(join("xfb_offset = ", dec.offset));
1412
1413 if (attr.empty())
1414 return "";
1415
1416 string res = "layout(";
1417 res += merge(attr);
1418 res += ") ";
1419 return res;
1420 }
1421
1422 const char *CompilerGLSL::format_to_glsl(spv::ImageFormat format)
1423 {
1424 if (options.es && is_desktop_only_format(format))
1425 SPIRV_CROSS_THROW("Attempting to use image format not supported in ES profile.");
1426
1427 switch (format)
1428 {
1429 case ImageFormatRgba32f:
1430 return "rgba32f";
1431 case ImageFormatRgba16f:
1432 return "rgba16f";
1433 case ImageFormatR32f:
1434 return "r32f";
1435 case ImageFormatRgba8:
1436 return "rgba8";
1437 case ImageFormatRgba8Snorm:
1438 return "rgba8_snorm";
1439 case ImageFormatRg32f:
1440 return "rg32f";
1441 case ImageFormatRg16f:
1442 return "rg16f";
1443 case ImageFormatRgba32i:
1444 return "rgba32i";
1445 case ImageFormatRgba16i:
1446 return "rgba16i";
1447 case ImageFormatR32i:
1448 return "r32i";
1449 case ImageFormatRgba8i:
1450 return "rgba8i";
1451 case ImageFormatRg32i:
1452 return "rg32i";
1453 case ImageFormatRg16i:
1454 return "rg16i";
1455 case ImageFormatRgba32ui:
1456 return "rgba32ui";
1457 case ImageFormatRgba16ui:
1458 return "rgba16ui";
1459 case ImageFormatR32ui:
1460 return "r32ui";
1461 case ImageFormatRgba8ui:
1462 return "rgba8ui";
1463 case ImageFormatRg32ui:
1464 return "rg32ui";
1465 case ImageFormatRg16ui:
1466 return "rg16ui";
1467 case ImageFormatR11fG11fB10f:
1468 return "r11f_g11f_b10f";
1469 case ImageFormatR16f:
1470 return "r16f";
1471 case ImageFormatRgb10A2:
1472 return "rgb10_a2";
1473 case ImageFormatR8:
1474 return "r8";
1475 case ImageFormatRg8:
1476 return "rg8";
1477 case ImageFormatR16:
1478 return "r16";
1479 case ImageFormatRg16:
1480 return "rg16";
1481 case ImageFormatRgba16:
1482 return "rgba16";
1483 case ImageFormatR16Snorm:
1484 return "r16_snorm";
1485 case ImageFormatRg16Snorm:
1486 return "rg16_snorm";
1487 case ImageFormatRgba16Snorm:
1488 return "rgba16_snorm";
1489 case ImageFormatR8Snorm:
1490 return "r8_snorm";
1491 case ImageFormatRg8Snorm:
1492 return "rg8_snorm";
1493 case ImageFormatR8ui:
1494 return "r8ui";
1495 case ImageFormatRg8ui:
1496 return "rg8ui";
1497 case ImageFormatR16ui:
1498 return "r16ui";
1499 case ImageFormatRgb10a2ui:
1500 return "rgb10_a2ui";
1501 case ImageFormatR8i:
1502 return "r8i";
1503 case ImageFormatRg8i:
1504 return "rg8i";
1505 case ImageFormatR16i:
1506 return "r16i";
1507 case ImageFormatR64i:
1508 return "r64i";
1509 case ImageFormatR64ui:
1510 return "r64ui";
1511 default:
1512 case ImageFormatUnknown:
1513 return nullptr;
1514 }
1515 }
1516
1517 uint32_t CompilerGLSL::type_to_packed_base_size(const SPIRType &type, BufferPackingStandard)
1518 {
1519 switch (type.basetype)
1520 {
1521 case SPIRType::Double:
1522 case SPIRType::Int64:
1523 case SPIRType::UInt64:
1524 return 8;
1525 case SPIRType::Float:
1526 case SPIRType::Int:
1527 case SPIRType::UInt:
1528 return 4;
1529 case SPIRType::Half:
1530 case SPIRType::Short:
1531 case SPIRType::UShort:
1532 case SPIRType::BFloat16:
1533 return 2;
1534 case SPIRType::SByte:
1535 case SPIRType::UByte:
1536 case SPIRType::FloatE4M3:
1537 case SPIRType::FloatE5M2:
1538 return 1;
1539
1540 default:
1541 SPIRV_CROSS_THROW("Unrecognized type in type_to_packed_base_size.");
1542 }
1543 }
1544
1545 uint32_t CompilerGLSL::type_to_packed_alignment(const SPIRType &type, const Bitset &flags,
1546 BufferPackingStandard packing)
1547 {
1548 // If using PhysicalStorageBuffer storage class, this is a pointer,
1549 // and is 64-bit.
1550 if (is_physical_pointer(type))
1551 {
1552 if (!type.pointer)
1553 SPIRV_CROSS_THROW("Types in PhysicalStorageBuffer must be pointers.");
1554
1555 if (ir.addressing_model == AddressingModelPhysicalStorageBuffer64)
1556 {
1557 if (packing_is_vec4_padded(packing) && type_is_array_of_pointers(type))
1558 return 16;
1559 else
1560 return 8;
1561 }
1562 else
1563 SPIRV_CROSS_THROW("AddressingModelPhysicalStorageBuffer64 must be used for PhysicalStorageBuffer.");
1564 }
1565 else if (is_array(type))
1566 {
1567 uint32_t minimum_alignment = 1;
1568 if (packing_is_vec4_padded(packing))
1569 minimum_alignment = 16;
1570
1571 auto *tmp = &get<SPIRType>(type.parent_type);
1572 while (!tmp->array.empty())
1573 tmp = &get<SPIRType>(tmp->parent_type);
1574
1575 // Get the alignment of the base type, then maybe round up.
1576 return max(minimum_alignment, type_to_packed_alignment(*tmp, flags, packing));
1577 }
1578
1579 if (type.basetype == SPIRType::Struct)
1580 {
1581 // Rule 9. Structs alignments are maximum alignment of its members.
1582 uint32_t alignment = 1;
1583 for (uint32_t i = 0; i < type.member_types.size(); i++)
1584 {
1585 auto member_flags = ir.meta[type.self].members[i].decoration_flags;
1586 alignment =
1587 max(alignment, type_to_packed_alignment(get<SPIRType>(type.member_types[i]), member_flags, packing));
1588 }
1589
1590 // In std140, struct alignment is rounded up to 16.
1591 if (packing_is_vec4_padded(packing))
1592 alignment = max<uint32_t>(alignment, 16u);
1593
1594 return alignment;
1595 }
1596 else
1597 {
1598 const uint32_t base_alignment = type_to_packed_base_size(type, packing);
1599
1600 // Alignment requirement for scalar block layout is always the alignment for the most basic component.
1601 if (packing_is_scalar(packing))
1602 return base_alignment;
1603
1604 // Vectors are *not* aligned in HLSL, but there's an extra rule where vectors cannot straddle
1605 // a vec4, this is handled outside since that part knows our current offset.
1606 if (type.columns == 1 && packing_is_hlsl(packing))
1607 return base_alignment;
1608
1609 // From 7.6.2.2 in GL 4.5 core spec.
1610 // Rule 1
1611 if (type.vecsize == 1 && type.columns == 1)
1612 return base_alignment;
1613
1614 // Rule 2
1615 if ((type.vecsize == 2 || type.vecsize == 4) && type.columns == 1)
1616 return type.vecsize * base_alignment;
1617
1618 // Rule 3
1619 if (type.vecsize == 3 && type.columns == 1)
1620 return 4 * base_alignment;
1621
1622 // Rule 4 implied. Alignment does not change in std430.
1623
1624 // Rule 5. Column-major matrices are stored as arrays of
1625 // vectors.
1626 if (flags.get(DecorationColMajor) && type.columns > 1)
1627 {
1628 if (packing_is_vec4_padded(packing))
1629 return 4 * base_alignment;
1630 else if (type.vecsize == 3)
1631 return 4 * base_alignment;
1632 else
1633 return type.vecsize * base_alignment;
1634 }
1635
1636 // Rule 6 implied.
1637
1638 // Rule 7.
1639 if (flags.get(DecorationRowMajor) && type.vecsize > 1)
1640 {
1641 if (packing_is_vec4_padded(packing))
1642 return 4 * base_alignment;
1643 else if (type.columns == 3)
1644 return 4 * base_alignment;
1645 else
1646 return type.columns * base_alignment;
1647 }
1648
1649 // Rule 8 implied.
1650 }
1651
1652 SPIRV_CROSS_THROW("Did not find suitable rule for type. Bogus decorations?");
1653 }
1654
1655 uint32_t CompilerGLSL::type_to_packed_array_stride(const SPIRType &type, const Bitset &flags,
1656 BufferPackingStandard packing)
1657 {
1658 // Array stride is equal to aligned size of the underlying type.
1659 uint32_t parent = type.parent_type;
1660 assert(parent);
1661
1662 auto &tmp = get<SPIRType>(parent);
1663
1664 uint32_t size = type_to_packed_size(tmp, flags, packing);
1665 uint32_t alignment = type_to_packed_alignment(type, flags, packing);
1666 return (size + alignment - 1) & ~(alignment - 1);
1667 }
1668
1669 uint32_t CompilerGLSL::type_to_packed_size(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing)
1670 {
1671 // If using PhysicalStorageBuffer storage class, this is a pointer,
1672 // and is 64-bit.
1673 if (is_physical_pointer(type))
1674 {
1675 if (!type.pointer)
1676 SPIRV_CROSS_THROW("Types in PhysicalStorageBuffer must be pointers.");
1677
1678 if (ir.addressing_model == AddressingModelPhysicalStorageBuffer64)
1679 return 8;
1680 else
1681 SPIRV_CROSS_THROW("AddressingModelPhysicalStorageBuffer64 must be used for PhysicalStorageBuffer.");
1682 }
1683 else if (is_array(type))
1684 {
1685 uint32_t packed_size = to_array_size_literal(type) * type_to_packed_array_stride(type, flags, packing);
1686
1687 // For arrays of vectors and matrices in HLSL, the last element has a size which depends on its vector size,
1688 // so that it is possible to pack other vectors into the last element.
1689 if (packing_is_hlsl(packing) && type.basetype != SPIRType::Struct)
1690 packed_size -= (4 - type.vecsize) * (type.width / 8);
1691
1692 return packed_size;
1693 }
1694
1695 uint32_t size = 0;
1696
1697 if (type.basetype == SPIRType::Struct)
1698 {
1699 uint32_t pad_alignment = 1;
1700
1701 for (uint32_t i = 0; i < type.member_types.size(); i++)
1702 {
1703 auto member_flags = ir.meta[type.self].members[i].decoration_flags;
1704 auto &member_type = get<SPIRType>(type.member_types[i]);
1705
1706 uint32_t packed_alignment = type_to_packed_alignment(member_type, member_flags, packing);
1707 uint32_t alignment = max(packed_alignment, pad_alignment);
1708
1709 // The next member following a struct member is aligned to the base alignment of the struct that came before.
1710 // GL 4.5 spec, 7.6.2.2.
1711 if (member_type.basetype == SPIRType::Struct)
1712 pad_alignment = packed_alignment;
1713 else
1714 pad_alignment = 1;
1715
1716 size = (size + alignment - 1) & ~(alignment - 1);
1717 size += type_to_packed_size(member_type, member_flags, packing);
1718 }
1719 }
1720 else
1721 {
1722 const uint32_t base_alignment = type_to_packed_base_size(type, packing);
1723
1724 if (packing_is_scalar(packing))
1725 {
1726 size = type.vecsize * type.columns * base_alignment;
1727 }
1728 else
1729 {
1730 if (type.columns == 1)
1731 size = type.vecsize * base_alignment;
1732
1733 if (flags.get(DecorationColMajor) && type.columns > 1)
1734 {
1735 if (packing_is_vec4_padded(packing))
1736 size = type.columns * 4 * base_alignment;
1737 else if (type.vecsize == 3)
1738 size = type.columns * 4 * base_alignment;
1739 else
1740 size = type.columns * type.vecsize * base_alignment;
1741 }
1742
1743 if (flags.get(DecorationRowMajor) && type.vecsize > 1)
1744 {
1745 if (packing_is_vec4_padded(packing))
1746 size = type.vecsize * 4 * base_alignment;
1747 else if (type.columns == 3)
1748 size = type.vecsize * 4 * base_alignment;
1749 else
1750 size = type.vecsize * type.columns * base_alignment;
1751 }
1752
1753 // For matrices in HLSL, the last element has a size which depends on its vector size,
1754 // so that it is possible to pack other vectors into the last element.
1755 if (packing_is_hlsl(packing) && type.columns > 1)
1756 size -= (4 - type.vecsize) * (type.width / 8);
1757 }
1758 }
1759
1760 return size;
1761 }
1762
1763 bool CompilerGLSL::buffer_is_packing_standard(const SPIRType &type, BufferPackingStandard packing,
1764 uint32_t *failed_validation_index, uint32_t start_offset,
1765 uint32_t end_offset)
1766 {
1767 // This is very tricky and error prone, but try to be exhaustive and correct here.
1768 // SPIR-V doesn't directly say if we're using std430 or std140.
1769 // SPIR-V communicates this using Offset and ArrayStride decorations (which is what really matters),
1770 // so we have to try to infer whether or not the original GLSL source was std140 or std430 based on this information.
1771 // We do not have to consider shared or packed since these layouts are not allowed in Vulkan SPIR-V (they are useless anyways, and custom offsets would do the same thing).
1772 //
1773 // It is almost certain that we're using std430, but it gets tricky with arrays in particular.
1774 // We will assume std430, but infer std140 if we can prove the struct is not compliant with std430.
1775 //
1776 // The only two differences between std140 and std430 are related to padding alignment/array stride
1777 // in arrays and structs. In std140 they take minimum vec4 alignment.
1778 // std430 only removes the vec4 requirement.
1779
1780 uint32_t offset = 0;
1781 uint32_t pad_alignment = 1;
1782
1783 bool is_top_level_block =
1784 has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
1785
1786 for (uint32_t i = 0; i < type.member_types.size(); i++)
1787 {
1788 auto &memb_type = get<SPIRType>(type.member_types[i]);
1789
1790 auto *type_meta = ir.find_meta(type.self);
1791 auto member_flags = type_meta ? type_meta->members[i].decoration_flags : Bitset{};
1792
1793 // Verify alignment rules.
1794 uint32_t packed_alignment = type_to_packed_alignment(memb_type, member_flags, packing);
1795
1796 // This is a rather dirty workaround to deal with some cases of OpSpecConstantOp used as array size, e.g:
1797 // layout(constant_id = 0) const int s = 10;
1798 // const int S = s + 5; // SpecConstantOp
1799 // buffer Foo { int data[S]; }; // <-- Very hard for us to deduce a fixed value here,
1800 // we would need full implementation of compile-time constant folding. :(
1801 // If we are the last member of a struct, there might be cases where the actual size of that member is irrelevant
1802 // for our analysis (e.g. unsized arrays).
1803 // This lets us simply ignore that there are spec constant op sized arrays in our buffers.
1804 // Querying size of this member will fail, so just don't call it unless we have to.
1805 //
1806 // This is likely "best effort" we can support without going into unacceptably complicated workarounds.
1807 bool member_can_be_unsized =
1808 is_top_level_block && size_t(i + 1) == type.member_types.size() && !memb_type.array.empty();
1809
1810 uint32_t packed_size = 0;
1811 if (!member_can_be_unsized || packing_is_hlsl(packing))
1812 packed_size = type_to_packed_size(memb_type, member_flags, packing);
1813
1814 // We only need to care about this if we have non-array types which can straddle the vec4 boundary.
1815 uint32_t actual_offset = type_struct_member_offset(type, i);
1816
1817 if (packing_is_hlsl(packing))
1818 {
1819 // If a member straddles across a vec4 boundary, alignment is actually vec4.
1820 uint32_t target_offset;
1821
1822 // If we intend to use explicit packing, we must check for improper straddle with that offset.
1823 // In implicit packing, we must check with implicit offset, since the explicit offset
1824 // might have already accounted for the straddle, and we'd miss the alignment promotion to vec4.
1825 // This is important when packing sub-structs that don't support packoffset().
1826 if (packing_has_flexible_offset(packing))
1827 target_offset = actual_offset;
1828 else
1829 target_offset = offset;
1830
1831 uint32_t begin_word = target_offset / 16;
1832 uint32_t end_word = (target_offset + packed_size - 1) / 16;
1833
1834 if (begin_word != end_word)
1835 packed_alignment = max<uint32_t>(packed_alignment, 16u);
1836 }
1837
1838 // Field is not in the specified range anymore and we can ignore any further fields.
1839 if (actual_offset >= end_offset)
1840 break;
1841
1842 uint32_t alignment = max(packed_alignment, pad_alignment);
1843 offset = (offset + alignment - 1) & ~(alignment - 1);
1844
1845 // The next member following a struct member is aligned to the base alignment of the struct that came before.
1846 // GL 4.5 spec, 7.6.2.2.
1847 if (memb_type.basetype == SPIRType::Struct && !memb_type.pointer)
1848 pad_alignment = packed_alignment;
1849 else
1850 pad_alignment = 1;
1851
1852 // Only care about packing if we are in the given range
1853 if (actual_offset >= start_offset)
1854 {
1855 // We only care about offsets in std140, std430, etc ...
1856 // For EnhancedLayout variants, we have the flexibility to choose our own offsets.
1857 if (!packing_has_flexible_offset(packing))
1858 {
1859 if (actual_offset != offset) // This cannot be the packing we're looking for.
1860 {
1861 if (failed_validation_index)
1862 *failed_validation_index = i;
1863 return false;
1864 }
1865 }
1866 else if ((actual_offset & (alignment - 1)) != 0)
1867 {
1868 // We still need to verify that alignment rules are observed, even if we have explicit offset.
1869 if (failed_validation_index)
1870 *failed_validation_index = i;
1871 return false;
1872 }
1873
1874 // Verify array stride rules.
1875 if (is_array(memb_type) &&
1876 type_to_packed_array_stride(memb_type, member_flags, packing) !=
1877 type_struct_member_array_stride(type, i))
1878 {
1879 if (failed_validation_index)
1880 *failed_validation_index = i;
1881 return false;
1882 }
1883
1884 // Verify that sub-structs also follow packing rules.
1885 // We cannot use enhanced layouts on substructs, so they better be up to spec.
1886 auto substruct_packing = packing_to_substruct_packing(packing);
1887
1888 if (!memb_type.pointer && !memb_type.member_types.empty() &&
1889 !buffer_is_packing_standard(memb_type, substruct_packing))
1890 {
1891 if (failed_validation_index)
1892 *failed_validation_index = i;
1893 return false;
1894 }
1895 }
1896
1897 // Bump size.
1898 offset = actual_offset + packed_size;
1899 }
1900
1901 return true;
1902 }
1903
1904 bool CompilerGLSL::can_use_io_location(StorageClass storage, bool block)
1905 {
1906 // Location specifiers are must have in SPIR-V, but they aren't really supported in earlier versions of GLSL.
1907 // Be very explicit here about how to solve the issue.
1908 if ((get_execution_model() != ExecutionModelVertex && storage == StorageClassInput) ||
1909 (get_execution_model() != ExecutionModelFragment && storage == StorageClassOutput))
1910 {
1911 uint32_t minimum_desktop_version = block ? 440 : 410;
1912 // ARB_enhanced_layouts vs ARB_separate_shader_objects ...
1913
1914 if (!options.es && options.version < minimum_desktop_version && !options.separate_shader_objects)
1915 return false;
1916 else if (options.es && options.version < 310)
1917 return false;
1918 }
1919
1920 if ((get_execution_model() == ExecutionModelVertex && storage == StorageClassInput) ||
1921 (get_execution_model() == ExecutionModelFragment && storage == StorageClassOutput))
1922 {
1923 if (options.es && options.version < 300)
1924 return false;
1925 else if (!options.es && options.version < 330)
1926 return false;
1927 }
1928
1929 if (storage == StorageClassUniform || storage == StorageClassUniformConstant || storage == StorageClassPushConstant)
1930 {
1931 if (options.es && options.version < 310)
1932 return false;
1933 else if (!options.es && options.version < 430)
1934 return false;
1935 }
1936
1937 return true;
1938 }
1939
1940 string CompilerGLSL::layout_for_variable(const SPIRVariable &var)
1941 {
1942 // FIXME: Come up with a better solution for when to disable layouts.
1943 // Having layouts depend on extensions as well as which types
1944 // of layouts are used. For now, the simple solution is to just disable
1945 // layouts for legacy versions.
1946 if (is_legacy())
1947 return "";
1948
1949 if (subpass_input_is_framebuffer_fetch(var.self))
1950 return "";
1951
1952 SmallVector<string> attr;
1953
1954 auto &type = get<SPIRType>(var.basetype);
1955 auto &flags = get_decoration_bitset(var.self);
1956 auto &typeflags = get_decoration_bitset(type.self);
1957
1958 if (flags.get(DecorationPassthroughNV))
1959 attr.push_back("passthrough");
1960
1961 if (options.vulkan_semantics && var.storage == StorageClassPushConstant)
1962 attr.push_back("push_constant");
1963 else if (var.storage == StorageClassShaderRecordBufferKHR)
1964 attr.push_back(ray_tracing_is_khr ? "shaderRecordEXT" : "shaderRecordNV");
1965
1966 if (flags.get(DecorationRowMajor))
1967 attr.push_back("row_major");
1968 if (flags.get(DecorationColMajor))
1969 attr.push_back("column_major");
1970
1971 if (options.vulkan_semantics)
1972 {
1973 if (flags.get(DecorationInputAttachmentIndex))
1974 attr.push_back(join("input_attachment_index = ", get_decoration(var.self, DecorationInputAttachmentIndex)));
1975 }
1976
1977 bool is_block = has_decoration(type.self, DecorationBlock);
1978 if (flags.get(DecorationLocation) && can_use_io_location(var.storage, is_block))
1979 {
1980 Bitset combined_decoration;
1981 for (uint32_t i = 0; i < ir.meta[type.self].members.size(); i++)
1982 combined_decoration.merge_or(combined_decoration_for_member(type, i));
1983
1984 // If our members have location decorations, we don't need to
1985 // emit location decorations at the top as well (looks weird).
1986 if (!combined_decoration.get(DecorationLocation))
1987 attr.push_back(join("location = ", get_decoration(var.self, DecorationLocation)));
1988 }
1989
1990 if (get_execution_model() == ExecutionModelFragment && var.storage == StorageClassOutput &&
1991 location_is_non_coherent_framebuffer_fetch(get_decoration(var.self, DecorationLocation)))
1992 {
1993 attr.push_back("noncoherent");
1994 }
1995
1996 // Transform feedback
1997 bool uses_enhanced_layouts = false;
1998 if (is_block && var.storage == StorageClassOutput)
1999 {
2000 // For blocks, there is a restriction where xfb_stride/xfb_buffer must only be declared on the block itself,
2001 // since all members must match the same xfb_buffer. The only thing we will declare for members of the block
2002 // is the xfb_offset.
2003 uint32_t member_count = uint32_t(type.member_types.size());
2004 bool have_xfb_buffer_stride = false;
2005 bool have_any_xfb_offset = false;
2006 bool have_geom_stream = false;
2007 uint32_t xfb_stride = 0, xfb_buffer = 0, geom_stream = 0;
2008
2009 if (flags.get(DecorationXfbBuffer) && flags.get(DecorationXfbStride))
2010 {
2011 have_xfb_buffer_stride = true;
2012 xfb_buffer = get_decoration(var.self, DecorationXfbBuffer);
2013 xfb_stride = get_decoration(var.self, DecorationXfbStride);
2014 }
2015
2016 if (flags.get(DecorationStream))
2017 {
2018 have_geom_stream = true;
2019 geom_stream = get_decoration(var.self, DecorationStream);
2020 }
2021
2022 // Verify that none of the members violate our assumption.
2023 for (uint32_t i = 0; i < member_count; i++)
2024 {
2025 if (has_member_decoration(type.self, i, DecorationStream))
2026 {
2027 uint32_t member_geom_stream = get_member_decoration(type.self, i, DecorationStream);
2028 if (have_geom_stream && member_geom_stream != geom_stream)
2029 SPIRV_CROSS_THROW("IO block member Stream mismatch.");
2030 have_geom_stream = true;
2031 geom_stream = member_geom_stream;
2032 }
2033
2034 // Only members with an Offset decoration participate in XFB.
2035 if (!has_member_decoration(type.self, i, DecorationOffset))
2036 continue;
2037 have_any_xfb_offset = true;
2038
2039 if (has_member_decoration(type.self, i, DecorationXfbBuffer))
2040 {
2041 uint32_t buffer_index = get_member_decoration(type.self, i, DecorationXfbBuffer);
2042 if (have_xfb_buffer_stride && buffer_index != xfb_buffer)
2043 SPIRV_CROSS_THROW("IO block member XfbBuffer mismatch.");
2044 have_xfb_buffer_stride = true;
2045 xfb_buffer = buffer_index;
2046 }
2047
2048 if (has_member_decoration(type.self, i, DecorationXfbStride))
2049 {
2050 uint32_t stride = get_member_decoration(type.self, i, DecorationXfbStride);
2051 if (have_xfb_buffer_stride && stride != xfb_stride)
2052 SPIRV_CROSS_THROW("IO block member XfbStride mismatch.");
2053 have_xfb_buffer_stride = true;
2054 xfb_stride = stride;
2055 }
2056 }
2057
2058 if (have_xfb_buffer_stride && have_any_xfb_offset)
2059 {
2060 attr.push_back(join("xfb_buffer = ", xfb_buffer));
2061 attr.push_back(join("xfb_stride = ", xfb_stride));
2062 uses_enhanced_layouts = true;
2063 }
2064
2065 if (have_geom_stream)
2066 {
2067 if (get_execution_model() != ExecutionModelGeometry)
2068 SPIRV_CROSS_THROW("Geometry streams can only be used in geometry shaders.");
2069 if (options.es)
2070 SPIRV_CROSS_THROW("Multiple geometry streams not supported in ESSL.");
2071 if (options.version < 400)
2072 require_extension_internal("GL_ARB_transform_feedback3");
2073 attr.push_back(join("stream = ", get_decoration(var.self, DecorationStream)));
2074 }
2075 }
2076 else if (var.storage == StorageClassOutput)
2077 {
2078 if (flags.get(DecorationXfbBuffer) && flags.get(DecorationXfbStride) && flags.get(DecorationOffset))
2079 {
2080 // XFB for standalone variables, we can emit all decorations.
2081 attr.push_back(join("xfb_buffer = ", get_decoration(var.self, DecorationXfbBuffer)));
2082 attr.push_back(join("xfb_stride = ", get_decoration(var.self, DecorationXfbStride)));
2083 attr.push_back(join("xfb_offset = ", get_decoration(var.self, DecorationOffset)));
2084 uses_enhanced_layouts = true;
2085 }
2086
2087 if (flags.get(DecorationStream))
2088 {
2089 if (get_execution_model() != ExecutionModelGeometry)
2090 SPIRV_CROSS_THROW("Geometry streams can only be used in geometry shaders.");
2091 if (options.es)
2092 SPIRV_CROSS_THROW("Multiple geometry streams not supported in ESSL.");
2093 if (options.version < 400)
2094 require_extension_internal("GL_ARB_transform_feedback3");
2095 attr.push_back(join("stream = ", get_decoration(var.self, DecorationStream)));
2096 }
2097 }
2098
2099 // Can only declare Component if we can declare location.
2100 if (flags.get(DecorationComponent) && can_use_io_location(var.storage, is_block))
2101 {
2102 uses_enhanced_layouts = true;
2103 attr.push_back(join("component = ", get_decoration(var.self, DecorationComponent)));
2104 }
2105
2106 if (uses_enhanced_layouts)
2107 {
2108 if (!options.es)
2109 {
2110 if (options.version < 440 && options.version >= 140)
2111 require_extension_internal("GL_ARB_enhanced_layouts");
2112 else if (options.version < 140)
2113 SPIRV_CROSS_THROW("GL_ARB_enhanced_layouts is not supported in targets below GLSL 1.40.");
2114 if (!options.es && options.version < 440)
2115 require_extension_internal("GL_ARB_enhanced_layouts");
2116 }
2117 else if (options.es)
2118 SPIRV_CROSS_THROW("GL_ARB_enhanced_layouts is not supported in ESSL.");
2119 }
2120
2121 if (flags.get(DecorationIndex))
2122 attr.push_back(join("index = ", get_decoration(var.self, DecorationIndex)));
2123
2124 // Do not emit set = decoration in regular GLSL output, but
2125 // we need to preserve it in Vulkan GLSL mode.
2126 if (var.storage != StorageClassPushConstant && var.storage != StorageClassShaderRecordBufferKHR)
2127 {
2128 if (flags.get(DecorationDescriptorSet) && options.vulkan_semantics)
2129 attr.push_back(join("set = ", get_decoration(var.self, DecorationDescriptorSet)));
2130 }
2131
2132 bool push_constant_block = options.vulkan_semantics && var.storage == StorageClassPushConstant;
2133 bool ssbo_block = var.storage == StorageClassStorageBuffer || var.storage == StorageClassShaderRecordBufferKHR ||
2134 (var.storage == StorageClassUniform && typeflags.get(DecorationBufferBlock));
2135 bool emulated_ubo = var.storage == StorageClassPushConstant && options.emit_push_constant_as_uniform_buffer;
2136 bool ubo_block = var.storage == StorageClassUniform && typeflags.get(DecorationBlock);
2137
2138 // GL 3.0/GLSL 1.30 is not considered legacy, but it doesn't have UBOs ...
2139 bool can_use_buffer_blocks = (options.es && options.version >= 300) || (!options.es && options.version >= 140);
2140
2141 // pretend no UBOs when options say so
2142 if (ubo_block && options.emit_uniform_buffer_as_plain_uniforms)
2143 can_use_buffer_blocks = false;
2144
2145 bool can_use_binding;
2146 if (options.es)
2147 can_use_binding = options.version >= 310;
2148 else
2149 can_use_binding = options.enable_420pack_extension || (options.version >= 420);
2150
2151 // Make sure we don't emit binding layout for a classic uniform on GLSL 1.30.
2152 if (!can_use_buffer_blocks && var.storage == StorageClassUniform)
2153 can_use_binding = false;
2154
2155 if (var.storage == StorageClassShaderRecordBufferKHR)
2156 can_use_binding = false;
2157
2158 if (can_use_binding && flags.get(DecorationBinding))
2159 attr.push_back(join("binding = ", get_decoration(var.self, DecorationBinding)));
2160
2161 if (var.storage != StorageClassOutput && flags.get(DecorationOffset))
2162 attr.push_back(join("offset = ", get_decoration(var.self, DecorationOffset)));
2163
2164 // Instead of adding explicit offsets for every element here, just assume we're using std140 or std430.
2165 // If SPIR-V does not comply with either layout, we cannot really work around it.
2166 if (can_use_buffer_blocks && (ubo_block || emulated_ubo))
2167 {
2168 attr.push_back(buffer_to_packing_standard(type, false, true));
2169 }
2170 else if (can_use_buffer_blocks && (push_constant_block || ssbo_block))
2171 {
2172 attr.push_back(buffer_to_packing_standard(type, true, true));
2173 }
2174
2175 // For images, the type itself adds a layout qualifer.
2176 // Only emit the format for storage images.
2177 if (type.basetype == SPIRType::Image && type.image.sampled == 2)
2178 {
2179 const char *fmt = format_to_glsl(type.image.format);
2180 if (fmt)
2181 attr.push_back(fmt);
2182 }
2183
2184 if (attr.empty())
2185 return "";
2186
2187 string res = "layout(";
2188 res += merge(attr);
2189 res += ") ";
2190 return res;
2191 }
2192
2193 string CompilerGLSL::buffer_to_packing_standard(const SPIRType &type,
2194 bool support_std430_without_scalar_layout,
2195 bool support_enhanced_layouts)
2196 {
2197 if (support_std430_without_scalar_layout && buffer_is_packing_standard(type, BufferPackingStd430))
2198 return "std430";
2199 else if (buffer_is_packing_standard(type, BufferPackingStd140))
2200 return "std140";
2201 else if (options.vulkan_semantics && buffer_is_packing_standard(type, BufferPackingScalar))
2202 {
2203 require_extension_internal("GL_EXT_scalar_block_layout");
2204 return "scalar";
2205 }
2206 else if (support_std430_without_scalar_layout &&
2207 support_enhanced_layouts &&
2208 buffer_is_packing_standard(type, BufferPackingStd430EnhancedLayout))
2209 {
2210 if (options.es && !options.vulkan_semantics)
2211 SPIRV_CROSS_THROW("Push constant block cannot be expressed as neither std430 nor std140. ES-targets do "
2212 "not support GL_ARB_enhanced_layouts.");
2213 if (!options.es && !options.vulkan_semantics && options.version < 440)
2214 require_extension_internal("GL_ARB_enhanced_layouts");
2215
2216 set_extended_decoration(type.self, SPIRVCrossDecorationExplicitOffset);
2217 return "std430";
2218 }
2219 else if (support_enhanced_layouts &&
2220 buffer_is_packing_standard(type, BufferPackingStd140EnhancedLayout))
2221 {
2222 // Fallback time. We might be able to use the ARB_enhanced_layouts to deal with this difference,
2223 // however, we can only use layout(offset) on the block itself, not any substructs, so the substructs better be the appropriate layout.
2224 // Enhanced layouts seem to always work in Vulkan GLSL, so no need for extensions there.
2225 if (options.es && !options.vulkan_semantics)
2226 SPIRV_CROSS_THROW("Push constant block cannot be expressed as neither std430 nor std140. ES-targets do "
2227 "not support GL_ARB_enhanced_layouts.");
2228 if (!options.es && !options.vulkan_semantics && options.version < 440)
2229 require_extension_internal("GL_ARB_enhanced_layouts");
2230
2231 set_extended_decoration(type.self, SPIRVCrossDecorationExplicitOffset);
2232 return "std140";
2233 }
2234 else if (options.vulkan_semantics &&
2235 support_enhanced_layouts &&
2236 buffer_is_packing_standard(type, BufferPackingScalarEnhancedLayout))
2237 {
2238 set_extended_decoration(type.self, SPIRVCrossDecorationExplicitOffset);
2239 require_extension_internal("GL_EXT_scalar_block_layout");
2240 return "scalar";
2241 }
2242 else if (!support_std430_without_scalar_layout && options.vulkan_semantics &&
2243 buffer_is_packing_standard(type, BufferPackingStd430))
2244 {
2245 // UBOs can support std430 with GL_EXT_scalar_block_layout.
2246 require_extension_internal("GL_EXT_scalar_block_layout");
2247 return "std430";
2248 }
2249 else if (!support_std430_without_scalar_layout && options.vulkan_semantics &&
2250 support_enhanced_layouts &&
2251 buffer_is_packing_standard(type, BufferPackingStd430EnhancedLayout))
2252 {
2253 // UBOs can support std430 with GL_EXT_scalar_block_layout.
2254 set_extended_decoration(type.self, SPIRVCrossDecorationExplicitOffset);
2255 require_extension_internal("GL_EXT_scalar_block_layout");
2256 return "std430";
2257 }
2258 else
2259 {
2260 SPIRV_CROSS_THROW("Buffer block cannot be expressed as any of std430, std140, scalar, even with enhanced "
2261 "layouts. You can try flattening this block to support a more flexible layout.");
2262 }
2263 }
2264
2265 void CompilerGLSL::emit_push_constant_block(const SPIRVariable &var)
2266 {
2267 if (flattened_buffer_blocks.count(var.self))
2268 emit_buffer_block_flattened(var);
2269 else if (options.vulkan_semantics)
2270 emit_push_constant_block_vulkan(var);
2271 else if (options.emit_push_constant_as_uniform_buffer)
2272 emit_buffer_block_native(var);
2273 else
2274 emit_push_constant_block_glsl(var);
2275 }
2276
2277 void CompilerGLSL::emit_push_constant_block_vulkan(const SPIRVariable &var)
2278 {
2279 emit_buffer_block(var);
2280 }
2281
2282 void CompilerGLSL::emit_push_constant_block_glsl(const SPIRVariable &var)
2283 {
2284 // OpenGL has no concept of push constant blocks, implement it as a uniform struct.
2285 auto &type = get<SPIRType>(var.basetype);
2286
2287 unset_decoration(var.self, DecorationBinding);
2288 unset_decoration(var.self, DecorationDescriptorSet);
2289
2290 #if 0
2291 if (flags & ((1ull << DecorationBinding) | (1ull << DecorationDescriptorSet)))
2292 SPIRV_CROSS_THROW("Push constant blocks cannot be compiled to GLSL with Binding or Set syntax. "
2293 "Remap to location with reflection API first or disable these decorations.");
2294 #endif
2295
2296 // We're emitting the push constant block as a regular struct, so disable the block qualifier temporarily.
2297 // Otherwise, we will end up emitting layout() qualifiers on naked structs which is not allowed.
2298 bool block_flag = has_decoration(type.self, DecorationBlock);
2299 unset_decoration(type.self, DecorationBlock);
2300
2301 emit_struct(type);
2302
2303 if (block_flag)
2304 set_decoration(type.self, DecorationBlock);
2305
2306 emit_uniform(var);
2307 statement("");
2308 }
2309
2310 void CompilerGLSL::emit_buffer_block(const SPIRVariable &var)
2311 {
2312 auto &type = get<SPIRType>(var.basetype);
2313 bool ubo_block = var.storage == StorageClassUniform && has_decoration(type.self, DecorationBlock);
2314
2315 if (flattened_buffer_blocks.count(var.self))
2316 emit_buffer_block_flattened(var);
2317 else if (is_legacy() || (!options.es && options.version == 130) ||
2318 (ubo_block && options.emit_uniform_buffer_as_plain_uniforms))
2319 emit_buffer_block_legacy(var);
2320 else
2321 emit_buffer_block_native(var);
2322 }
2323
2324 void CompilerGLSL::emit_buffer_block_legacy(const SPIRVariable &var)
2325 {
2326 auto &type = get<SPIRType>(var.basetype);
2327 bool ssbo = var.storage == StorageClassStorageBuffer ||
2328 ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
2329 if (ssbo)
2330 SPIRV_CROSS_THROW("SSBOs not supported in legacy targets.");
2331
2332 // We're emitting the push constant block as a regular struct, so disable the block qualifier temporarily.
2333 // Otherwise, we will end up emitting layout() qualifiers on naked structs which is not allowed.
2334 auto &block_flags = ir.meta[type.self].decoration.decoration_flags;
2335 bool block_flag = block_flags.get(DecorationBlock);
2336 block_flags.clear(DecorationBlock);
2337 emit_struct(type);
2338 if (block_flag)
2339 block_flags.set(DecorationBlock);
2340 emit_uniform(var);
2341 statement("");
2342 }
2343
2344 void CompilerGLSL::emit_buffer_reference_block(uint32_t type_id, bool forward_declaration)
2345 {
2346 auto &type = get<SPIRType>(type_id);
2347 string buffer_name;
2348
2349 if (forward_declaration && is_physical_pointer_to_buffer_block(type))
2350 {
2351 // Block names should never alias, but from HLSL input they kind of can because block types are reused for UAVs ...
2352 // Allow aliased name since we might be declaring the block twice. Once with buffer reference (forward declared) and one proper declaration.
2353 // The names must match up.
2354 buffer_name = to_name(type.self, false);
2355
2356 // Shaders never use the block by interface name, so we don't
2357 // have to track this other than updating name caches.
2358 // If we have a collision for any reason, just fallback immediately.
2359 if (ir.meta[type.self].decoration.alias.empty() ||
2360 block_ssbo_names.find(buffer_name) != end(block_ssbo_names) ||
2361 resource_names.find(buffer_name) != end(resource_names))
2362 {
2363 buffer_name = join("_", type.self);
2364 }
2365
2366 // Make sure we get something unique for both global name scope and block name scope.
2367 // See GLSL 4.5 spec: section 4.3.9 for details.
2368 add_variable(block_ssbo_names, resource_names, buffer_name);
2369
2370 // If for some reason buffer_name is an illegal name, make a final fallback to a workaround name.
2371 // This cannot conflict with anything else, so we're safe now.
2372 // We cannot reuse this fallback name in neither global scope (blocked by block_names) nor block name scope.
2373 if (buffer_name.empty())
2374 buffer_name = join("_", type.self);
2375
2376 block_names.insert(buffer_name);
2377 block_ssbo_names.insert(buffer_name);
2378
2379 // Ensure we emit the correct name when emitting non-forward pointer type.
2380 ir.meta[type.self].decoration.alias = buffer_name;
2381 }
2382 else
2383 {
2384 buffer_name = type_to_glsl(type);
2385 }
2386
2387 if (!forward_declaration)
2388 {
2389 auto itr = physical_storage_type_to_alignment.find(type_id);
2390 uint32_t alignment = 0;
2391 if (itr != physical_storage_type_to_alignment.end())
2392 alignment = itr->second.alignment;
2393
2394 if (is_physical_pointer_to_buffer_block(type))
2395 {
2396 SmallVector<std::string> attributes;
2397 attributes.push_back("buffer_reference");
2398 if (alignment)
2399 attributes.push_back(join("buffer_reference_align = ", alignment));
2400 attributes.push_back(buffer_to_packing_standard(type, true, true));
2401
2402 auto flags = ir.get_buffer_block_type_flags(type);
2403 string decorations;
2404 if (flags.get(DecorationRestrict))
2405 decorations += " restrict";
2406 if (flags.get(DecorationCoherent))
2407 decorations += " coherent";
2408 if (flags.get(DecorationNonReadable))
2409 decorations += " writeonly";
2410 if (flags.get(DecorationNonWritable))
2411 decorations += " readonly";
2412
2413 statement("layout(", merge(attributes), ")", decorations, " buffer ", buffer_name);
2414 }
2415 else
2416 {
2417 string packing_standard;
2418 if (type.basetype == SPIRType::Struct)
2419 {
2420 // The non-block type is embedded in a block, so we cannot use enhanced layouts :(
2421 packing_standard = buffer_to_packing_standard(type, true, false) + ", ";
2422 }
2423 else if (is_array(get_pointee_type(type)))
2424 {
2425 SPIRType wrap_type{OpTypeStruct};
2426 wrap_type.self = ir.increase_bound_by(1);
2427 wrap_type.member_types.push_back(get_pointee_type_id(type_id));
2428 ir.set_member_decoration(wrap_type.self, 0, DecorationOffset, 0);
2429 packing_standard = buffer_to_packing_standard(wrap_type, true, false) + ", ";
2430 }
2431
2432 if (alignment)
2433 statement("layout(", packing_standard, "buffer_reference, buffer_reference_align = ", alignment, ") buffer ", buffer_name);
2434 else
2435 statement("layout(", packing_standard, "buffer_reference) buffer ", buffer_name);
2436 }
2437
2438 begin_scope();
2439
2440 if (is_physical_pointer_to_buffer_block(type))
2441 {
2442 type.member_name_cache.clear();
2443
2444 uint32_t i = 0;
2445 for (auto &member : type.member_types)
2446 {
2447 add_member_name(type, i);
2448 emit_struct_member(type, member, i);
2449 i++;
2450 }
2451 }
2452 else
2453 {
2454 auto &pointee_type = get_pointee_type(type);
2455 statement(type_to_glsl(pointee_type), " value", type_to_array_glsl(pointee_type, 0), ";");
2456 }
2457
2458 end_scope_decl();
2459 statement("");
2460 }
2461 else
2462 {
2463 statement("layout(buffer_reference) buffer ", buffer_name, ";");
2464 }
2465 }
2466
2467 void CompilerGLSL::emit_buffer_block_native(const SPIRVariable &var)
2468 {
2469 auto &type = get<SPIRType>(var.basetype);
2470
2471 Bitset flags = ir.get_buffer_block_flags(var);
2472 bool ssbo = var.storage == StorageClassStorageBuffer || var.storage == StorageClassShaderRecordBufferKHR ||
2473 ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
2474 bool is_restrict = ssbo && flags.get(DecorationRestrict);
2475 bool is_writeonly = ssbo && flags.get(DecorationNonReadable);
2476 bool is_readonly = ssbo && flags.get(DecorationNonWritable);
2477 bool is_coherent = ssbo && flags.get(DecorationCoherent);
2478
2479 // Block names should never alias, but from HLSL input they kind of can because block types are reused for UAVs ...
2480 auto buffer_name = to_name(type.self, false);
2481
2482 auto &block_namespace = ssbo ? block_ssbo_names : block_ubo_names;
2483
2484 // Shaders never use the block by interface name, so we don't
2485 // have to track this other than updating name caches.
2486 // If we have a collision for any reason, just fallback immediately.
2487 if (ir.meta[type.self].decoration.alias.empty() || block_namespace.find(buffer_name) != end(block_namespace) ||
2488 resource_names.find(buffer_name) != end(resource_names))
2489 {
2490 buffer_name = get_block_fallback_name(var.self);
2491 }
2492
2493 // Make sure we get something unique for both global name scope and block name scope.
2494 // See GLSL 4.5 spec: section 4.3.9 for details.
2495 add_variable(block_namespace, resource_names, buffer_name);
2496
2497 // If for some reason buffer_name is an illegal name, make a final fallback to a workaround name.
2498 // This cannot conflict with anything else, so we're safe now.
2499 // We cannot reuse this fallback name in neither global scope (blocked by block_names) nor block name scope.
2500 if (buffer_name.empty())
2501 buffer_name = join("_", get<SPIRType>(var.basetype).self, "_", var.self);
2502
2503 block_names.insert(buffer_name);
2504 block_namespace.insert(buffer_name);
2505
2506 // Save for post-reflection later.
2507 declared_block_names[var.self] = buffer_name;
2508
2509 statement(layout_for_variable(var), is_coherent ? "coherent " : "", is_restrict ? "restrict " : "",
2510 is_writeonly ? "writeonly " : "", is_readonly ? "readonly " : "", ssbo ? "buffer " : "uniform ",
2511 buffer_name);
2512
2513 begin_scope();
2514
2515 type.member_name_cache.clear();
2516
2517 uint32_t i = 0;
2518 for (auto &member : type.member_types)
2519 {
2520 add_member_name(type, i);
2521 emit_struct_member(type, member, i);
2522 i++;
2523 }
2524
2525 // Don't declare empty blocks in GLSL, this is not allowed.
2526 if (type_is_empty(type) && !backend.supports_empty_struct)
2527 statement("int empty_struct_member;");
2528
2529 // var.self can be used as a backup name for the block name,
2530 // so we need to make sure we don't disturb the name here on a recompile.
2531 // It will need to be reset if we have to recompile.
2532 preserve_alias_on_reset(var.self);
2533 add_resource_name(var.self);
2534 end_scope_decl(to_name(var.self) + type_to_array_glsl(type, var.self));
2535 statement("");
2536 }
2537
2538 void CompilerGLSL::emit_buffer_block_flattened(const SPIRVariable &var)
2539 {
2540 auto &type = get<SPIRType>(var.basetype);
2541
2542 // Block names should never alias.
2543 auto buffer_name = to_name(type.self, false);
2544 size_t buffer_size = (get_declared_struct_size(type) + 15) / 16;
2545
2546 SPIRType::BaseType basic_type;
2547 if (get_common_basic_type(type, basic_type))
2548 {
2549 SPIRType tmp { OpTypeVector };
2550 tmp.basetype = basic_type;
2551 tmp.vecsize = 4;
2552 if (basic_type != SPIRType::Float && basic_type != SPIRType::Int && basic_type != SPIRType::UInt)
2553 SPIRV_CROSS_THROW("Basic types in a flattened UBO must be float, int or uint.");
2554
2555 auto flags = ir.get_buffer_block_flags(var);
2556 statement("uniform ", flags_to_qualifiers_glsl(tmp, flags), type_to_glsl(tmp), " ", buffer_name, "[",
2557 buffer_size, "];");
2558 }
2559 else
2560 SPIRV_CROSS_THROW("All basic types in a flattened block must be the same.");
2561 }
2562
2563 const char *CompilerGLSL::to_storage_qualifiers_glsl(const SPIRVariable &var)
2564 {
2565 auto &execution = get_entry_point();
2566
2567 if (subpass_input_is_framebuffer_fetch(var.self))
2568 return "";
2569
2570 if (var.storage == StorageClassInput || var.storage == StorageClassOutput)
2571 {
2572 if (is_legacy() && execution.model == ExecutionModelVertex)
2573 return var.storage == StorageClassInput ? "attribute " : "varying ";
2574 else if (is_legacy() && execution.model == ExecutionModelFragment)
2575 return "varying "; // Fragment outputs are renamed so they never hit this case.
2576 else if (execution.model == ExecutionModelFragment && var.storage == StorageClassOutput)
2577 {
2578 uint32_t loc = get_decoration(var.self, DecorationLocation);
2579 bool is_inout = location_is_framebuffer_fetch(loc);
2580 if (is_inout)
2581 return "inout ";
2582 else
2583 return "out ";
2584 }
2585 else
2586 return var.storage == StorageClassInput ? "in " : "out ";
2587 }
2588 else if (var.storage == StorageClassUniformConstant || var.storage == StorageClassUniform ||
2589 var.storage == StorageClassPushConstant || var.storage == StorageClassAtomicCounter)
2590 {
2591 return "uniform ";
2592 }
2593 else if (var.storage == StorageClassRayPayloadKHR)
2594 {
2595 return ray_tracing_is_khr ? "rayPayloadEXT " : "rayPayloadNV ";
2596 }
2597 else if (var.storage == StorageClassIncomingRayPayloadKHR)
2598 {
2599 return ray_tracing_is_khr ? "rayPayloadInEXT " : "rayPayloadInNV ";
2600 }
2601 else if (var.storage == StorageClassHitAttributeKHR)
2602 {
2603 return ray_tracing_is_khr ? "hitAttributeEXT " : "hitAttributeNV ";
2604 }
2605 else if (var.storage == StorageClassCallableDataKHR)
2606 {
2607 return ray_tracing_is_khr ? "callableDataEXT " : "callableDataNV ";
2608 }
2609 else if (var.storage == StorageClassIncomingCallableDataKHR)
2610 {
2611 return ray_tracing_is_khr ? "callableDataInEXT " : "callableDataInNV ";
2612 }
2613
2614 return "";
2615 }
2616
2617 void CompilerGLSL::emit_flattened_io_block_member(const std::string &basename, const SPIRType &type, const char *qual,
2618 const SmallVector<uint32_t> &indices)
2619 {
2620 uint32_t member_type_id = type.self;
2621 const SPIRType *member_type = &type;
2622 const SPIRType *parent_type = nullptr;
2623 auto flattened_name = basename;
2624 for (auto &index : indices)
2625 {
2626 flattened_name += "_";
2627 flattened_name += to_member_name(*member_type, index);
2628 parent_type = member_type;
2629 member_type_id = member_type->member_types[index];
2630 member_type = &get<SPIRType>(member_type_id);
2631 }
2632
2633 assert(member_type->basetype != SPIRType::Struct);
2634
2635 // We're overriding struct member names, so ensure we do so on the primary type.
2636 if (parent_type->type_alias)
2637 parent_type = &get<SPIRType>(parent_type->type_alias);
2638
2639 // Sanitize underscores because joining the two identifiers might create more than 1 underscore in a row,
2640 // which is not allowed.
2641 ParsedIR::sanitize_underscores(flattened_name);
2642
2643 uint32_t last_index = indices.back();
2644
2645 // Pass in the varying qualifier here so it will appear in the correct declaration order.
2646 // Replace member name while emitting it so it encodes both struct name and member name.
2647 auto backup_name = get_member_name(parent_type->self, last_index);
2648 auto member_name = to_member_name(*parent_type, last_index);
2649 set_member_name(parent_type->self, last_index, flattened_name);
2650 emit_struct_member(*parent_type, member_type_id, last_index, qual);
2651 // Restore member name.
2652 set_member_name(parent_type->self, last_index, member_name);
2653 }
2654
2655 void CompilerGLSL::emit_flattened_io_block_struct(const std::string &basename, const SPIRType &type, const char *qual,
2656 const SmallVector<uint32_t> &indices)
2657 {
2658 auto sub_indices = indices;
2659 sub_indices.push_back(0);
2660
2661 const SPIRType *member_type = &type;
2662 for (auto &index : indices)
2663 member_type = &get<SPIRType>(member_type->member_types[index]);
2664
2665 assert(member_type->basetype == SPIRType::Struct);
2666
2667 if (!member_type->array.empty())
2668 SPIRV_CROSS_THROW("Cannot flatten array of structs in I/O blocks.");
2669
2670 for (uint32_t i = 0; i < uint32_t(member_type->member_types.size()); i++)
2671 {
2672 sub_indices.back() = i;
2673 if (get<SPIRType>(member_type->member_types[i]).basetype == SPIRType::Struct)
2674 emit_flattened_io_block_struct(basename, type, qual, sub_indices);
2675 else
2676 emit_flattened_io_block_member(basename, type, qual, sub_indices);
2677 }
2678 }
2679
2680 void CompilerGLSL::emit_flattened_io_block(const SPIRVariable &var, const char *qual)
2681 {
2682 auto &var_type = get<SPIRType>(var.basetype);
2683 if (!var_type.array.empty())
2684 SPIRV_CROSS_THROW("Array of varying structs cannot be flattened to legacy-compatible varyings.");
2685
2686 // Emit flattened types based on the type alias. Normally, we are never supposed to emit
2687 // struct declarations for aliased types.
2688 auto &type = var_type.type_alias ? get<SPIRType>(var_type.type_alias) : var_type;
2689
2690 auto old_flags = ir.meta[type.self].decoration.decoration_flags;
2691 // Emit the members as if they are part of a block to get all qualifiers.
2692 ir.meta[type.self].decoration.decoration_flags.set(DecorationBlock);
2693
2694 type.member_name_cache.clear();
2695
2696 SmallVector<uint32_t> member_indices;
2697 member_indices.push_back(0);
2698 auto basename = to_name(var.self);
2699
2700 uint32_t i = 0;
2701 for (auto &member : type.member_types)
2702 {
2703 add_member_name(type, i);
2704 auto &membertype = get<SPIRType>(member);
2705
2706 member_indices.back() = i;
2707 if (membertype.basetype == SPIRType::Struct)
2708 emit_flattened_io_block_struct(basename, type, qual, member_indices);
2709 else
2710 emit_flattened_io_block_member(basename, type, qual, member_indices);
2711 i++;
2712 }
2713
2714 ir.meta[type.self].decoration.decoration_flags = old_flags;
2715
2716 // Treat this variable as fully flattened from now on.
2717 flattened_structs[var.self] = true;
2718 }
2719
2720 void CompilerGLSL::emit_interface_block(const SPIRVariable &var)
2721 {
2722 auto &type = get<SPIRType>(var.basetype);
2723
2724 if (var.storage == StorageClassInput && type.basetype == SPIRType::Double &&
2725 !options.es && options.version < 410)
2726 {
2727 require_extension_internal("GL_ARB_vertex_attrib_64bit");
2728 }
2729
2730 // Either make it plain in/out or in/out blocks depending on what shader is doing ...
2731 bool block = ir.meta[type.self].decoration.decoration_flags.get(DecorationBlock);
2732 const char *qual = to_storage_qualifiers_glsl(var);
2733
2734 if (block)
2735 {
2736 // ESSL earlier than 310 and GLSL earlier than 150 did not support
2737 // I/O variables which are struct types.
2738 // To support this, flatten the struct into separate varyings instead.
2739 if (options.force_flattened_io_blocks || (options.es && options.version < 310) ||
2740 (!options.es && options.version < 150))
2741 {
2742 // I/O blocks on ES require version 310 with Android Extension Pack extensions, or core version 320.
2743 // On desktop, I/O blocks were introduced with geometry shaders in GL 3.2 (GLSL 150).
2744 emit_flattened_io_block(var, qual);
2745 }
2746 else
2747 {
2748 if (options.es && options.version < 320)
2749 {
2750 // Geometry and tessellation extensions imply this extension.
2751 if (!has_extension("GL_EXT_geometry_shader") && !has_extension("GL_EXT_tessellation_shader"))
2752 require_extension_internal("GL_EXT_shader_io_blocks");
2753 }
2754
2755 // Workaround to make sure we can emit "patch in/out" correctly.
2756 fixup_io_block_patch_primitive_qualifiers(var);
2757
2758 // Block names should never alias.
2759 auto block_name = to_name(type.self, false);
2760
2761 // The namespace for I/O blocks is separate from other variables in GLSL.
2762 auto &block_namespace = type.storage == StorageClassInput ? block_input_names : block_output_names;
2763
2764 // Shaders never use the block by interface name, so we don't
2765 // have to track this other than updating name caches.
2766 if (block_name.empty() || block_namespace.find(block_name) != end(block_namespace))
2767 block_name = get_fallback_name(type.self);
2768 else
2769 block_namespace.insert(block_name);
2770
2771 // If for some reason buffer_name is an illegal name, make a final fallback to a workaround name.
2772 // This cannot conflict with anything else, so we're safe now.
2773 if (block_name.empty())
2774 block_name = join("_", get<SPIRType>(var.basetype).self, "_", var.self);
2775
2776 // Instance names cannot alias block names.
2777 resource_names.insert(block_name);
2778
2779 const char *block_qualifier;
2780 if (has_decoration(var.self, DecorationPatch))
2781 block_qualifier = "patch ";
2782 else if (has_decoration(var.self, DecorationPerPrimitiveEXT))
2783 block_qualifier = "perprimitiveEXT ";
2784 else if (has_decoration(var.self, DecorationPerVertexKHR))
2785 block_qualifier = "pervertexEXT ";
2786 else
2787 block_qualifier = "";
2788
2789 statement(layout_for_variable(var), block_qualifier, qual, block_name);
2790 begin_scope();
2791
2792 type.member_name_cache.clear();
2793
2794 uint32_t i = 0;
2795 for (auto &member : type.member_types)
2796 {
2797 add_member_name(type, i);
2798 emit_struct_member(type, member, i);
2799 i++;
2800 }
2801
2802 add_resource_name(var.self);
2803 end_scope_decl(join(to_name(var.self), type_to_array_glsl(type, var.self)));
2804 statement("");
2805 }
2806 }
2807 else
2808 {
2809 // ESSL earlier than 310 and GLSL earlier than 150 did not support
2810 // I/O variables which are struct types.
2811 // To support this, flatten the struct into separate varyings instead.
2812 if (type.basetype == SPIRType::Struct &&
2813 (options.force_flattened_io_blocks || (options.es && options.version < 310) ||
2814 (!options.es && options.version < 150)))
2815 {
2816 emit_flattened_io_block(var, qual);
2817 }
2818 else
2819 {
2820 add_resource_name(var.self);
2821
2822 // Legacy GLSL did not support int attributes, we automatically
2823 // declare them as float and cast them on load/store
2824 SPIRType newtype = type;
2825 if (is_legacy() && var.storage == StorageClassInput && type.basetype == SPIRType::Int)
2826 newtype.basetype = SPIRType::Float;
2827
2828 // Tessellation control and evaluation shaders must have either
2829 // gl_MaxPatchVertices or unsized arrays for input arrays.
2830 // Opt for unsized as it's the more "correct" variant to use.
2831 if (type.storage == StorageClassInput && !type.array.empty() &&
2832 !has_decoration(var.self, DecorationPatch) &&
2833 (get_entry_point().model == ExecutionModelTessellationControl ||
2834 get_entry_point().model == ExecutionModelTessellationEvaluation))
2835 {
2836 newtype.array.back() = 0;
2837 newtype.array_size_literal.back() = true;
2838 }
2839
2840 statement(layout_for_variable(var), to_qualifiers_glsl(var.self),
2841 variable_decl(newtype, to_name(var.self), var.self), ";");
2842 }
2843 }
2844 }
2845
2846 void CompilerGLSL::emit_uniform(const SPIRVariable &var)
2847 {
2848 auto &type = get<SPIRType>(var.basetype);
2849 if (type.basetype == SPIRType::Image && type.image.sampled == 2 && type.image.dim != DimSubpassData)
2850 {
2851 if (!options.es && options.version < 420)
2852 require_extension_internal("GL_ARB_shader_image_load_store");
2853 else if (options.es && options.version < 310)
2854 SPIRV_CROSS_THROW("At least ESSL 3.10 required for shader image load store.");
2855 }
2856
2857 add_resource_name(var.self);
2858 statement(layout_for_variable(var), variable_decl(var), ";");
2859 }
2860
2861 string CompilerGLSL::constant_value_macro_name(uint32_t id) const
2862 {
2863 return join("SPIRV_CROSS_CONSTANT_ID_", id);
2864 }
2865
2866 void CompilerGLSL::emit_specialization_constant_op(const SPIRConstantOp &constant)
2867 {
2868 auto &type = get<SPIRType>(constant.basetype);
2869 // This will break. It is bogus and should not be legal.
2870 if (type_is_top_level_block(type))
2871 return;
2872 add_resource_name(constant.self);
2873 auto name = to_name(constant.self);
2874 statement("const ", variable_decl(type, name), " = ", constant_op_expression(constant), ";");
2875 }
2876
2877 int CompilerGLSL::get_constant_mapping_to_workgroup_component(const SPIRConstant &c) const
2878 {
2879 auto &entry_point = get_entry_point();
2880 int index = -1;
2881
2882 // Need to redirect specialization constants which are used as WorkGroupSize to the builtin,
2883 // since the spec constant declarations are never explicitly declared.
2884 if (entry_point.workgroup_size.constant == 0 && entry_point.flags.get(ExecutionModeLocalSizeId))
2885 {
2886 if (c.self == entry_point.workgroup_size.id_x)
2887 index = 0;
2888 else if (c.self == entry_point.workgroup_size.id_y)
2889 index = 1;
2890 else if (c.self == entry_point.workgroup_size.id_z)
2891 index = 2;
2892 }
2893
2894 return index;
2895 }
2896
2897 void CompilerGLSL::emit_constant(const SPIRConstant &constant)
2898 {
2899 auto &type = get<SPIRType>(constant.constant_type);
2900
2901 // This will break. It is bogus and should not be legal.
2902 if (type_is_top_level_block(type))
2903 return;
2904
2905 SpecializationConstant wg_x, wg_y, wg_z;
2906 ID workgroup_size_id = get_work_group_size_specialization_constants(wg_x, wg_y, wg_z);
2907
2908 // This specialization constant is implicitly declared by emitting layout() in;
2909 if (constant.self == workgroup_size_id)
2910 return;
2911
2912 // These specialization constants are implicitly declared by emitting layout() in;
2913 // In legacy GLSL, we will still need to emit macros for these, so a layout() in; declaration
2914 // later can use macro overrides for work group size.
2915 bool is_workgroup_size_constant = ConstantID(constant.self) == wg_x.id || ConstantID(constant.self) == wg_y.id ||
2916 ConstantID(constant.self) == wg_z.id;
2917
2918 if (options.vulkan_semantics && is_workgroup_size_constant)
2919 {
2920 // Vulkan GLSL does not need to declare workgroup spec constants explicitly, it is handled in layout().
2921 return;
2922 }
2923 else if (!options.vulkan_semantics && is_workgroup_size_constant &&
2924 !has_decoration(constant.self, DecorationSpecId))
2925 {
2926 // Only bother declaring a workgroup size if it is actually a specialization constant, because we need macros.
2927 return;
2928 }
2929
2930 add_resource_name(constant.self);
2931 auto name = to_name(constant.self);
2932
2933 // Only scalars have constant IDs.
2934 if (has_decoration(constant.self, DecorationSpecId))
2935 {
2936 if (options.vulkan_semantics)
2937 {
2938 statement("layout(constant_id = ", get_decoration(constant.self, DecorationSpecId), ") const ",
2939 variable_decl(type, name), " = ", constant_expression(constant), ";");
2940 }
2941 else
2942 {
2943 const string &macro_name = constant.specialization_constant_macro_name;
2944 statement("#ifndef ", macro_name);
2945 statement("#define ", macro_name, " ", constant_expression(constant));
2946 statement("#endif");
2947
2948 // For workgroup size constants, only emit the macros.
2949 if (!is_workgroup_size_constant)
2950 statement("const ", variable_decl(type, name), " = ", macro_name, ";");
2951 }
2952 }
2953 else
2954 {
2955 statement("const ", variable_decl(type, name), " = ", constant_expression(constant), ";");
2956 }
2957 }
2958
2959 void CompilerGLSL::emit_entry_point_declarations()
2960 {
2961 }
2962
2963 void CompilerGLSL::replace_illegal_names(const unordered_set<string> &keywords)
2964 {
2965 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
2966 if (is_hidden_variable(var))
2967 return;
2968
2969 auto *meta = ir.find_meta(var.self);
2970 if (!meta)
2971 return;
2972
2973 auto &m = meta->decoration;
2974 if (keywords.find(m.alias) != end(keywords))
2975 m.alias = join("_", m.alias);
2976 });
2977
2978 ir.for_each_typed_id<SPIRFunction>([&](uint32_t, const SPIRFunction &func) {
2979 auto *meta = ir.find_meta(func.self);
2980 if (!meta)
2981 return;
2982
2983 auto &m = meta->decoration;
2984 if (keywords.find(m.alias) != end(keywords))
2985 m.alias = join("_", m.alias);
2986 });
2987
2988 ir.for_each_typed_id<SPIRType>([&](uint32_t, const SPIRType &type) {
2989 auto *meta = ir.find_meta(type.self);
2990 if (!meta)
2991 return;
2992
2993 auto &m = meta->decoration;
2994 if (keywords.find(m.alias) != end(keywords))
2995 m.alias = join("_", m.alias);
2996
2997 for (auto &memb : meta->members)
2998 if (keywords.find(memb.alias) != end(keywords))
2999 memb.alias = join("_", memb.alias);
3000 });
3001 }
3002
3003 void CompilerGLSL::replace_illegal_names()
3004 {
3005 // clang-format off
3006 static const unordered_set<string> keywords = {
3007 "abs", "acos", "acosh", "all", "any", "asin", "asinh", "atan", "atanh",
3008 "atomicAdd", "atomicCompSwap", "atomicCounter", "atomicCounterDecrement", "atomicCounterIncrement",
3009 "atomicExchange", "atomicMax", "atomicMin", "atomicOr", "atomicXor",
3010 "bitCount", "bitfieldExtract", "bitfieldInsert", "bitfieldReverse",
3011 "ceil", "cos", "cosh", "cross", "degrees",
3012 "dFdx", "dFdxCoarse", "dFdxFine",
3013 "dFdy", "dFdyCoarse", "dFdyFine",
3014 "distance", "dot", "EmitStreamVertex", "EmitVertex", "EndPrimitive", "EndStreamPrimitive", "equal", "exp", "exp2",
3015 "faceforward", "findLSB", "findMSB", "float16BitsToInt16", "float16BitsToUint16", "floatBitsToInt", "floatBitsToUint", "floor", "fma", "fract",
3016 "frexp", "fwidth", "fwidthCoarse", "fwidthFine",
3017 "greaterThan", "greaterThanEqual", "groupMemoryBarrier",
3018 "imageAtomicAdd", "imageAtomicAnd", "imageAtomicCompSwap", "imageAtomicExchange", "imageAtomicMax", "imageAtomicMin", "imageAtomicOr", "imageAtomicXor",
3019 "imageLoad", "imageSamples", "imageSize", "imageStore", "imulExtended", "int16BitsToFloat16", "intBitsToFloat", "interpolateAtOffset", "interpolateAtCentroid", "interpolateAtSample",
3020 "inverse", "inversesqrt", "isinf", "isnan", "ldexp", "length", "lessThan", "lessThanEqual", "log", "log2",
3021 "matrixCompMult", "max", "memoryBarrier", "memoryBarrierAtomicCounter", "memoryBarrierBuffer", "memoryBarrierImage", "memoryBarrierShared",
3022 "min", "mix", "mod", "modf", "noise", "noise1", "noise2", "noise3", "noise4", "normalize", "not", "notEqual",
3023 "outerProduct", "packDouble2x32", "packHalf2x16", "packInt2x16", "packInt4x16", "packSnorm2x16", "packSnorm4x8",
3024 "packUint2x16", "packUint4x16", "packUnorm2x16", "packUnorm4x8", "pow",
3025 "radians", "reflect", "refract", "round", "roundEven", "sign", "sin", "sinh", "smoothstep", "sqrt", "step",
3026 "tan", "tanh", "texelFetch", "texelFetchOffset", "texture", "textureGather", "textureGatherOffset", "textureGatherOffsets",
3027 "textureGrad", "textureGradOffset", "textureLod", "textureLodOffset", "textureOffset", "textureProj", "textureProjGrad",
3028 "textureProjGradOffset", "textureProjLod", "textureProjLodOffset", "textureProjOffset", "textureQueryLevels", "textureQueryLod", "textureSamples", "textureSize",
3029 "transpose", "trunc", "uaddCarry", "uint16BitsToFloat16", "uintBitsToFloat", "umulExtended", "unpackDouble2x32", "unpackHalf2x16", "unpackInt2x16", "unpackInt4x16",
3030 "unpackSnorm2x16", "unpackSnorm4x8", "unpackUint2x16", "unpackUint4x16", "unpackUnorm2x16", "unpackUnorm4x8", "usubBorrow",
3031
3032 "active", "asm", "atomic_uint", "attribute", "bool", "break", "buffer",
3033 "bvec2", "bvec3", "bvec4", "case", "cast", "centroid", "class", "coherent", "common", "const", "continue", "default", "discard",
3034 "dmat2", "dmat2x2", "dmat2x3", "dmat2x4", "dmat3", "dmat3x2", "dmat3x3", "dmat3x4", "dmat4", "dmat4x2", "dmat4x3", "dmat4x4",
3035 "do", "double", "dvec2", "dvec3", "dvec4", "else", "enum", "extern", "external", "false", "filter", "fixed", "flat", "float",
3036 "for", "fvec2", "fvec3", "fvec4", "goto", "half", "highp", "hvec2", "hvec3", "hvec4", "if", "iimage1D", "iimage1DArray",
3037 "iimage2D", "iimage2DArray", "iimage2DMS", "iimage2DMSArray", "iimage2DRect", "iimage3D", "iimageBuffer", "iimageCube",
3038 "iimageCubeArray", "image1D", "image1DArray", "image2D", "image2DArray", "image2DMS", "image2DMSArray", "image2DRect",
3039 "image3D", "imageBuffer", "imageCube", "imageCubeArray", "in", "inline", "inout", "input", "int", "interface", "invariant",
3040 "isampler1D", "isampler1DArray", "isampler2D", "isampler2DArray", "isampler2DMS", "isampler2DMSArray", "isampler2DRect",
3041 "isampler3D", "isamplerBuffer", "isamplerCube", "isamplerCubeArray", "ivec2", "ivec3", "ivec4", "layout", "long", "lowp",
3042 "mat2", "mat2x2", "mat2x3", "mat2x4", "mat3", "mat3x2", "mat3x3", "mat3x4", "mat4", "mat4x2", "mat4x3", "mat4x4", "mediump",
3043 "namespace", "noinline", "noperspective", "out", "output", "packed", "partition", "patch", "precise", "precision", "public", "readonly",
3044 "resource", "restrict", "return", "sample", "sampler1D", "sampler1DArray", "sampler1DArrayShadow",
3045 "sampler1DShadow", "sampler2D", "sampler2DArray", "sampler2DArrayShadow", "sampler2DMS", "sampler2DMSArray",
3046 "sampler2DRect", "sampler2DRectShadow", "sampler2DShadow", "sampler3D", "sampler3DRect", "samplerBuffer",
3047 "samplerCube", "samplerCubeArray", "samplerCubeArrayShadow", "samplerCubeShadow", "shared", "short", "sizeof", "smooth", "static",
3048 "struct", "subroutine", "superp", "switch", "template", "this", "true", "typedef", "uimage1D", "uimage1DArray", "uimage2D",
3049 "uimage2DArray", "uimage2DMS", "uimage2DMSArray", "uimage2DRect", "uimage3D", "uimageBuffer", "uimageCube",
3050 "uimageCubeArray", "uint", "uniform", "union", "unsigned", "usampler1D", "usampler1DArray", "usampler2D", "usampler2DArray",
3051 "usampler2DMS", "usampler2DMSArray", "usampler2DRect", "usampler3D", "usamplerBuffer", "usamplerCube",
3052 "usamplerCubeArray", "using", "uvec2", "uvec3", "uvec4", "varying", "vec2", "vec3", "vec4", "void", "volatile",
3053 "while", "writeonly",
3054 };
3055 // clang-format on
3056
3057 replace_illegal_names(keywords);
3058 }
3059
3060 void CompilerGLSL::replace_fragment_output(SPIRVariable &var)
3061 {
3062 auto &m = ir.meta[var.self].decoration;
3063 uint32_t location = 0;
3064 if (m.decoration_flags.get(DecorationLocation))
3065 location = m.location;
3066
3067 // If our variable is arrayed, we must not emit the array part of this as the SPIR-V will
3068 // do the access chain part of this for us.
3069 auto &type = get<SPIRType>(var.basetype);
3070
3071 if (type.array.empty())
3072 {
3073 // Redirect the write to a specific render target in legacy GLSL.
3074 m.alias = join("gl_FragData[", location, "]");
3075
3076 if (is_legacy_es() && location != 0)
3077 require_extension_internal("GL_EXT_draw_buffers");
3078 }
3079 else if (type.array.size() == 1)
3080 {
3081 // If location is non-zero, we probably have to add an offset.
3082 // This gets really tricky since we'd have to inject an offset in the access chain.
3083 // FIXME: This seems like an extremely odd-ball case, so it's probably fine to leave it like this for now.
3084 m.alias = "gl_FragData";
3085 if (location != 0)
3086 SPIRV_CROSS_THROW("Arrayed output variable used, but location is not 0. "
3087 "This is unimplemented in SPIRV-Cross.");
3088
3089 if (is_legacy_es())
3090 require_extension_internal("GL_EXT_draw_buffers");
3091 }
3092 else
3093 SPIRV_CROSS_THROW("Array-of-array output variable used. This cannot be implemented in legacy GLSL.");
3094
3095 var.compat_builtin = true; // We don't want to declare this variable, but use the name as-is.
3096 }
3097
3098 void CompilerGLSL::replace_fragment_outputs()
3099 {
3100 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
3101 auto &type = this->get<SPIRType>(var.basetype);
3102
3103 if (!is_builtin_variable(var) && !var.remapped_variable && type.pointer && var.storage == StorageClassOutput)
3104 replace_fragment_output(var);
3105 });
3106 }
3107
3108 string CompilerGLSL::remap_swizzle(const SPIRType &out_type, uint32_t input_components, const string &expr)
3109 {
3110 if (out_type.vecsize == input_components)
3111 return expr;
3112 else if (input_components == 1 && !backend.can_swizzle_scalar)
3113 return join(type_to_glsl(out_type), "(", expr, ")");
3114 else
3115 {
3116 // FIXME: This will not work with packed expressions.
3117 auto e = enclose_expression(expr) + ".";
3118 // Just clamp the swizzle index if we have more outputs than inputs.
3119 for (uint32_t c = 0; c < out_type.vecsize; c++)
3120 e += index_to_swizzle(min(c, input_components - 1));
3121 if (backend.swizzle_is_function && out_type.vecsize > 1)
3122 e += "()";
3123
3124 remove_duplicate_swizzle(e);
3125 return e;
3126 }
3127 }
3128
3129 void CompilerGLSL::emit_pls()
3130 {
3131 auto &execution = get_entry_point();
3132 if (execution.model != ExecutionModelFragment)
3133 SPIRV_CROSS_THROW("Pixel local storage only supported in fragment shaders.");
3134
3135 if (!options.es)
3136 SPIRV_CROSS_THROW("Pixel local storage only supported in OpenGL ES.");
3137
3138 if (options.version < 300)
3139 SPIRV_CROSS_THROW("Pixel local storage only supported in ESSL 3.0 and above.");
3140
3141 if (!pls_inputs.empty())
3142 {
3143 statement("__pixel_local_inEXT _PLSIn");
3144 begin_scope();
3145 for (auto &input : pls_inputs)
3146 statement(pls_decl(input), ";");
3147 end_scope_decl();
3148 statement("");
3149 }
3150
3151 if (!pls_outputs.empty())
3152 {
3153 statement("__pixel_local_outEXT _PLSOut");
3154 begin_scope();
3155 for (auto &output : pls_outputs)
3156 statement(pls_decl(output), ";");
3157 end_scope_decl();
3158 statement("");
3159 }
3160 }
3161
3162 void CompilerGLSL::fixup_image_load_store_access()
3163 {
3164 if (!options.enable_storage_image_qualifier_deduction)
3165 return;
3166
3167 ir.for_each_typed_id<SPIRVariable>([&](uint32_t var, const SPIRVariable &) {
3168 auto &vartype = expression_type(var);
3169 if (vartype.basetype == SPIRType::Image && vartype.image.sampled == 2)
3170 {
3171 // Very old glslangValidator and HLSL compilers do not emit required qualifiers here.
3172 // Solve this by making the image access as restricted as possible and loosen up if we need to.
3173 // If any no-read/no-write flags are actually set, assume that the compiler knows what it's doing.
3174
3175 if (!has_decoration(var, DecorationNonWritable) && !has_decoration(var, DecorationNonReadable))
3176 {
3177 set_decoration(var, DecorationNonWritable);
3178 set_decoration(var, DecorationNonReadable);
3179 }
3180 }
3181 });
3182 }
3183
3184 static bool is_block_builtin(BuiltIn builtin)
3185 {
3186 return builtin == BuiltInPosition || builtin == BuiltInPointSize || builtin == BuiltInClipDistance ||
3187 builtin == BuiltInCullDistance;
3188 }
3189
3190 bool CompilerGLSL::should_force_emit_builtin_block(StorageClass storage)
3191 {
3192 // If the builtin block uses XFB, we need to force explicit redeclaration of the builtin block.
3193
3194 if (storage != StorageClassOutput)
3195 return false;
3196 bool should_force = false;
3197
3198 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
3199 if (should_force)
3200 return;
3201
3202 auto &type = this->get<SPIRType>(var.basetype);
3203 bool block = has_decoration(type.self, DecorationBlock);
3204 if (var.storage == storage && block && is_builtin_variable(var))
3205 {
3206 uint32_t member_count = uint32_t(type.member_types.size());
3207 for (uint32_t i = 0; i < member_count; i++)
3208 {
3209 if (has_member_decoration(type.self, i, DecorationBuiltIn) &&
3210 is_block_builtin(BuiltIn(get_member_decoration(type.self, i, DecorationBuiltIn))) &&
3211 has_member_decoration(type.self, i, DecorationOffset))
3212 {
3213 should_force = true;
3214 }
3215 }
3216 }
3217 else if (var.storage == storage && !block && is_builtin_variable(var))
3218 {
3219 if (is_block_builtin(BuiltIn(get_decoration(type.self, DecorationBuiltIn))) &&
3220 has_decoration(var.self, DecorationOffset))
3221 {
3222 should_force = true;
3223 }
3224 }
3225 });
3226
3227 // If we're declaring clip/cull planes with control points we need to force block declaration.
3228 if ((get_execution_model() == ExecutionModelTessellationControl ||
3229 get_execution_model() == ExecutionModelMeshEXT) &&
3230 (clip_distance_count || cull_distance_count))
3231 {
3232 should_force = true;
3233 }
3234
3235 // Either glslang bug or oversight, but global invariant position does not work in mesh shaders.
3236 if (get_execution_model() == ExecutionModelMeshEXT && position_invariant)
3237 should_force = true;
3238
3239 return should_force;
3240 }
3241
3242 void CompilerGLSL::fixup_implicit_builtin_block_names(ExecutionModel model)
3243 {
3244 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
3245 auto &type = this->get<SPIRType>(var.basetype);
3246 bool block = has_decoration(type.self, DecorationBlock);
3247 if ((var.storage == StorageClassOutput || var.storage == StorageClassInput) && block &&
3248 is_builtin_variable(var))
3249 {
3250 if (model != ExecutionModelMeshEXT)
3251 {
3252 // Make sure the array has a supported name in the code.
3253 if (var.storage == StorageClassOutput)
3254 set_name(var.self, "gl_out");
3255 else if (var.storage == StorageClassInput)
3256 set_name(var.self, "gl_in");
3257 }
3258 else
3259 {
3260 auto flags = get_buffer_block_flags(var.self);
3261 if (flags.get(DecorationPerPrimitiveEXT))
3262 {
3263 set_name(var.self, "gl_MeshPrimitivesEXT");
3264 set_name(type.self, "gl_MeshPerPrimitiveEXT");
3265 }
3266 else
3267 {
3268 set_name(var.self, "gl_MeshVerticesEXT");
3269 set_name(type.self, "gl_MeshPerVertexEXT");
3270 }
3271 }
3272 }
3273
3274 if (model == ExecutionModelMeshEXT && var.storage == StorageClassOutput && !block)
3275 {
3276 auto *m = ir.find_meta(var.self);
3277 if (m && m->decoration.builtin)
3278 {
3279 auto builtin_type = m->decoration.builtin_type;
3280 if (builtin_type == BuiltInPrimitivePointIndicesEXT)
3281 set_name(var.self, "gl_PrimitivePointIndicesEXT");
3282 else if (builtin_type == BuiltInPrimitiveLineIndicesEXT)
3283 set_name(var.self, "gl_PrimitiveLineIndicesEXT");
3284 else if (builtin_type == BuiltInPrimitiveTriangleIndicesEXT)
3285 set_name(var.self, "gl_PrimitiveTriangleIndicesEXT");
3286 }
3287 }
3288 });
3289 }
3290
3291 void CompilerGLSL::emit_declared_builtin_block(StorageClass storage, ExecutionModel model)
3292 {
3293 Bitset emitted_builtins;
3294 Bitset global_builtins;
3295 const SPIRVariable *block_var = nullptr;
3296 bool emitted_block = false;
3297
3298 // Need to use declared size in the type.
3299 // These variables might have been declared, but not statically used, so we haven't deduced their size yet.
3300 uint32_t cull_distance_size = 0;
3301 uint32_t clip_distance_size = 0;
3302
3303 bool have_xfb_buffer_stride = false;
3304 bool have_geom_stream = false;
3305 bool have_any_xfb_offset = false;
3306 uint32_t xfb_stride = 0, xfb_buffer = 0, geom_stream = 0;
3307 std::unordered_map<uint32_t, uint32_t> builtin_xfb_offsets;
3308
3309 const auto builtin_is_per_vertex_set = [](BuiltIn builtin) -> bool {
3310 return builtin == BuiltInPosition || builtin == BuiltInPointSize ||
3311 builtin == BuiltInClipDistance || builtin == BuiltInCullDistance;
3312 };
3313
3314 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
3315 auto &type = this->get<SPIRType>(var.basetype);
3316 bool block = has_decoration(type.self, DecorationBlock);
3317 Bitset builtins;
3318
3319 if (var.storage == storage && block && is_builtin_variable(var))
3320 {
3321 uint32_t index = 0;
3322 for (auto &m : ir.meta[type.self].members)
3323 {
3324 if (m.builtin && builtin_is_per_vertex_set(m.builtin_type))
3325 {
3326 builtins.set(m.builtin_type);
3327 if (m.builtin_type == BuiltInCullDistance)
3328 cull_distance_size = to_array_size_literal(this->get<SPIRType>(type.member_types[index]));
3329 else if (m.builtin_type == BuiltInClipDistance)
3330 clip_distance_size = to_array_size_literal(this->get<SPIRType>(type.member_types[index]));
3331
3332 if (is_block_builtin(m.builtin_type) && m.decoration_flags.get(DecorationOffset))
3333 {
3334 have_any_xfb_offset = true;
3335 builtin_xfb_offsets[m.builtin_type] = m.offset;
3336 }
3337
3338 if (is_block_builtin(m.builtin_type) && m.decoration_flags.get(DecorationStream))
3339 {
3340 uint32_t stream = m.stream;
3341 if (have_geom_stream && geom_stream != stream)
3342 SPIRV_CROSS_THROW("IO block member Stream mismatch.");
3343 have_geom_stream = true;
3344 geom_stream = stream;
3345 }
3346 }
3347 index++;
3348 }
3349
3350 if (storage == StorageClassOutput && has_decoration(var.self, DecorationXfbBuffer) &&
3351 has_decoration(var.self, DecorationXfbStride))
3352 {
3353 uint32_t buffer_index = get_decoration(var.self, DecorationXfbBuffer);
3354 uint32_t stride = get_decoration(var.self, DecorationXfbStride);
3355 if (have_xfb_buffer_stride && buffer_index != xfb_buffer)
3356 SPIRV_CROSS_THROW("IO block member XfbBuffer mismatch.");
3357 if (have_xfb_buffer_stride && stride != xfb_stride)
3358 SPIRV_CROSS_THROW("IO block member XfbBuffer mismatch.");
3359 have_xfb_buffer_stride = true;
3360 xfb_buffer = buffer_index;
3361 xfb_stride = stride;
3362 }
3363
3364 if (storage == StorageClassOutput && has_decoration(var.self, DecorationStream))
3365 {
3366 uint32_t stream = get_decoration(var.self, DecorationStream);
3367 if (have_geom_stream && geom_stream != stream)
3368 SPIRV_CROSS_THROW("IO block member Stream mismatch.");
3369 have_geom_stream = true;
3370 geom_stream = stream;
3371 }
3372 }
3373 else if (var.storage == storage && !block && is_builtin_variable(var))
3374 {
3375 // While we're at it, collect all declared global builtins (HLSL mostly ...).
3376 auto &m = ir.meta[var.self].decoration;
3377 if (m.builtin && builtin_is_per_vertex_set(m.builtin_type))
3378 {
3379 // For mesh/tesc output, Clip/Cull is an array-of-array. Look at innermost array type
3380 // for correct result.
3381 global_builtins.set(m.builtin_type);
3382 if (m.builtin_type == BuiltInCullDistance)
3383 cull_distance_size = to_array_size_literal(type, 0);
3384 else if (m.builtin_type == BuiltInClipDistance)
3385 clip_distance_size = to_array_size_literal(type, 0);
3386
3387 if (is_block_builtin(m.builtin_type) && m.decoration_flags.get(DecorationXfbStride) &&
3388 m.decoration_flags.get(DecorationXfbBuffer) && m.decoration_flags.get(DecorationOffset))
3389 {
3390 have_any_xfb_offset = true;
3391 builtin_xfb_offsets[m.builtin_type] = m.offset;
3392 uint32_t buffer_index = m.xfb_buffer;
3393 uint32_t stride = m.xfb_stride;
3394 if (have_xfb_buffer_stride && buffer_index != xfb_buffer)
3395 SPIRV_CROSS_THROW("IO block member XfbBuffer mismatch.");
3396 if (have_xfb_buffer_stride && stride != xfb_stride)
3397 SPIRV_CROSS_THROW("IO block member XfbBuffer mismatch.");
3398 have_xfb_buffer_stride = true;
3399 xfb_buffer = buffer_index;
3400 xfb_stride = stride;
3401 }
3402
3403 if (is_block_builtin(m.builtin_type) && m.decoration_flags.get(DecorationStream))
3404 {
3405 uint32_t stream = get_decoration(var.self, DecorationStream);
3406 if (have_geom_stream && geom_stream != stream)
3407 SPIRV_CROSS_THROW("IO block member Stream mismatch.");
3408 have_geom_stream = true;
3409 geom_stream = stream;
3410 }
3411 }
3412 }
3413
3414 if (builtins.empty())
3415 return;
3416
3417 if (emitted_block)
3418 SPIRV_CROSS_THROW("Cannot use more than one builtin I/O block.");
3419
3420 emitted_builtins = builtins;
3421 emitted_block = true;
3422 block_var = &var;
3423 });
3424
3425 global_builtins =
3426 Bitset(global_builtins.get_lower() & ((1ull << BuiltInPosition) | (1ull << BuiltInPointSize) |
3427 (1ull << BuiltInClipDistance) | (1ull << BuiltInCullDistance)));
3428
3429 // Try to collect all other declared builtins.
3430 if (!emitted_block)
3431 emitted_builtins = global_builtins;
3432
3433 // Can't declare an empty interface block.
3434 if (emitted_builtins.empty())
3435 return;
3436
3437 if (storage == StorageClassOutput)
3438 {
3439 SmallVector<string> attr;
3440 if (have_xfb_buffer_stride && have_any_xfb_offset)
3441 {
3442 if (!options.es)
3443 {
3444 if (options.version < 440 && options.version >= 140)
3445 require_extension_internal("GL_ARB_enhanced_layouts");
3446 else if (options.version < 140)
3447 SPIRV_CROSS_THROW("Component decoration is not supported in targets below GLSL 1.40.");
3448 if (!options.es && options.version < 440)
3449 require_extension_internal("GL_ARB_enhanced_layouts");
3450 }
3451 else if (options.es)
3452 SPIRV_CROSS_THROW("Need GL_ARB_enhanced_layouts for xfb_stride or xfb_buffer.");
3453 attr.push_back(join("xfb_buffer = ", xfb_buffer, ", xfb_stride = ", xfb_stride));
3454 }
3455
3456 if (have_geom_stream)
3457 {
3458 if (get_execution_model() != ExecutionModelGeometry)
3459 SPIRV_CROSS_THROW("Geometry streams can only be used in geometry shaders.");
3460 if (options.es)
3461 SPIRV_CROSS_THROW("Multiple geometry streams not supported in ESSL.");
3462 if (options.version < 400)
3463 require_extension_internal("GL_ARB_transform_feedback3");
3464 attr.push_back(join("stream = ", geom_stream));
3465 }
3466
3467 if (model == ExecutionModelMeshEXT)
3468 statement("out gl_MeshPerVertexEXT");
3469 else if (!attr.empty())
3470 statement("layout(", merge(attr), ") out gl_PerVertex");
3471 else
3472 statement("out gl_PerVertex");
3473 }
3474 else
3475 {
3476 // If we have passthrough, there is no way PerVertex cannot be passthrough.
3477 if (get_entry_point().geometry_passthrough)
3478 statement("layout(passthrough) in gl_PerVertex");
3479 else
3480 statement("in gl_PerVertex");
3481 }
3482
3483 begin_scope();
3484 if (emitted_builtins.get(BuiltInPosition))
3485 {
3486 auto itr = builtin_xfb_offsets.find(BuiltInPosition);
3487 if (itr != end(builtin_xfb_offsets))
3488 statement("layout(xfb_offset = ", itr->second, ") vec4 gl_Position;");
3489 else if (position_invariant)
3490 statement("invariant vec4 gl_Position;");
3491 else
3492 statement("vec4 gl_Position;");
3493 }
3494
3495 if (emitted_builtins.get(BuiltInPointSize))
3496 {
3497 auto itr = builtin_xfb_offsets.find(BuiltInPointSize);
3498 if (itr != end(builtin_xfb_offsets))
3499 statement("layout(xfb_offset = ", itr->second, ") float gl_PointSize;");
3500 else
3501 statement("float gl_PointSize;");
3502 }
3503
3504 if (emitted_builtins.get(BuiltInClipDistance))
3505 {
3506 auto itr = builtin_xfb_offsets.find(BuiltInClipDistance);
3507 if (itr != end(builtin_xfb_offsets))
3508 statement("layout(xfb_offset = ", itr->second, ") float gl_ClipDistance[", clip_distance_size, "];");
3509 else
3510 statement("float gl_ClipDistance[", clip_distance_size, "];");
3511 }
3512
3513 if (emitted_builtins.get(BuiltInCullDistance))
3514 {
3515 auto itr = builtin_xfb_offsets.find(BuiltInCullDistance);
3516 if (itr != end(builtin_xfb_offsets))
3517 statement("layout(xfb_offset = ", itr->second, ") float gl_CullDistance[", cull_distance_size, "];");
3518 else
3519 statement("float gl_CullDistance[", cull_distance_size, "];");
3520 }
3521
3522 bool builtin_array = model == ExecutionModelTessellationControl ||
3523 (model == ExecutionModelMeshEXT && storage == StorageClassOutput) ||
3524 (model == ExecutionModelGeometry && storage == StorageClassInput) ||
3525 (model == ExecutionModelTessellationEvaluation && storage == StorageClassInput);
3526
3527 if (builtin_array)
3528 {
3529 const char *instance_name;
3530 if (model == ExecutionModelMeshEXT)
3531 instance_name = "gl_MeshVerticesEXT"; // Per primitive is never synthesized.
3532 else
3533 instance_name = storage == StorageClassInput ? "gl_in" : "gl_out";
3534
3535 if (model == ExecutionModelTessellationControl && storage == StorageClassOutput)
3536 end_scope_decl(join(instance_name, "[", get_entry_point().output_vertices, "]"));
3537 else
3538 end_scope_decl(join(instance_name, "[]"));
3539 }
3540 else
3541 end_scope_decl();
3542 statement("");
3543 }
3544
3545 bool CompilerGLSL::variable_is_lut(const SPIRVariable &var) const
3546 {
3547 bool statically_assigned = var.statically_assigned && var.static_expression != ID(0) && var.remapped_variable;
3548
3549 if (statically_assigned)
3550 {
3551 auto *constant = maybe_get<SPIRConstant>(var.static_expression);
3552 if (constant && constant->is_used_as_lut)
3553 return true;
3554 }
3555
3556 return false;
3557 }
3558
3559 void CompilerGLSL::emit_resources()
3560 {
3561 auto &execution = get_entry_point();
3562
3563 replace_illegal_names();
3564
3565 // Legacy GL uses gl_FragData[], redeclare all fragment outputs
3566 // with builtins.
3567 if (execution.model == ExecutionModelFragment && is_legacy())
3568 replace_fragment_outputs();
3569
3570 // Emit PLS blocks if we have such variables.
3571 if (!pls_inputs.empty() || !pls_outputs.empty())
3572 emit_pls();
3573
3574 switch (execution.model)
3575 {
3576 case ExecutionModelGeometry:
3577 case ExecutionModelTessellationControl:
3578 case ExecutionModelTessellationEvaluation:
3579 case ExecutionModelMeshEXT:
3580 fixup_implicit_builtin_block_names(execution.model);
3581 break;
3582
3583 default:
3584 break;
3585 }
3586
3587 bool global_invariant_position = position_invariant && (options.es || options.version >= 120);
3588
3589 // Emit custom gl_PerVertex for SSO compatibility.
3590 if (options.separate_shader_objects && !options.es && execution.model != ExecutionModelFragment)
3591 {
3592 switch (execution.model)
3593 {
3594 case ExecutionModelGeometry:
3595 case ExecutionModelTessellationControl:
3596 case ExecutionModelTessellationEvaluation:
3597 emit_declared_builtin_block(StorageClassInput, execution.model);
3598 emit_declared_builtin_block(StorageClassOutput, execution.model);
3599 global_invariant_position = false;
3600 break;
3601
3602 case ExecutionModelVertex:
3603 case ExecutionModelMeshEXT:
3604 emit_declared_builtin_block(StorageClassOutput, execution.model);
3605 global_invariant_position = false;
3606 break;
3607
3608 default:
3609 break;
3610 }
3611 }
3612 else if (should_force_emit_builtin_block(StorageClassOutput))
3613 {
3614 emit_declared_builtin_block(StorageClassOutput, execution.model);
3615 global_invariant_position = false;
3616 }
3617 else if (execution.geometry_passthrough)
3618 {
3619 // Need to declare gl_in with Passthrough.
3620 // If we're doing passthrough, we cannot emit an output block, so the output block test above will never pass.
3621 emit_declared_builtin_block(StorageClassInput, execution.model);
3622 }
3623 else
3624 {
3625 // Need to redeclare clip/cull distance with explicit size to use them.
3626 // SPIR-V mandates these builtins have a size declared.
3627 const char *storage = execution.model == ExecutionModelFragment ? "in" : "out";
3628 if (clip_distance_count != 0)
3629 statement(storage, " float gl_ClipDistance[", clip_distance_count, "];");
3630 if (cull_distance_count != 0)
3631 statement(storage, " float gl_CullDistance[", cull_distance_count, "];");
3632 if (clip_distance_count != 0 || cull_distance_count != 0)
3633 statement("");
3634 }
3635
3636 if (global_invariant_position)
3637 {
3638 statement("invariant gl_Position;");
3639 statement("");
3640 }
3641
3642 bool emitted = false;
3643
3644 if (ir.addressing_model == AddressingModelPhysicalStorageBuffer64)
3645 {
3646 // Output buffer reference block forward declarations.
3647 ir.for_each_typed_id<SPIRType>([&](uint32_t id, SPIRType &type)
3648 {
3649 if (is_physical_pointer(type))
3650 {
3651 bool emit_type = true;
3652 if (!is_physical_pointer_to_buffer_block(type))
3653 {
3654 // Only forward-declare if we intend to emit it in the non_block_pointer types.
3655 // Otherwise, these are just "benign" pointer types that exist as a result of access chains.
3656 emit_type = std::find(physical_storage_non_block_pointer_types.begin(),
3657 physical_storage_non_block_pointer_types.end(),
3658 id) != physical_storage_non_block_pointer_types.end();
3659 }
3660
3661 if (emit_type)
3662 {
3663 emit_buffer_reference_block(id, true);
3664 emitted = true;
3665 }
3666 }
3667 });
3668 }
3669
3670 if (emitted)
3671 statement("");
3672 emitted = false;
3673
3674 // If emitted Vulkan GLSL,
3675 // emit specialization constants as actual floats,
3676 // spec op expressions will redirect to the constant name.
3677 //
3678 {
3679 auto loop_lock = ir.create_loop_hard_lock();
3680 for (auto &id_ : ir.ids_for_constant_undef_or_type)
3681 {
3682 auto &id = ir.ids[id_];
3683
3684 // Skip declaring any bogus constants or undefs which use block types.
3685 // We don't declare block types directly, so this will never work.
3686 // Should not be legal SPIR-V, so this is considered a workaround.
3687
3688 if (id.get_type() == TypeConstant)
3689 {
3690 auto &c = id.get<SPIRConstant>();
3691
3692 bool needs_declaration = c.specialization || c.is_used_as_lut;
3693
3694 if (needs_declaration)
3695 {
3696 if (!options.vulkan_semantics && c.specialization)
3697 {
3698 c.specialization_constant_macro_name =
3699 constant_value_macro_name(get_decoration(c.self, DecorationSpecId));
3700 }
3701 emit_constant(c);
3702 emitted = true;
3703 }
3704 }
3705 else if (id.get_type() == TypeConstantOp)
3706 {
3707 emit_specialization_constant_op(id.get<SPIRConstantOp>());
3708 emitted = true;
3709 }
3710 else if (id.get_type() == TypeType)
3711 {
3712 auto *type = &id.get<SPIRType>();
3713
3714 bool is_natural_struct = type->basetype == SPIRType::Struct && type->array.empty() && !type->pointer &&
3715 (!has_decoration(type->self, DecorationBlock) &&
3716 !has_decoration(type->self, DecorationBufferBlock));
3717
3718 // Special case, ray payload and hit attribute blocks are not really blocks, just regular structs.
3719 if (type->basetype == SPIRType::Struct && type->pointer &&
3720 has_decoration(type->self, DecorationBlock) &&
3721 (type->storage == StorageClassRayPayloadKHR || type->storage == StorageClassIncomingRayPayloadKHR ||
3722 type->storage == StorageClassHitAttributeKHR))
3723 {
3724 type = &get<SPIRType>(type->parent_type);
3725 is_natural_struct = true;
3726 }
3727
3728 if (is_natural_struct)
3729 {
3730 if (emitted)
3731 statement("");
3732 emitted = false;
3733
3734 emit_struct(*type);
3735 }
3736 }
3737 else if (id.get_type() == TypeUndef)
3738 {
3739 auto &undef = id.get<SPIRUndef>();
3740 auto &type = this->get<SPIRType>(undef.basetype);
3741 // OpUndef can be void for some reason ...
3742 if (type.basetype == SPIRType::Void)
3743 continue;
3744
3745 // This will break. It is bogus and should not be legal.
3746 if (type_is_top_level_block(type))
3747 continue;
3748
3749 string initializer;
3750 if (options.force_zero_initialized_variables && type_can_zero_initialize(type))
3751 initializer = join(" = ", to_zero_initialized_expression(undef.basetype));
3752
3753 // FIXME: If used in a constant, we must declare it as one.
3754 statement(variable_decl(type, to_name(undef.self), undef.self), initializer, ";");
3755 emitted = true;
3756 }
3757 }
3758 }
3759
3760 if (emitted)
3761 statement("");
3762
3763 // If we needed to declare work group size late, check here.
3764 // If the work group size depends on a specialization constant, we need to declare the layout() block
3765 // after constants (and their macros) have been declared.
3766 if (execution.model == ExecutionModelGLCompute && !options.vulkan_semantics &&
3767 (execution.workgroup_size.constant != 0 || execution.flags.get(ExecutionModeLocalSizeId)))
3768 {
3769 SpecializationConstant wg_x, wg_y, wg_z;
3770 get_work_group_size_specialization_constants(wg_x, wg_y, wg_z);
3771
3772 if ((wg_x.id != ConstantID(0)) || (wg_y.id != ConstantID(0)) || (wg_z.id != ConstantID(0)))
3773 {
3774 SmallVector<string> inputs;
3775 build_workgroup_size(inputs, wg_x, wg_y, wg_z);
3776 statement("layout(", merge(inputs), ") in;");
3777 statement("");
3778 }
3779 }
3780
3781 emitted = false;
3782
3783 if (ir.addressing_model == AddressingModelPhysicalStorageBuffer64)
3784 {
3785 // Output buffer reference blocks.
3786 // Buffer reference blocks can reference themselves to support things like linked lists.
3787 for (auto type : physical_storage_non_block_pointer_types)
3788 emit_buffer_reference_block(type, false);
3789
3790 ir.for_each_typed_id<SPIRType>([&](uint32_t id, SPIRType &type) {
3791 if (is_physical_pointer_to_buffer_block(type))
3792 emit_buffer_reference_block(id, false);
3793 });
3794 }
3795
3796 // Output UBOs and SSBOs
3797 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
3798 auto &type = this->get<SPIRType>(var.basetype);
3799
3800 bool is_block_storage = type.storage == StorageClassStorageBuffer || type.storage == StorageClassUniform ||
3801 type.storage == StorageClassShaderRecordBufferKHR;
3802 bool has_block_flags = ir.meta[type.self].decoration.decoration_flags.get(DecorationBlock) ||
3803 ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
3804
3805 if (var.storage != StorageClassFunction && type.pointer && is_block_storage && !is_hidden_variable(var) &&
3806 has_block_flags)
3807 {
3808 emit_buffer_block(var);
3809 }
3810 });
3811
3812 // Output push constant blocks
3813 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
3814 auto &type = this->get<SPIRType>(var.basetype);
3815 if (var.storage != StorageClassFunction && type.pointer && type.storage == StorageClassPushConstant &&
3816 !is_hidden_variable(var))
3817 {
3818 emit_push_constant_block(var);
3819 }
3820 });
3821
3822 bool skip_separate_image_sampler = !combined_image_samplers.empty() || !options.vulkan_semantics;
3823
3824 // Output Uniform Constants (values, samplers, images, etc).
3825 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
3826 auto &type = this->get<SPIRType>(var.basetype);
3827
3828 // If we're remapping separate samplers and images, only emit the combined samplers.
3829 if (skip_separate_image_sampler)
3830 {
3831 // Sampler buffers are always used without a sampler, and they will also work in regular GL.
3832 bool sampler_buffer = type.basetype == SPIRType::Image && type.image.dim == DimBuffer;
3833 bool separate_image = type.basetype == SPIRType::Image && type.image.sampled == 1;
3834 bool separate_sampler = type.basetype == SPIRType::Sampler;
3835 if (!sampler_buffer && (separate_image || separate_sampler))
3836 return;
3837 }
3838
3839 if (var.storage != StorageClassFunction && type.pointer &&
3840 (type.storage == StorageClassUniformConstant || type.storage == StorageClassAtomicCounter ||
3841 type.storage == StorageClassRayPayloadKHR || type.storage == StorageClassIncomingRayPayloadKHR ||
3842 type.storage == StorageClassCallableDataKHR || type.storage == StorageClassIncomingCallableDataKHR ||
3843 type.storage == StorageClassHitAttributeKHR) &&
3844 !is_hidden_variable(var))
3845 {
3846 emit_uniform(var);
3847 emitted = true;
3848 }
3849 });
3850
3851 if (emitted)
3852 statement("");
3853 emitted = false;
3854
3855 bool emitted_base_instance = false;
3856
3857 // Output in/out interfaces.
3858 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
3859 auto &type = this->get<SPIRType>(var.basetype);
3860
3861 bool is_hidden = is_hidden_variable(var);
3862
3863 // Unused output I/O variables might still be required to implement framebuffer fetch.
3864 if (var.storage == StorageClassOutput && !is_legacy() &&
3865 location_is_framebuffer_fetch(get_decoration(var.self, DecorationLocation)) != 0)
3866 {
3867 is_hidden = false;
3868 }
3869
3870 if (var.storage != StorageClassFunction && type.pointer &&
3871 (var.storage == StorageClassInput || var.storage == StorageClassOutput) &&
3872 interface_variable_exists_in_entry_point(var.self) && !is_hidden)
3873 {
3874 if (options.es && get_execution_model() == ExecutionModelVertex && var.storage == StorageClassInput &&
3875 type.array.size() == 1)
3876 {
3877 SPIRV_CROSS_THROW("OpenGL ES doesn't support array input variables in vertex shader.");
3878 }
3879 emit_interface_block(var);
3880 emitted = true;
3881 }
3882 else if (is_builtin_variable(var))
3883 {
3884 auto builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
3885 // For gl_InstanceIndex emulation on GLES, the API user needs to
3886 // supply this uniform.
3887
3888 // The draw parameter extension is soft-enabled on GL with some fallbacks.
3889 if (!options.vulkan_semantics)
3890 {
3891 if (!emitted_base_instance &&
3892 ((options.vertex.support_nonzero_base_instance && builtin == BuiltInInstanceIndex) ||
3893 (builtin == BuiltInBaseInstance)))
3894 {
3895 statement("#ifdef GL_ARB_shader_draw_parameters");
3896 statement("#define SPIRV_Cross_BaseInstance gl_BaseInstanceARB");
3897 statement("#else");
3898 // A crude, but simple workaround which should be good enough for non-indirect draws.
3899 statement("uniform int SPIRV_Cross_BaseInstance;");
3900 statement("#endif");
3901 emitted = true;
3902 emitted_base_instance = true;
3903 }
3904 else if (builtin == BuiltInBaseVertex)
3905 {
3906 statement("#ifdef GL_ARB_shader_draw_parameters");
3907 statement("#define SPIRV_Cross_BaseVertex gl_BaseVertexARB");
3908 statement("#else");
3909 // A crude, but simple workaround which should be good enough for non-indirect draws.
3910 statement("uniform int SPIRV_Cross_BaseVertex;");
3911 statement("#endif");
3912 }
3913 else if (builtin == BuiltInDrawIndex)
3914 {
3915 statement("#ifndef GL_ARB_shader_draw_parameters");
3916 // Cannot really be worked around.
3917 statement("#error GL_ARB_shader_draw_parameters is not supported.");
3918 statement("#endif");
3919 }
3920 }
3921 }
3922 });
3923
3924 // Global variables.
3925 for (auto global : global_variables)
3926 {
3927 auto &var = get<SPIRVariable>(global);
3928 if (is_hidden_variable(var, true))
3929 continue;
3930
3931 if (var.storage != StorageClassOutput)
3932 {
3933 if (!variable_is_lut(var))
3934 {
3935 add_resource_name(var.self);
3936
3937 string initializer;
3938 if (options.force_zero_initialized_variables && var.storage == StorageClassPrivate &&
3939 !var.initializer && !var.static_expression && type_can_zero_initialize(get_variable_data_type(var)))
3940 {
3941 initializer = join(" = ", to_zero_initialized_expression(get_variable_data_type_id(var)));
3942 }
3943
3944 statement(variable_decl(var), initializer, ";");
3945 emitted = true;
3946 }
3947 }
3948 else if (var.initializer && maybe_get<SPIRConstant>(var.initializer) != nullptr)
3949 {
3950 emit_output_variable_initializer(var);
3951 }
3952 }
3953
3954 if (emitted)
3955 statement("");
3956 }
3957
3958 void CompilerGLSL::emit_output_variable_initializer(const SPIRVariable &var)
3959 {
3960 // If a StorageClassOutput variable has an initializer, we need to initialize it in main().
3961 auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point);
3962 auto &type = get<SPIRType>(var.basetype);
3963 bool is_patch = has_decoration(var.self, DecorationPatch);
3964 bool is_block = has_decoration(type.self, DecorationBlock);
3965 bool is_control_point = get_execution_model() == ExecutionModelTessellationControl && !is_patch;
3966
3967 if (is_block)
3968 {
3969 uint32_t member_count = uint32_t(type.member_types.size());
3970 bool type_is_array = type.array.size() == 1;
3971 uint32_t array_size = 1;
3972 if (type_is_array)
3973 array_size = to_array_size_literal(type);
3974 uint32_t iteration_count = is_control_point ? 1 : array_size;
3975
3976 // If the initializer is a block, we must initialize each block member one at a time.
3977 for (uint32_t i = 0; i < member_count; i++)
3978 {
3979 // These outputs might not have been properly declared, so don't initialize them in that case.
3980 if (has_member_decoration(type.self, i, DecorationBuiltIn))
3981 {
3982 if (get_member_decoration(type.self, i, DecorationBuiltIn) == BuiltInCullDistance &&
3983 !cull_distance_count)
3984 continue;
3985
3986 if (get_member_decoration(type.self, i, DecorationBuiltIn) == BuiltInClipDistance &&
3987 !clip_distance_count)
3988 continue;
3989 }
3990
3991 // We need to build a per-member array first, essentially transposing from AoS to SoA.
3992 // This code path hits when we have an array of blocks.
3993 string lut_name;
3994 if (type_is_array)
3995 {
3996 lut_name = join("_", var.self, "_", i, "_init");
3997 uint32_t member_type_id = get<SPIRType>(var.basetype).member_types[i];
3998 auto &member_type = get<SPIRType>(member_type_id);
3999 auto array_type = member_type;
4000 array_type.parent_type = member_type_id;
4001 array_type.op = OpTypeArray;
4002 array_type.array.push_back(array_size);
4003 array_type.array_size_literal.push_back(true);
4004
4005 SmallVector<string> exprs;
4006 exprs.reserve(array_size);
4007 auto &c = get<SPIRConstant>(var.initializer);
4008 for (uint32_t j = 0; j < array_size; j++)
4009 exprs.push_back(to_expression(get<SPIRConstant>(c.subconstants[j]).subconstants[i]));
4010 statement("const ", type_to_glsl(array_type), " ", lut_name, type_to_array_glsl(array_type, 0), " = ",
4011 type_to_glsl_constructor(array_type), "(", merge(exprs, ", "), ");");
4012 }
4013
4014 for (uint32_t j = 0; j < iteration_count; j++)
4015 {
4016 entry_func.fixup_hooks_in.push_back([=, &var]() {
4017 AccessChainMeta meta;
4018 auto &c = this->get<SPIRConstant>(var.initializer);
4019
4020 uint32_t invocation_id = 0;
4021 uint32_t member_index_id = 0;
4022 if (is_control_point)
4023 {
4024 uint32_t ids = ir.increase_bound_by(3);
4025 auto &uint_type = set<SPIRType>(ids, OpTypeInt);
4026 uint_type.basetype = SPIRType::UInt;
4027 uint_type.width = 32;
4028 set<SPIRExpression>(ids + 1, builtin_to_glsl(BuiltInInvocationId, StorageClassInput), ids, true);
4029 set<SPIRConstant>(ids + 2, ids, i, false);
4030 invocation_id = ids + 1;
4031 member_index_id = ids + 2;
4032 }
4033
4034 if (is_patch)
4035 {
4036 statement("if (gl_InvocationID == 0)");
4037 begin_scope();
4038 }
4039
4040 if (type_is_array && !is_control_point)
4041 {
4042 uint32_t indices[2] = { j, i };
4043 auto chain = access_chain_internal(var.self, indices, 2, ACCESS_CHAIN_INDEX_IS_LITERAL_BIT, &meta);
4044 statement(chain, " = ", lut_name, "[", j, "];");
4045 }
4046 else if (is_control_point)
4047 {
4048 uint32_t indices[2] = { invocation_id, member_index_id };
4049 auto chain = access_chain_internal(var.self, indices, 2, 0, &meta);
4050 statement(chain, " = ", lut_name, "[", builtin_to_glsl(BuiltInInvocationId, StorageClassInput), "];");
4051 }
4052 else
4053 {
4054 auto chain =
4055 access_chain_internal(var.self, &i, 1, ACCESS_CHAIN_INDEX_IS_LITERAL_BIT, &meta);
4056 statement(chain, " = ", to_expression(c.subconstants[i]), ";");
4057 }
4058
4059 if (is_patch)
4060 end_scope();
4061 });
4062 }
4063 }
4064 }
4065 else if (is_control_point)
4066 {
4067 auto lut_name = join("_", var.self, "_init");
4068 statement("const ", type_to_glsl(type), " ", lut_name, type_to_array_glsl(type, 0),
4069 " = ", to_expression(var.initializer), ";");
4070 entry_func.fixup_hooks_in.push_back([&, lut_name]() {
4071 statement(to_expression(var.self), "[gl_InvocationID] = ", lut_name, "[gl_InvocationID];");
4072 });
4073 }
4074 else if (has_decoration(var.self, DecorationBuiltIn) &&
4075 BuiltIn(get_decoration(var.self, DecorationBuiltIn)) == BuiltInSampleMask)
4076 {
4077 // We cannot copy the array since gl_SampleMask is unsized in GLSL. Unroll time! <_<
4078 entry_func.fixup_hooks_in.push_back([&] {
4079 auto &c = this->get<SPIRConstant>(var.initializer);
4080 uint32_t num_constants = uint32_t(c.subconstants.size());
4081 for (uint32_t i = 0; i < num_constants; i++)
4082 {
4083 // Don't use to_expression on constant since it might be uint, just fish out the raw int.
4084 statement(to_expression(var.self), "[", i, "] = ",
4085 convert_to_string(this->get<SPIRConstant>(c.subconstants[i]).scalar_i32()), ";");
4086 }
4087 });
4088 }
4089 else
4090 {
4091 auto lut_name = join("_", var.self, "_init");
4092 statement("const ", type_to_glsl(type), " ", lut_name,
4093 type_to_array_glsl(type, var.self), " = ", to_expression(var.initializer), ";");
4094 entry_func.fixup_hooks_in.push_back([&, lut_name, is_patch]() {
4095 if (is_patch)
4096 {
4097 statement("if (gl_InvocationID == 0)");
4098 begin_scope();
4099 }
4100 statement(to_expression(var.self), " = ", lut_name, ";");
4101 if (is_patch)
4102 end_scope();
4103 });
4104 }
4105 }
4106
4107 void CompilerGLSL::emit_subgroup_arithmetic_workaround(const std::string &func, Op op, GroupOperation group_op)
4108 {
4109 std::string result;
4110 switch (group_op)
4111 {
4112 case GroupOperationReduce:
4113 result = "reduction";
4114 break;
4115
4116 case GroupOperationExclusiveScan:
4117 result = "excl_scan";
4118 break;
4119
4120 case GroupOperationInclusiveScan:
4121 result = "incl_scan";
4122 break;
4123
4124 default:
4125 SPIRV_CROSS_THROW("Unsupported workaround for arithmetic group operation");
4126 }
4127
4128 struct TypeInfo
4129 {
4130 std::string type;
4131 std::string identity;
4132 };
4133
4134 std::vector<TypeInfo> type_infos;
4135 switch (op)
4136 {
4137 case OpGroupNonUniformIAdd:
4138 {
4139 type_infos.emplace_back(TypeInfo{ "uint", "0u" });
4140 type_infos.emplace_back(TypeInfo{ "uvec2", "uvec2(0u)" });
4141 type_infos.emplace_back(TypeInfo{ "uvec3", "uvec3(0u)" });
4142 type_infos.emplace_back(TypeInfo{ "uvec4", "uvec4(0u)" });
4143 type_infos.emplace_back(TypeInfo{ "int", "0" });
4144 type_infos.emplace_back(TypeInfo{ "ivec2", "ivec2(0)" });
4145 type_infos.emplace_back(TypeInfo{ "ivec3", "ivec3(0)" });
4146 type_infos.emplace_back(TypeInfo{ "ivec4", "ivec4(0)" });
4147 break;
4148 }
4149
4150 case OpGroupNonUniformFAdd:
4151 {
4152 type_infos.emplace_back(TypeInfo{ "float", "0.0f" });
4153 type_infos.emplace_back(TypeInfo{ "vec2", "vec2(0.0f)" });
4154 type_infos.emplace_back(TypeInfo{ "vec3", "vec3(0.0f)" });
4155 type_infos.emplace_back(TypeInfo{ "vec4", "vec4(0.0f)" });
4156 // ARB_gpu_shader_fp64 is required in GL4.0 which in turn is required by NV_thread_shuffle
4157 type_infos.emplace_back(TypeInfo{ "double", "0.0LF" });
4158 type_infos.emplace_back(TypeInfo{ "dvec2", "dvec2(0.0LF)" });
4159 type_infos.emplace_back(TypeInfo{ "dvec3", "dvec3(0.0LF)" });
4160 type_infos.emplace_back(TypeInfo{ "dvec4", "dvec4(0.0LF)" });
4161 break;
4162 }
4163
4164 case OpGroupNonUniformIMul:
4165 {
4166 type_infos.emplace_back(TypeInfo{ "uint", "1u" });
4167 type_infos.emplace_back(TypeInfo{ "uvec2", "uvec2(1u)" });
4168 type_infos.emplace_back(TypeInfo{ "uvec3", "uvec3(1u)" });
4169 type_infos.emplace_back(TypeInfo{ "uvec4", "uvec4(1u)" });
4170 type_infos.emplace_back(TypeInfo{ "int", "1" });
4171 type_infos.emplace_back(TypeInfo{ "ivec2", "ivec2(1)" });
4172 type_infos.emplace_back(TypeInfo{ "ivec3", "ivec3(1)" });
4173 type_infos.emplace_back(TypeInfo{ "ivec4", "ivec4(1)" });
4174 break;
4175 }
4176
4177 case OpGroupNonUniformFMul:
4178 {
4179 type_infos.emplace_back(TypeInfo{ "float", "1.0f" });
4180 type_infos.emplace_back(TypeInfo{ "vec2", "vec2(1.0f)" });
4181 type_infos.emplace_back(TypeInfo{ "vec3", "vec3(1.0f)" });
4182 type_infos.emplace_back(TypeInfo{ "vec4", "vec4(1.0f)" });
4183 type_infos.emplace_back(TypeInfo{ "double", "0.0LF" });
4184 type_infos.emplace_back(TypeInfo{ "dvec2", "dvec2(1.0LF)" });
4185 type_infos.emplace_back(TypeInfo{ "dvec3", "dvec3(1.0LF)" });
4186 type_infos.emplace_back(TypeInfo{ "dvec4", "dvec4(1.0LF)" });
4187 break;
4188 }
4189
4190 default:
4191 SPIRV_CROSS_THROW("Unsupported workaround for arithmetic group operation");
4192 }
4193
4194 const bool op_is_addition = op == OpGroupNonUniformIAdd || op == OpGroupNonUniformFAdd;
4195 const bool op_is_multiplication = op == OpGroupNonUniformIMul || op == OpGroupNonUniformFMul;
4196 std::string op_symbol;
4197 if (op_is_addition)
4198 {
4199 op_symbol = "+=";
4200 }
4201 else if (op_is_multiplication)
4202 {
4203 op_symbol = "*=";
4204 }
4205
4206 for (const TypeInfo &t : type_infos)
4207 {
4208 statement(t.type, " ", func, "(", t.type, " v)");
4209 begin_scope();
4210 statement(t.type, " ", result, " = ", t.identity, ";");
4211 statement("uvec4 active_threads = subgroupBallot(true);");
4212 statement("if (subgroupBallotBitCount(active_threads) == gl_SubgroupSize)");
4213 begin_scope();
4214 statement("uint total = gl_SubgroupSize / 2u;");
4215 statement(result, " = v;");
4216 statement("for (uint i = 1u; i <= total; i <<= 1u)");
4217 begin_scope();
4218 statement("bool valid;");
4219 if (group_op == GroupOperationReduce)
4220 {
4221 statement(t.type, " s = shuffleXorNV(", result, ", i, gl_SubgroupSize, valid);");
4222 }
4223 else if (group_op == GroupOperationExclusiveScan || group_op == GroupOperationInclusiveScan)
4224 {
4225 statement(t.type, " s = shuffleUpNV(", result, ", i, gl_SubgroupSize, valid);");
4226 }
4227 if (op_is_addition || op_is_multiplication)
4228 {
4229 statement(result, " ", op_symbol, " valid ? s : ", t.identity, ";");
4230 }
4231 end_scope();
4232 if (group_op == GroupOperationExclusiveScan)
4233 {
4234 statement(result, " = shuffleUpNV(", result, ", 1u, gl_SubgroupSize);");
4235 statement("if (subgroupElect())");
4236 begin_scope();
4237 statement(result, " = ", t.identity, ";");
4238 end_scope();
4239 }
4240 end_scope();
4241 statement("else");
4242 begin_scope();
4243 if (group_op == GroupOperationExclusiveScan)
4244 {
4245 statement("uint total = subgroupBallotBitCount(gl_SubgroupLtMask);");
4246 }
4247 else if (group_op == GroupOperationInclusiveScan)
4248 {
4249 statement("uint total = subgroupBallotBitCount(gl_SubgroupLeMask);");
4250 }
4251 statement("for (uint i = 0u; i < gl_SubgroupSize; ++i)");
4252 begin_scope();
4253 statement("bool valid = subgroupBallotBitExtract(active_threads, i);");
4254 statement(t.type, " s = shuffleNV(v, i, gl_SubgroupSize);");
4255 if (group_op == GroupOperationExclusiveScan || group_op == GroupOperationInclusiveScan)
4256 {
4257 statement("valid = valid && (i < total);");
4258 }
4259 if (op_is_addition || op_is_multiplication)
4260 {
4261 statement(result, " ", op_symbol, " valid ? s : ", t.identity, ";");
4262 }
4263 end_scope();
4264 end_scope();
4265 statement("return ", result, ";");
4266 end_scope();
4267 }
4268 }
4269
4270 void CompilerGLSL::emit_extension_workarounds(spv::ExecutionModel model)
4271 {
4272 static const char *workaround_types[] = { "int", "ivec2", "ivec3", "ivec4", "uint", "uvec2", "uvec3", "uvec4",
4273 "float", "vec2", "vec3", "vec4", "double", "dvec2", "dvec3", "dvec4" };
4274
4275 if (!options.vulkan_semantics)
4276 {
4277 using Supp = ShaderSubgroupSupportHelper;
4278 auto result = shader_subgroup_supporter.resolve();
4279
4280 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupMask))
4281 {
4282 auto exts = Supp::get_candidates_for_feature(Supp::SubgroupMask, result);
4283
4284 for (auto &e : exts)
4285 {
4286 const char *name = Supp::get_extension_name(e);
4287 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4288
4289 switch (e)
4290 {
4291 case Supp::NV_shader_thread_group:
4292 statement("#define gl_SubgroupEqMask uvec4(gl_ThreadEqMaskNV, 0u, 0u, 0u)");
4293 statement("#define gl_SubgroupGeMask uvec4(gl_ThreadGeMaskNV, 0u, 0u, 0u)");
4294 statement("#define gl_SubgroupGtMask uvec4(gl_ThreadGtMaskNV, 0u, 0u, 0u)");
4295 statement("#define gl_SubgroupLeMask uvec4(gl_ThreadLeMaskNV, 0u, 0u, 0u)");
4296 statement("#define gl_SubgroupLtMask uvec4(gl_ThreadLtMaskNV, 0u, 0u, 0u)");
4297 break;
4298 case Supp::ARB_shader_ballot:
4299 statement("#define gl_SubgroupEqMask uvec4(unpackUint2x32(gl_SubGroupEqMaskARB), 0u, 0u)");
4300 statement("#define gl_SubgroupGeMask uvec4(unpackUint2x32(gl_SubGroupGeMaskARB), 0u, 0u)");
4301 statement("#define gl_SubgroupGtMask uvec4(unpackUint2x32(gl_SubGroupGtMaskARB), 0u, 0u)");
4302 statement("#define gl_SubgroupLeMask uvec4(unpackUint2x32(gl_SubGroupLeMaskARB), 0u, 0u)");
4303 statement("#define gl_SubgroupLtMask uvec4(unpackUint2x32(gl_SubGroupLtMaskARB), 0u, 0u)");
4304 break;
4305 default:
4306 break;
4307 }
4308 }
4309 statement("#endif");
4310 statement("");
4311 }
4312
4313 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupSize))
4314 {
4315 auto exts = Supp::get_candidates_for_feature(Supp::SubgroupSize, result);
4316
4317 for (auto &e : exts)
4318 {
4319 const char *name = Supp::get_extension_name(e);
4320 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4321
4322 switch (e)
4323 {
4324 case Supp::NV_shader_thread_group:
4325 statement("#define gl_SubgroupSize gl_WarpSizeNV");
4326 break;
4327 case Supp::ARB_shader_ballot:
4328 statement("#define gl_SubgroupSize gl_SubGroupSizeARB");
4329 break;
4330 case Supp::AMD_gcn_shader:
4331 statement("#define gl_SubgroupSize uint(gl_SIMDGroupSizeAMD)");
4332 break;
4333 default:
4334 break;
4335 }
4336 }
4337 statement("#endif");
4338 statement("");
4339 }
4340
4341 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupInvocationID))
4342 {
4343 auto exts = Supp::get_candidates_for_feature(Supp::SubgroupInvocationID, result);
4344
4345 for (auto &e : exts)
4346 {
4347 const char *name = Supp::get_extension_name(e);
4348 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4349
4350 switch (e)
4351 {
4352 case Supp::NV_shader_thread_group:
4353 statement("#define gl_SubgroupInvocationID gl_ThreadInWarpNV");
4354 break;
4355 case Supp::ARB_shader_ballot:
4356 statement("#define gl_SubgroupInvocationID gl_SubGroupInvocationARB");
4357 break;
4358 default:
4359 break;
4360 }
4361 }
4362 statement("#endif");
4363 statement("");
4364 }
4365
4366 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupID))
4367 {
4368 auto exts = Supp::get_candidates_for_feature(Supp::SubgroupID, result);
4369
4370 for (auto &e : exts)
4371 {
4372 const char *name = Supp::get_extension_name(e);
4373 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4374
4375 switch (e)
4376 {
4377 case Supp::NV_shader_thread_group:
4378 statement("#define gl_SubgroupID gl_WarpIDNV");
4379 break;
4380 default:
4381 break;
4382 }
4383 }
4384 statement("#endif");
4385 statement("");
4386 }
4387
4388 if (shader_subgroup_supporter.is_feature_requested(Supp::NumSubgroups))
4389 {
4390 auto exts = Supp::get_candidates_for_feature(Supp::NumSubgroups, result);
4391
4392 for (auto &e : exts)
4393 {
4394 const char *name = Supp::get_extension_name(e);
4395 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4396
4397 switch (e)
4398 {
4399 case Supp::NV_shader_thread_group:
4400 statement("#define gl_NumSubgroups gl_WarpsPerSMNV");
4401 break;
4402 default:
4403 break;
4404 }
4405 }
4406 statement("#endif");
4407 statement("");
4408 }
4409
4410 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupBroadcast_First))
4411 {
4412 auto exts = Supp::get_candidates_for_feature(Supp::SubgroupBroadcast_First, result);
4413
4414 for (auto &e : exts)
4415 {
4416 const char *name = Supp::get_extension_name(e);
4417 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4418
4419 switch (e)
4420 {
4421 case Supp::NV_shader_thread_shuffle:
4422 for (const char *t : workaround_types)
4423 {
4424 statement(t, " subgroupBroadcastFirst(", t,
4425 " value) { return shuffleNV(value, findLSB(ballotThreadNV(true)), gl_WarpSizeNV); }");
4426 }
4427 for (const char *t : workaround_types)
4428 {
4429 statement(t, " subgroupBroadcast(", t,
4430 " value, uint id) { return shuffleNV(value, id, gl_WarpSizeNV); }");
4431 }
4432 break;
4433 case Supp::ARB_shader_ballot:
4434 for (const char *t : workaround_types)
4435 {
4436 statement(t, " subgroupBroadcastFirst(", t,
4437 " value) { return readFirstInvocationARB(value); }");
4438 }
4439 for (const char *t : workaround_types)
4440 {
4441 statement(t, " subgroupBroadcast(", t,
4442 " value, uint id) { return readInvocationARB(value, id); }");
4443 }
4444 break;
4445 default:
4446 break;
4447 }
4448 }
4449 statement("#endif");
4450 statement("");
4451 }
4452
4453 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupBallotFindLSB_MSB))
4454 {
4455 auto exts = Supp::get_candidates_for_feature(Supp::SubgroupBallotFindLSB_MSB, result);
4456
4457 for (auto &e : exts)
4458 {
4459 const char *name = Supp::get_extension_name(e);
4460 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4461
4462 switch (e)
4463 {
4464 case Supp::NV_shader_thread_group:
4465 statement("uint subgroupBallotFindLSB(uvec4 value) { return findLSB(value.x); }");
4466 statement("uint subgroupBallotFindMSB(uvec4 value) { return findMSB(value.x); }");
4467 break;
4468 default:
4469 break;
4470 }
4471 }
4472 statement("#else");
4473 statement("uint subgroupBallotFindLSB(uvec4 value)");
4474 begin_scope();
4475 statement("int firstLive = findLSB(value.x);");
4476 statement("return uint(firstLive != -1 ? firstLive : (findLSB(value.y) + 32));");
4477 end_scope();
4478 statement("uint subgroupBallotFindMSB(uvec4 value)");
4479 begin_scope();
4480 statement("int firstLive = findMSB(value.y);");
4481 statement("return uint(firstLive != -1 ? (firstLive + 32) : findMSB(value.x));");
4482 end_scope();
4483 statement("#endif");
4484 statement("");
4485 }
4486
4487 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupAll_Any_AllEqualBool))
4488 {
4489 auto exts = Supp::get_candidates_for_feature(Supp::SubgroupAll_Any_AllEqualBool, result);
4490
4491 for (auto &e : exts)
4492 {
4493 const char *name = Supp::get_extension_name(e);
4494 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4495
4496 switch (e)
4497 {
4498 case Supp::NV_gpu_shader_5:
4499 statement("bool subgroupAll(bool value) { return allThreadsNV(value); }");
4500 statement("bool subgroupAny(bool value) { return anyThreadNV(value); }");
4501 statement("bool subgroupAllEqual(bool value) { return allThreadsEqualNV(value); }");
4502 break;
4503 case Supp::ARB_shader_group_vote:
4504 statement("bool subgroupAll(bool v) { return allInvocationsARB(v); }");
4505 statement("bool subgroupAny(bool v) { return anyInvocationARB(v); }");
4506 statement("bool subgroupAllEqual(bool v) { return allInvocationsEqualARB(v); }");
4507 break;
4508 case Supp::AMD_gcn_shader:
4509 statement("bool subgroupAll(bool value) { return ballotAMD(value) == ballotAMD(true); }");
4510 statement("bool subgroupAny(bool value) { return ballotAMD(value) != 0ull; }");
4511 statement("bool subgroupAllEqual(bool value) { uint64_t b = ballotAMD(value); return b == 0ull || "
4512 "b == ballotAMD(true); }");
4513 break;
4514 default:
4515 break;
4516 }
4517 }
4518 statement("#endif");
4519 statement("");
4520 }
4521
4522 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupAllEqualT))
4523 {
4524 statement("#ifndef GL_KHR_shader_subgroup_vote");
4525 statement(
4526 "#define _SPIRV_CROSS_SUBGROUP_ALL_EQUAL_WORKAROUND(type) bool subgroupAllEqual(type value) { return "
4527 "subgroupAllEqual(subgroupBroadcastFirst(value) == value); }");
4528 for (const char *t : workaround_types)
4529 statement("_SPIRV_CROSS_SUBGROUP_ALL_EQUAL_WORKAROUND(", t, ")");
4530 statement("#undef _SPIRV_CROSS_SUBGROUP_ALL_EQUAL_WORKAROUND");
4531 statement("#endif");
4532 statement("");
4533 }
4534
4535 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupBallot))
4536 {
4537 auto exts = Supp::get_candidates_for_feature(Supp::SubgroupBallot, result);
4538
4539 for (auto &e : exts)
4540 {
4541 const char *name = Supp::get_extension_name(e);
4542 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4543
4544 switch (e)
4545 {
4546 case Supp::NV_shader_thread_group:
4547 statement("uvec4 subgroupBallot(bool v) { return uvec4(ballotThreadNV(v), 0u, 0u, 0u); }");
4548 break;
4549 case Supp::ARB_shader_ballot:
4550 statement("uvec4 subgroupBallot(bool v) { return uvec4(unpackUint2x32(ballotARB(v)), 0u, 0u); }");
4551 break;
4552 default:
4553 break;
4554 }
4555 }
4556 statement("#endif");
4557 statement("");
4558 }
4559
4560 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupElect))
4561 {
4562 statement("#ifndef GL_KHR_shader_subgroup_basic");
4563 statement("bool subgroupElect()");
4564 begin_scope();
4565 statement("uvec4 activeMask = subgroupBallot(true);");
4566 statement("uint firstLive = subgroupBallotFindLSB(activeMask);");
4567 statement("return gl_SubgroupInvocationID == firstLive;");
4568 end_scope();
4569 statement("#endif");
4570 statement("");
4571 }
4572
4573 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupBarrier))
4574 {
4575 // Extensions we're using in place of GL_KHR_shader_subgroup_basic state
4576 // that subgroup execute in lockstep so this barrier is implicit.
4577 // However the GL 4.6 spec also states that `barrier` implies a shared memory barrier,
4578 // and a specific test of optimizing scans by leveraging lock-step invocation execution,
4579 // has shown that a `memoryBarrierShared` is needed in place of a `subgroupBarrier`.
4580 // https://github.com/buildaworldnet/IrrlichtBAW/commit/d8536857991b89a30a6b65d29441e51b64c2c7ad#diff-9f898d27be1ea6fc79b03d9b361e299334c1a347b6e4dc344ee66110c6aa596aR19
4581 statement("#ifndef GL_KHR_shader_subgroup_basic");
4582 statement("void subgroupBarrier() { memoryBarrierShared(); }");
4583 statement("#endif");
4584 statement("");
4585 }
4586
4587 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupMemBarrier))
4588 {
4589 if (model == spv::ExecutionModelGLCompute)
4590 {
4591 statement("#ifndef GL_KHR_shader_subgroup_basic");
4592 statement("void subgroupMemoryBarrier() { groupMemoryBarrier(); }");
4593 statement("void subgroupMemoryBarrierBuffer() { groupMemoryBarrier(); }");
4594 statement("void subgroupMemoryBarrierShared() { memoryBarrierShared(); }");
4595 statement("void subgroupMemoryBarrierImage() { groupMemoryBarrier(); }");
4596 statement("#endif");
4597 }
4598 else
4599 {
4600 statement("#ifndef GL_KHR_shader_subgroup_basic");
4601 statement("void subgroupMemoryBarrier() { memoryBarrier(); }");
4602 statement("void subgroupMemoryBarrierBuffer() { memoryBarrierBuffer(); }");
4603 statement("void subgroupMemoryBarrierImage() { memoryBarrierImage(); }");
4604 statement("#endif");
4605 }
4606 statement("");
4607 }
4608
4609 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupInverseBallot_InclBitCount_ExclBitCout))
4610 {
4611 statement("#ifndef GL_KHR_shader_subgroup_ballot");
4612 statement("bool subgroupInverseBallot(uvec4 value)");
4613 begin_scope();
4614 statement("return any(notEqual(value.xy & gl_SubgroupEqMask.xy, uvec2(0u)));");
4615 end_scope();
4616
4617 statement("uint subgroupBallotInclusiveBitCount(uvec4 value)");
4618 begin_scope();
4619 statement("uvec2 v = value.xy & gl_SubgroupLeMask.xy;");
4620 statement("ivec2 c = bitCount(v);");
4621 statement_no_indent("#ifdef GL_NV_shader_thread_group");
4622 statement("return uint(c.x);");
4623 statement_no_indent("#else");
4624 statement("return uint(c.x + c.y);");
4625 statement_no_indent("#endif");
4626 end_scope();
4627
4628 statement("uint subgroupBallotExclusiveBitCount(uvec4 value)");
4629 begin_scope();
4630 statement("uvec2 v = value.xy & gl_SubgroupLtMask.xy;");
4631 statement("ivec2 c = bitCount(v);");
4632 statement_no_indent("#ifdef GL_NV_shader_thread_group");
4633 statement("return uint(c.x);");
4634 statement_no_indent("#else");
4635 statement("return uint(c.x + c.y);");
4636 statement_no_indent("#endif");
4637 end_scope();
4638 statement("#endif");
4639 statement("");
4640 }
4641
4642 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupBallotBitCount))
4643 {
4644 statement("#ifndef GL_KHR_shader_subgroup_ballot");
4645 statement("uint subgroupBallotBitCount(uvec4 value)");
4646 begin_scope();
4647 statement("ivec2 c = bitCount(value.xy);");
4648 statement_no_indent("#ifdef GL_NV_shader_thread_group");
4649 statement("return uint(c.x);");
4650 statement_no_indent("#else");
4651 statement("return uint(c.x + c.y);");
4652 statement_no_indent("#endif");
4653 end_scope();
4654 statement("#endif");
4655 statement("");
4656 }
4657
4658 if (shader_subgroup_supporter.is_feature_requested(Supp::SubgroupBallotBitExtract))
4659 {
4660 statement("#ifndef GL_KHR_shader_subgroup_ballot");
4661 statement("bool subgroupBallotBitExtract(uvec4 value, uint index)");
4662 begin_scope();
4663 statement_no_indent("#ifdef GL_NV_shader_thread_group");
4664 statement("uint shifted = value.x >> index;");
4665 statement_no_indent("#else");
4666 statement("uint shifted = value[index >> 5u] >> (index & 0x1fu);");
4667 statement_no_indent("#endif");
4668 statement("return (shifted & 1u) != 0u;");
4669 end_scope();
4670 statement("#endif");
4671 statement("");
4672 }
4673
4674 auto arithmetic_feature_helper =
4675 [&](Supp::Feature feat, std::string func_name, spv::Op op, spv::GroupOperation group_op)
4676 {
4677 if (shader_subgroup_supporter.is_feature_requested(feat))
4678 {
4679 auto exts = Supp::get_candidates_for_feature(feat, result);
4680 for (auto &e : exts)
4681 {
4682 const char *name = Supp::get_extension_name(e);
4683 statement(&e == &exts.front() ? "#if" : "#elif", " defined(", name, ")");
4684
4685 switch (e)
4686 {
4687 case Supp::NV_shader_thread_shuffle:
4688 emit_subgroup_arithmetic_workaround(func_name, op, group_op);
4689 break;
4690 default:
4691 break;
4692 }
4693 }
4694 statement("#endif");
4695 statement("");
4696 }
4697 };
4698
4699 arithmetic_feature_helper(Supp::SubgroupArithmeticIAddReduce, "subgroupAdd", OpGroupNonUniformIAdd,
4700 GroupOperationReduce);
4701 arithmetic_feature_helper(Supp::SubgroupArithmeticIAddExclusiveScan, "subgroupExclusiveAdd",
4702 OpGroupNonUniformIAdd, GroupOperationExclusiveScan);
4703 arithmetic_feature_helper(Supp::SubgroupArithmeticIAddInclusiveScan, "subgroupInclusiveAdd",
4704 OpGroupNonUniformIAdd, GroupOperationInclusiveScan);
4705 arithmetic_feature_helper(Supp::SubgroupArithmeticFAddReduce, "subgroupAdd", OpGroupNonUniformFAdd,
4706 GroupOperationReduce);
4707 arithmetic_feature_helper(Supp::SubgroupArithmeticFAddExclusiveScan, "subgroupExclusiveAdd",
4708 OpGroupNonUniformFAdd, GroupOperationExclusiveScan);
4709 arithmetic_feature_helper(Supp::SubgroupArithmeticFAddInclusiveScan, "subgroupInclusiveAdd",
4710 OpGroupNonUniformFAdd, GroupOperationInclusiveScan);
4711
4712 arithmetic_feature_helper(Supp::SubgroupArithmeticIMulReduce, "subgroupMul", OpGroupNonUniformIMul,
4713 GroupOperationReduce);
4714 arithmetic_feature_helper(Supp::SubgroupArithmeticIMulExclusiveScan, "subgroupExclusiveMul",
4715 OpGroupNonUniformIMul, GroupOperationExclusiveScan);
4716 arithmetic_feature_helper(Supp::SubgroupArithmeticIMulInclusiveScan, "subgroupInclusiveMul",
4717 OpGroupNonUniformIMul, GroupOperationInclusiveScan);
4718 arithmetic_feature_helper(Supp::SubgroupArithmeticFMulReduce, "subgroupMul", OpGroupNonUniformFMul,
4719 GroupOperationReduce);
4720 arithmetic_feature_helper(Supp::SubgroupArithmeticFMulExclusiveScan, "subgroupExclusiveMul",
4721 OpGroupNonUniformFMul, GroupOperationExclusiveScan);
4722 arithmetic_feature_helper(Supp::SubgroupArithmeticFMulInclusiveScan, "subgroupInclusiveMul",
4723 OpGroupNonUniformFMul, GroupOperationInclusiveScan);
4724 }
4725
4726 if (!workaround_ubo_load_overload_types.empty())
4727 {
4728 for (auto &type_id : workaround_ubo_load_overload_types)
4729 {
4730 auto &type = get<SPIRType>(type_id);
4731
4732 if (options.es && is_matrix(type))
4733 {
4734 // Need both variants.
4735 // GLSL cannot overload on precision, so need to dispatch appropriately.
4736 statement("highp ", type_to_glsl(type), " spvWorkaroundRowMajor(highp ", type_to_glsl(type), " wrap) { return wrap; }");
4737 statement("mediump ", type_to_glsl(type), " spvWorkaroundRowMajorMP(mediump ", type_to_glsl(type), " wrap) { return wrap; }");
4738 }
4739 else
4740 {
4741 statement(type_to_glsl(type), " spvWorkaroundRowMajor(", type_to_glsl(type), " wrap) { return wrap; }");
4742 }
4743 }
4744 statement("");
4745 }
4746 }
4747
4748 void CompilerGLSL::emit_polyfills(uint32_t polyfills, bool relaxed)
4749 {
4750 const char *qual = "";
4751 const char *suffix = (options.es && relaxed) ? "MP" : "";
4752 if (options.es)
4753 qual = relaxed ? "mediump " : "highp ";
4754
4755 if (polyfills & PolyfillTranspose2x2)
4756 {
4757 statement(qual, "mat2 spvTranspose", suffix, "(", qual, "mat2 m)");
4758 begin_scope();
4759 statement("return mat2(m[0][0], m[1][0], m[0][1], m[1][1]);");
4760 end_scope();
4761 statement("");
4762 }
4763
4764 if (polyfills & PolyfillTranspose3x3)
4765 {
4766 statement(qual, "mat3 spvTranspose", suffix, "(", qual, "mat3 m)");
4767 begin_scope();
4768 statement("return mat3(m[0][0], m[1][0], m[2][0], m[0][1], m[1][1], m[2][1], m[0][2], m[1][2], m[2][2]);");
4769 end_scope();
4770 statement("");
4771 }
4772
4773 if (polyfills & PolyfillTranspose4x4)
4774 {
4775 statement(qual, "mat4 spvTranspose", suffix, "(", qual, "mat4 m)");
4776 begin_scope();
4777 statement("return mat4(m[0][0], m[1][0], m[2][0], m[3][0], m[0][1], m[1][1], m[2][1], m[3][1], m[0][2], "
4778 "m[1][2], m[2][2], m[3][2], m[0][3], m[1][3], m[2][3], m[3][3]);");
4779 end_scope();
4780 statement("");
4781 }
4782
4783 if (polyfills & PolyfillDeterminant2x2)
4784 {
4785 statement(qual, "float spvDeterminant", suffix, "(", qual, "mat2 m)");
4786 begin_scope();
4787 statement("return m[0][0] * m[1][1] - m[0][1] * m[1][0];");
4788 end_scope();
4789 statement("");
4790 }
4791
4792 if (polyfills & PolyfillDeterminant3x3)
4793 {
4794 statement(qual, "float spvDeterminant", suffix, "(", qual, "mat3 m)");
4795 begin_scope();
4796 statement("return dot(m[0], vec3(m[1][1] * m[2][2] - m[1][2] * m[2][1], "
4797 "m[1][2] * m[2][0] - m[1][0] * m[2][2], "
4798 "m[1][0] * m[2][1] - m[1][1] * m[2][0]));");
4799 end_scope();
4800 statement("");
4801 }
4802
4803 if (polyfills & PolyfillDeterminant4x4)
4804 {
4805 statement(qual, "float spvDeterminant", suffix, "(", qual, "mat4 m)");
4806 begin_scope();
4807 statement("return dot(m[0], vec4("
4808 "m[2][1] * m[3][2] * m[1][3] - m[3][1] * m[2][2] * m[1][3] + m[3][1] * m[1][2] * m[2][3] - m[1][1] * m[3][2] * m[2][3] - m[2][1] * m[1][2] * m[3][3] + m[1][1] * m[2][2] * m[3][3], "
4809 "m[3][0] * m[2][2] * m[1][3] - m[2][0] * m[3][2] * m[1][3] - m[3][0] * m[1][2] * m[2][3] + m[1][0] * m[3][2] * m[2][3] + m[2][0] * m[1][2] * m[3][3] - m[1][0] * m[2][2] * m[3][3], "
4810 "m[2][0] * m[3][1] * m[1][3] - m[3][0] * m[2][1] * m[1][3] + m[3][0] * m[1][1] * m[2][3] - m[1][0] * m[3][1] * m[2][3] - m[2][0] * m[1][1] * m[3][3] + m[1][0] * m[2][1] * m[3][3], "
4811 "m[3][0] * m[2][1] * m[1][2] - m[2][0] * m[3][1] * m[1][2] - m[3][0] * m[1][1] * m[2][2] + m[1][0] * m[3][1] * m[2][2] + m[2][0] * m[1][1] * m[3][2] - m[1][0] * m[2][1] * m[3][2]));");
4812 end_scope();
4813 statement("");
4814 }
4815
4816 if (polyfills & PolyfillMatrixInverse2x2)
4817 {
4818 statement(qual, "mat2 spvInverse", suffix, "(", qual, "mat2 m)");
4819 begin_scope();
4820 statement("return mat2(m[1][1], -m[0][1], -m[1][0], m[0][0]) "
4821 "* (1.0 / (m[0][0] * m[1][1] - m[1][0] * m[0][1]));");
4822 end_scope();
4823 statement("");
4824 }
4825
4826 if (polyfills & PolyfillMatrixInverse3x3)
4827 {
4828 statement(qual, "mat3 spvInverse", suffix, "(", qual, "mat3 m)");
4829 begin_scope();
4830 statement(qual, "vec3 t = vec3(m[1][1] * m[2][2] - m[1][2] * m[2][1], m[1][2] * m[2][0] - m[1][0] * m[2][2], m[1][0] * m[2][1] - m[1][1] * m[2][0]);");
4831 statement("return mat3(t[0], "
4832 "m[0][2] * m[2][1] - m[0][1] * m[2][2], "
4833 "m[0][1] * m[1][2] - m[0][2] * m[1][1], "
4834 "t[1], "
4835 "m[0][0] * m[2][2] - m[0][2] * m[2][0], "
4836 "m[0][2] * m[1][0] - m[0][0] * m[1][2], "
4837 "t[2], "
4838 "m[0][1] * m[2][0] - m[0][0] * m[2][1], "
4839 "m[0][0] * m[1][1] - m[0][1] * m[1][0]) "
4840 "* (1.0 / dot(m[0], t));");
4841 end_scope();
4842 statement("");
4843 }
4844
4845 if (polyfills & PolyfillMatrixInverse4x4)
4846 {
4847 statement(qual, "mat4 spvInverse", suffix, "(", qual, "mat4 m)");
4848 begin_scope();
4849 statement(qual, "vec4 t = vec4("
4850 "m[2][1] * m[3][2] * m[1][3] - m[3][1] * m[2][2] * m[1][3] + m[3][1] * m[1][2] * m[2][3] - m[1][1] * m[3][2] * m[2][3] - m[2][1] * m[1][2] * m[3][3] + m[1][1] * m[2][2] * m[3][3], "
4851 "m[3][0] * m[2][2] * m[1][3] - m[2][0] * m[3][2] * m[1][3] - m[3][0] * m[1][2] * m[2][3] + m[1][0] * m[3][2] * m[2][3] + m[2][0] * m[1][2] * m[3][3] - m[1][0] * m[2][2] * m[3][3], "
4852 "m[2][0] * m[3][1] * m[1][3] - m[3][0] * m[2][1] * m[1][3] + m[3][0] * m[1][1] * m[2][3] - m[1][0] * m[3][1] * m[2][3] - m[2][0] * m[1][1] * m[3][3] + m[1][0] * m[2][1] * m[3][3], "
4853 "m[3][0] * m[2][1] * m[1][2] - m[2][0] * m[3][1] * m[1][2] - m[3][0] * m[1][1] * m[2][2] + m[1][0] * m[3][1] * m[2][2] + m[2][0] * m[1][1] * m[3][2] - m[1][0] * m[2][1] * m[3][2]);");
4854 statement("return mat4("
4855 "t[0], "
4856 "m[3][1] * m[2][2] * m[0][3] - m[2][1] * m[3][2] * m[0][3] - m[3][1] * m[0][2] * m[2][3] + m[0][1] * m[3][2] * m[2][3] + m[2][1] * m[0][2] * m[3][3] - m[0][1] * m[2][2] * m[3][3], "
4857 "m[1][1] * m[3][2] * m[0][3] - m[3][1] * m[1][2] * m[0][3] + m[3][1] * m[0][2] * m[1][3] - m[0][1] * m[3][2] * m[1][3] - m[1][1] * m[0][2] * m[3][3] + m[0][1] * m[1][2] * m[3][3], "
4858 "m[2][1] * m[1][2] * m[0][3] - m[1][1] * m[2][2] * m[0][3] - m[2][1] * m[0][2] * m[1][3] + m[0][1] * m[2][2] * m[1][3] + m[1][1] * m[0][2] * m[2][3] - m[0][1] * m[1][2] * m[2][3], "
4859 "t[1], "
4860 "m[2][0] * m[3][2] * m[0][3] - m[3][0] * m[2][2] * m[0][3] + m[3][0] * m[0][2] * m[2][3] - m[0][0] * m[3][2] * m[2][3] - m[2][0] * m[0][2] * m[3][3] + m[0][0] * m[2][2] * m[3][3], "
4861 "m[3][0] * m[1][2] * m[0][3] - m[1][0] * m[3][2] * m[0][3] - m[3][0] * m[0][2] * m[1][3] + m[0][0] * m[3][2] * m[1][3] + m[1][0] * m[0][2] * m[3][3] - m[0][0] * m[1][2] * m[3][3], "
4862 "m[1][0] * m[2][2] * m[0][3] - m[2][0] * m[1][2] * m[0][3] + m[2][0] * m[0][2] * m[1][3] - m[0][0] * m[2][2] * m[1][3] - m[1][0] * m[0][2] * m[2][3] + m[0][0] * m[1][2] * m[2][3], "
4863 "t[2], "
4864 "m[3][0] * m[2][1] * m[0][3] - m[2][0] * m[3][1] * m[0][3] - m[3][0] * m[0][1] * m[2][3] + m[0][0] * m[3][1] * m[2][3] + m[2][0] * m[0][1] * m[3][3] - m[0][0] * m[2][1] * m[3][3], "
4865 "m[1][0] * m[3][1] * m[0][3] - m[3][0] * m[1][1] * m[0][3] + m[3][0] * m[0][1] * m[1][3] - m[0][0] * m[3][1] * m[1][3] - m[1][0] * m[0][1] * m[3][3] + m[0][0] * m[1][1] * m[3][3], "
4866 "m[2][0] * m[1][1] * m[0][3] - m[1][0] * m[2][1] * m[0][3] - m[2][0] * m[0][1] * m[1][3] + m[0][0] * m[2][1] * m[1][3] + m[1][0] * m[0][1] * m[2][3] - m[0][0] * m[1][1] * m[2][3], "
4867 "t[3], "
4868 "m[2][0] * m[3][1] * m[0][2] - m[3][0] * m[2][1] * m[0][2] + m[3][0] * m[0][1] * m[2][2] - m[0][0] * m[3][1] * m[2][2] - m[2][0] * m[0][1] * m[3][2] + m[0][0] * m[2][1] * m[3][2], "
4869 "m[3][0] * m[1][1] * m[0][2] - m[1][0] * m[3][1] * m[0][2] - m[3][0] * m[0][1] * m[1][2] + m[0][0] * m[3][1] * m[1][2] + m[1][0] * m[0][1] * m[3][2] - m[0][0] * m[1][1] * m[3][2], "
4870 "m[1][0] * m[2][1] * m[0][2] - m[2][0] * m[1][1] * m[0][2] + m[2][0] * m[0][1] * m[1][2] - m[0][0] * m[2][1] * m[1][2] - m[1][0] * m[0][1] * m[2][2] + m[0][0] * m[1][1] * m[2][2]) "
4871 "* (1.0 / dot(m[0], t));");
4872 end_scope();
4873 statement("");
4874 }
4875
4876 if (!relaxed)
4877 {
4878 static const Polyfill polys[3][3] = {
4879 { PolyfillNMin16, PolyfillNMin32, PolyfillNMin64 },
4880 { PolyfillNMax16, PolyfillNMax32, PolyfillNMax64 },
4881 { PolyfillNClamp16, PolyfillNClamp32, PolyfillNClamp64 },
4882 };
4883
4884 static const GLSLstd450 glsl_ops[] = { GLSLstd450NMin, GLSLstd450NMax, GLSLstd450NClamp };
4885 static const char *spv_ops[] = { "spvNMin", "spvNMax", "spvNClamp" };
4886 bool has_poly = false;
4887
4888 for (uint32_t i = 0; i < 3; i++)
4889 {
4890 for (uint32_t j = 0; j < 3; j++)
4891 {
4892 if ((polyfills & polys[i][j]) == 0)
4893 continue;
4894
4895 const char *types[3][4] = {
4896 { "float16_t", "f16vec2", "f16vec3", "f16vec4" },
4897 { "float", "vec2", "vec3", "vec4" },
4898 { "double", "dvec2", "dvec3", "dvec4" },
4899 };
4900
4901 for (uint32_t k = 0; k < 4; k++)
4902 {
4903 auto *type = types[j][k];
4904
4905 if (i < 2)
4906 {
4907 statement("spirv_instruction(set = \"GLSL.std.450\", id = ", glsl_ops[i], ") ",
4908 type, " ", spv_ops[i], "(", type, ", ", type, ");");
4909 }
4910 else
4911 {
4912 statement("spirv_instruction(set = \"GLSL.std.450\", id = ", glsl_ops[i], ") ",
4913 type, " ", spv_ops[i], "(", type, ", ", type, ", ", type, ");");
4914 }
4915
4916 has_poly = true;
4917 }
4918 }
4919 }
4920
4921 if (has_poly)
4922 statement("");
4923 }
4924 else
4925 {
4926 // Mediump intrinsics don't work correctly, so wrap the intrinsic in an outer shell that ensures mediump
4927 // propagation.
4928
4929 static const Polyfill polys[3][3] = {
4930 { PolyfillNMin16, PolyfillNMin32, PolyfillNMin64 },
4931 { PolyfillNMax16, PolyfillNMax32, PolyfillNMax64 },
4932 { PolyfillNClamp16, PolyfillNClamp32, PolyfillNClamp64 },
4933 };
4934
4935 static const char *spv_ops[] = { "spvNMin", "spvNMax", "spvNClamp" };
4936
4937 for (uint32_t i = 0; i < 3; i++)
4938 {
4939 for (uint32_t j = 0; j < 3; j++)
4940 {
4941 if ((polyfills & polys[i][j]) == 0)
4942 continue;
4943
4944 const char *types[3][4] = {
4945 { "float16_t", "f16vec2", "f16vec3", "f16vec4" },
4946 { "float", "vec2", "vec3", "vec4" },
4947 { "double", "dvec2", "dvec3", "dvec4" },
4948 };
4949
4950 for (uint32_t k = 0; k < 4; k++)
4951 {
4952 auto *type = types[j][k];
4953
4954 if (i < 2)
4955 {
4956 statement("mediump ", type, " ", spv_ops[i], "Relaxed(",
4957 "mediump ", type, " a, mediump ", type, " b)");
4958 begin_scope();
4959 statement("mediump ", type, " res = ", spv_ops[i], "(a, b);");
4960 statement("return res;");
4961 end_scope();
4962 statement("");
4963 }
4964 else
4965 {
4966 statement("mediump ", type, " ", spv_ops[i], "Relaxed(",
4967 "mediump ", type, " a, mediump ", type, " b, mediump ", type, " c)");
4968 begin_scope();
4969 statement("mediump ", type, " res = ", spv_ops[i], "(a, b, c);");
4970 statement("return res;");
4971 end_scope();
4972 statement("");
4973 }
4974 }
4975 }
4976 }
4977 }
4978 }
4979
4980 // Returns a string representation of the ID, usable as a function arg.
4981 // Default is to simply return the expression representation fo the arg ID.
4982 // Subclasses may override to modify the return value.
4983 string CompilerGLSL::to_func_call_arg(const SPIRFunction::Parameter &, uint32_t id)
4984 {
4985 // BDA expects pointers through function interface.
4986 if (is_physical_pointer(expression_type(id)))
4987 return to_pointer_expression(id);
4988
4989 // Make sure that we use the name of the original variable, and not the parameter alias.
4990 uint32_t name_id = id;
4991 auto *var = maybe_get<SPIRVariable>(id);
4992 if (var && var->basevariable)
4993 name_id = var->basevariable;
4994 return to_unpacked_expression(name_id);
4995 }
4996
4997 void CompilerGLSL::force_temporary_and_recompile(uint32_t id)
4998 {
4999 auto res = forced_temporaries.insert(id);
5000
5001 // Forcing new temporaries guarantees forward progress.
5002 if (res.second)
5003 force_recompile_guarantee_forward_progress();
5004 else
5005 force_recompile();
5006 }
5007
5008 uint32_t CompilerGLSL::consume_temporary_in_precision_context(uint32_t type_id, uint32_t id, Options::Precision precision)
5009 {
5010 // Constants do not have innate precision.
5011 auto handle_type = ir.ids[id].get_type();
5012 if (handle_type == TypeConstant || handle_type == TypeConstantOp || handle_type == TypeUndef)
5013 return id;
5014
5015 // Ignore anything that isn't 32-bit values.
5016 auto &type = get<SPIRType>(type_id);
5017 if (type.pointer)
5018 return id;
5019 if (type.basetype != SPIRType::Float && type.basetype != SPIRType::UInt && type.basetype != SPIRType::Int)
5020 return id;
5021
5022 if (precision == Options::DontCare)
5023 {
5024 // If precision is consumed as don't care (operations only consisting of constants),
5025 // we need to bind the expression to a temporary,
5026 // otherwise we have no way of controlling the precision later.
5027 auto itr = forced_temporaries.insert(id);
5028 if (itr.second)
5029 force_recompile_guarantee_forward_progress();
5030 return id;
5031 }
5032
5033 auto current_precision = has_decoration(id, DecorationRelaxedPrecision) ? Options::Mediump : Options::Highp;
5034 if (current_precision == precision)
5035 return id;
5036
5037 auto itr = temporary_to_mirror_precision_alias.find(id);
5038 if (itr == temporary_to_mirror_precision_alias.end())
5039 {
5040 uint32_t alias_id = ir.increase_bound_by(1);
5041 auto &m = ir.meta[alias_id];
5042 if (auto *input_m = ir.find_meta(id))
5043 m = *input_m;
5044
5045 const char *prefix;
5046 if (precision == Options::Mediump)
5047 {
5048 set_decoration(alias_id, DecorationRelaxedPrecision);
5049 prefix = "mp_copy_";
5050 }
5051 else
5052 {
5053 unset_decoration(alias_id, DecorationRelaxedPrecision);
5054 prefix = "hp_copy_";
5055 }
5056
5057 auto alias_name = join(prefix, to_name(id));
5058 ParsedIR::sanitize_underscores(alias_name);
5059 set_name(alias_id, alias_name);
5060
5061 emit_op(type_id, alias_id, to_expression(id), true);
5062 temporary_to_mirror_precision_alias[id] = alias_id;
5063 forced_temporaries.insert(id);
5064 forced_temporaries.insert(alias_id);
5065 force_recompile_guarantee_forward_progress();
5066 id = alias_id;
5067 }
5068 else
5069 {
5070 id = itr->second;
5071 }
5072
5073 return id;
5074 }
5075
5076 void CompilerGLSL::handle_invalid_expression(uint32_t id)
5077 {
5078 // We tried to read an invalidated expression.
5079 // This means we need another pass at compilation, but next time,
5080 // force temporary variables so that they cannot be invalidated.
5081 force_temporary_and_recompile(id);
5082
5083 // If the invalid expression happened as a result of a CompositeInsert
5084 // overwrite, we must block this from happening next iteration.
5085 if (composite_insert_overwritten.count(id))
5086 block_composite_insert_overwrite.insert(id);
5087 }
5088
5089 // Converts the format of the current expression from packed to unpacked,
5090 // by wrapping the expression in a constructor of the appropriate type.
5091 // GLSL does not support packed formats, so simply return the expression.
5092 // Subclasses that do will override.
5093 string CompilerGLSL::unpack_expression_type(string expr_str, const SPIRType &, uint32_t, bool, bool)
5094 {
5095 return expr_str;
5096 }
5097
5098 // Sometimes we proactively enclosed an expression where it turns out we might have not needed it after all.
5099 void CompilerGLSL::strip_enclosed_expression(string &expr)
5100 {
5101 if (expr.size() < 2 || expr.front() != '(' || expr.back() != ')')
5102 return;
5103
5104 // Have to make sure that our first and last parens actually enclose everything inside it.
5105 uint32_t paren_count = 0;
5106 for (auto &c : expr)
5107 {
5108 if (c == '(')
5109 paren_count++;
5110 else if (c == ')')
5111 {
5112 paren_count--;
5113
5114 // If we hit 0 and this is not the final char, our first and final parens actually don't
5115 // enclose the expression, and we cannot strip, e.g.: (a + b) * (c + d).
5116 if (paren_count == 0 && &c != &expr.back())
5117 return;
5118 }
5119 }
5120 expr.erase(expr.size() - 1, 1);
5121 expr.erase(begin(expr));
5122 }
5123
5124 bool CompilerGLSL::needs_enclose_expression(const std::string &expr)
5125 {
5126 bool need_parens = false;
5127
5128 // If the expression starts with a unary we need to enclose to deal with cases where we have back-to-back
5129 // unary expressions.
5130 if (!expr.empty())
5131 {
5132 auto c = expr.front();
5133 if (c == '-' || c == '+' || c == '!' || c == '~' || c == '&' || c == '*')
5134 need_parens = true;
5135 }
5136
5137 if (!need_parens)
5138 {
5139 uint32_t paren_count = 0;
5140 for (auto c : expr)
5141 {
5142 if (c == '(' || c == '[')
5143 paren_count++;
5144 else if (c == ')' || c == ']')
5145 {
5146 assert(paren_count);
5147 paren_count--;
5148 }
5149 else if (c == ' ' && paren_count == 0)
5150 {
5151 need_parens = true;
5152 break;
5153 }
5154 }
5155 assert(paren_count == 0);
5156 }
5157
5158 return need_parens;
5159 }
5160
5161 string CompilerGLSL::enclose_expression(const string &expr)
5162 {
5163 // If this expression contains any spaces which are not enclosed by parentheses,
5164 // we need to enclose it so we can treat the whole string as an expression.
5165 // This happens when two expressions have been part of a binary op earlier.
5166 if (needs_enclose_expression(expr))
5167 return join('(', expr, ')');
5168 else
5169 return expr;
5170 }
5171
5172 string CompilerGLSL::dereference_expression(const SPIRType &expr_type, const std::string &expr)
5173 {
5174 // If this expression starts with an address-of operator ('&'), then
5175 // just return the part after the operator.
5176 // TODO: Strip parens if unnecessary?
5177 if (expr.front() == '&')
5178 return expr.substr(1);
5179 else if (backend.native_pointers)
5180 return join('*', expr);
5181 else if (is_physical_pointer(expr_type) && !is_physical_pointer_to_buffer_block(expr_type))
5182 return join(enclose_expression(expr), ".value");
5183 else
5184 return expr;
5185 }
5186
5187 string CompilerGLSL::address_of_expression(const std::string &expr)
5188 {
5189 if (expr.size() > 3 && expr[0] == '(' && expr[1] == '*' && expr.back() == ')')
5190 {
5191 // If we have an expression which looks like (*foo), taking the address of it is the same as stripping
5192 // the first two and last characters. We might have to enclose the expression.
5193 // This doesn't work for cases like (*foo + 10),
5194 // but this is an r-value expression which we cannot take the address of anyways.
5195 return enclose_expression(expr.substr(2, expr.size() - 3));
5196 }
5197 else if (expr.front() == '*')
5198 {
5199 // If this expression starts with a dereference operator ('*'), then
5200 // just return the part after the operator.
5201 return expr.substr(1);
5202 }
5203 else
5204 return join('&', enclose_expression(expr));
5205 }
5206
5207 // Just like to_expression except that we enclose the expression inside parentheses if needed.
5208 string CompilerGLSL::to_enclosed_expression(uint32_t id, bool register_expression_read)
5209 {
5210 return enclose_expression(to_expression(id, register_expression_read));
5211 }
5212
5213 // Used explicitly when we want to read a row-major expression, but without any transpose shenanigans.
5214 // need_transpose must be forced to false.
5215 string CompilerGLSL::to_unpacked_row_major_matrix_expression(uint32_t id)
5216 {
5217 return unpack_expression_type(to_expression(id), expression_type(id),
5218 get_extended_decoration(id, SPIRVCrossDecorationPhysicalTypeID),
5219 has_extended_decoration(id, SPIRVCrossDecorationPhysicalTypePacked), true);
5220 }
5221
5222 string CompilerGLSL::to_unpacked_expression(uint32_t id, bool register_expression_read)
5223 {
5224 // If we need to transpose, it will also take care of unpacking rules.
5225 auto *e = maybe_get<SPIRExpression>(id);
5226 bool need_transpose = e && e->need_transpose;
5227 bool is_remapped = has_extended_decoration(id, SPIRVCrossDecorationPhysicalTypeID);
5228 bool is_packed = has_extended_decoration(id, SPIRVCrossDecorationPhysicalTypePacked);
5229
5230 if (!need_transpose && (is_remapped || is_packed))
5231 {
5232 return unpack_expression_type(to_expression(id, register_expression_read),
5233 get_pointee_type(expression_type_id(id)),
5234 get_extended_decoration(id, SPIRVCrossDecorationPhysicalTypeID),
5235 has_extended_decoration(id, SPIRVCrossDecorationPhysicalTypePacked), false);
5236 }
5237 else
5238 return to_expression(id, register_expression_read);
5239 }
5240
5241 string CompilerGLSL::to_enclosed_unpacked_expression(uint32_t id, bool register_expression_read)
5242 {
5243 return enclose_expression(to_unpacked_expression(id, register_expression_read));
5244 }
5245
5246 string CompilerGLSL::to_dereferenced_expression(uint32_t id, bool register_expression_read)
5247 {
5248 auto &type = expression_type(id);
5249
5250 if (is_pointer(type) && should_dereference(id))
5251 return dereference_expression(type, to_enclosed_expression(id, register_expression_read));
5252 else
5253 return to_expression(id, register_expression_read);
5254 }
5255
5256 string CompilerGLSL::to_pointer_expression(uint32_t id, bool register_expression_read)
5257 {
5258 auto &type = expression_type(id);
5259 if (is_pointer(type) && expression_is_lvalue(id) && !should_dereference(id))
5260 return address_of_expression(to_enclosed_expression(id, register_expression_read));
5261 else
5262 return to_unpacked_expression(id, register_expression_read);
5263 }
5264
5265 string CompilerGLSL::to_enclosed_pointer_expression(uint32_t id, bool register_expression_read)
5266 {
5267 auto &type = expression_type(id);
5268 if (is_pointer(type) && expression_is_lvalue(id) && !should_dereference(id))
5269 return address_of_expression(to_enclosed_expression(id, register_expression_read));
5270 else
5271 return to_enclosed_unpacked_expression(id, register_expression_read);
5272 }
5273
5274 string CompilerGLSL::to_extract_component_expression(uint32_t id, uint32_t index)
5275 {
5276 auto expr = to_enclosed_expression(id);
5277 if (has_extended_decoration(id, SPIRVCrossDecorationPhysicalTypePacked))
5278 return join(expr, "[", index, "]");
5279 else
5280 return join(expr, ".", index_to_swizzle(index));
5281 }
5282
5283 string CompilerGLSL::to_extract_constant_composite_expression(uint32_t result_type, const SPIRConstant &c,
5284 const uint32_t *chain, uint32_t length)
5285 {
5286 // It is kinda silly if application actually enter this path since they know the constant up front.
5287 // It is useful here to extract the plain constant directly.
5288 SPIRConstant tmp;
5289 tmp.constant_type = result_type;
5290 auto &composite_type = get<SPIRType>(c.constant_type);
5291 assert(composite_type.basetype != SPIRType::Struct && composite_type.array.empty());
5292 assert(!c.specialization);
5293
5294 if (is_matrix(composite_type))
5295 {
5296 if (length == 2)
5297 {
5298 tmp.m.c[0].vecsize = 1;
5299 tmp.m.columns = 1;
5300 tmp.m.c[0].r[0] = c.m.c[chain[0]].r[chain[1]];
5301 }
5302 else
5303 {
5304 assert(length == 1);
5305 tmp.m.c[0].vecsize = composite_type.vecsize;
5306 tmp.m.columns = 1;
5307 tmp.m.c[0] = c.m.c[chain[0]];
5308 }
5309 }
5310 else
5311 {
5312 assert(length == 1);
5313 tmp.m.c[0].vecsize = 1;
5314 tmp.m.columns = 1;
5315 tmp.m.c[0].r[0] = c.m.c[0].r[chain[0]];
5316 }
5317
5318 return constant_expression(tmp);
5319 }
5320
5321 string CompilerGLSL::to_rerolled_array_expression(const SPIRType &parent_type,
5322 const string &base_expr, const SPIRType &type)
5323 {
5324 bool remapped_boolean = parent_type.basetype == SPIRType::Struct &&
5325 type.basetype == SPIRType::Boolean &&
5326 backend.boolean_in_struct_remapped_type != SPIRType::Boolean;
5327
5328 SPIRType tmp_type { OpNop };
5329 if (remapped_boolean)
5330 {
5331 tmp_type = get<SPIRType>(type.parent_type);
5332 tmp_type.basetype = backend.boolean_in_struct_remapped_type;
5333 }
5334 else if (type.basetype == SPIRType::Boolean && backend.boolean_in_struct_remapped_type != SPIRType::Boolean)
5335 {
5336 // It's possible that we have an r-value expression that was OpLoaded from a struct.
5337 // We have to reroll this and explicitly cast the input to bool, because the r-value is short.
5338 tmp_type = get<SPIRType>(type.parent_type);
5339 remapped_boolean = true;
5340 }
5341
5342 uint32_t size = to_array_size_literal(type);
5343 auto &parent = get<SPIRType>(type.parent_type);
5344 string expr = "{ ";
5345
5346 for (uint32_t i = 0; i < size; i++)
5347 {
5348 auto subexpr = join(base_expr, "[", convert_to_string(i), "]");
5349 if (!is_array(parent))
5350 {
5351 if (remapped_boolean)
5352 subexpr = join(type_to_glsl(tmp_type), "(", subexpr, ")");
5353 expr += subexpr;
5354 }
5355 else
5356 expr += to_rerolled_array_expression(parent_type, subexpr, parent);
5357
5358 if (i + 1 < size)
5359 expr += ", ";
5360 }
5361
5362 expr += " }";
5363 return expr;
5364 }
5365
5366 string CompilerGLSL::to_composite_constructor_expression(const SPIRType &parent_type, uint32_t id, bool block_like_type)
5367 {
5368 auto &type = expression_type(id);
5369
5370 bool reroll_array = false;
5371 bool remapped_boolean = parent_type.basetype == SPIRType::Struct &&
5372 type.basetype == SPIRType::Boolean &&
5373 backend.boolean_in_struct_remapped_type != SPIRType::Boolean;
5374
5375 if (is_array(type))
5376 {
5377 reroll_array = !backend.array_is_value_type ||
5378 (block_like_type && !backend.array_is_value_type_in_buffer_blocks);
5379
5380 if (remapped_boolean)
5381 {
5382 // Forced to reroll if we have to change bool[] to short[].
5383 reroll_array = true;
5384 }
5385 }
5386
5387 if (reroll_array)
5388 {
5389 // For this case, we need to "re-roll" an array initializer from a temporary.
5390 // We cannot simply pass the array directly, since it decays to a pointer and it cannot
5391 // participate in a struct initializer. E.g.
5392 // float arr[2] = { 1.0, 2.0 };
5393 // Foo foo = { arr }; must be transformed to
5394 // Foo foo = { { arr[0], arr[1] } };
5395 // The array sizes cannot be deduced from specialization constants since we cannot use any loops.
5396
5397 // We're only triggering one read of the array expression, but this is fine since arrays have to be declared
5398 // as temporaries anyways.
5399 return to_rerolled_array_expression(parent_type, to_enclosed_expression(id), type);
5400 }
5401 else
5402 {
5403 auto expr = to_unpacked_expression(id);
5404 if (remapped_boolean)
5405 {
5406 auto tmp_type = type;
5407 tmp_type.basetype = backend.boolean_in_struct_remapped_type;
5408 expr = join(type_to_glsl(tmp_type), "(", expr, ")");
5409 }
5410
5411 return expr;
5412 }
5413 }
5414
5415 string CompilerGLSL::to_non_uniform_aware_expression(uint32_t id)
5416 {
5417 string expr = to_expression(id);
5418
5419 if (has_decoration(id, DecorationNonUniform))
5420 convert_non_uniform_expression(expr, id);
5421
5422 return expr;
5423 }
5424
5425 string CompilerGLSL::to_atomic_ptr_expression(uint32_t id)
5426 {
5427 string expr = to_non_uniform_aware_expression(id);
5428 // If we have naked pointer to POD, we need to dereference to get the proper ".value" resolve.
5429 if (should_dereference(id))
5430 expr = dereference_expression(expression_type(id), expr);
5431 return expr;
5432 }
5433
5434 string CompilerGLSL::to_expression(uint32_t id, bool register_expression_read)
5435 {
5436 auto itr = invalid_expressions.find(id);
5437 if (itr != end(invalid_expressions))
5438 handle_invalid_expression(id);
5439
5440 if (ir.ids[id].get_type() == TypeExpression)
5441 {
5442 // We might have a more complex chain of dependencies.
5443 // A possible scenario is that we
5444 //
5445 // %1 = OpLoad
5446 // %2 = OpDoSomething %1 %1. here %2 will have a dependency on %1.
5447 // %3 = OpDoSomethingAgain %2 %2. Here %3 will lose the link to %1 since we don't propagate the dependencies like that.
5448 // OpStore %1 %foo // Here we can invalidate %1, and hence all expressions which depend on %1. Only %2 will know since it's part of invalid_expressions.
5449 // %4 = OpDoSomethingAnotherTime %3 %3 // If we forward all expressions we will see %1 expression after store, not before.
5450 //
5451 // However, we can propagate up a list of depended expressions when we used %2, so we can check if %2 is invalid when reading %3 after the store,
5452 // and see that we should not forward reads of the original variable.
5453 auto &expr = get<SPIRExpression>(id);
5454 for (uint32_t dep : expr.expression_dependencies)
5455 if (invalid_expressions.find(dep) != end(invalid_expressions))
5456 handle_invalid_expression(dep);
5457 }
5458
5459 if (register_expression_read)
5460 track_expression_read(id);
5461
5462 switch (ir.ids[id].get_type())
5463 {
5464 case TypeExpression:
5465 {
5466 auto &e = get<SPIRExpression>(id);
5467 if (e.base_expression)
5468 return to_enclosed_expression(e.base_expression) + e.expression;
5469 else if (e.need_transpose)
5470 {
5471 // This should not be reached for access chains, since we always deal explicitly with transpose state
5472 // when consuming an access chain expression.
5473 uint32_t physical_type_id = get_extended_decoration(id, SPIRVCrossDecorationPhysicalTypeID);
5474 bool is_packed = has_extended_decoration(id, SPIRVCrossDecorationPhysicalTypePacked);
5475 bool relaxed = has_decoration(id, DecorationRelaxedPrecision);
5476 return convert_row_major_matrix(e.expression, get<SPIRType>(e.expression_type), physical_type_id,
5477 is_packed, relaxed);
5478 }
5479 else if (flattened_structs.count(id))
5480 {
5481 return load_flattened_struct(e.expression, get<SPIRType>(e.expression_type));
5482 }
5483 else
5484 {
5485 if (is_forcing_recompilation())
5486 {
5487 // During first compilation phase, certain expression patterns can trigger exponential growth of memory.
5488 // Avoid this by returning dummy expressions during this phase.
5489 // Do not use empty expressions here, because those are sentinels for other cases.
5490 return "_";
5491 }
5492 else
5493 return e.expression;
5494 }
5495 }
5496
5497 case TypeConstant:
5498 {
5499 auto &c = get<SPIRConstant>(id);
5500 auto &type = get<SPIRType>(c.constant_type);
5501
5502 // WorkGroupSize may be a constant.
5503 if (has_decoration(c.self, DecorationBuiltIn))
5504 return builtin_to_glsl(BuiltIn(get_decoration(c.self, DecorationBuiltIn)), StorageClassGeneric);
5505 else if (c.specialization)
5506 {
5507 if (backend.workgroup_size_is_hidden)
5508 {
5509 int wg_index = get_constant_mapping_to_workgroup_component(c);
5510 if (wg_index >= 0)
5511 {
5512 auto wg_size = join(builtin_to_glsl(BuiltInWorkgroupSize, StorageClassInput), vector_swizzle(1, wg_index));
5513 if (type.basetype != SPIRType::UInt)
5514 wg_size = bitcast_expression(type, SPIRType::UInt, wg_size);
5515 return wg_size;
5516 }
5517 }
5518
5519 if (expression_is_forwarded(id))
5520 return constant_expression(c);
5521
5522 return to_name(id);
5523 }
5524 else if (c.is_used_as_lut)
5525 return to_name(id);
5526 else if (type.basetype == SPIRType::Struct && !backend.can_declare_struct_inline)
5527 return to_name(id);
5528 else if (!type.array.empty() && !backend.can_declare_arrays_inline)
5529 return to_name(id);
5530 else
5531 return constant_expression(c);
5532 }
5533
5534 case TypeConstantOp:
5535 return to_name(id);
5536
5537 case TypeVariable:
5538 {
5539 auto &var = get<SPIRVariable>(id);
5540 // If we try to use a loop variable before the loop header, we have to redirect it to the static expression,
5541 // the variable has not been declared yet.
5542 if (var.statically_assigned || (var.loop_variable && !var.loop_variable_enable))
5543 {
5544 // We might try to load from a loop variable before it has been initialized.
5545 // Prefer static expression and fallback to initializer.
5546 if (var.static_expression)
5547 return to_expression(var.static_expression);
5548 else if (var.initializer)
5549 return to_expression(var.initializer);
5550 else
5551 {
5552 // We cannot declare the variable yet, so have to fake it.
5553 uint32_t undef_id = ir.increase_bound_by(1);
5554 return emit_uninitialized_temporary_expression(get_variable_data_type_id(var), undef_id).expression;
5555 }
5556 }
5557 else if (var.deferred_declaration)
5558 {
5559 var.deferred_declaration = false;
5560 return variable_decl(var);
5561 }
5562 else if (flattened_structs.count(id))
5563 {
5564 return load_flattened_struct(to_name(id), get<SPIRType>(var.basetype));
5565 }
5566 else
5567 {
5568 auto &dec = ir.meta[var.self].decoration;
5569 if (dec.builtin)
5570 return builtin_to_glsl(dec.builtin_type, var.storage);
5571 else
5572 return to_name(id);
5573 }
5574 }
5575
5576 case TypeCombinedImageSampler:
5577 // This type should never be taken the expression of directly.
5578 // The intention is that texture sampling functions will extract the image and samplers
5579 // separately and take their expressions as needed.
5580 // GLSL does not use this type because OpSampledImage immediately creates a combined image sampler
5581 // expression ala sampler2D(texture, sampler).
5582 SPIRV_CROSS_THROW("Combined image samplers have no default expression representation.");
5583
5584 case TypeAccessChain:
5585 // We cannot express this type. They only have meaning in other OpAccessChains, OpStore or OpLoad.
5586 SPIRV_CROSS_THROW("Access chains have no default expression representation.");
5587
5588 default:
5589 return to_name(id);
5590 }
5591 }
5592
5593 SmallVector<ConstantID> CompilerGLSL::get_composite_constant_ids(ConstantID const_id)
5594 {
5595 if (auto *constant = maybe_get<SPIRConstant>(const_id))
5596 {
5597 const auto &type = get<SPIRType>(constant->constant_type);
5598 if (is_array(type) || type.basetype == SPIRType::Struct)
5599 return constant->subconstants;
5600 if (is_matrix(type))
5601 return SmallVector<ConstantID>(constant->m.id);
5602 if (is_vector(type))
5603 return SmallVector<ConstantID>(constant->m.c[0].id);
5604 SPIRV_CROSS_THROW("Unexpected scalar constant!");
5605 }
5606 if (!const_composite_insert_ids.count(const_id))
5607 SPIRV_CROSS_THROW("Unimplemented for this OpSpecConstantOp!");
5608 return const_composite_insert_ids[const_id];
5609 }
5610
5611 void CompilerGLSL::fill_composite_constant(SPIRConstant &constant, TypeID type_id,
5612 const SmallVector<ConstantID> &initializers)
5613 {
5614 auto &type = get<SPIRType>(type_id);
5615 constant.specialization = true;
5616 if (is_array(type) || type.basetype == SPIRType::Struct)
5617 {
5618 constant.subconstants = initializers;
5619 }
5620 else if (is_matrix(type))
5621 {
5622 constant.m.columns = type.columns;
5623 for (uint32_t i = 0; i < type.columns; ++i)
5624 {
5625 constant.m.id[i] = initializers[i];
5626 constant.m.c[i].vecsize = type.vecsize;
5627 }
5628 }
5629 else if (is_vector(type))
5630 {
5631 constant.m.c[0].vecsize = type.vecsize;
5632 for (uint32_t i = 0; i < type.vecsize; ++i)
5633 constant.m.c[0].id[i] = initializers[i];
5634 }
5635 else
5636 SPIRV_CROSS_THROW("Unexpected scalar in SpecConstantOp CompositeInsert!");
5637 }
5638
5639 void CompilerGLSL::set_composite_constant(ConstantID const_id, TypeID type_id,
5640 const SmallVector<ConstantID> &initializers)
5641 {
5642 if (maybe_get<SPIRConstantOp>(const_id))
5643 {
5644 const_composite_insert_ids[const_id] = initializers;
5645 return;
5646 }
5647
5648 auto &constant = set<SPIRConstant>(const_id, type_id);
5649 fill_composite_constant(constant, type_id, initializers);
5650 forwarded_temporaries.insert(const_id);
5651 }
5652
5653 TypeID CompilerGLSL::get_composite_member_type(TypeID type_id, uint32_t member_idx)
5654 {
5655 auto &type = get<SPIRType>(type_id);
5656 if (is_array(type))
5657 return type.parent_type;
5658 if (type.basetype == SPIRType::Struct)
5659 return type.member_types[member_idx];
5660 if (is_matrix(type))
5661 return type.parent_type;
5662 if (is_vector(type))
5663 return type.parent_type;
5664 SPIRV_CROSS_THROW("Shouldn't reach lower than vector handling OpSpecConstantOp CompositeInsert!");
5665 }
5666
5667 string CompilerGLSL::constant_op_expression(const SPIRConstantOp &cop)
5668 {
5669 auto &type = get<SPIRType>(cop.basetype);
5670 bool binary = false;
5671 bool unary = false;
5672 string op;
5673
5674 if (is_legacy() && is_unsigned_opcode(cop.opcode))
5675 SPIRV_CROSS_THROW("Unsigned integers are not supported on legacy targets.");
5676
5677 // TODO: Find a clean way to reuse emit_instruction.
5678 switch (cop.opcode)
5679 {
5680 case OpSConvert:
5681 case OpUConvert:
5682 case OpFConvert:
5683 op = type_to_glsl_constructor(type);
5684 break;
5685
5686 #define GLSL_BOP(opname, x) \
5687 case Op##opname: \
5688 binary = true; \
5689 op = x; \
5690 break
5691
5692 #define GLSL_UOP(opname, x) \
5693 case Op##opname: \
5694 unary = true; \
5695 op = x; \
5696 break
5697
5698 GLSL_UOP(SNegate, "-");
5699 GLSL_UOP(Not, "~");
5700 GLSL_BOP(IAdd, "+");
5701 GLSL_BOP(ISub, "-");
5702 GLSL_BOP(IMul, "*");
5703 GLSL_BOP(SDiv, "/");
5704 GLSL_BOP(UDiv, "/");
5705 GLSL_BOP(UMod, "%");
5706 GLSL_BOP(SMod, "%");
5707 GLSL_BOP(ShiftRightLogical, ">>");
5708 GLSL_BOP(ShiftRightArithmetic, ">>");
5709 GLSL_BOP(ShiftLeftLogical, "<<");
5710 GLSL_BOP(BitwiseOr, "|");
5711 GLSL_BOP(BitwiseXor, "^");
5712 GLSL_BOP(BitwiseAnd, "&");
5713 GLSL_BOP(LogicalOr, "||");
5714 GLSL_BOP(LogicalAnd, "&&");
5715 GLSL_UOP(LogicalNot, "!");
5716 GLSL_BOP(LogicalEqual, "==");
5717 GLSL_BOP(LogicalNotEqual, "!=");
5718 GLSL_BOP(IEqual, "==");
5719 GLSL_BOP(INotEqual, "!=");
5720 GLSL_BOP(ULessThan, "<");
5721 GLSL_BOP(SLessThan, "<");
5722 GLSL_BOP(ULessThanEqual, "<=");
5723 GLSL_BOP(SLessThanEqual, "<=");
5724 GLSL_BOP(UGreaterThan, ">");
5725 GLSL_BOP(SGreaterThan, ">");
5726 GLSL_BOP(UGreaterThanEqual, ">=");
5727 GLSL_BOP(SGreaterThanEqual, ">=");
5728
5729 case OpSRem:
5730 {
5731 uint32_t op0 = cop.arguments[0];
5732 uint32_t op1 = cop.arguments[1];
5733 return join(to_enclosed_expression(op0), " - ", to_enclosed_expression(op1), " * ", "(",
5734 to_enclosed_expression(op0), " / ", to_enclosed_expression(op1), ")");
5735 }
5736
5737 case OpSelect:
5738 {
5739 if (cop.arguments.size() < 3)
5740 SPIRV_CROSS_THROW("Not enough arguments to OpSpecConstantOp.");
5741
5742 // This one is pretty annoying. It's triggered from
5743 // uint(bool), int(bool) from spec constants.
5744 // In order to preserve its compile-time constness in Vulkan GLSL,
5745 // we need to reduce the OpSelect expression back to this simplified model.
5746 // If we cannot, fail.
5747 if (to_trivial_mix_op(type, op, cop.arguments[2], cop.arguments[1], cop.arguments[0]))
5748 {
5749 // Implement as a simple cast down below.
5750 }
5751 else
5752 {
5753 // Implement a ternary and pray the compiler understands it :)
5754 return to_ternary_expression(type, cop.arguments[0], cop.arguments[1], cop.arguments[2]);
5755 }
5756 break;
5757 }
5758
5759 case OpVectorShuffle:
5760 {
5761 string expr = type_to_glsl_constructor(type);
5762 expr += "(";
5763
5764 uint32_t left_components = expression_type(cop.arguments[0]).vecsize;
5765 string left_arg = to_enclosed_expression(cop.arguments[0]);
5766 string right_arg = to_enclosed_expression(cop.arguments[1]);
5767
5768 for (uint32_t i = 2; i < uint32_t(cop.arguments.size()); i++)
5769 {
5770 uint32_t index = cop.arguments[i];
5771 if (index == 0xFFFFFFFF)
5772 {
5773 SPIRConstant c;
5774 c.constant_type = type.parent_type;
5775 assert(type.parent_type != ID(0));
5776 expr += constant_expression(c);
5777 }
5778 else if (index >= left_components)
5779 {
5780 expr += right_arg + "." + "xyzw"[index - left_components];
5781 }
5782 else
5783 {
5784 expr += left_arg + "." + "xyzw"[index];
5785 }
5786
5787 if (i + 1 < uint32_t(cop.arguments.size()))
5788 expr += ", ";
5789 }
5790
5791 expr += ")";
5792 return expr;
5793 }
5794
5795 case OpCompositeExtract:
5796 {
5797 auto expr = access_chain_internal(cop.arguments[0], &cop.arguments[1], uint32_t(cop.arguments.size() - 1),
5798 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT, nullptr);
5799 return expr;
5800 }
5801
5802 case OpCompositeInsert:
5803 {
5804 SmallVector<ConstantID> new_init = get_composite_constant_ids(cop.arguments[1]);
5805 uint32_t idx;
5806 uint32_t target_id = cop.self;
5807 uint32_t target_type_id = cop.basetype;
5808 // We have to drill down to the part we want to modify, and create new
5809 // constants for each containing part.
5810 for (idx = 2; idx < cop.arguments.size() - 1; ++idx)
5811 {
5812 uint32_t new_const = ir.increase_bound_by(1);
5813 uint32_t old_const = new_init[cop.arguments[idx]];
5814 new_init[cop.arguments[idx]] = new_const;
5815 set_composite_constant(target_id, target_type_id, new_init);
5816 new_init = get_composite_constant_ids(old_const);
5817 target_id = new_const;
5818 target_type_id = get_composite_member_type(target_type_id, cop.arguments[idx]);
5819 }
5820 // Now replace the initializer with the one from this instruction.
5821 new_init[cop.arguments[idx]] = cop.arguments[0];
5822 set_composite_constant(target_id, target_type_id, new_init);
5823 SPIRConstant tmp_const(cop.basetype);
5824 fill_composite_constant(tmp_const, cop.basetype, const_composite_insert_ids[cop.self]);
5825 return constant_expression(tmp_const);
5826 }
5827
5828 default:
5829 // Some opcodes are unimplemented here, these are currently not possible to test from glslang.
5830 SPIRV_CROSS_THROW("Unimplemented spec constant op.");
5831 }
5832
5833 uint32_t bit_width = 0;
5834 if (unary || binary || cop.opcode == OpSConvert || cop.opcode == OpUConvert)
5835 bit_width = expression_type(cop.arguments[0]).width;
5836
5837 SPIRType::BaseType input_type;
5838 bool skip_cast_if_equal_type = opcode_is_sign_invariant(cop.opcode);
5839
5840 switch (cop.opcode)
5841 {
5842 case OpIEqual:
5843 case OpINotEqual:
5844 input_type = to_signed_basetype(bit_width);
5845 break;
5846
5847 case OpSLessThan:
5848 case OpSLessThanEqual:
5849 case OpSGreaterThan:
5850 case OpSGreaterThanEqual:
5851 case OpSMod:
5852 case OpSDiv:
5853 case OpShiftRightArithmetic:
5854 case OpSConvert:
5855 case OpSNegate:
5856 input_type = to_signed_basetype(bit_width);
5857 break;
5858
5859 case OpULessThan:
5860 case OpULessThanEqual:
5861 case OpUGreaterThan:
5862 case OpUGreaterThanEqual:
5863 case OpUMod:
5864 case OpUDiv:
5865 case OpShiftRightLogical:
5866 case OpUConvert:
5867 input_type = to_unsigned_basetype(bit_width);
5868 break;
5869
5870 default:
5871 input_type = type.basetype;
5872 break;
5873 }
5874
5875 #undef GLSL_BOP
5876 #undef GLSL_UOP
5877 if (binary)
5878 {
5879 if (cop.arguments.size() < 2)
5880 SPIRV_CROSS_THROW("Not enough arguments to OpSpecConstantOp.");
5881
5882 string cast_op0;
5883 string cast_op1;
5884 auto expected_type = binary_op_bitcast_helper(cast_op0, cast_op1, input_type, cop.arguments[0],
5885 cop.arguments[1], skip_cast_if_equal_type);
5886
5887 if (type.basetype != input_type && type.basetype != SPIRType::Boolean)
5888 {
5889 expected_type.basetype = input_type;
5890 auto expr = bitcast_glsl_op(type, expected_type);
5891 expr += '(';
5892 expr += join(cast_op0, " ", op, " ", cast_op1);
5893 expr += ')';
5894 return expr;
5895 }
5896 else
5897 return join("(", cast_op0, " ", op, " ", cast_op1, ")");
5898 }
5899 else if (unary)
5900 {
5901 if (cop.arguments.size() < 1)
5902 SPIRV_CROSS_THROW("Not enough arguments to OpSpecConstantOp.");
5903
5904 // Auto-bitcast to result type as needed.
5905 // Works around various casting scenarios in glslang as there is no OpBitcast for specialization constants.
5906 return join("(", op, bitcast_glsl(type, cop.arguments[0]), ")");
5907 }
5908 else if (cop.opcode == OpSConvert || cop.opcode == OpUConvert)
5909 {
5910 if (cop.arguments.size() < 1)
5911 SPIRV_CROSS_THROW("Not enough arguments to OpSpecConstantOp.");
5912
5913 auto &arg_type = expression_type(cop.arguments[0]);
5914 if (arg_type.width < type.width && input_type != arg_type.basetype)
5915 {
5916 auto expected = arg_type;
5917 expected.basetype = input_type;
5918 return join(op, "(", bitcast_glsl(expected, cop.arguments[0]), ")");
5919 }
5920 else
5921 return join(op, "(", to_expression(cop.arguments[0]), ")");
5922 }
5923 else
5924 {
5925 if (cop.arguments.size() < 1)
5926 SPIRV_CROSS_THROW("Not enough arguments to OpSpecConstantOp.");
5927 return join(op, "(", to_expression(cop.arguments[0]), ")");
5928 }
5929 }
5930
5931 string CompilerGLSL::constant_expression(const SPIRConstant &c,
5932 bool inside_block_like_struct_scope,
5933 bool inside_struct_scope)
5934 {
5935 auto &type = get<SPIRType>(c.constant_type);
5936
5937 if (is_pointer(type))
5938 {
5939 return backend.null_pointer_literal;
5940 }
5941 else if (c.is_null_array_specialized_length && backend.requires_matching_array_initializer)
5942 {
5943 require_extension_internal("GL_EXT_null_initializer");
5944 return backend.constant_null_initializer;
5945 }
5946 else if (c.replicated && type.op != spv::OpTypeArray)
5947 {
5948 if (type.op == spv::OpTypeMatrix)
5949 {
5950 uint32_t num_elements = type.columns;
5951 // GLSL does not allow the replication constructor for matrices
5952 // mat4(vec4(0.0)) needs to be manually expanded to mat4(vec4(0.0), vec4(0.0), vec4(0.0), vec4(0.0));
5953 std::string res;
5954 res += type_to_glsl(type);
5955 res += "(";
5956 for (uint32_t i = 0; i < num_elements; i++)
5957 {
5958 res += to_expression(c.subconstants[0]);
5959 if (i < num_elements - 1)
5960 res += ", ";
5961 }
5962 res += ")";
5963 return res;
5964 }
5965 else
5966 {
5967 return join(type_to_glsl(type), "(", to_expression(c.subconstants[0]), ")");
5968 }
5969 }
5970 else if (!c.subconstants.empty())
5971 {
5972 // Handles Arrays and structures.
5973 string res;
5974
5975 // Only consider the decay if we are inside a struct scope where we are emitting a member with Offset decoration.
5976 // Outside a block-like struct declaration, we can always bind to a constant array with templated type.
5977 // Should look at ArrayStride here as well, but it's possible to declare a constant struct
5978 // with Offset = 0, using no ArrayStride on the enclosed array type.
5979 // A particular CTS test hits this scenario.
5980 bool array_type_decays = inside_block_like_struct_scope &&
5981 is_array(type) &&
5982 !backend.array_is_value_type_in_buffer_blocks;
5983
5984 // Allow Metal to use the array<T> template to make arrays a value type
5985 bool needs_trailing_tracket = false;
5986 if (backend.use_initializer_list && backend.use_typed_initializer_list && type.basetype == SPIRType::Struct &&
5987 !is_array(type))
5988 {
5989 res = type_to_glsl_constructor(type) + "{ ";
5990 }
5991 else if (backend.use_initializer_list && backend.use_typed_initializer_list && backend.array_is_value_type &&
5992 is_array(type) && !array_type_decays)
5993 {
5994 const auto *p_type = &type;
5995 SPIRType tmp_type { OpNop };
5996
5997 if (inside_struct_scope &&
5998 backend.boolean_in_struct_remapped_type != SPIRType::Boolean &&
5999 type.basetype == SPIRType::Boolean)
6000 {
6001 tmp_type = type;
6002 tmp_type.basetype = backend.boolean_in_struct_remapped_type;
6003 p_type = &tmp_type;
6004 }
6005
6006 res = type_to_glsl_constructor(*p_type) + "({ ";
6007 needs_trailing_tracket = true;
6008 }
6009 else if (backend.use_initializer_list)
6010 {
6011 res = "{ ";
6012 }
6013 else
6014 {
6015 res = type_to_glsl_constructor(type) + "(";
6016 }
6017
6018 uint32_t subconstant_index = 0;
6019 size_t num_elements = c.subconstants.size();
6020 if (c.replicated)
6021 {
6022 if (type.array.size() != 1)
6023 SPIRV_CROSS_THROW("Multidimensional arrays not yet supported as replicated constans");
6024 num_elements = type.array[0];
6025 }
6026 for (size_t i = 0; i < num_elements; i++)
6027 {
6028 auto &elem = c.subconstants[c.replicated ? 0 : i];
6029 if (auto *op = maybe_get<SPIRConstantOp>(elem))
6030 {
6031 res += constant_op_expression(*op);
6032 }
6033 else if (maybe_get<SPIRUndef>(elem) != nullptr)
6034 {
6035 res += to_name(elem);
6036 }
6037 else
6038 {
6039 auto &subc = get<SPIRConstant>(elem);
6040 if (subc.specialization && !expression_is_forwarded(elem))
6041 res += to_name(elem);
6042 else
6043 {
6044 if (!is_array(type) && type.basetype == SPIRType::Struct)
6045 {
6046 // When we get down to emitting struct members, override the block-like information.
6047 // For constants, we can freely mix and match block-like state.
6048 inside_block_like_struct_scope =
6049 has_member_decoration(type.self, subconstant_index, DecorationOffset);
6050 }
6051
6052 if (type.basetype == SPIRType::Struct)
6053 inside_struct_scope = true;
6054
6055 res += constant_expression(subc, inside_block_like_struct_scope, inside_struct_scope);
6056 }
6057 }
6058
6059 if (i != num_elements - 1)
6060 res += ", ";
6061
6062 subconstant_index++;
6063 }
6064
6065 res += backend.use_initializer_list ? " }" : ")";
6066 if (needs_trailing_tracket)
6067 res += ")";
6068
6069 return res;
6070 }
6071 else if (type.basetype == SPIRType::Struct && type.member_types.size() == 0)
6072 {
6073 // Metal tessellation likes empty structs which are then constant expressions.
6074 if (backend.supports_empty_struct)
6075 return "{ }";
6076 else if (backend.use_typed_initializer_list)
6077 return join(type_to_glsl(type), "{ 0 }");
6078 else if (backend.use_initializer_list)
6079 return "{ 0 }";
6080 else
6081 return join(type_to_glsl(type), "(0)");
6082 }
6083 else if (c.columns() == 1 && type.op != spv::OpTypeCooperativeMatrixKHR)
6084 {
6085 auto res = constant_expression_vector(c, 0);
6086
6087 if (inside_struct_scope &&
6088 backend.boolean_in_struct_remapped_type != SPIRType::Boolean &&
6089 type.basetype == SPIRType::Boolean)
6090 {
6091 SPIRType tmp_type = type;
6092 tmp_type.basetype = backend.boolean_in_struct_remapped_type;
6093 res = join(type_to_glsl(tmp_type), "(", res, ")");
6094 }
6095
6096 return res;
6097 }
6098 else
6099 {
6100 string res = type_to_glsl(type) + "(";
6101 for (uint32_t col = 0; col < c.columns(); col++)
6102 {
6103 if (c.specialization_constant_id(col) != 0)
6104 res += to_name(c.specialization_constant_id(col));
6105 else
6106 res += constant_expression_vector(c, col);
6107
6108 if (col + 1 < c.columns())
6109 res += ", ";
6110 }
6111 res += ")";
6112
6113 if (inside_struct_scope &&
6114 backend.boolean_in_struct_remapped_type != SPIRType::Boolean &&
6115 type.basetype == SPIRType::Boolean)
6116 {
6117 SPIRType tmp_type = type;
6118 tmp_type.basetype = backend.boolean_in_struct_remapped_type;
6119 res = join(type_to_glsl(tmp_type), "(", res, ")");
6120 }
6121
6122 return res;
6123 }
6124 }
6125
6126 #ifdef _MSC_VER
6127 // snprintf does not exist or is buggy on older MSVC versions, some of them
6128 // being used by MinGW. Use sprintf instead and disable corresponding warning.
6129 #pragma warning(push)
6130 #pragma warning(disable : 4996)
6131 #endif
6132
6133 string CompilerGLSL::convert_floate4m3_to_string(const SPIRConstant &c, uint32_t col, uint32_t row)
6134 {
6135 string res;
6136 float float_value = c.scalar_floate4m3(col, row);
6137
6138 // There is no infinity in e4m3.
6139 if (std::isnan(float_value))
6140 {
6141 SPIRType type { OpTypeFloat };
6142 type.basetype = SPIRType::Half;
6143 type.vecsize = 1;
6144 type.columns = 1;
6145 res = join(type_to_glsl(type), "(0.0 / 0.0)");
6146 }
6147 else
6148 {
6149 SPIRType type { OpTypeFloat };
6150 type.basetype = SPIRType::FloatE4M3;
6151 type.vecsize = 1;
6152 type.columns = 1;
6153 res = join(type_to_glsl(type), "(", format_float(float_value), ")");
6154 }
6155
6156 return res;
6157 }
6158
6159 string CompilerGLSL::convert_half_to_string(const SPIRConstant &c, uint32_t col, uint32_t row)
6160 {
6161 string res;
6162 bool is_bfloat8 = get<SPIRType>(c.constant_type).basetype == SPIRType::FloatE5M2;
6163 float float_value = is_bfloat8 ? c.scalar_bf8(col, row) : c.scalar_f16(col, row);
6164
6165 // There is no literal "hf" in GL_NV_gpu_shader5, so to avoid lots
6166 // of complicated workarounds, just value-cast to the half type always.
6167 if (std::isnan(float_value) || std::isinf(float_value))
6168 {
6169 SPIRType type { OpTypeFloat };
6170 type.basetype = is_bfloat8 ? SPIRType::FloatE5M2 : SPIRType::Half;
6171 type.vecsize = 1;
6172 type.columns = 1;
6173
6174 if (float_value == numeric_limits<float>::infinity())
6175 res = join(type_to_glsl(type), "(1.0 / 0.0)");
6176 else if (float_value == -numeric_limits<float>::infinity())
6177 res = join(type_to_glsl(type), "(-1.0 / 0.0)");
6178 else if (std::isnan(float_value))
6179 res = join(type_to_glsl(type), "(0.0 / 0.0)");
6180 else
6181 SPIRV_CROSS_THROW("Cannot represent non-finite floating point constant.");
6182 }
6183 else
6184 {
6185 SPIRType type { OpTypeFloat };
6186 type.basetype = is_bfloat8 ? SPIRType::FloatE5M2 : SPIRType::Half;
6187 type.vecsize = 1;
6188 type.columns = 1;
6189 res = join(type_to_glsl(type), "(", format_float(float_value), ")");
6190 }
6191
6192 return res;
6193 }
6194
6195 string CompilerGLSL::convert_float_to_string(const SPIRConstant &c, uint32_t col, uint32_t row)
6196 {
6197 string res;
6198
6199 bool is_bfloat16 = get<SPIRType>(c.constant_type).basetype == SPIRType::BFloat16;
6200 float float_value = is_bfloat16 ? c.scalar_bf16(col, row) : c.scalar_f32(col, row);
6201
6202 if (std::isnan(float_value) || std::isinf(float_value))
6203 {
6204 // Use special representation.
6205 if (!is_legacy())
6206 {
6207 SPIRType out_type { OpTypeFloat };
6208 SPIRType in_type { OpTypeInt };
6209 out_type.basetype = SPIRType::Float;
6210 in_type.basetype = SPIRType::UInt;
6211 out_type.vecsize = 1;
6212 in_type.vecsize = 1;
6213 out_type.width = 32;
6214 in_type.width = 32;
6215
6216 char print_buffer[32];
6217 #ifdef _WIN32
6218 sprintf(print_buffer, "0x%xu", c.scalar(col, row));
6219 #else
6220 snprintf(print_buffer, sizeof(print_buffer), "0x%xu", c.scalar(col, row));
6221 #endif
6222
6223 const char *comment = "inf";
6224 if (float_value == -numeric_limits<float>::infinity())
6225 comment = "-inf";
6226 else if (std::isnan(float_value))
6227 comment = "nan";
6228 res = join(bitcast_glsl_op(out_type, in_type), "(", print_buffer, " /* ", comment, " */)");
6229 }
6230 else
6231 {
6232 if (float_value == numeric_limits<float>::infinity())
6233 {
6234 if (backend.float_literal_suffix)
6235 res = "(1.0f / 0.0f)";
6236 else
6237 res = "(1.0 / 0.0)";
6238 }
6239 else if (float_value == -numeric_limits<float>::infinity())
6240 {
6241 if (backend.float_literal_suffix)
6242 res = "(-1.0f / 0.0f)";
6243 else
6244 res = "(-1.0 / 0.0)";
6245 }
6246 else if (std::isnan(float_value))
6247 {
6248 if (backend.float_literal_suffix)
6249 res = "(0.0f / 0.0f)";
6250 else
6251 res = "(0.0 / 0.0)";
6252 }
6253 else
6254 SPIRV_CROSS_THROW("Cannot represent non-finite floating point constant.");
6255 }
6256 }
6257 else
6258 {
6259 res = format_float(float_value);
6260 if (backend.float_literal_suffix)
6261 res += "f";
6262 }
6263
6264 if (is_bfloat16)
6265 res = join("bfloat16_t(", res, ")");
6266
6267 return res;
6268 }
6269
6270 std::string CompilerGLSL::convert_double_to_string(const SPIRConstant &c, uint32_t col, uint32_t row)
6271 {
6272 string res;
6273 double double_value = c.scalar_f64(col, row);
6274
6275 if (std::isnan(double_value) || std::isinf(double_value))
6276 {
6277 // Use special representation.
6278 if (!is_legacy())
6279 {
6280 SPIRType out_type { OpTypeFloat };
6281 SPIRType in_type { OpTypeInt };
6282 out_type.basetype = SPIRType::Double;
6283 in_type.basetype = SPIRType::UInt64;
6284 out_type.vecsize = 1;
6285 in_type.vecsize = 1;
6286 out_type.width = 64;
6287 in_type.width = 64;
6288
6289 uint64_t u64_value = c.scalar_u64(col, row);
6290
6291 if (options.es && options.version < 310) // GL_NV_gpu_shader5 fallback requires 310.
6292 SPIRV_CROSS_THROW("64-bit integers not supported in ES profile before version 310.");
6293 require_extension_internal("GL_ARB_gpu_shader_int64");
6294
6295 char print_buffer[64];
6296 #ifdef _WIN32
6297 sprintf(print_buffer, "0x%llx%s", static_cast<unsigned long long>(u64_value),
6298 backend.long_long_literal_suffix ? "ull" : "ul");
6299 #else
6300 snprintf(print_buffer, sizeof(print_buffer), "0x%llx%s", static_cast<unsigned long long>(u64_value),
6301 backend.long_long_literal_suffix ? "ull" : "ul");
6302 #endif
6303
6304 const char *comment = "inf";
6305 if (double_value == -numeric_limits<double>::infinity())
6306 comment = "-inf";
6307 else if (std::isnan(double_value))
6308 comment = "nan";
6309 res = join(bitcast_glsl_op(out_type, in_type), "(", print_buffer, " /* ", comment, " */)");
6310 }
6311 else
6312 {
6313 if (options.es)
6314 SPIRV_CROSS_THROW("FP64 not supported in ES profile.");
6315 if (options.version < 400)
6316 require_extension_internal("GL_ARB_gpu_shader_fp64");
6317
6318 if (double_value == numeric_limits<double>::infinity())
6319 {
6320 if (backend.double_literal_suffix)
6321 res = "(1.0lf / 0.0lf)";
6322 else
6323 res = "(1.0 / 0.0)";
6324 }
6325 else if (double_value == -numeric_limits<double>::infinity())
6326 {
6327 if (backend.double_literal_suffix)
6328 res = "(-1.0lf / 0.0lf)";
6329 else
6330 res = "(-1.0 / 0.0)";
6331 }
6332 else if (std::isnan(double_value))
6333 {
6334 if (backend.double_literal_suffix)
6335 res = "(0.0lf / 0.0lf)";
6336 else
6337 res = "(0.0 / 0.0)";
6338 }
6339 else
6340 SPIRV_CROSS_THROW("Cannot represent non-finite floating point constant.");
6341 }
6342 }
6343 else
6344 {
6345 res = format_double(double_value);
6346 if (backend.double_literal_suffix)
6347 res += "lf";
6348 }
6349
6350 return res;
6351 }
6352
6353 #ifdef _MSC_VER
6354 #pragma warning(pop)
6355 #endif
6356
6357 string CompilerGLSL::constant_expression_vector(const SPIRConstant &c, uint32_t vector)
6358 {
6359 auto type = get<SPIRType>(c.constant_type);
6360 type.columns = 1;
6361
6362 auto scalar_type = type;
6363 scalar_type.vecsize = 1;
6364
6365 string res;
6366 bool splat = backend.use_constructor_splatting && c.vector_size() > 1;
6367 bool swizzle_splat = backend.can_swizzle_scalar && c.vector_size() > 1;
6368
6369 if (!type_is_floating_point(type))
6370 {
6371 // Cannot swizzle literal integers as a special case.
6372 swizzle_splat = false;
6373 }
6374
6375 if (splat || swizzle_splat)
6376 {
6377 // Cannot use constant splatting if we have specialization constants somewhere in the vector.
6378 for (uint32_t i = 0; i < c.vector_size(); i++)
6379 {
6380 if (c.specialization_constant_id(vector, i) != 0)
6381 {
6382 splat = false;
6383 swizzle_splat = false;
6384 break;
6385 }
6386 }
6387 }
6388
6389 if (splat || swizzle_splat)
6390 {
6391 if (type.width == 64)
6392 {
6393 uint64_t ident = c.scalar_u64(vector, 0);
6394 for (uint32_t i = 1; i < c.vector_size(); i++)
6395 {
6396 if (ident != c.scalar_u64(vector, i))
6397 {
6398 splat = false;
6399 swizzle_splat = false;
6400 break;
6401 }
6402 }
6403 }
6404 else
6405 {
6406 uint32_t ident = c.scalar(vector, 0);
6407 for (uint32_t i = 1; i < c.vector_size(); i++)
6408 {
6409 if (ident != c.scalar(vector, i))
6410 {
6411 splat = false;
6412 swizzle_splat = false;
6413 }
6414 }
6415 }
6416 }
6417
6418 if (c.vector_size() > 1 && !swizzle_splat)
6419 res += type_to_glsl(type) + "(";
6420
6421 switch (type.basetype)
6422 {
6423 case SPIRType::FloatE4M3:
6424 if (splat || swizzle_splat)
6425 {
6426 res += convert_floate4m3_to_string(c, vector, 0);
6427 if (swizzle_splat)
6428 res = remap_swizzle(get<SPIRType>(c.constant_type), 1, res);
6429 }
6430 else
6431 {
6432 for (uint32_t i = 0; i < c.vector_size(); i++)
6433 {
6434 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6435 res += to_expression(c.specialization_constant_id(vector, i));
6436 else
6437 res += convert_floate4m3_to_string(c, vector, i);
6438
6439 if (i + 1 < c.vector_size())
6440 res += ", ";
6441 }
6442 }
6443 break;
6444
6445 case SPIRType::FloatE5M2:
6446 case SPIRType::Half:
6447 if (splat || swizzle_splat)
6448 {
6449 res += convert_half_to_string(c, vector, 0);
6450 if (swizzle_splat)
6451 res = remap_swizzle(get<SPIRType>(c.constant_type), 1, res);
6452 }
6453 else
6454 {
6455 for (uint32_t i = 0; i < c.vector_size(); i++)
6456 {
6457 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6458 res += to_expression(c.specialization_constant_id(vector, i));
6459 else
6460 res += convert_half_to_string(c, vector, i);
6461
6462 if (i + 1 < c.vector_size())
6463 res += ", ";
6464 }
6465 }
6466 break;
6467
6468 case SPIRType::BFloat16:
6469 case SPIRType::Float:
6470 if (splat || swizzle_splat)
6471 {
6472 res += convert_float_to_string(c, vector, 0);
6473 if (swizzle_splat)
6474 res = remap_swizzle(get<SPIRType>(c.constant_type), 1, res);
6475 }
6476 else
6477 {
6478 for (uint32_t i = 0; i < c.vector_size(); i++)
6479 {
6480 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6481 res += to_expression(c.specialization_constant_id(vector, i));
6482 else
6483 res += convert_float_to_string(c, vector, i);
6484
6485 if (i + 1 < c.vector_size())
6486 res += ", ";
6487 }
6488 }
6489 break;
6490
6491 case SPIRType::Double:
6492 if (splat || swizzle_splat)
6493 {
6494 res += convert_double_to_string(c, vector, 0);
6495 if (swizzle_splat)
6496 res = remap_swizzle(get<SPIRType>(c.constant_type), 1, res);
6497 }
6498 else
6499 {
6500 for (uint32_t i = 0; i < c.vector_size(); i++)
6501 {
6502 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6503 res += to_expression(c.specialization_constant_id(vector, i));
6504 else
6505 res += convert_double_to_string(c, vector, i);
6506
6507 if (i + 1 < c.vector_size())
6508 res += ", ";
6509 }
6510 }
6511 break;
6512
6513 case SPIRType::Int64:
6514 {
6515 auto tmp = type;
6516 tmp.vecsize = 1;
6517 tmp.columns = 1;
6518 auto int64_type = type_to_glsl(tmp);
6519
6520 if (splat)
6521 {
6522 res += convert_to_string(c.scalar_i64(vector, 0), int64_type, backend.long_long_literal_suffix);
6523 }
6524 else
6525 {
6526 for (uint32_t i = 0; i < c.vector_size(); i++)
6527 {
6528 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6529 res += to_expression(c.specialization_constant_id(vector, i));
6530 else
6531 res += convert_to_string(c.scalar_i64(vector, i), int64_type, backend.long_long_literal_suffix);
6532
6533 if (i + 1 < c.vector_size())
6534 res += ", ";
6535 }
6536 }
6537 break;
6538 }
6539
6540 case SPIRType::UInt64:
6541 if (splat)
6542 {
6543 res += convert_to_string(c.scalar_u64(vector, 0));
6544 if (backend.long_long_literal_suffix)
6545 res += "ull";
6546 else
6547 res += "ul";
6548 }
6549 else
6550 {
6551 for (uint32_t i = 0; i < c.vector_size(); i++)
6552 {
6553 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6554 res += to_expression(c.specialization_constant_id(vector, i));
6555 else
6556 {
6557 res += convert_to_string(c.scalar_u64(vector, i));
6558 if (backend.long_long_literal_suffix)
6559 res += "ull";
6560 else
6561 res += "ul";
6562 }
6563
6564 if (i + 1 < c.vector_size())
6565 res += ", ";
6566 }
6567 }
6568 break;
6569
6570 case SPIRType::UInt:
6571 if (splat)
6572 {
6573 res += convert_to_string(c.scalar(vector, 0));
6574 if (is_legacy() && !has_extension("GL_EXT_gpu_shader4"))
6575 {
6576 // Fake unsigned constant literals with signed ones if possible.
6577 // Things like array sizes, etc, tend to be unsigned even though they could just as easily be signed.
6578 if (c.scalar_i32(vector, 0) < 0)
6579 SPIRV_CROSS_THROW("Tried to convert uint literal into int, but this made the literal negative.");
6580 }
6581 else if (backend.uint32_t_literal_suffix)
6582 res += "u";
6583 }
6584 else
6585 {
6586 for (uint32_t i = 0; i < c.vector_size(); i++)
6587 {
6588 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6589 res += to_expression(c.specialization_constant_id(vector, i));
6590 else
6591 {
6592 res += convert_to_string(c.scalar(vector, i));
6593 if (is_legacy() && !has_extension("GL_EXT_gpu_shader4"))
6594 {
6595 // Fake unsigned constant literals with signed ones if possible.
6596 // Things like array sizes, etc, tend to be unsigned even though they could just as easily be signed.
6597 if (c.scalar_i32(vector, i) < 0)
6598 SPIRV_CROSS_THROW("Tried to convert uint literal into int, but this made "
6599 "the literal negative.");
6600 }
6601 else if (backend.uint32_t_literal_suffix)
6602 res += "u";
6603 }
6604
6605 if (i + 1 < c.vector_size())
6606 res += ", ";
6607 }
6608 }
6609 break;
6610
6611 case SPIRType::Int:
6612 if (splat)
6613 res += convert_to_string(c.scalar_i32(vector, 0));
6614 else
6615 {
6616 for (uint32_t i = 0; i < c.vector_size(); i++)
6617 {
6618 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6619 res += to_expression(c.specialization_constant_id(vector, i));
6620 else
6621 res += convert_to_string(c.scalar_i32(vector, i));
6622 if (i + 1 < c.vector_size())
6623 res += ", ";
6624 }
6625 }
6626 break;
6627
6628 case SPIRType::UShort:
6629 if (splat)
6630 {
6631 res += convert_to_string(c.scalar(vector, 0));
6632 }
6633 else
6634 {
6635 for (uint32_t i = 0; i < c.vector_size(); i++)
6636 {
6637 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6638 res += to_expression(c.specialization_constant_id(vector, i));
6639 else
6640 {
6641 if (*backend.uint16_t_literal_suffix)
6642 {
6643 res += convert_to_string(c.scalar_u16(vector, i));
6644 res += backend.uint16_t_literal_suffix;
6645 }
6646 else
6647 {
6648 // If backend doesn't have a literal suffix, we need to value cast.
6649 res += type_to_glsl(scalar_type);
6650 res += "(";
6651 res += convert_to_string(c.scalar_u16(vector, i));
6652 res += ")";
6653 }
6654 }
6655
6656 if (i + 1 < c.vector_size())
6657 res += ", ";
6658 }
6659 }
6660 break;
6661
6662 case SPIRType::Short:
6663 if (splat)
6664 {
6665 res += convert_to_string(c.scalar_i16(vector, 0));
6666 }
6667 else
6668 {
6669 for (uint32_t i = 0; i < c.vector_size(); i++)
6670 {
6671 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6672 res += to_expression(c.specialization_constant_id(vector, i));
6673 else
6674 {
6675 if (*backend.int16_t_literal_suffix)
6676 {
6677 res += convert_to_string(c.scalar_i16(vector, i));
6678 res += backend.int16_t_literal_suffix;
6679 }
6680 else
6681 {
6682 // If backend doesn't have a literal suffix, we need to value cast.
6683 res += type_to_glsl(scalar_type);
6684 res += "(";
6685 res += convert_to_string(c.scalar_i16(vector, i));
6686 res += ")";
6687 }
6688 }
6689
6690 if (i + 1 < c.vector_size())
6691 res += ", ";
6692 }
6693 }
6694 break;
6695
6696 case SPIRType::UByte:
6697 if (splat)
6698 {
6699 res += convert_to_string(c.scalar_u8(vector, 0));
6700 }
6701 else
6702 {
6703 for (uint32_t i = 0; i < c.vector_size(); i++)
6704 {
6705 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6706 res += to_expression(c.specialization_constant_id(vector, i));
6707 else
6708 {
6709 res += type_to_glsl(scalar_type);
6710 res += "(";
6711 res += convert_to_string(c.scalar_u8(vector, i));
6712 res += ")";
6713 }
6714
6715 if (i + 1 < c.vector_size())
6716 res += ", ";
6717 }
6718 }
6719 break;
6720
6721 case SPIRType::SByte:
6722 if (splat)
6723 {
6724 res += convert_to_string(c.scalar_i8(vector, 0));
6725 }
6726 else
6727 {
6728 for (uint32_t i = 0; i < c.vector_size(); i++)
6729 {
6730 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6731 res += to_expression(c.specialization_constant_id(vector, i));
6732 else
6733 {
6734 res += type_to_glsl(scalar_type);
6735 res += "(";
6736 res += convert_to_string(c.scalar_i8(vector, i));
6737 res += ")";
6738 }
6739
6740 if (i + 1 < c.vector_size())
6741 res += ", ";
6742 }
6743 }
6744 break;
6745
6746 case SPIRType::Boolean:
6747 if (splat)
6748 res += c.scalar(vector, 0) ? "true" : "false";
6749 else
6750 {
6751 for (uint32_t i = 0; i < c.vector_size(); i++)
6752 {
6753 if (c.vector_size() > 1 && c.specialization_constant_id(vector, i) != 0)
6754 res += to_expression(c.specialization_constant_id(vector, i));
6755 else
6756 res += c.scalar(vector, i) ? "true" : "false";
6757
6758 if (i + 1 < c.vector_size())
6759 res += ", ";
6760 }
6761 }
6762 break;
6763
6764 default:
6765 SPIRV_CROSS_THROW("Invalid constant expression basetype.");
6766 }
6767
6768 if (c.vector_size() > 1 && !swizzle_splat)
6769 res += ")";
6770
6771 return res;
6772 }
6773
6774 SPIRExpression &CompilerGLSL::emit_uninitialized_temporary_expression(uint32_t type, uint32_t id)
6775 {
6776 forced_temporaries.insert(id);
6777 emit_uninitialized_temporary(type, id);
6778 return set<SPIRExpression>(id, to_name(id), type, true);
6779 }
6780
6781 void CompilerGLSL::emit_uninitialized_temporary(uint32_t result_type, uint32_t result_id)
6782 {
6783 // If we're declaring temporaries inside continue blocks,
6784 // we must declare the temporary in the loop header so that the continue block can avoid declaring new variables.
6785 if (!block_temporary_hoisting && current_continue_block && !hoisted_temporaries.count(result_id))
6786 {
6787 auto &header = get<SPIRBlock>(current_continue_block->loop_dominator);
6788 if (find_if(begin(header.declare_temporary), end(header.declare_temporary),
6789 [result_type, result_id](const pair<uint32_t, uint32_t> &tmp) {
6790 return tmp.first == result_type && tmp.second == result_id;
6791 }) == end(header.declare_temporary))
6792 {
6793 header.declare_temporary.emplace_back(result_type, result_id);
6794 hoisted_temporaries.insert(result_id);
6795 force_recompile();
6796 }
6797 }
6798 else if (hoisted_temporaries.count(result_id) == 0)
6799 {
6800 auto &type = get<SPIRType>(result_type);
6801 auto &flags = get_decoration_bitset(result_id);
6802
6803 // The result_id has not been made into an expression yet, so use flags interface.
6804 add_local_variable_name(result_id);
6805
6806 string initializer;
6807 if (options.force_zero_initialized_variables && type_can_zero_initialize(type))
6808 initializer = join(" = ", to_zero_initialized_expression(result_type));
6809
6810 statement(flags_to_qualifiers_glsl(type, flags), variable_decl(type, to_name(result_id)), initializer, ";");
6811 }
6812 }
6813
6814 string CompilerGLSL::declare_temporary(uint32_t result_type, uint32_t result_id)
6815 {
6816 auto &type = get<SPIRType>(result_type);
6817
6818 // If we're declaring temporaries inside continue blocks,
6819 // we must declare the temporary in the loop header so that the continue block can avoid declaring new variables.
6820 if (!block_temporary_hoisting && current_continue_block && !hoisted_temporaries.count(result_id))
6821 {
6822 auto &header = get<SPIRBlock>(current_continue_block->loop_dominator);
6823 if (find_if(begin(header.declare_temporary), end(header.declare_temporary),
6824 [result_type, result_id](const pair<uint32_t, uint32_t> &tmp) {
6825 return tmp.first == result_type && tmp.second == result_id;
6826 }) == end(header.declare_temporary))
6827 {
6828 header.declare_temporary.emplace_back(result_type, result_id);
6829 hoisted_temporaries.insert(result_id);
6830 force_recompile_guarantee_forward_progress();
6831 }
6832
6833 return join(to_name(result_id), " = ");
6834 }
6835 else if (hoisted_temporaries.count(result_id))
6836 {
6837 // The temporary has already been declared earlier, so just "declare" the temporary by writing to it.
6838 return join(to_name(result_id), " = ");
6839 }
6840 else
6841 {
6842 // The result_id has not been made into an expression yet, so use flags interface.
6843 add_local_variable_name(result_id);
6844 auto &flags = get_decoration_bitset(result_id);
6845 return join(flags_to_qualifiers_glsl(type, flags), variable_decl(type, to_name(result_id)), " = ");
6846 }
6847 }
6848
6849 bool CompilerGLSL::expression_is_forwarded(uint32_t id) const
6850 {
6851 return forwarded_temporaries.count(id) != 0;
6852 }
6853
6854 bool CompilerGLSL::expression_suppresses_usage_tracking(uint32_t id) const
6855 {
6856 return suppressed_usage_tracking.count(id) != 0;
6857 }
6858
6859 bool CompilerGLSL::expression_read_implies_multiple_reads(uint32_t id) const
6860 {
6861 auto *expr = maybe_get<SPIRExpression>(id);
6862 if (!expr)
6863 return false;
6864
6865 // If we're emitting code at a deeper loop level than when we emitted the expression,
6866 // we're probably reading the same expression over and over.
6867 return current_loop_level > expr->emitted_loop_level;
6868 }
6869
6870 SPIRExpression &CompilerGLSL::emit_op(uint32_t result_type, uint32_t result_id, const string &rhs, bool forwarding,
6871 bool suppress_usage_tracking)
6872 {
6873 if (forwarding && (forced_temporaries.find(result_id) == end(forced_temporaries)))
6874 {
6875 // Just forward it without temporary.
6876 // If the forward is trivial, we do not force flushing to temporary for this expression.
6877 forwarded_temporaries.insert(result_id);
6878 if (suppress_usage_tracking)
6879 suppressed_usage_tracking.insert(result_id);
6880
6881 return set<SPIRExpression>(result_id, rhs, result_type, true);
6882 }
6883 else
6884 {
6885 // If expression isn't immutable, bind it to a temporary and make the new temporary immutable (they always are).
6886 statement(declare_temporary(result_type, result_id), rhs, ";");
6887 return set<SPIRExpression>(result_id, to_name(result_id), result_type, true);
6888 }
6889 }
6890
6891 void CompilerGLSL::emit_unary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op)
6892 {
6893 bool forward = should_forward(op0);
6894 emit_op(result_type, result_id, join(op, to_enclosed_unpacked_expression(op0)), forward);
6895 inherit_expression_dependencies(result_id, op0);
6896 }
6897
6898 void CompilerGLSL::emit_unary_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op)
6899 {
6900 auto &type = get<SPIRType>(result_type);
6901 bool forward = should_forward(op0);
6902 emit_op(result_type, result_id, join(type_to_glsl(type), "(", op, to_enclosed_unpacked_expression(op0), ")"), forward);
6903 inherit_expression_dependencies(result_id, op0);
6904 }
6905
6906 void CompilerGLSL::emit_mesh_tasks(SPIRBlock &block)
6907 {
6908 statement("EmitMeshTasksEXT(",
6909 to_unpacked_expression(block.mesh.groups[0]), ", ",
6910 to_unpacked_expression(block.mesh.groups[1]), ", ",
6911 to_unpacked_expression(block.mesh.groups[2]), ");");
6912 }
6913
6914 void CompilerGLSL::emit_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op)
6915 {
6916 // Various FP arithmetic opcodes such as add, sub, mul will hit this.
6917 bool force_temporary_precise = backend.support_precise_qualifier &&
6918 has_decoration(result_id, DecorationNoContraction) &&
6919 type_is_floating_point(get<SPIRType>(result_type));
6920 bool forward = should_forward(op0) && should_forward(op1) && !force_temporary_precise;
6921
6922 emit_op(result_type, result_id,
6923 join(to_enclosed_unpacked_expression(op0), " ", op, " ", to_enclosed_unpacked_expression(op1)), forward);
6924
6925 inherit_expression_dependencies(result_id, op0);
6926 inherit_expression_dependencies(result_id, op1);
6927 }
6928
6929 void CompilerGLSL::emit_unrolled_unary_op(uint32_t result_type, uint32_t result_id, uint32_t operand, const char *op)
6930 {
6931 auto &type = get<SPIRType>(result_type);
6932 auto expr = type_to_glsl_constructor(type);
6933 expr += '(';
6934 for (uint32_t i = 0; i < type.vecsize; i++)
6935 {
6936 // Make sure to call to_expression multiple times to ensure
6937 // that these expressions are properly flushed to temporaries if needed.
6938 expr += op;
6939 expr += to_extract_component_expression(operand, i);
6940
6941 if (i + 1 < type.vecsize)
6942 expr += ", ";
6943 }
6944 expr += ')';
6945 emit_op(result_type, result_id, expr, should_forward(operand));
6946
6947 inherit_expression_dependencies(result_id, operand);
6948 }
6949
6950 void CompilerGLSL::emit_unrolled_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
6951 const char *op, bool negate, SPIRType::BaseType expected_type)
6952 {
6953 auto &type0 = expression_type(op0);
6954 auto &type1 = expression_type(op1);
6955
6956 SPIRType target_type0 = type0;
6957 SPIRType target_type1 = type1;
6958 target_type0.basetype = expected_type;
6959 target_type1.basetype = expected_type;
6960 target_type0.vecsize = 1;
6961 target_type1.vecsize = 1;
6962
6963 auto &type = get<SPIRType>(result_type);
6964 auto expr = type_to_glsl_constructor(type);
6965 expr += '(';
6966 for (uint32_t i = 0; i < type.vecsize; i++)
6967 {
6968 // Make sure to call to_expression multiple times to ensure
6969 // that these expressions are properly flushed to temporaries if needed.
6970 if (negate)
6971 expr += "!(";
6972
6973 if (expected_type != SPIRType::Unknown && type0.basetype != expected_type)
6974 expr += bitcast_expression(target_type0, type0.basetype, to_extract_component_expression(op0, i));
6975 else
6976 expr += to_extract_component_expression(op0, i);
6977
6978 expr += ' ';
6979 expr += op;
6980 expr += ' ';
6981
6982 if (expected_type != SPIRType::Unknown && type1.basetype != expected_type)
6983 expr += bitcast_expression(target_type1, type1.basetype, to_extract_component_expression(op1, i));
6984 else
6985 expr += to_extract_component_expression(op1, i);
6986
6987 if (negate)
6988 expr += ")";
6989
6990 if (i + 1 < type.vecsize)
6991 expr += ", ";
6992 }
6993 expr += ')';
6994 emit_op(result_type, result_id, expr, should_forward(op0) && should_forward(op1));
6995
6996 inherit_expression_dependencies(result_id, op0);
6997 inherit_expression_dependencies(result_id, op1);
6998 }
6999
7000 SPIRType CompilerGLSL::binary_op_bitcast_helper(string &cast_op0, string &cast_op1, SPIRType::BaseType &input_type,
7001 uint32_t op0, uint32_t op1, bool skip_cast_if_equal_type)
7002 {
7003 auto &type0 = expression_type(op0);
7004 auto &type1 = expression_type(op1);
7005
7006 // We have to bitcast if our inputs are of different type, or if our types are not equal to expected inputs.
7007 // For some functions like OpIEqual and INotEqual, we don't care if inputs are of different types than expected
7008 // since equality test is exactly the same.
7009 bool cast = (type0.basetype != type1.basetype) || (!skip_cast_if_equal_type && type0.basetype != input_type);
7010
7011 // Create a fake type so we can bitcast to it.
7012 // We only deal with regular arithmetic types here like int, uints and so on.
7013 SPIRType expected_type{type0.op};
7014 expected_type.basetype = input_type;
7015 expected_type.vecsize = type0.vecsize;
7016 expected_type.columns = type0.columns;
7017 expected_type.width = type0.width;
7018
7019 if (cast)
7020 {
7021 cast_op0 = bitcast_glsl(expected_type, op0);
7022 cast_op1 = bitcast_glsl(expected_type, op1);
7023 }
7024 else
7025 {
7026 // If we don't cast, our actual input type is that of the first (or second) argument.
7027 cast_op0 = to_enclosed_unpacked_expression(op0);
7028 cast_op1 = to_enclosed_unpacked_expression(op1);
7029 input_type = type0.basetype;
7030 }
7031
7032 return expected_type;
7033 }
7034
7035 bool CompilerGLSL::emit_complex_bitcast(uint32_t result_type, uint32_t id, uint32_t op0)
7036 {
7037 // Some bitcasts may require complex casting sequences, and are implemented here.
7038 // Otherwise a simply unary function will do with bitcast_glsl_op.
7039
7040 auto &output_type = get<SPIRType>(result_type);
7041 auto &input_type = expression_type(op0);
7042 string expr;
7043
7044 if (output_type.basetype == SPIRType::Half && input_type.basetype == SPIRType::Float && input_type.vecsize == 1)
7045 expr = join("unpackFloat2x16(floatBitsToUint(", to_unpacked_expression(op0), "))");
7046 else if (output_type.basetype == SPIRType::Float && input_type.basetype == SPIRType::Half &&
7047 input_type.vecsize == 2)
7048 expr = join("uintBitsToFloat(packFloat2x16(", to_unpacked_expression(op0), "))");
7049 else
7050 return false;
7051
7052 emit_op(result_type, id, expr, should_forward(op0));
7053 return true;
7054 }
7055
7056 void CompilerGLSL::emit_binary_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7057 const char *op, SPIRType::BaseType input_type,
7058 bool skip_cast_if_equal_type,
7059 bool implicit_integer_promotion)
7060 {
7061 string cast_op0, cast_op1;
7062 auto expected_type = binary_op_bitcast_helper(cast_op0, cast_op1, input_type, op0, op1, skip_cast_if_equal_type);
7063 auto &out_type = get<SPIRType>(result_type);
7064
7065 // We might have casted away from the result type, so bitcast again.
7066 // For example, arithmetic right shift with uint inputs.
7067 // Special case boolean outputs since relational opcodes output booleans instead of int/uint.
7068 auto bitop = join(cast_op0, " ", op, " ", cast_op1);
7069 string expr;
7070
7071 if (implicit_integer_promotion)
7072 {
7073 // Simple value cast.
7074 expr = join(type_to_glsl(out_type), '(', bitop, ')');
7075 }
7076 else if (out_type.basetype != input_type && out_type.basetype != SPIRType::Boolean)
7077 {
7078 expected_type.basetype = input_type;
7079 expr = join(bitcast_glsl_op(out_type, expected_type), '(', bitop, ')');
7080 }
7081 else
7082 {
7083 expr = std::move(bitop);
7084 }
7085
7086 emit_op(result_type, result_id, expr, should_forward(op0) && should_forward(op1));
7087 inherit_expression_dependencies(result_id, op0);
7088 inherit_expression_dependencies(result_id, op1);
7089 }
7090
7091 void CompilerGLSL::emit_unary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op)
7092 {
7093 bool forward = should_forward(op0);
7094 emit_op(result_type, result_id, join(op, "(", to_unpacked_expression(op0), ")"), forward);
7095 inherit_expression_dependencies(result_id, op0);
7096 }
7097
7098 void CompilerGLSL::emit_binary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7099 const char *op)
7100 {
7101 // Opaque types (e.g. OpTypeSampledImage) must always be forwarded in GLSL
7102 const auto &type = get_type(result_type);
7103 bool must_forward = type_is_opaque_value(type);
7104 bool forward = must_forward || (should_forward(op0) && should_forward(op1));
7105 emit_op(result_type, result_id, join(op, "(", to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), ")"),
7106 forward);
7107 inherit_expression_dependencies(result_id, op0);
7108 inherit_expression_dependencies(result_id, op1);
7109 }
7110
7111 void CompilerGLSL::emit_atomic_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7112 const char *op)
7113 {
7114 auto &type = get<SPIRType>(result_type);
7115 if (type_is_floating_point(type))
7116 {
7117 if (!options.vulkan_semantics)
7118 SPIRV_CROSS_THROW("Floating point atomics requires Vulkan semantics.");
7119 if (options.es)
7120 SPIRV_CROSS_THROW("Floating point atomics requires desktop GLSL.");
7121 require_extension_internal("GL_EXT_shader_atomic_float");
7122 }
7123
7124 if (type.basetype == SPIRType::UInt64 || type.basetype == SPIRType::Int64)
7125 require_extension_internal("GL_EXT_shader_atomic_int64");
7126
7127 forced_temporaries.insert(result_id);
7128 emit_op(result_type, result_id,
7129 join(op, "(", to_atomic_ptr_expression(op0), ", ",
7130 to_unpacked_expression(op1), ")"), false);
7131 flush_all_atomic_capable_variables();
7132 }
7133
7134 void CompilerGLSL::emit_atomic_func_op(uint32_t result_type, uint32_t result_id,
7135 uint32_t op0, uint32_t op1, uint32_t op2,
7136 const char *op)
7137 {
7138 forced_temporaries.insert(result_id);
7139 emit_op(result_type, result_id,
7140 join(op, "(", to_non_uniform_aware_expression(op0), ", ",
7141 to_unpacked_expression(op1), ", ", to_unpacked_expression(op2), ")"), false);
7142 flush_all_atomic_capable_variables();
7143 }
7144
7145 void CompilerGLSL::emit_unary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op,
7146 SPIRType::BaseType input_type, SPIRType::BaseType expected_result_type)
7147 {
7148 auto &out_type = get<SPIRType>(result_type);
7149 auto &expr_type = expression_type(op0);
7150 auto expected_type = out_type;
7151
7152 // Bit-widths might be different in unary cases because we use it for SConvert/UConvert and friends.
7153 expected_type.basetype = input_type;
7154 expected_type.width = expr_type.width;
7155
7156 string cast_op;
7157 if (expr_type.basetype != input_type)
7158 {
7159 if (expr_type.basetype == SPIRType::Boolean)
7160 cast_op = join(type_to_glsl(expected_type), "(", to_unpacked_expression(op0), ")");
7161 else
7162 cast_op = bitcast_glsl(expected_type, op0);
7163 }
7164 else
7165 cast_op = to_unpacked_expression(op0);
7166
7167 string expr;
7168 if (out_type.basetype != expected_result_type)
7169 {
7170 expected_type.basetype = expected_result_type;
7171 expected_type.width = out_type.width;
7172 if (out_type.basetype == SPIRType::Boolean)
7173 expr = type_to_glsl(out_type);
7174 else
7175 expr = bitcast_glsl_op(out_type, expected_type);
7176 expr += '(';
7177 expr += join(op, "(", cast_op, ")");
7178 expr += ')';
7179 }
7180 else
7181 {
7182 expr += join(op, "(", cast_op, ")");
7183 }
7184
7185 emit_op(result_type, result_id, expr, should_forward(op0));
7186 inherit_expression_dependencies(result_id, op0);
7187 }
7188
7189 // Very special case. Handling bitfieldExtract requires us to deal with different bitcasts of different signs
7190 // and different vector sizes all at once. Need a special purpose method here.
7191 void CompilerGLSL::emit_trinary_func_op_bitextract(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7192 uint32_t op2, const char *op,
7193 SPIRType::BaseType expected_result_type,
7194 SPIRType::BaseType input_type0, SPIRType::BaseType input_type1,
7195 SPIRType::BaseType input_type2)
7196 {
7197 auto &out_type = get<SPIRType>(result_type);
7198 auto expected_type = out_type;
7199 expected_type.basetype = input_type0;
7200
7201 string cast_op0 =
7202 expression_type(op0).basetype != input_type0 ? bitcast_glsl(expected_type, op0) : to_unpacked_expression(op0);
7203
7204 auto op1_expr = to_unpacked_expression(op1);
7205 auto op2_expr = to_unpacked_expression(op2);
7206
7207 // Use value casts here instead. Input must be exactly int or uint, but SPIR-V might be 16-bit.
7208 expected_type.basetype = input_type1;
7209 expected_type.vecsize = 1;
7210 string cast_op1 = expression_type(op1).basetype != input_type1 ?
7211 join(type_to_glsl_constructor(expected_type), "(", op1_expr, ")") :
7212 op1_expr;
7213
7214 expected_type.basetype = input_type2;
7215 expected_type.vecsize = 1;
7216 string cast_op2 = expression_type(op2).basetype != input_type2 ?
7217 join(type_to_glsl_constructor(expected_type), "(", op2_expr, ")") :
7218 op2_expr;
7219
7220 string expr;
7221 if (out_type.basetype != expected_result_type)
7222 {
7223 expected_type.vecsize = out_type.vecsize;
7224 expected_type.basetype = expected_result_type;
7225 expr = bitcast_glsl_op(out_type, expected_type);
7226 expr += '(';
7227 expr += join(op, "(", cast_op0, ", ", cast_op1, ", ", cast_op2, ")");
7228 expr += ')';
7229 }
7230 else
7231 {
7232 expr += join(op, "(", cast_op0, ", ", cast_op1, ", ", cast_op2, ")");
7233 }
7234
7235 emit_op(result_type, result_id, expr, should_forward(op0) && should_forward(op1) && should_forward(op2));
7236 inherit_expression_dependencies(result_id, op0);
7237 inherit_expression_dependencies(result_id, op1);
7238 inherit_expression_dependencies(result_id, op2);
7239 }
7240
7241 void CompilerGLSL::emit_trinary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7242 uint32_t op2, const char *op, SPIRType::BaseType input_type)
7243 {
7244 auto &out_type = get<SPIRType>(result_type);
7245 auto expected_type = out_type;
7246 expected_type.basetype = input_type;
7247 string cast_op0 =
7248 expression_type(op0).basetype != input_type ? bitcast_glsl(expected_type, op0) : to_unpacked_expression(op0);
7249 string cast_op1 =
7250 expression_type(op1).basetype != input_type ? bitcast_glsl(expected_type, op1) : to_unpacked_expression(op1);
7251 string cast_op2 =
7252 expression_type(op2).basetype != input_type ? bitcast_glsl(expected_type, op2) : to_unpacked_expression(op2);
7253
7254 string expr;
7255 if (out_type.basetype != input_type)
7256 {
7257 expr = bitcast_glsl_op(out_type, expected_type);
7258 expr += '(';
7259 expr += join(op, "(", cast_op0, ", ", cast_op1, ", ", cast_op2, ")");
7260 expr += ')';
7261 }
7262 else
7263 {
7264 expr += join(op, "(", cast_op0, ", ", cast_op1, ", ", cast_op2, ")");
7265 }
7266
7267 emit_op(result_type, result_id, expr, should_forward(op0) && should_forward(op1) && should_forward(op2));
7268 inherit_expression_dependencies(result_id, op0);
7269 inherit_expression_dependencies(result_id, op1);
7270 inherit_expression_dependencies(result_id, op2);
7271 }
7272
7273 void CompilerGLSL::emit_binary_func_op_cast_clustered(uint32_t result_type, uint32_t result_id, uint32_t op0,
7274 uint32_t op1, const char *op, SPIRType::BaseType input_type)
7275 {
7276 // Special purpose method for implementing clustered subgroup opcodes.
7277 // Main difference is that op1 does not participate in any casting, it needs to be a literal.
7278 auto &out_type = get<SPIRType>(result_type);
7279 auto expected_type = out_type;
7280 expected_type.basetype = input_type;
7281 string cast_op0 =
7282 expression_type(op0).basetype != input_type ? bitcast_glsl(expected_type, op0) : to_unpacked_expression(op0);
7283
7284 string expr;
7285 if (out_type.basetype != input_type)
7286 {
7287 expr = bitcast_glsl_op(out_type, expected_type);
7288 expr += '(';
7289 expr += join(op, "(", cast_op0, ", ", to_expression(op1), ")");
7290 expr += ')';
7291 }
7292 else
7293 {
7294 expr += join(op, "(", cast_op0, ", ", to_expression(op1), ")");
7295 }
7296
7297 emit_op(result_type, result_id, expr, should_forward(op0));
7298 inherit_expression_dependencies(result_id, op0);
7299 }
7300
7301 void CompilerGLSL::emit_binary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7302 const char *op, SPIRType::BaseType input_type, bool skip_cast_if_equal_type)
7303 {
7304 string cast_op0, cast_op1;
7305 auto expected_type = binary_op_bitcast_helper(cast_op0, cast_op1, input_type, op0, op1, skip_cast_if_equal_type);
7306 auto &out_type = get<SPIRType>(result_type);
7307
7308 // Special case boolean outputs since relational opcodes output booleans instead of int/uint.
7309 string expr;
7310 if (out_type.basetype != input_type && out_type.basetype != SPIRType::Boolean)
7311 {
7312 expected_type.basetype = input_type;
7313 expr = bitcast_glsl_op(out_type, expected_type);
7314 expr += '(';
7315 expr += join(op, "(", cast_op0, ", ", cast_op1, ")");
7316 expr += ')';
7317 }
7318 else
7319 {
7320 expr += join(op, "(", cast_op0, ", ", cast_op1, ")");
7321 }
7322
7323 emit_op(result_type, result_id, expr, should_forward(op0) && should_forward(op1));
7324 inherit_expression_dependencies(result_id, op0);
7325 inherit_expression_dependencies(result_id, op1);
7326 }
7327
7328 void CompilerGLSL::emit_trinary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7329 uint32_t op2, const char *op)
7330 {
7331 bool forward = should_forward(op0) && should_forward(op1) && should_forward(op2);
7332 emit_op(result_type, result_id,
7333 join(op, "(", to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), ", ",
7334 to_unpacked_expression(op2), ")"),
7335 forward);
7336
7337 inherit_expression_dependencies(result_id, op0);
7338 inherit_expression_dependencies(result_id, op1);
7339 inherit_expression_dependencies(result_id, op2);
7340 }
7341
7342 void CompilerGLSL::emit_quaternary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7343 uint32_t op2, uint32_t op3, const char *op)
7344 {
7345 bool forward = should_forward(op0) && should_forward(op1) && should_forward(op2) && should_forward(op3);
7346 emit_op(result_type, result_id,
7347 join(op, "(", to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), ", ",
7348 to_unpacked_expression(op2), ", ", to_unpacked_expression(op3), ")"),
7349 forward);
7350
7351 inherit_expression_dependencies(result_id, op0);
7352 inherit_expression_dependencies(result_id, op1);
7353 inherit_expression_dependencies(result_id, op2);
7354 inherit_expression_dependencies(result_id, op3);
7355 }
7356
7357 void CompilerGLSL::emit_bitfield_insert_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
7358 uint32_t op2, uint32_t op3, const char *op,
7359 SPIRType::BaseType offset_count_type)
7360 {
7361 // Only need to cast offset/count arguments. Types of base/insert must be same as result type,
7362 // and bitfieldInsert is sign invariant.
7363 bool forward = should_forward(op0) && should_forward(op1) && should_forward(op2) && should_forward(op3);
7364
7365 auto op0_expr = to_unpacked_expression(op0);
7366 auto op1_expr = to_unpacked_expression(op1);
7367 auto op2_expr = to_unpacked_expression(op2);
7368 auto op3_expr = to_unpacked_expression(op3);
7369
7370 assert(offset_count_type == SPIRType::UInt || offset_count_type == SPIRType::Int);
7371 SPIRType target_type { OpTypeInt };
7372 target_type.width = 32;
7373 target_type.vecsize = 1;
7374 target_type.basetype = offset_count_type;
7375
7376 if (expression_type(op2).basetype != offset_count_type)
7377 {
7378 // Value-cast here. Input might be 16-bit. GLSL requires int.
7379 op2_expr = join(type_to_glsl_constructor(target_type), "(", op2_expr, ")");
7380 }
7381
7382 if (expression_type(op3).basetype != offset_count_type)
7383 {
7384 // Value-cast here. Input might be 16-bit. GLSL requires int.
7385 op3_expr = join(type_to_glsl_constructor(target_type), "(", op3_expr, ")");
7386 }
7387
7388 emit_op(result_type, result_id, join(op, "(", op0_expr, ", ", op1_expr, ", ", op2_expr, ", ", op3_expr, ")"),
7389 forward);
7390
7391 inherit_expression_dependencies(result_id, op0);
7392 inherit_expression_dependencies(result_id, op1);
7393 inherit_expression_dependencies(result_id, op2);
7394 inherit_expression_dependencies(result_id, op3);
7395 }
7396
7397 string CompilerGLSL::legacy_tex_op(const std::string &op, const SPIRType &imgtype, uint32_t tex)
7398 {
7399 const char *type;
7400 switch (imgtype.image.dim)
7401 {
7402 case spv::Dim1D:
7403 // Force 2D path for ES.
7404 if (options.es)
7405 type = (imgtype.image.arrayed && !options.es) ? "2DArray" : "2D";
7406 else
7407 type = (imgtype.image.arrayed && !options.es) ? "1DArray" : "1D";
7408 break;
7409 case spv::Dim2D:
7410 type = (imgtype.image.arrayed && !options.es) ? "2DArray" : "2D";
7411 break;
7412 case spv::Dim3D:
7413 type = "3D";
7414 break;
7415 case spv::DimCube:
7416 type = "Cube";
7417 break;
7418 case spv::DimRect:
7419 type = "2DRect";
7420 break;
7421 case spv::DimBuffer:
7422 type = "Buffer";
7423 break;
7424 case spv::DimSubpassData:
7425 type = "2D";
7426 break;
7427 default:
7428 type = "";
7429 break;
7430 }
7431
7432 // In legacy GLSL, an extension is required for textureLod in the fragment
7433 // shader or textureGrad anywhere.
7434 bool legacy_lod_ext = false;
7435 auto &execution = get_entry_point();
7436 if (op == "textureGrad" || op == "textureProjGrad" ||
7437 ((op == "textureLod" || op == "textureProjLod") && execution.model != ExecutionModelVertex))
7438 {
7439 if (is_legacy_es())
7440 {
7441 legacy_lod_ext = true;
7442 require_extension_internal("GL_EXT_shader_texture_lod");
7443 }
7444 else if (is_legacy_desktop())
7445 require_extension_internal("GL_ARB_shader_texture_lod");
7446 }
7447
7448 if (op == "textureLodOffset" || op == "textureProjLodOffset")
7449 {
7450 if (is_legacy_es())
7451 SPIRV_CROSS_THROW(join(op, " not allowed in legacy ES"));
7452
7453 require_extension_internal("GL_EXT_gpu_shader4");
7454 }
7455
7456 // GLES has very limited support for shadow samplers.
7457 // Basically shadow2D and shadow2DProj work through EXT_shadow_samplers,
7458 // everything else can just throw
7459 bool is_comparison = is_depth_image(imgtype, tex);
7460 if (is_comparison && is_legacy_es())
7461 {
7462 if (op == "texture" || op == "textureProj")
7463 require_extension_internal("GL_EXT_shadow_samplers");
7464 else
7465 SPIRV_CROSS_THROW(join(op, " not allowed on depth samplers in legacy ES"));
7466
7467 if (imgtype.image.dim == spv::DimCube)
7468 return "shadowCubeNV";
7469 }
7470
7471 if (op == "textureSize")
7472 {
7473 if (is_legacy_es())
7474 SPIRV_CROSS_THROW("textureSize not supported in legacy ES");
7475 if (is_comparison)
7476 SPIRV_CROSS_THROW("textureSize not supported on shadow sampler in legacy GLSL");
7477 require_extension_internal("GL_EXT_gpu_shader4");
7478 }
7479
7480 if (op == "texelFetch" && is_legacy_es())
7481 SPIRV_CROSS_THROW("texelFetch not supported in legacy ES");
7482
7483 bool is_es_and_depth = is_legacy_es() && is_comparison;
7484 std::string type_prefix = is_comparison ? "shadow" : "texture";
7485
7486 if (op == "texture")
7487 return is_es_and_depth ? join(type_prefix, type, "EXT") : join(type_prefix, type);
7488 else if (op == "textureLod")
7489 return join(type_prefix, type, legacy_lod_ext ? "LodEXT" : "Lod");
7490 else if (op == "textureProj")
7491 return join(type_prefix, type, is_es_and_depth ? "ProjEXT" : "Proj");
7492 else if (op == "textureGrad")
7493 return join(type_prefix, type, is_legacy_es() ? "GradEXT" : is_legacy_desktop() ? "GradARB" : "Grad");
7494 else if (op == "textureProjLod")
7495 return join(type_prefix, type, legacy_lod_ext ? "ProjLodEXT" : "ProjLod");
7496 else if (op == "textureLodOffset")
7497 return join(type_prefix, type, "LodOffset");
7498 else if (op == "textureProjGrad")
7499 return join(type_prefix, type,
7500 is_legacy_es() ? "ProjGradEXT" : is_legacy_desktop() ? "ProjGradARB" : "ProjGrad");
7501 else if (op == "textureProjLodOffset")
7502 return join(type_prefix, type, "ProjLodOffset");
7503 else if (op == "textureSize")
7504 return join("textureSize", type);
7505 else if (op == "texelFetch")
7506 return join("texelFetch", type);
7507 else
7508 {
7509 SPIRV_CROSS_THROW(join("Unsupported legacy texture op: ", op));
7510 }
7511 }
7512
7513 bool CompilerGLSL::to_trivial_mix_op(const SPIRType &type, string &op, uint32_t left, uint32_t right, uint32_t lerp)
7514 {
7515 auto *cleft = maybe_get<SPIRConstant>(left);
7516 auto *cright = maybe_get<SPIRConstant>(right);
7517 auto &lerptype = expression_type(lerp);
7518
7519 // If our targets aren't constants, we cannot use construction.
7520 if (!cleft || !cright)
7521 return false;
7522
7523 // If our targets are spec constants, we cannot use construction.
7524 if (cleft->specialization || cright->specialization)
7525 return false;
7526
7527 auto &value_type = get<SPIRType>(cleft->constant_type);
7528
7529 if (lerptype.basetype != SPIRType::Boolean)
7530 return false;
7531 if (value_type.basetype == SPIRType::Struct || is_array(value_type))
7532 return false;
7533 if (!backend.use_constructor_splatting && value_type.vecsize != lerptype.vecsize)
7534 return false;
7535
7536 // Only valid way in SPIR-V 1.4 to use matrices in select is a scalar select.
7537 // matrix(scalar) constructor fills in diagnonals, so gets messy very quickly.
7538 // Just avoid this case.
7539 if (value_type.columns > 1)
7540 return false;
7541
7542 // If our bool selects between 0 and 1, we can cast from bool instead, making our trivial constructor.
7543 bool ret = true;
7544 for (uint32_t row = 0; ret && row < value_type.vecsize; row++)
7545 {
7546 switch (type.basetype)
7547 {
7548 case SPIRType::Short:
7549 case SPIRType::UShort:
7550 ret = cleft->scalar_u16(0, row) == 0 && cright->scalar_u16(0, row) == 1;
7551 break;
7552
7553 case SPIRType::Int:
7554 case SPIRType::UInt:
7555 ret = cleft->scalar(0, row) == 0 && cright->scalar(0, row) == 1;
7556 break;
7557
7558 case SPIRType::Half:
7559 ret = cleft->scalar_f16(0, row) == 0.0f && cright->scalar_f16(0, row) == 1.0f;
7560 break;
7561
7562 case SPIRType::Float:
7563 ret = cleft->scalar_f32(0, row) == 0.0f && cright->scalar_f32(0, row) == 1.0f;
7564 break;
7565
7566 case SPIRType::Double:
7567 ret = cleft->scalar_f64(0, row) == 0.0 && cright->scalar_f64(0, row) == 1.0;
7568 break;
7569
7570 case SPIRType::Int64:
7571 case SPIRType::UInt64:
7572 ret = cleft->scalar_u64(0, row) == 0 && cright->scalar_u64(0, row) == 1;
7573 break;
7574
7575 default:
7576 ret = false;
7577 break;
7578 }
7579 }
7580
7581 if (ret)
7582 op = type_to_glsl_constructor(type);
7583 return ret;
7584 }
7585
7586 string CompilerGLSL::to_ternary_expression(const SPIRType &restype, uint32_t select, uint32_t true_value,
7587 uint32_t false_value)
7588 {
7589 string expr;
7590 auto &lerptype = expression_type(select);
7591
7592 if (lerptype.vecsize == 1)
7593 expr = join(to_enclosed_expression(select), " ? ", to_enclosed_pointer_expression(true_value), " : ",
7594 to_enclosed_pointer_expression(false_value));
7595 else
7596 {
7597 auto swiz = [this](uint32_t expression, uint32_t i) { return to_extract_component_expression(expression, i); };
7598
7599 expr = type_to_glsl_constructor(restype);
7600 expr += "(";
7601 for (uint32_t i = 0; i < restype.vecsize; i++)
7602 {
7603 expr += swiz(select, i);
7604 expr += " ? ";
7605 expr += swiz(true_value, i);
7606 expr += " : ";
7607 expr += swiz(false_value, i);
7608 if (i + 1 < restype.vecsize)
7609 expr += ", ";
7610 }
7611 expr += ")";
7612 }
7613
7614 return expr;
7615 }
7616
7617 void CompilerGLSL::emit_mix_op(uint32_t result_type, uint32_t id, uint32_t left, uint32_t right, uint32_t lerp)
7618 {
7619 auto &lerptype = expression_type(lerp);
7620 auto &restype = get<SPIRType>(result_type);
7621
7622 // If this results in a variable pointer, assume it may be written through.
7623 if (restype.pointer)
7624 {
7625 register_write(left);
7626 register_write(right);
7627 }
7628
7629 string mix_op;
7630 bool has_boolean_mix = *backend.boolean_mix_function &&
7631 ((options.es && options.version >= 310) || (!options.es && options.version >= 450));
7632 bool trivial_mix = to_trivial_mix_op(restype, mix_op, left, right, lerp);
7633
7634 // Cannot use boolean mix when the lerp argument is just one boolean,
7635 // fall back to regular trinary statements.
7636 if (lerptype.vecsize == 1)
7637 has_boolean_mix = false;
7638
7639 // If we can reduce the mix to a simple cast, do so.
7640 // This helps for cases like int(bool), uint(bool) which is implemented with
7641 // OpSelect bool 1 0.
7642 if (trivial_mix)
7643 {
7644 emit_unary_func_op(result_type, id, lerp, mix_op.c_str());
7645 }
7646 else if (!has_boolean_mix && lerptype.basetype == SPIRType::Boolean)
7647 {
7648 // Boolean mix not supported on desktop without extension.
7649 // Was added in OpenGL 4.5 with ES 3.1 compat.
7650 //
7651 // Could use GL_EXT_shader_integer_mix on desktop at least,
7652 // but Apple doesn't support it. :(
7653 // Just implement it as ternary expressions.
7654 auto expr = to_ternary_expression(get<SPIRType>(result_type), lerp, right, left);
7655 emit_op(result_type, id, expr, should_forward(left) && should_forward(right) && should_forward(lerp));
7656 inherit_expression_dependencies(id, left);
7657 inherit_expression_dependencies(id, right);
7658 inherit_expression_dependencies(id, lerp);
7659 }
7660 else if (lerptype.basetype == SPIRType::Boolean)
7661 emit_trinary_func_op(result_type, id, left, right, lerp, backend.boolean_mix_function);
7662 else
7663 emit_trinary_func_op(result_type, id, left, right, lerp, "mix");
7664 }
7665
7666 string CompilerGLSL::to_combined_image_sampler(VariableID image_id, VariableID samp_id)
7667 {
7668 // Keep track of the array indices we have used to load the image.
7669 // We'll need to use the same array index into the combined image sampler array.
7670 auto image_expr = to_non_uniform_aware_expression(image_id);
7671 string array_expr;
7672 auto array_index = image_expr.find_first_of('[');
7673 if (array_index != string::npos)
7674 array_expr = image_expr.substr(array_index, string::npos);
7675
7676 auto &args = current_function->arguments;
7677
7678 // For GLSL and ESSL targets, we must enumerate all possible combinations for sampler2D(texture2D, sampler) and redirect
7679 // all possible combinations into new sampler2D uniforms.
7680 auto *image = maybe_get_backing_variable(image_id);
7681 auto *samp = maybe_get_backing_variable(samp_id);
7682 if (image)
7683 image_id = image->self;
7684 if (samp)
7685 samp_id = samp->self;
7686
7687 auto image_itr = find_if(begin(args), end(args),
7688 [image_id](const SPIRFunction::Parameter &param) { return image_id == param.id; });
7689
7690 auto sampler_itr = find_if(begin(args), end(args),
7691 [samp_id](const SPIRFunction::Parameter &param) { return samp_id == param.id; });
7692
7693 if (image_itr != end(args) || sampler_itr != end(args))
7694 {
7695 // If any parameter originates from a parameter, we will find it in our argument list.
7696 bool global_image = image_itr == end(args);
7697 bool global_sampler = sampler_itr == end(args);
7698 VariableID iid = global_image ? image_id : VariableID(uint32_t(image_itr - begin(args)));
7699 VariableID sid = global_sampler ? samp_id : VariableID(uint32_t(sampler_itr - begin(args)));
7700
7701 auto &combined = current_function->combined_parameters;
7702 auto itr = find_if(begin(combined), end(combined), [=](const SPIRFunction::CombinedImageSamplerParameter &p) {
7703 return p.global_image == global_image && p.global_sampler == global_sampler && p.image_id == iid &&
7704 p.sampler_id == sid;
7705 });
7706
7707 if (itr != end(combined))
7708 return to_expression(itr->id) + array_expr;
7709 else
7710 {
7711 SPIRV_CROSS_THROW("Cannot find mapping for combined sampler parameter, was "
7712 "build_combined_image_samplers() used "
7713 "before compile() was called?");
7714 }
7715 }
7716 else
7717 {
7718 // For global sampler2D, look directly at the global remapping table.
7719 auto &mapping = combined_image_samplers;
7720 auto itr = find_if(begin(mapping), end(mapping), [image_id, samp_id](const CombinedImageSampler &combined) {
7721 return combined.image_id == image_id && combined.sampler_id == samp_id;
7722 });
7723
7724 if (itr != end(combined_image_samplers))
7725 return to_expression(itr->combined_id) + array_expr;
7726 else
7727 {
7728 SPIRV_CROSS_THROW("Cannot find mapping for combined sampler, was build_combined_image_samplers() used "
7729 "before compile() was called?");
7730 }
7731 }
7732 }
7733
7734 bool CompilerGLSL::is_supported_subgroup_op_in_opengl(spv::Op op, const uint32_t *ops)
7735 {
7736 switch (op)
7737 {
7738 case OpGroupNonUniformElect:
7739 case OpGroupNonUniformBallot:
7740 case OpGroupNonUniformBallotFindLSB:
7741 case OpGroupNonUniformBallotFindMSB:
7742 case OpGroupNonUniformBroadcast:
7743 case OpGroupNonUniformBroadcastFirst:
7744 case OpGroupNonUniformAll:
7745 case OpGroupNonUniformAny:
7746 case OpGroupNonUniformAllEqual:
7747 case OpControlBarrier:
7748 case OpMemoryBarrier:
7749 case OpGroupNonUniformBallotBitCount:
7750 case OpGroupNonUniformBallotBitExtract:
7751 case OpGroupNonUniformInverseBallot:
7752 return true;
7753 case OpGroupNonUniformIAdd:
7754 case OpGroupNonUniformFAdd:
7755 case OpGroupNonUniformIMul:
7756 case OpGroupNonUniformFMul:
7757 {
7758 const GroupOperation operation = static_cast<GroupOperation>(ops[3]);
7759 if (operation == GroupOperationReduce || operation == GroupOperationInclusiveScan ||
7760 operation == GroupOperationExclusiveScan)
7761 {
7762 return true;
7763 }
7764 else
7765 {
7766 return false;
7767 }
7768 }
7769 default:
7770 return false;
7771 }
7772 }
7773
7774 void CompilerGLSL::emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id)
7775 {
7776 if (options.vulkan_semantics && combined_image_samplers.empty())
7777 {
7778 emit_binary_func_op(result_type, result_id, image_id, samp_id,
7779 type_to_glsl(get<SPIRType>(result_type), result_id).c_str());
7780 }
7781 else
7782 {
7783 // Make sure to suppress usage tracking. It is illegal to create temporaries of opaque types.
7784 emit_op(result_type, result_id, to_combined_image_sampler(image_id, samp_id), true, true);
7785 }
7786
7787 // Make sure to suppress usage tracking and any expression invalidation.
7788 // It is illegal to create temporaries of opaque types.
7789 forwarded_temporaries.erase(result_id);
7790 }
7791
7792 static inline bool image_opcode_is_sample_no_dref(Op op)
7793 {
7794 switch (op)
7795 {
7796 case OpImageSampleExplicitLod:
7797 case OpImageSampleImplicitLod:
7798 case OpImageSampleProjExplicitLod:
7799 case OpImageSampleProjImplicitLod:
7800 case OpImageFetch:
7801 case OpImageRead:
7802 case OpImageSparseSampleExplicitLod:
7803 case OpImageSparseSampleImplicitLod:
7804 case OpImageSparseSampleProjExplicitLod:
7805 case OpImageSparseSampleProjImplicitLod:
7806 case OpImageSparseFetch:
7807 case OpImageSparseRead:
7808 return true;
7809
7810 default:
7811 return false;
7812 }
7813 }
7814
7815 void CompilerGLSL::emit_sparse_feedback_temporaries(uint32_t result_type_id, uint32_t id, uint32_t &feedback_id,
7816 uint32_t &texel_id)
7817 {
7818 // Need to allocate two temporaries.
7819 if (options.es)
7820 SPIRV_CROSS_THROW("Sparse texture feedback is not supported on ESSL.");
7821 require_extension_internal("GL_ARB_sparse_texture2");
7822
7823 auto &temps = extra_sub_expressions[id];
7824 if (temps == 0)
7825 temps = ir.increase_bound_by(2);
7826
7827 feedback_id = temps + 0;
7828 texel_id = temps + 1;
7829
7830 auto &return_type = get<SPIRType>(result_type_id);
7831 if (return_type.basetype != SPIRType::Struct || return_type.member_types.size() != 2)
7832 SPIRV_CROSS_THROW("Invalid return type for sparse feedback.");
7833 emit_uninitialized_temporary(return_type.member_types[0], feedback_id);
7834 emit_uninitialized_temporary(return_type.member_types[1], texel_id);
7835 }
7836
7837 uint32_t CompilerGLSL::get_sparse_feedback_texel_id(uint32_t id) const
7838 {
7839 auto itr = extra_sub_expressions.find(id);
7840 if (itr == extra_sub_expressions.end())
7841 return 0;
7842 else
7843 return itr->second + 1;
7844 }
7845
7846 void CompilerGLSL::emit_texture_op(const Instruction &i, bool sparse)
7847 {
7848 auto *ops = stream(i);
7849 auto op = static_cast<Op>(i.op);
7850
7851 SmallVector<uint32_t> inherited_expressions;
7852
7853 uint32_t result_type_id = ops[0];
7854 uint32_t id = ops[1];
7855 auto &return_type = get<SPIRType>(result_type_id);
7856
7857 uint32_t sparse_code_id = 0;
7858 uint32_t sparse_texel_id = 0;
7859 if (sparse)
7860 emit_sparse_feedback_temporaries(result_type_id, id, sparse_code_id, sparse_texel_id);
7861
7862 bool forward = false;
7863 string expr = to_texture_op(i, sparse, &forward, inherited_expressions);
7864
7865 if (sparse)
7866 {
7867 statement(to_expression(sparse_code_id), " = ", expr, ";");
7868 expr = join(type_to_glsl(return_type), "(", to_expression(sparse_code_id), ", ", to_expression(sparse_texel_id),
7869 ")");
7870 forward = true;
7871 inherited_expressions.clear();
7872 }
7873
7874 emit_op(result_type_id, id, expr, forward);
7875 for (auto &inherit : inherited_expressions)
7876 inherit_expression_dependencies(id, inherit);
7877
7878 // Do not register sparse ops as control dependent as they are always lowered to a temporary.
7879 switch (op)
7880 {
7881 case OpImageSampleDrefImplicitLod:
7882 case OpImageSampleImplicitLod:
7883 case OpImageSampleProjImplicitLod:
7884 case OpImageSampleProjDrefImplicitLod:
7885 register_control_dependent_expression(id);
7886 break;
7887
7888 default:
7889 break;
7890 }
7891 }
7892
7893 std::string CompilerGLSL::to_texture_op(const Instruction &i, bool sparse, bool *forward,
7894 SmallVector<uint32_t> &inherited_expressions)
7895 {
7896 auto *ops = stream(i);
7897 auto op = static_cast<Op>(i.op);
7898 uint32_t length = i.length;
7899
7900 uint32_t result_type_id = ops[0];
7901 VariableID img = ops[2];
7902 uint32_t coord = ops[3];
7903 uint32_t dref = 0;
7904 uint32_t comp = 0;
7905 bool gather = false;
7906 bool proj = false;
7907 bool fetch = false;
7908 bool nonuniform_expression = false;
7909 const uint32_t *opt = nullptr;
7910
7911 auto &result_type = get<SPIRType>(result_type_id);
7912
7913 inherited_expressions.push_back(coord);
7914 if (has_decoration(img, DecorationNonUniform) && !maybe_get_backing_variable(img))
7915 nonuniform_expression = true;
7916
7917 switch (op)
7918 {
7919 case OpImageSampleDrefImplicitLod:
7920 case OpImageSampleDrefExplicitLod:
7921 case OpImageSparseSampleDrefImplicitLod:
7922 case OpImageSparseSampleDrefExplicitLod:
7923 dref = ops[4];
7924 opt = &ops[5];
7925 length -= 5;
7926 break;
7927
7928 case OpImageSampleProjDrefImplicitLod:
7929 case OpImageSampleProjDrefExplicitLod:
7930 case OpImageSparseSampleProjDrefImplicitLod:
7931 case OpImageSparseSampleProjDrefExplicitLod:
7932 dref = ops[4];
7933 opt = &ops[5];
7934 length -= 5;
7935 proj = true;
7936 break;
7937
7938 case OpImageDrefGather:
7939 case OpImageSparseDrefGather:
7940 dref = ops[4];
7941 opt = &ops[5];
7942 length -= 5;
7943 gather = true;
7944 if (options.es && options.version < 310)
7945 SPIRV_CROSS_THROW("textureGather requires ESSL 310.");
7946 else if (!options.es && options.version < 400)
7947 SPIRV_CROSS_THROW("textureGather with depth compare requires GLSL 400.");
7948 break;
7949
7950 case OpImageGather:
7951 case OpImageSparseGather:
7952 comp = ops[4];
7953 opt = &ops[5];
7954 length -= 5;
7955 gather = true;
7956 if (options.es && options.version < 310)
7957 SPIRV_CROSS_THROW("textureGather requires ESSL 310.");
7958 else if (!options.es && options.version < 400)
7959 {
7960 if (!expression_is_constant_null(comp))
7961 SPIRV_CROSS_THROW("textureGather with component requires GLSL 400.");
7962 require_extension_internal("GL_ARB_texture_gather");
7963 }
7964 break;
7965
7966 case OpImageFetch:
7967 case OpImageSparseFetch:
7968 case OpImageRead: // Reads == fetches in Metal (other langs will not get here)
7969 opt = &ops[4];
7970 length -= 4;
7971 fetch = true;
7972 break;
7973
7974 case OpImageSampleProjImplicitLod:
7975 case OpImageSampleProjExplicitLod:
7976 case OpImageSparseSampleProjImplicitLod:
7977 case OpImageSparseSampleProjExplicitLod:
7978 opt = &ops[4];
7979 length -= 4;
7980 proj = true;
7981 break;
7982
7983 default:
7984 opt = &ops[4];
7985 length -= 4;
7986 break;
7987 }
7988
7989 // Bypass pointers because we need the real image struct
7990 auto &type = expression_type(img);
7991 auto &imgtype = get<SPIRType>(type.self);
7992
7993 uint32_t coord_components = 0;
7994 switch (imgtype.image.dim)
7995 {
7996 case spv::Dim1D:
7997 coord_components = 1;
7998 break;
7999 case spv::Dim2D:
8000 coord_components = 2;
8001 break;
8002 case spv::Dim3D:
8003 coord_components = 3;
8004 break;
8005 case spv::DimCube:
8006 coord_components = 3;
8007 break;
8008 case spv::DimBuffer:
8009 coord_components = 1;
8010 break;
8011 default:
8012 coord_components = 2;
8013 break;
8014 }
8015
8016 if (dref)
8017 inherited_expressions.push_back(dref);
8018
8019 if (proj)
8020 coord_components++;
8021 if (imgtype.image.arrayed)
8022 coord_components++;
8023
8024 uint32_t bias = 0;
8025 uint32_t lod = 0;
8026 uint32_t grad_x = 0;
8027 uint32_t grad_y = 0;
8028 uint32_t coffset = 0;
8029 uint32_t offset = 0;
8030 uint32_t coffsets = 0;
8031 uint32_t sample = 0;
8032 uint32_t minlod = 0;
8033 uint32_t flags = 0;
8034
8035 if (length)
8036 {
8037 flags = *opt++;
8038 length--;
8039 }
8040
8041 auto test = [&](uint32_t &v, uint32_t flag) {
8042 if (length && (flags & flag))
8043 {
8044 v = *opt++;
8045 inherited_expressions.push_back(v);
8046 length--;
8047 }
8048 };
8049
8050 test(bias, ImageOperandsBiasMask);
8051 test(lod, ImageOperandsLodMask);
8052 test(grad_x, ImageOperandsGradMask);
8053 test(grad_y, ImageOperandsGradMask);
8054 test(coffset, ImageOperandsConstOffsetMask);
8055 test(offset, ImageOperandsOffsetMask);
8056 test(coffsets, ImageOperandsConstOffsetsMask);
8057 test(sample, ImageOperandsSampleMask);
8058 test(minlod, ImageOperandsMinLodMask);
8059
8060 TextureFunctionBaseArguments base_args = {};
8061 base_args.img = img;
8062 base_args.imgtype = &imgtype;
8063 base_args.is_fetch = fetch != 0;
8064 base_args.is_gather = gather != 0;
8065 base_args.is_proj = proj != 0;
8066
8067 string expr;
8068 TextureFunctionNameArguments name_args = {};
8069
8070 name_args.base = base_args;
8071 name_args.has_array_offsets = coffsets != 0;
8072 name_args.has_offset = coffset != 0 || offset != 0;
8073 name_args.has_grad = grad_x != 0 || grad_y != 0;
8074 name_args.has_dref = dref != 0;
8075 name_args.is_sparse_feedback = sparse;
8076 name_args.has_min_lod = minlod != 0;
8077 name_args.lod = lod;
8078 expr += to_function_name(name_args);
8079 expr += "(";
8080
8081 uint32_t sparse_texel_id = 0;
8082 if (sparse)
8083 sparse_texel_id = get_sparse_feedback_texel_id(ops[1]);
8084
8085 TextureFunctionArguments args = {};
8086 args.base = base_args;
8087 args.coord = coord;
8088 args.coord_components = coord_components;
8089 args.dref = dref;
8090 args.grad_x = grad_x;
8091 args.grad_y = grad_y;
8092 args.lod = lod;
8093 args.has_array_offsets = coffsets != 0;
8094
8095 if (coffsets)
8096 args.offset = coffsets;
8097 else if (coffset)
8098 args.offset = coffset;
8099 else
8100 args.offset = offset;
8101
8102 args.bias = bias;
8103 args.component = comp;
8104 args.sample = sample;
8105 args.sparse_texel = sparse_texel_id;
8106 args.min_lod = minlod;
8107 args.nonuniform_expression = nonuniform_expression;
8108 expr += to_function_args(args, forward);
8109 expr += ")";
8110
8111 // texture(samplerXShadow) returns float. shadowX() returns vec4, but only in desktop GLSL. Swizzle here.
8112 if (is_legacy() && !options.es && is_depth_image(imgtype, img))
8113 expr += ".r";
8114
8115 // Sampling from a texture which was deduced to be a depth image, might actually return 1 component here.
8116 // Remap back to 4 components as sampling opcodes expect.
8117 if (backend.comparison_image_samples_scalar && image_opcode_is_sample_no_dref(op))
8118 {
8119 bool image_is_depth = false;
8120 const auto *combined = maybe_get<SPIRCombinedImageSampler>(img);
8121 VariableID image_id = combined ? combined->image : img;
8122
8123 if (combined && is_depth_image(imgtype, combined->image))
8124 image_is_depth = true;
8125 else if (is_depth_image(imgtype, img))
8126 image_is_depth = true;
8127
8128 // We must also check the backing variable for the image.
8129 // We might have loaded an OpImage, and used that handle for two different purposes.
8130 // Once with comparison, once without.
8131 auto *image_variable = maybe_get_backing_variable(image_id);
8132 if (image_variable && is_depth_image(get<SPIRType>(image_variable->basetype), image_variable->self))
8133 image_is_depth = true;
8134
8135 if (image_is_depth)
8136 expr = remap_swizzle(result_type, 1, expr);
8137 }
8138
8139 if (!sparse && !backend.support_small_type_sampling_result && result_type.width < 32)
8140 {
8141 // Just value cast (narrowing) to expected type since we cannot rely on narrowing to work automatically.
8142 // Hopefully compiler picks this up and converts the texturing instruction to the appropriate precision.
8143 expr = join(type_to_glsl_constructor(result_type), "(", expr, ")");
8144 }
8145
8146 // Deals with reads from MSL. We might need to downconvert to fewer components.
8147 if (op == OpImageRead)
8148 expr = remap_swizzle(result_type, 4, expr);
8149
8150 return expr;
8151 }
8152
8153 bool CompilerGLSL::expression_is_constant_null(uint32_t id) const
8154 {
8155 auto *c = maybe_get<SPIRConstant>(id);
8156 if (!c)
8157 return false;
8158 return c->constant_is_null();
8159 }
8160
8161 bool CompilerGLSL::expression_is_non_value_type_array(uint32_t ptr)
8162 {
8163 auto &type = expression_type(ptr);
8164 if (!is_array(get_pointee_type(type)))
8165 return false;
8166
8167 if (!backend.array_is_value_type)
8168 return true;
8169
8170 auto *var = maybe_get_backing_variable(ptr);
8171 if (!var)
8172 return false;
8173
8174 auto &backed_type = get<SPIRType>(var->basetype);
8175 return !backend.array_is_value_type_in_buffer_blocks && backed_type.basetype == SPIRType::Struct &&
8176 has_member_decoration(backed_type.self, 0, DecorationOffset);
8177 }
8178
8179 // Returns the function name for a texture sampling function for the specified image and sampling characteristics.
8180 // For some subclasses, the function is a method on the specified image.
8181 string CompilerGLSL::to_function_name(const TextureFunctionNameArguments &args)
8182 {
8183 if (args.has_min_lod)
8184 {
8185 if (options.es)
8186 SPIRV_CROSS_THROW("Sparse residency is not supported in ESSL.");
8187 require_extension_internal("GL_ARB_sparse_texture_clamp");
8188 }
8189
8190 string fname;
8191 auto &imgtype = *args.base.imgtype;
8192 VariableID tex = args.base.img;
8193
8194 // textureLod on sampler2DArrayShadow and samplerCubeShadow does not exist in GLSL for some reason.
8195 // To emulate this, we will have to use textureGrad with a constant gradient of 0.
8196 // The workaround will assert that the LOD is in fact constant 0, or we cannot emit correct code.
8197 // This happens for HLSL SampleCmpLevelZero on Texture2DArray and TextureCube.
8198 bool workaround_lod_array_shadow_as_grad = false;
8199 if (((imgtype.image.arrayed && imgtype.image.dim == Dim2D) || imgtype.image.dim == DimCube) &&
8200 is_depth_image(imgtype, tex) && args.lod && !args.base.is_fetch)
8201 {
8202 if (!expression_is_constant_null(args.lod))
8203 {
8204 SPIRV_CROSS_THROW("textureLod on sampler2DArrayShadow is not constant 0.0. This cannot be "
8205 "expressed in GLSL.");
8206 }
8207 workaround_lod_array_shadow_as_grad = true;
8208 }
8209
8210 if (args.is_sparse_feedback)
8211 fname += "sparse";
8212
8213 if (args.base.is_fetch)
8214 fname += args.is_sparse_feedback ? "TexelFetch" : "texelFetch";
8215 else
8216 {
8217 fname += args.is_sparse_feedback ? "Texture" : "texture";
8218
8219 if (args.base.is_gather)
8220 fname += "Gather";
8221 if (args.has_array_offsets)
8222 fname += "Offsets";
8223 if (args.base.is_proj)
8224 fname += "Proj";
8225 if (args.has_grad || workaround_lod_array_shadow_as_grad)
8226 fname += "Grad";
8227 if (args.lod != 0 && !workaround_lod_array_shadow_as_grad)
8228 fname += "Lod";
8229 }
8230
8231 if (args.has_offset)
8232 fname += "Offset";
8233
8234 if (args.has_min_lod)
8235 fname += "Clamp";
8236
8237 if (args.is_sparse_feedback || args.has_min_lod)
8238 fname += "ARB";
8239
8240 return (is_legacy() && !args.base.is_gather) ? legacy_tex_op(fname, imgtype, tex) : fname;
8241 }
8242
8243 std::string CompilerGLSL::convert_separate_image_to_expression(uint32_t id)
8244 {
8245 auto *var = maybe_get_backing_variable(id);
8246
8247 // If we are fetching from a plain OpTypeImage, we must combine with a dummy sampler in GLSL.
8248 // In Vulkan GLSL, we can make use of the newer GL_EXT_samplerless_texture_functions.
8249 if (var)
8250 {
8251 auto &type = get<SPIRType>(var->basetype);
8252 if (type.basetype == SPIRType::Image && type.image.sampled == 1 && type.image.dim != DimBuffer)
8253 {
8254 if (options.vulkan_semantics)
8255 {
8256 if (dummy_sampler_id)
8257 {
8258 // Don't need to consider Shadow state since the dummy sampler is always non-shadow.
8259 auto sampled_type = type;
8260 sampled_type.basetype = SPIRType::SampledImage;
8261 return join(type_to_glsl(sampled_type), "(", to_non_uniform_aware_expression(id), ", ",
8262 to_expression(dummy_sampler_id), ")");
8263 }
8264 else
8265 {
8266 // Newer glslang supports this extension to deal with texture2D as argument to texture functions.
8267 require_extension_internal("GL_EXT_samplerless_texture_functions");
8268 }
8269 }
8270 else
8271 {
8272 if (!dummy_sampler_id)
8273 SPIRV_CROSS_THROW("Cannot find dummy sampler ID. Was "
8274 "build_dummy_sampler_for_combined_images() called?");
8275
8276 return to_combined_image_sampler(id, dummy_sampler_id);
8277 }
8278 }
8279 }
8280
8281 return to_non_uniform_aware_expression(id);
8282 }
8283
8284 // Returns the function args for a texture sampling function for the specified image and sampling characteristics.
8285 string CompilerGLSL::to_function_args(const TextureFunctionArguments &args, bool *p_forward)
8286 {
8287 VariableID img = args.base.img;
8288 auto &imgtype = *args.base.imgtype;
8289
8290 string farg_str;
8291 if (args.base.is_fetch)
8292 farg_str = convert_separate_image_to_expression(img);
8293 else
8294 farg_str = to_non_uniform_aware_expression(img);
8295
8296 if (args.nonuniform_expression && farg_str.find_first_of('[') != string::npos)
8297 {
8298 // Only emit nonuniformEXT() wrapper if the underlying expression is arrayed in some way.
8299 farg_str = join(backend.nonuniform_qualifier, "(", farg_str, ")");
8300 }
8301
8302 bool swizz_func = backend.swizzle_is_function;
8303 auto swizzle = [swizz_func](uint32_t comps, uint32_t in_comps) -> const char * {
8304 if (comps == in_comps)
8305 return "";
8306
8307 switch (comps)
8308 {
8309 case 1:
8310 return ".x";
8311 case 2:
8312 return swizz_func ? ".xy()" : ".xy";
8313 case 3:
8314 return swizz_func ? ".xyz()" : ".xyz";
8315 default:
8316 return "";
8317 }
8318 };
8319
8320 bool forward = should_forward(args.coord);
8321
8322 // The IR can give us more components than we need, so chop them off as needed.
8323 auto swizzle_expr = swizzle(args.coord_components, expression_type(args.coord).vecsize);
8324 // Only enclose the UV expression if needed.
8325 auto coord_expr =
8326 (*swizzle_expr == '\0') ? to_expression(args.coord) : (to_enclosed_expression(args.coord) + swizzle_expr);
8327
8328 // texelFetch only takes int, not uint.
8329 auto &coord_type = expression_type(args.coord);
8330 if (coord_type.basetype == SPIRType::UInt)
8331 {
8332 auto expected_type = coord_type;
8333 expected_type.vecsize = args.coord_components;
8334 expected_type.basetype = SPIRType::Int;
8335 coord_expr = bitcast_expression(expected_type, coord_type.basetype, coord_expr);
8336 }
8337
8338 // textureLod on sampler2DArrayShadow and samplerCubeShadow does not exist in GLSL for some reason.
8339 // To emulate this, we will have to use textureGrad with a constant gradient of 0.
8340 // The workaround will assert that the LOD is in fact constant 0, or we cannot emit correct code.
8341 // This happens for HLSL SampleCmpLevelZero on Texture2DArray and TextureCube.
8342 bool workaround_lod_array_shadow_as_grad =
8343 ((imgtype.image.arrayed && imgtype.image.dim == Dim2D) || imgtype.image.dim == DimCube) &&
8344 is_depth_image(imgtype, img) && args.lod != 0 && !args.base.is_fetch;
8345
8346 if (args.dref)
8347 {
8348 forward = forward && should_forward(args.dref);
8349
8350 // SPIR-V splits dref and coordinate.
8351 if (args.base.is_gather ||
8352 args.coord_components == 4) // GLSL also splits the arguments in two. Same for textureGather.
8353 {
8354 farg_str += ", ";
8355 farg_str += to_expression(args.coord);
8356 farg_str += ", ";
8357 farg_str += to_expression(args.dref);
8358 }
8359 else if (args.base.is_proj)
8360 {
8361 // Have to reshuffle so we get vec4(coord, dref, proj), special case.
8362 // Other shading languages splits up the arguments for coord and compare value like SPIR-V.
8363 // The coordinate type for textureProj shadow is always vec4 even for sampler1DShadow.
8364 farg_str += ", vec4(";
8365
8366 if (imgtype.image.dim == Dim1D)
8367 {
8368 // Could reuse coord_expr, but we will mess up the temporary usage checking.
8369 farg_str += to_enclosed_expression(args.coord) + ".x";
8370 farg_str += ", ";
8371 farg_str += "0.0, ";
8372 farg_str += to_expression(args.dref);
8373 farg_str += ", ";
8374 farg_str += to_enclosed_expression(args.coord) + ".y)";
8375 }
8376 else if (imgtype.image.dim == Dim2D)
8377 {
8378 // Could reuse coord_expr, but we will mess up the temporary usage checking.
8379 farg_str += to_enclosed_expression(args.coord) + (swizz_func ? ".xy()" : ".xy");
8380 farg_str += ", ";
8381 farg_str += to_expression(args.dref);
8382 farg_str += ", ";
8383 farg_str += to_enclosed_expression(args.coord) + ".z)";
8384 }
8385 else
8386 SPIRV_CROSS_THROW("Invalid type for textureProj with shadow.");
8387 }
8388 else
8389 {
8390 // Create a composite which merges coord/dref into a single vector.
8391 auto type = expression_type(args.coord);
8392 type.vecsize = args.coord_components + 1;
8393 if (imgtype.image.dim == Dim1D && options.es)
8394 type.vecsize++;
8395 farg_str += ", ";
8396 farg_str += type_to_glsl_constructor(type);
8397 farg_str += "(";
8398
8399 if (imgtype.image.dim == Dim1D && options.es)
8400 {
8401 if (imgtype.image.arrayed)
8402 {
8403 farg_str += enclose_expression(coord_expr) + ".x";
8404 farg_str += ", 0.0, ";
8405 farg_str += enclose_expression(coord_expr) + ".y";
8406 }
8407 else
8408 {
8409 farg_str += coord_expr;
8410 farg_str += ", 0.0";
8411 }
8412 }
8413 else
8414 farg_str += coord_expr;
8415
8416 farg_str += ", ";
8417 farg_str += to_expression(args.dref);
8418 farg_str += ")";
8419 }
8420 }
8421 else
8422 {
8423 if (imgtype.image.dim == Dim1D && options.es)
8424 {
8425 // Have to fake a second coordinate.
8426 if (type_is_floating_point(coord_type))
8427 {
8428 // Cannot mix proj and array.
8429 if (imgtype.image.arrayed || args.base.is_proj)
8430 {
8431 coord_expr = join("vec3(", enclose_expression(coord_expr), ".x, 0.0, ",
8432 enclose_expression(coord_expr), ".y)");
8433 }
8434 else
8435 coord_expr = join("vec2(", coord_expr, ", 0.0)");
8436 }
8437 else
8438 {
8439 if (imgtype.image.arrayed)
8440 {
8441 coord_expr = join("ivec3(", enclose_expression(coord_expr),
8442 ".x, 0, ",
8443 enclose_expression(coord_expr), ".y)");
8444 }
8445 else
8446 coord_expr = join("ivec2(", coord_expr, ", 0)");
8447 }
8448 }
8449
8450 farg_str += ", ";
8451 farg_str += coord_expr;
8452 }
8453
8454 if (args.grad_x || args.grad_y)
8455 {
8456 forward = forward && should_forward(args.grad_x);
8457 forward = forward && should_forward(args.grad_y);
8458 farg_str += ", ";
8459 farg_str += to_expression(args.grad_x);
8460 farg_str += ", ";
8461 farg_str += to_expression(args.grad_y);
8462 }
8463
8464 if (args.lod)
8465 {
8466 if (workaround_lod_array_shadow_as_grad)
8467 {
8468 // Implement textureGrad() instead. LOD == 0.0 is implemented as gradient of 0.0.
8469 // Implementing this as plain texture() is not safe on some implementations.
8470 if (imgtype.image.dim == Dim2D)
8471 farg_str += ", vec2(0.0), vec2(0.0)";
8472 else if (imgtype.image.dim == DimCube)
8473 farg_str += ", vec3(0.0), vec3(0.0)";
8474 }
8475 else
8476 {
8477 forward = forward && should_forward(args.lod);
8478 farg_str += ", ";
8479
8480 // Lod expression for TexelFetch in GLSL must be int, and only int.
8481 if (args.base.is_fetch && imgtype.image.dim != DimBuffer && !imgtype.image.ms)
8482 farg_str += bitcast_expression(SPIRType::Int, args.lod);
8483 else
8484 farg_str += to_expression(args.lod);
8485 }
8486 }
8487 else if (args.base.is_fetch && imgtype.image.dim != DimBuffer && !imgtype.image.ms)
8488 {
8489 // Lod argument is optional in OpImageFetch, but we require a LOD value, pick 0 as the default.
8490 farg_str += ", 0";
8491 }
8492
8493 if (args.offset)
8494 {
8495 forward = forward && should_forward(args.offset);
8496 farg_str += ", ";
8497 farg_str += bitcast_expression(SPIRType::Int, args.offset);
8498 }
8499
8500 if (args.sample)
8501 {
8502 farg_str += ", ";
8503 farg_str += bitcast_expression(SPIRType::Int, args.sample);
8504 }
8505
8506 if (args.min_lod)
8507 {
8508 farg_str += ", ";
8509 farg_str += to_expression(args.min_lod);
8510 }
8511
8512 if (args.sparse_texel)
8513 {
8514 // Sparse texel output parameter comes after everything else, except it's before the optional, component/bias arguments.
8515 farg_str += ", ";
8516 farg_str += to_expression(args.sparse_texel);
8517 }
8518
8519 if (args.bias)
8520 {
8521 forward = forward && should_forward(args.bias);
8522 farg_str += ", ";
8523 farg_str += to_expression(args.bias);
8524 }
8525
8526 if (args.component && !expression_is_constant_null(args.component))
8527 {
8528 forward = forward && should_forward(args.component);
8529 farg_str += ", ";
8530 farg_str += bitcast_expression(SPIRType::Int, args.component);
8531 }
8532
8533 *p_forward = forward;
8534
8535 return farg_str;
8536 }
8537
8538 Op CompilerGLSL::get_remapped_spirv_op(Op op) const
8539 {
8540 if (options.relax_nan_checks)
8541 {
8542 switch (op)
8543 {
8544 case OpFUnordLessThan:
8545 op = OpFOrdLessThan;
8546 break;
8547 case OpFUnordLessThanEqual:
8548 op = OpFOrdLessThanEqual;
8549 break;
8550 case OpFUnordGreaterThan:
8551 op = OpFOrdGreaterThan;
8552 break;
8553 case OpFUnordGreaterThanEqual:
8554 op = OpFOrdGreaterThanEqual;
8555 break;
8556 case OpFUnordEqual:
8557 op = OpFOrdEqual;
8558 break;
8559 case OpFOrdNotEqual:
8560 op = OpFUnordNotEqual;
8561 break;
8562
8563 default:
8564 break;
8565 }
8566 }
8567
8568 return op;
8569 }
8570
8571 GLSLstd450 CompilerGLSL::get_remapped_glsl_op(GLSLstd450 std450_op) const
8572 {
8573 // Relax to non-NaN aware opcodes.
8574 if (options.relax_nan_checks)
8575 {
8576 switch (std450_op)
8577 {
8578 case GLSLstd450NClamp:
8579 std450_op = GLSLstd450FClamp;
8580 break;
8581 case GLSLstd450NMin:
8582 std450_op = GLSLstd450FMin;
8583 break;
8584 case GLSLstd450NMax:
8585 std450_op = GLSLstd450FMax;
8586 break;
8587 default:
8588 break;
8589 }
8590 }
8591
8592 return std450_op;
8593 }
8594
8595 void CompilerGLSL::emit_glsl_op(uint32_t result_type, uint32_t id, uint32_t eop, const uint32_t *args, uint32_t length)
8596 {
8597 auto op = static_cast<GLSLstd450>(eop);
8598
8599 if (is_legacy() && is_unsigned_glsl_opcode(op))
8600 SPIRV_CROSS_THROW("Unsigned integers are not supported on legacy GLSL targets.");
8601
8602 // If we need to do implicit bitcasts, make sure we do it with the correct type.
8603 uint32_t integer_width = get_integer_width_for_glsl_instruction(op, args, length);
8604 auto int_type = to_signed_basetype(integer_width);
8605 auto uint_type = to_unsigned_basetype(integer_width);
8606
8607 op = get_remapped_glsl_op(op);
8608
8609 switch (op)
8610 {
8611 // FP fiddling
8612 case GLSLstd450Round:
8613 if (!is_legacy())
8614 emit_unary_func_op(result_type, id, args[0], "round");
8615 else
8616 {
8617 auto op0 = to_enclosed_expression(args[0]);
8618 auto &op0_type = expression_type(args[0]);
8619 auto expr = join("floor(", op0, " + ", type_to_glsl_constructor(op0_type), "(0.5))");
8620 bool forward = should_forward(args[0]);
8621 emit_op(result_type, id, expr, forward);
8622 inherit_expression_dependencies(id, args[0]);
8623 }
8624 break;
8625
8626 case GLSLstd450RoundEven:
8627 if (!is_legacy())
8628 emit_unary_func_op(result_type, id, args[0], "roundEven");
8629 else if (!options.es)
8630 {
8631 // This extension provides round() with round-to-even semantics.
8632 require_extension_internal("GL_EXT_gpu_shader4");
8633 emit_unary_func_op(result_type, id, args[0], "round");
8634 }
8635 else
8636 SPIRV_CROSS_THROW("roundEven supported only in ESSL 300.");
8637 break;
8638
8639 case GLSLstd450Trunc:
8640 if (!is_legacy())
8641 emit_unary_func_op(result_type, id, args[0], "trunc");
8642 else
8643 {
8644 // Implement by value-casting to int and back.
8645 bool forward = should_forward(args[0]);
8646 auto op0 = to_unpacked_expression(args[0]);
8647 auto &op0_type = expression_type(args[0]);
8648 auto via_type = op0_type;
8649 via_type.basetype = SPIRType::Int;
8650 auto expr = join(type_to_glsl(op0_type), "(", type_to_glsl(via_type), "(", op0, "))");
8651 emit_op(result_type, id, expr, forward);
8652 inherit_expression_dependencies(id, args[0]);
8653 }
8654 break;
8655
8656 case GLSLstd450SAbs:
8657 emit_unary_func_op_cast(result_type, id, args[0], "abs", int_type, int_type);
8658 break;
8659 case GLSLstd450FAbs:
8660 emit_unary_func_op(result_type, id, args[0], "abs");
8661 break;
8662 case GLSLstd450SSign:
8663 emit_unary_func_op_cast(result_type, id, args[0], "sign", int_type, int_type);
8664 break;
8665 case GLSLstd450FSign:
8666 emit_unary_func_op(result_type, id, args[0], "sign");
8667 break;
8668 case GLSLstd450Floor:
8669 emit_unary_func_op(result_type, id, args[0], "floor");
8670 break;
8671 case GLSLstd450Ceil:
8672 emit_unary_func_op(result_type, id, args[0], "ceil");
8673 break;
8674 case GLSLstd450Fract:
8675 emit_unary_func_op(result_type, id, args[0], "fract");
8676 break;
8677 case GLSLstd450Radians:
8678 emit_unary_func_op(result_type, id, args[0], "radians");
8679 break;
8680 case GLSLstd450Degrees:
8681 emit_unary_func_op(result_type, id, args[0], "degrees");
8682 break;
8683 case GLSLstd450Fma:
8684 if ((!options.es && options.version < 400) || (options.es && options.version < 320))
8685 {
8686 auto expr = join(to_enclosed_expression(args[0]), " * ", to_enclosed_expression(args[1]), " + ",
8687 to_enclosed_expression(args[2]));
8688
8689 emit_op(result_type, id, expr,
8690 should_forward(args[0]) && should_forward(args[1]) && should_forward(args[2]));
8691 for (uint32_t i = 0; i < 3; i++)
8692 inherit_expression_dependencies(id, args[i]);
8693 }
8694 else
8695 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "fma");
8696 break;
8697
8698 case GLSLstd450Modf:
8699 register_call_out_argument(args[1]);
8700 if (!is_legacy())
8701 {
8702 forced_temporaries.insert(id);
8703 emit_binary_func_op(result_type, id, args[0], args[1], "modf");
8704 }
8705 else
8706 {
8707 //NB. legacy GLSL doesn't have trunc() either, so we do a value cast
8708 auto &op1_type = expression_type(args[1]);
8709 auto via_type = op1_type;
8710 via_type.basetype = SPIRType::Int;
8711 statement(to_expression(args[1]), " = ",
8712 type_to_glsl(op1_type), "(", type_to_glsl(via_type),
8713 "(", to_expression(args[0]), "));");
8714 emit_binary_op(result_type, id, args[0], args[1], "-");
8715 }
8716 break;
8717
8718 case GLSLstd450ModfStruct:
8719 {
8720 auto &type = get<SPIRType>(result_type);
8721 emit_uninitialized_temporary_expression(result_type, id);
8722 if (!is_legacy())
8723 {
8724 statement(to_expression(id), ".", to_member_name(type, 0), " = ", "modf(", to_expression(args[0]), ", ",
8725 to_expression(id), ".", to_member_name(type, 1), ");");
8726 }
8727 else
8728 {
8729 //NB. legacy GLSL doesn't have trunc() either, so we do a value cast
8730 auto &op0_type = expression_type(args[0]);
8731 auto via_type = op0_type;
8732 via_type.basetype = SPIRType::Int;
8733 statement(to_expression(id), ".", to_member_name(type, 1), " = ", type_to_glsl(op0_type),
8734 "(", type_to_glsl(via_type), "(", to_expression(args[0]), "));");
8735 statement(to_expression(id), ".", to_member_name(type, 0), " = ", to_enclosed_expression(args[0]), " - ",
8736 to_expression(id), ".", to_member_name(type, 1), ";");
8737 }
8738 break;
8739 }
8740
8741 // Minmax
8742 case GLSLstd450UMin:
8743 emit_binary_func_op_cast(result_type, id, args[0], args[1], "min", uint_type, false);
8744 break;
8745
8746 case GLSLstd450SMin:
8747 emit_binary_func_op_cast(result_type, id, args[0], args[1], "min", int_type, false);
8748 break;
8749
8750 case GLSLstd450FMin:
8751 emit_binary_func_op(result_type, id, args[0], args[1], "min");
8752 break;
8753
8754 case GLSLstd450FMax:
8755 emit_binary_func_op(result_type, id, args[0], args[1], "max");
8756 break;
8757
8758 case GLSLstd450UMax:
8759 emit_binary_func_op_cast(result_type, id, args[0], args[1], "max", uint_type, false);
8760 break;
8761
8762 case GLSLstd450SMax:
8763 emit_binary_func_op_cast(result_type, id, args[0], args[1], "max", int_type, false);
8764 break;
8765
8766 case GLSLstd450FClamp:
8767 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp");
8768 break;
8769
8770 case GLSLstd450UClamp:
8771 emit_trinary_func_op_cast(result_type, id, args[0], args[1], args[2], "clamp", uint_type);
8772 break;
8773
8774 case GLSLstd450SClamp:
8775 emit_trinary_func_op_cast(result_type, id, args[0], args[1], args[2], "clamp", int_type);
8776 break;
8777
8778 // Trig
8779 case GLSLstd450Sin:
8780 emit_unary_func_op(result_type, id, args[0], "sin");
8781 break;
8782 case GLSLstd450Cos:
8783 emit_unary_func_op(result_type, id, args[0], "cos");
8784 break;
8785 case GLSLstd450Tan:
8786 emit_unary_func_op(result_type, id, args[0], "tan");
8787 break;
8788 case GLSLstd450Asin:
8789 emit_unary_func_op(result_type, id, args[0], "asin");
8790 break;
8791 case GLSLstd450Acos:
8792 emit_unary_func_op(result_type, id, args[0], "acos");
8793 break;
8794 case GLSLstd450Atan:
8795 emit_unary_func_op(result_type, id, args[0], "atan");
8796 break;
8797 case GLSLstd450Sinh:
8798 if (!is_legacy())
8799 emit_unary_func_op(result_type, id, args[0], "sinh");
8800 else
8801 {
8802 bool forward = should_forward(args[0]);
8803 auto expr = join("(exp(", to_expression(args[0]), ") - exp(-", to_enclosed_expression(args[0]), ")) * 0.5");
8804 emit_op(result_type, id, expr, forward);
8805 inherit_expression_dependencies(id, args[0]);
8806 }
8807 break;
8808 case GLSLstd450Cosh:
8809 if (!is_legacy())
8810 emit_unary_func_op(result_type, id, args[0], "cosh");
8811 else
8812 {
8813 bool forward = should_forward(args[0]);
8814 auto expr = join("(exp(", to_expression(args[0]), ") + exp(-", to_enclosed_expression(args[0]), ")) * 0.5");
8815 emit_op(result_type, id, expr, forward);
8816 inherit_expression_dependencies(id, args[0]);
8817 }
8818 break;
8819 case GLSLstd450Tanh:
8820 if (!is_legacy())
8821 emit_unary_func_op(result_type, id, args[0], "tanh");
8822 else
8823 {
8824 // Create temporaries to store the result of exp(arg) and exp(-arg).
8825 uint32_t &ids = extra_sub_expressions[id];
8826 if (!ids)
8827 {
8828 ids = ir.increase_bound_by(2);
8829
8830 // Inherit precision qualifier (legacy has no NoContraction).
8831 if (has_decoration(id, DecorationRelaxedPrecision))
8832 {
8833 set_decoration(ids, DecorationRelaxedPrecision);
8834 set_decoration(ids + 1, DecorationRelaxedPrecision);
8835 }
8836 }
8837 uint32_t epos_id = ids;
8838 uint32_t eneg_id = ids + 1;
8839
8840 emit_op(result_type, epos_id, join("exp(", to_expression(args[0]), ")"), false);
8841 emit_op(result_type, eneg_id, join("exp(-", to_enclosed_expression(args[0]), ")"), false);
8842 inherit_expression_dependencies(epos_id, args[0]);
8843 inherit_expression_dependencies(eneg_id, args[0]);
8844
8845 auto expr = join("(", to_enclosed_expression(epos_id), " - ", to_enclosed_expression(eneg_id), ") / "
8846 "(", to_enclosed_expression(epos_id), " + ", to_enclosed_expression(eneg_id), ")");
8847 emit_op(result_type, id, expr, true);
8848 inherit_expression_dependencies(id, epos_id);
8849 inherit_expression_dependencies(id, eneg_id);
8850 }
8851 break;
8852 case GLSLstd450Asinh:
8853 if (!is_legacy())
8854 emit_unary_func_op(result_type, id, args[0], "asinh");
8855 else
8856 emit_emulated_ahyper_op(result_type, id, args[0], GLSLstd450Asinh);
8857 break;
8858 case GLSLstd450Acosh:
8859 if (!is_legacy())
8860 emit_unary_func_op(result_type, id, args[0], "acosh");
8861 else
8862 emit_emulated_ahyper_op(result_type, id, args[0], GLSLstd450Acosh);
8863 break;
8864 case GLSLstd450Atanh:
8865 if (!is_legacy())
8866 emit_unary_func_op(result_type, id, args[0], "atanh");
8867 else
8868 emit_emulated_ahyper_op(result_type, id, args[0], GLSLstd450Atanh);
8869 break;
8870 case GLSLstd450Atan2:
8871 emit_binary_func_op(result_type, id, args[0], args[1], "atan");
8872 break;
8873
8874 // Exponentials
8875 case GLSLstd450Pow:
8876 emit_binary_func_op(result_type, id, args[0], args[1], "pow");
8877 break;
8878 case GLSLstd450Exp:
8879 emit_unary_func_op(result_type, id, args[0], "exp");
8880 break;
8881 case GLSLstd450Log:
8882 emit_unary_func_op(result_type, id, args[0], "log");
8883 break;
8884 case GLSLstd450Exp2:
8885 emit_unary_func_op(result_type, id, args[0], "exp2");
8886 break;
8887 case GLSLstd450Log2:
8888 emit_unary_func_op(result_type, id, args[0], "log2");
8889 break;
8890 case GLSLstd450Sqrt:
8891 emit_unary_func_op(result_type, id, args[0], "sqrt");
8892 break;
8893 case GLSLstd450InverseSqrt:
8894 emit_unary_func_op(result_type, id, args[0], "inversesqrt");
8895 break;
8896
8897 // Matrix math
8898 case GLSLstd450Determinant:
8899 {
8900 // No need to transpose - it doesn't affect the determinant
8901 auto *e = maybe_get<SPIRExpression>(args[0]);
8902 bool old_transpose = e && e->need_transpose;
8903 if (old_transpose)
8904 e->need_transpose = false;
8905
8906 if (options.version < 150) // also matches ES 100
8907 {
8908 auto &type = expression_type(args[0]);
8909 assert(type.vecsize >= 2 && type.vecsize <= 4);
8910 assert(type.vecsize == type.columns);
8911
8912 // ARB_gpu_shader_fp64 needs GLSL 150, other types are not valid
8913 if (type.basetype != SPIRType::Float)
8914 SPIRV_CROSS_THROW("Unsupported type for matrix determinant");
8915
8916 bool relaxed = has_decoration(id, DecorationRelaxedPrecision);
8917 require_polyfill(static_cast<Polyfill>(PolyfillDeterminant2x2 << (type.vecsize - 2)),
8918 relaxed);
8919 emit_unary_func_op(result_type, id, args[0],
8920 (options.es && relaxed) ? "spvDeterminantMP" : "spvDeterminant");
8921 }
8922 else
8923 emit_unary_func_op(result_type, id, args[0], "determinant");
8924
8925 if (old_transpose)
8926 e->need_transpose = true;
8927 break;
8928 }
8929
8930 case GLSLstd450MatrixInverse:
8931 {
8932 // The inverse of the transpose is the same as the transpose of
8933 // the inverse, so we can just flip need_transpose of the result.
8934 auto *a = maybe_get<SPIRExpression>(args[0]);
8935 bool old_transpose = a && a->need_transpose;
8936 if (old_transpose)
8937 a->need_transpose = false;
8938
8939 const char *func = "inverse";
8940 if (options.version < 140) // also matches ES 100
8941 {
8942 auto &type = get<SPIRType>(result_type);
8943 assert(type.vecsize >= 2 && type.vecsize <= 4);
8944 assert(type.vecsize == type.columns);
8945
8946 // ARB_gpu_shader_fp64 needs GLSL 150, other types are invalid
8947 if (type.basetype != SPIRType::Float)
8948 SPIRV_CROSS_THROW("Unsupported type for matrix inverse");
8949
8950 bool relaxed = has_decoration(id, DecorationRelaxedPrecision);
8951 require_polyfill(static_cast<Polyfill>(PolyfillMatrixInverse2x2 << (type.vecsize - 2)),
8952 relaxed);
8953 func = (options.es && relaxed) ? "spvInverseMP" : "spvInverse";
8954 }
8955
8956 bool forward = should_forward(args[0]);
8957 auto &e = emit_op(result_type, id, join(func, "(", to_unpacked_expression(args[0]), ")"), forward);
8958 inherit_expression_dependencies(id, args[0]);
8959
8960 if (old_transpose)
8961 {
8962 e.need_transpose = true;
8963 a->need_transpose = true;
8964 }
8965 break;
8966 }
8967
8968 // Lerping
8969 case GLSLstd450FMix:
8970 case GLSLstd450IMix:
8971 {
8972 emit_mix_op(result_type, id, args[0], args[1], args[2]);
8973 break;
8974 }
8975 case GLSLstd450Step:
8976 emit_binary_func_op(result_type, id, args[0], args[1], "step");
8977 break;
8978 case GLSLstd450SmoothStep:
8979 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "smoothstep");
8980 break;
8981
8982 // Packing
8983 case GLSLstd450Frexp:
8984 register_call_out_argument(args[1]);
8985 forced_temporaries.insert(id);
8986 emit_binary_func_op(result_type, id, args[0], args[1], "frexp");
8987 break;
8988
8989 case GLSLstd450FrexpStruct:
8990 {
8991 auto &type = get<SPIRType>(result_type);
8992 emit_uninitialized_temporary_expression(result_type, id);
8993 statement(to_expression(id), ".", to_member_name(type, 0), " = ", "frexp(", to_expression(args[0]), ", ",
8994 to_expression(id), ".", to_member_name(type, 1), ");");
8995 break;
8996 }
8997
8998 case GLSLstd450Ldexp:
8999 {
9000 bool forward = should_forward(args[0]) && should_forward(args[1]);
9001
9002 auto op0 = to_unpacked_expression(args[0]);
9003 auto op1 = to_unpacked_expression(args[1]);
9004 auto &op1_type = expression_type(args[1]);
9005 if (op1_type.basetype != SPIRType::Int)
9006 {
9007 // Need a value cast here.
9008 auto target_type = op1_type;
9009 target_type.basetype = SPIRType::Int;
9010 op1 = join(type_to_glsl_constructor(target_type), "(", op1, ")");
9011 }
9012
9013 auto expr = join("ldexp(", op0, ", ", op1, ")");
9014
9015 emit_op(result_type, id, expr, forward);
9016 inherit_expression_dependencies(id, args[0]);
9017 inherit_expression_dependencies(id, args[1]);
9018 break;
9019 }
9020
9021 case GLSLstd450PackSnorm4x8:
9022 emit_unary_func_op(result_type, id, args[0], "packSnorm4x8");
9023 break;
9024 case GLSLstd450PackUnorm4x8:
9025 emit_unary_func_op(result_type, id, args[0], "packUnorm4x8");
9026 break;
9027 case GLSLstd450PackSnorm2x16:
9028 emit_unary_func_op(result_type, id, args[0], "packSnorm2x16");
9029 break;
9030 case GLSLstd450PackUnorm2x16:
9031 emit_unary_func_op(result_type, id, args[0], "packUnorm2x16");
9032 break;
9033 case GLSLstd450PackHalf2x16:
9034 emit_unary_func_op(result_type, id, args[0], "packHalf2x16");
9035 break;
9036 case GLSLstd450UnpackSnorm4x8:
9037 emit_unary_func_op(result_type, id, args[0], "unpackSnorm4x8");
9038 break;
9039 case GLSLstd450UnpackUnorm4x8:
9040 emit_unary_func_op(result_type, id, args[0], "unpackUnorm4x8");
9041 break;
9042 case GLSLstd450UnpackSnorm2x16:
9043 emit_unary_func_op(result_type, id, args[0], "unpackSnorm2x16");
9044 break;
9045 case GLSLstd450UnpackUnorm2x16:
9046 emit_unary_func_op(result_type, id, args[0], "unpackUnorm2x16");
9047 break;
9048 case GLSLstd450UnpackHalf2x16:
9049 emit_unary_func_op(result_type, id, args[0], "unpackHalf2x16");
9050 break;
9051
9052 case GLSLstd450PackDouble2x32:
9053 emit_unary_func_op(result_type, id, args[0], "packDouble2x32");
9054 break;
9055 case GLSLstd450UnpackDouble2x32:
9056 emit_unary_func_op(result_type, id, args[0], "unpackDouble2x32");
9057 break;
9058
9059 // Vector math
9060 case GLSLstd450Length:
9061 emit_unary_func_op(result_type, id, args[0], "length");
9062 break;
9063 case GLSLstd450Distance:
9064 emit_binary_func_op(result_type, id, args[0], args[1], "distance");
9065 break;
9066 case GLSLstd450Cross:
9067 emit_binary_func_op(result_type, id, args[0], args[1], "cross");
9068 break;
9069 case GLSLstd450Normalize:
9070 emit_unary_func_op(result_type, id, args[0], "normalize");
9071 break;
9072 case GLSLstd450FaceForward:
9073 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "faceforward");
9074 break;
9075 case GLSLstd450Reflect:
9076 emit_binary_func_op(result_type, id, args[0], args[1], "reflect");
9077 break;
9078 case GLSLstd450Refract:
9079 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "refract");
9080 break;
9081
9082 // Bit-fiddling
9083 case GLSLstd450FindILsb:
9084 // findLSB always returns int.
9085 emit_unary_func_op_cast(result_type, id, args[0], "findLSB", expression_type(args[0]).basetype, int_type);
9086 break;
9087
9088 case GLSLstd450FindSMsb:
9089 emit_unary_func_op_cast(result_type, id, args[0], "findMSB", int_type, int_type);
9090 break;
9091
9092 case GLSLstd450FindUMsb:
9093 emit_unary_func_op_cast(result_type, id, args[0], "findMSB", uint_type,
9094 int_type); // findMSB always returns int.
9095 break;
9096
9097 // Multisampled varying
9098 case GLSLstd450InterpolateAtCentroid:
9099 emit_unary_func_op(result_type, id, args[0], "interpolateAtCentroid");
9100 break;
9101 case GLSLstd450InterpolateAtSample:
9102 emit_binary_func_op(result_type, id, args[0], args[1], "interpolateAtSample");
9103 break;
9104 case GLSLstd450InterpolateAtOffset:
9105 emit_binary_func_op(result_type, id, args[0], args[1], "interpolateAtOffset");
9106 break;
9107
9108 case GLSLstd450NMin:
9109 case GLSLstd450NMax:
9110 {
9111 if (options.vulkan_semantics)
9112 {
9113 require_extension_internal("GL_EXT_spirv_intrinsics");
9114 bool relaxed = has_decoration(id, DecorationRelaxedPrecision);
9115 Polyfill poly = {};
9116 switch (get<SPIRType>(result_type).width)
9117 {
9118 case 16:
9119 poly = op == GLSLstd450NMin ? PolyfillNMin16 : PolyfillNMax16;
9120 break;
9121
9122 case 32:
9123 poly = op == GLSLstd450NMin ? PolyfillNMin32 : PolyfillNMax32;
9124 break;
9125
9126 case 64:
9127 poly = op == GLSLstd450NMin ? PolyfillNMin64 : PolyfillNMax64;
9128 break;
9129
9130 default:
9131 SPIRV_CROSS_THROW("Invalid bit width for NMin/NMax.");
9132 }
9133
9134 require_polyfill(poly, relaxed);
9135
9136 // Function return decorations are broken, so need to do double polyfill.
9137 if (relaxed)
9138 require_polyfill(poly, false);
9139
9140 const char *op_str;
9141 if (relaxed)
9142 op_str = op == GLSLstd450NMin ? "spvNMinRelaxed" : "spvNMaxRelaxed";
9143 else
9144 op_str = op == GLSLstd450NMin ? "spvNMin" : "spvNMax";
9145
9146 emit_binary_func_op(result_type, id, args[0], args[1], op_str);
9147 }
9148 else
9149 {
9150 emit_nminmax_op(result_type, id, args[0], args[1], op);
9151 }
9152 break;
9153 }
9154
9155 case GLSLstd450NClamp:
9156 {
9157 if (options.vulkan_semantics)
9158 {
9159 require_extension_internal("GL_EXT_spirv_intrinsics");
9160 bool relaxed = has_decoration(id, DecorationRelaxedPrecision);
9161 Polyfill poly = {};
9162 switch (get<SPIRType>(result_type).width)
9163 {
9164 case 16:
9165 poly = PolyfillNClamp16;
9166 break;
9167
9168 case 32:
9169 poly = PolyfillNClamp32;
9170 break;
9171
9172 case 64:
9173 poly = PolyfillNClamp64;
9174 break;
9175
9176 default:
9177 SPIRV_CROSS_THROW("Invalid bit width for NMin/NMax.");
9178 }
9179
9180 require_polyfill(poly, relaxed);
9181
9182 // Function return decorations are broken, so need to do double polyfill.
9183 if (relaxed)
9184 require_polyfill(poly, false);
9185
9186 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], relaxed ? "spvNClampRelaxed" : "spvNClamp");
9187 }
9188 else
9189 {
9190 // Make sure we have a unique ID here to avoid aliasing the extra sub-expressions between clamp and NMin sub-op.
9191 // IDs cannot exceed 24 bits, so we can make use of the higher bits for some unique flags.
9192 uint32_t &max_id = extra_sub_expressions[id | EXTRA_SUB_EXPRESSION_TYPE_AUX];
9193 if (!max_id)
9194 max_id = ir.increase_bound_by(1);
9195
9196 // Inherit precision qualifiers.
9197 ir.meta[max_id] = ir.meta[id];
9198
9199 emit_nminmax_op(result_type, max_id, args[0], args[1], GLSLstd450NMax);
9200 emit_nminmax_op(result_type, id, max_id, args[2], GLSLstd450NMin);
9201 }
9202 break;
9203 }
9204
9205 default:
9206 statement("// unimplemented GLSL op ", eop);
9207 break;
9208 }
9209 }
9210
9211 void CompilerGLSL::emit_nminmax_op(uint32_t result_type, uint32_t id, uint32_t op0, uint32_t op1, GLSLstd450 op)
9212 {
9213 // Need to emulate this call.
9214 uint32_t &ids = extra_sub_expressions[id];
9215 if (!ids)
9216 {
9217 ids = ir.increase_bound_by(5);
9218 auto btype = get<SPIRType>(result_type);
9219 btype.basetype = SPIRType::Boolean;
9220 set<SPIRType>(ids, btype);
9221 }
9222
9223 uint32_t btype_id = ids + 0;
9224 uint32_t left_nan_id = ids + 1;
9225 uint32_t right_nan_id = ids + 2;
9226 uint32_t tmp_id = ids + 3;
9227 uint32_t mixed_first_id = ids + 4;
9228
9229 // Inherit precision qualifiers.
9230 ir.meta[tmp_id] = ir.meta[id];
9231 ir.meta[mixed_first_id] = ir.meta[id];
9232
9233 if (!is_legacy())
9234 {
9235 emit_unary_func_op(btype_id, left_nan_id, op0, "isnan");
9236 emit_unary_func_op(btype_id, right_nan_id, op1, "isnan");
9237 }
9238 else if (expression_type(op0).vecsize > 1)
9239 {
9240 // If the number doesn't equal itself, it must be NaN
9241 emit_binary_func_op(btype_id, left_nan_id, op0, op0, "notEqual");
9242 emit_binary_func_op(btype_id, right_nan_id, op1, op1, "notEqual");
9243 }
9244 else
9245 {
9246 emit_binary_op(btype_id, left_nan_id, op0, op0, "!=");
9247 emit_binary_op(btype_id, right_nan_id, op1, op1, "!=");
9248 }
9249 emit_binary_func_op(result_type, tmp_id, op0, op1, op == GLSLstd450NMin ? "min" : "max");
9250 emit_mix_op(result_type, mixed_first_id, tmp_id, op1, left_nan_id);
9251 emit_mix_op(result_type, id, mixed_first_id, op0, right_nan_id);
9252 }
9253
9254 void CompilerGLSL::emit_emulated_ahyper_op(uint32_t result_type, uint32_t id, uint32_t op0, GLSLstd450 op)
9255 {
9256 const char *one = backend.float_literal_suffix ? "1.0f" : "1.0";
9257 std::string expr;
9258 bool forward = should_forward(op0);
9259
9260 switch (op)
9261 {
9262 case GLSLstd450Asinh:
9263 expr = join("log(", to_enclosed_expression(op0), " + sqrt(",
9264 to_enclosed_expression(op0), " * ", to_enclosed_expression(op0), " + ", one, "))");
9265 emit_op(result_type, id, expr, forward);
9266 break;
9267
9268 case GLSLstd450Acosh:
9269 expr = join("log(", to_enclosed_expression(op0), " + sqrt(",
9270 to_enclosed_expression(op0), " * ", to_enclosed_expression(op0), " - ", one, "))");
9271 break;
9272
9273 case GLSLstd450Atanh:
9274 expr = join("log((", one, " + ", to_enclosed_expression(op0), ") / "
9275 "(", one, " - ", to_enclosed_expression(op0), ")) * 0.5",
9276 backend.float_literal_suffix ? "f" : "");
9277 break;
9278
9279 default:
9280 SPIRV_CROSS_THROW("Invalid op.");
9281 }
9282
9283 emit_op(result_type, id, expr, forward);
9284 inherit_expression_dependencies(id, op0);
9285 }
9286
9287 void CompilerGLSL::emit_spv_amd_shader_ballot_op(uint32_t result_type, uint32_t id, uint32_t eop, const uint32_t *args,
9288 uint32_t)
9289 {
9290 require_extension_internal("GL_AMD_shader_ballot");
9291
9292 enum AMDShaderBallot
9293 {
9294 SwizzleInvocationsAMD = 1,
9295 SwizzleInvocationsMaskedAMD = 2,
9296 WriteInvocationAMD = 3,
9297 MbcntAMD = 4
9298 };
9299
9300 auto op = static_cast<AMDShaderBallot>(eop);
9301
9302 switch (op)
9303 {
9304 case SwizzleInvocationsAMD:
9305 emit_binary_func_op(result_type, id, args[0], args[1], "swizzleInvocationsAMD");
9306 register_control_dependent_expression(id);
9307 break;
9308
9309 case SwizzleInvocationsMaskedAMD:
9310 emit_binary_func_op(result_type, id, args[0], args[1], "swizzleInvocationsMaskedAMD");
9311 register_control_dependent_expression(id);
9312 break;
9313
9314 case WriteInvocationAMD:
9315 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "writeInvocationAMD");
9316 register_control_dependent_expression(id);
9317 break;
9318
9319 case MbcntAMD:
9320 emit_unary_func_op(result_type, id, args[0], "mbcntAMD");
9321 register_control_dependent_expression(id);
9322 break;
9323
9324 default:
9325 statement("// unimplemented SPV AMD shader ballot op ", eop);
9326 break;
9327 }
9328 }
9329
9330 void CompilerGLSL::emit_spv_amd_shader_explicit_vertex_parameter_op(uint32_t result_type, uint32_t id, uint32_t eop,
9331 const uint32_t *args, uint32_t)
9332 {
9333 require_extension_internal("GL_AMD_shader_explicit_vertex_parameter");
9334
9335 enum AMDShaderExplicitVertexParameter
9336 {
9337 InterpolateAtVertexAMD = 1
9338 };
9339
9340 auto op = static_cast<AMDShaderExplicitVertexParameter>(eop);
9341
9342 switch (op)
9343 {
9344 case InterpolateAtVertexAMD:
9345 emit_binary_func_op(result_type, id, args[0], args[1], "interpolateAtVertexAMD");
9346 break;
9347
9348 default:
9349 statement("// unimplemented SPV AMD shader explicit vertex parameter op ", eop);
9350 break;
9351 }
9352 }
9353
9354 void CompilerGLSL::emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t id, uint32_t eop,
9355 const uint32_t *args, uint32_t)
9356 {
9357 require_extension_internal("GL_AMD_shader_trinary_minmax");
9358
9359 enum AMDShaderTrinaryMinMax
9360 {
9361 FMin3AMD = 1,
9362 UMin3AMD = 2,
9363 SMin3AMD = 3,
9364 FMax3AMD = 4,
9365 UMax3AMD = 5,
9366 SMax3AMD = 6,
9367 FMid3AMD = 7,
9368 UMid3AMD = 8,
9369 SMid3AMD = 9
9370 };
9371
9372 auto op = static_cast<AMDShaderTrinaryMinMax>(eop);
9373
9374 switch (op)
9375 {
9376 case FMin3AMD:
9377 case UMin3AMD:
9378 case SMin3AMD:
9379 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "min3");
9380 break;
9381
9382 case FMax3AMD:
9383 case UMax3AMD:
9384 case SMax3AMD:
9385 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "max3");
9386 break;
9387
9388 case FMid3AMD:
9389 case UMid3AMD:
9390 case SMid3AMD:
9391 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "mid3");
9392 break;
9393
9394 default:
9395 statement("// unimplemented SPV AMD shader trinary minmax op ", eop);
9396 break;
9397 }
9398 }
9399
9400 void CompilerGLSL::emit_spv_amd_gcn_shader_op(uint32_t result_type, uint32_t id, uint32_t eop, const uint32_t *args,
9401 uint32_t)
9402 {
9403 require_extension_internal("GL_AMD_gcn_shader");
9404
9405 enum AMDGCNShader
9406 {
9407 CubeFaceIndexAMD = 1,
9408 CubeFaceCoordAMD = 2,
9409 TimeAMD = 3
9410 };
9411
9412 auto op = static_cast<AMDGCNShader>(eop);
9413
9414 switch (op)
9415 {
9416 case CubeFaceIndexAMD:
9417 emit_unary_func_op(result_type, id, args[0], "cubeFaceIndexAMD");
9418 break;
9419 case CubeFaceCoordAMD:
9420 emit_unary_func_op(result_type, id, args[0], "cubeFaceCoordAMD");
9421 break;
9422 case TimeAMD:
9423 {
9424 string expr = "timeAMD()";
9425 emit_op(result_type, id, expr, true);
9426 register_control_dependent_expression(id);
9427 break;
9428 }
9429
9430 default:
9431 statement("// unimplemented SPV AMD gcn shader op ", eop);
9432 break;
9433 }
9434 }
9435
9436 void CompilerGLSL::emit_subgroup_op(const Instruction &i)
9437 {
9438 const uint32_t *ops = stream(i);
9439 auto op = static_cast<Op>(i.op);
9440
9441 if (!options.vulkan_semantics && !is_supported_subgroup_op_in_opengl(op, ops))
9442 SPIRV_CROSS_THROW("This subgroup operation is only supported in Vulkan semantics.");
9443
9444 // If we need to do implicit bitcasts, make sure we do it with the correct type.
9445 uint32_t integer_width = get_integer_width_for_instruction(i);
9446 auto int_type = to_signed_basetype(integer_width);
9447 auto uint_type = to_unsigned_basetype(integer_width);
9448
9449 switch (op)
9450 {
9451 case OpGroupNonUniformElect:
9452 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupElect);
9453 break;
9454
9455 case OpGroupNonUniformBallotBitCount:
9456 {
9457 const GroupOperation operation = static_cast<GroupOperation>(ops[3]);
9458 if (operation == GroupOperationReduce)
9459 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupBallotBitCount);
9460 else if (operation == GroupOperationInclusiveScan || operation == GroupOperationExclusiveScan)
9461 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupInverseBallot_InclBitCount_ExclBitCout);
9462 }
9463 break;
9464
9465 case OpGroupNonUniformBallotBitExtract:
9466 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupBallotBitExtract);
9467 break;
9468
9469 case OpGroupNonUniformInverseBallot:
9470 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupInverseBallot_InclBitCount_ExclBitCout);
9471 break;
9472
9473 case OpGroupNonUniformBallot:
9474 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupBallot);
9475 break;
9476
9477 case OpGroupNonUniformBallotFindLSB:
9478 case OpGroupNonUniformBallotFindMSB:
9479 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupBallotFindLSB_MSB);
9480 break;
9481
9482 case OpGroupNonUniformBroadcast:
9483 case OpGroupNonUniformBroadcastFirst:
9484 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupBroadcast_First);
9485 break;
9486
9487 case OpGroupNonUniformShuffle:
9488 case OpGroupNonUniformShuffleXor:
9489 require_extension_internal("GL_KHR_shader_subgroup_shuffle");
9490 break;
9491
9492 case OpGroupNonUniformShuffleUp:
9493 case OpGroupNonUniformShuffleDown:
9494 require_extension_internal("GL_KHR_shader_subgroup_shuffle_relative");
9495 break;
9496
9497 case OpGroupNonUniformRotateKHR:
9498 require_extension_internal("GL_KHR_shader_subgroup_rotate");
9499 break;
9500
9501 case OpGroupNonUniformAll:
9502 case OpGroupNonUniformAny:
9503 case OpGroupNonUniformAllEqual:
9504 {
9505 const SPIRType &type = expression_type(ops[3]);
9506 if (type.basetype == SPIRType::BaseType::Boolean && type.vecsize == 1u)
9507 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupAll_Any_AllEqualBool);
9508 else
9509 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupAllEqualT);
9510 }
9511 break;
9512
9513 // clang-format off
9514 #define GLSL_GROUP_OP(OP)\
9515 case OpGroupNonUniform##OP:\
9516 {\
9517 auto operation = static_cast<GroupOperation>(ops[3]);\
9518 if (operation == GroupOperationClusteredReduce)\
9519 require_extension_internal("GL_KHR_shader_subgroup_clustered");\
9520 else if (operation == GroupOperationReduce)\
9521 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupArithmetic##OP##Reduce);\
9522 else if (operation == GroupOperationExclusiveScan)\
9523 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupArithmetic##OP##ExclusiveScan);\
9524 else if (operation == GroupOperationInclusiveScan)\
9525 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupArithmetic##OP##InclusiveScan);\
9526 else\
9527 SPIRV_CROSS_THROW("Invalid group operation.");\
9528 break;\
9529 }
9530
9531 GLSL_GROUP_OP(IAdd)
9532 GLSL_GROUP_OP(FAdd)
9533 GLSL_GROUP_OP(IMul)
9534 GLSL_GROUP_OP(FMul)
9535
9536 #undef GLSL_GROUP_OP
9537 // clang-format on
9538
9539 case OpGroupNonUniformFMin:
9540 case OpGroupNonUniformFMax:
9541 case OpGroupNonUniformSMin:
9542 case OpGroupNonUniformSMax:
9543 case OpGroupNonUniformUMin:
9544 case OpGroupNonUniformUMax:
9545 case OpGroupNonUniformBitwiseAnd:
9546 case OpGroupNonUniformBitwiseOr:
9547 case OpGroupNonUniformBitwiseXor:
9548 case OpGroupNonUniformLogicalAnd:
9549 case OpGroupNonUniformLogicalOr:
9550 case OpGroupNonUniformLogicalXor:
9551 {
9552 auto operation = static_cast<GroupOperation>(ops[3]);
9553 if (operation == GroupOperationClusteredReduce)
9554 {
9555 require_extension_internal("GL_KHR_shader_subgroup_clustered");
9556 }
9557 else if (operation == GroupOperationExclusiveScan || operation == GroupOperationInclusiveScan ||
9558 operation == GroupOperationReduce)
9559 {
9560 require_extension_internal("GL_KHR_shader_subgroup_arithmetic");
9561 }
9562 else
9563 SPIRV_CROSS_THROW("Invalid group operation.");
9564 break;
9565 }
9566
9567 case OpGroupNonUniformQuadSwap:
9568 case OpGroupNonUniformQuadBroadcast:
9569 require_extension_internal("GL_KHR_shader_subgroup_quad");
9570 break;
9571
9572 case OpGroupNonUniformQuadAllKHR:
9573 case OpGroupNonUniformQuadAnyKHR:
9574 // Require both extensions to be enabled.
9575 require_extension_internal("GL_KHR_shader_subgroup_vote");
9576 require_extension_internal("GL_EXT_shader_quad_control");
9577 break;
9578
9579 default:
9580 SPIRV_CROSS_THROW("Invalid opcode for subgroup.");
9581 }
9582
9583 uint32_t result_type = ops[0];
9584 uint32_t id = ops[1];
9585
9586 // These quad ops do not have a scope parameter.
9587 if (op != OpGroupNonUniformQuadAllKHR && op != OpGroupNonUniformQuadAnyKHR)
9588 {
9589 auto scope = static_cast<Scope>(evaluate_constant_u32(ops[2]));
9590 if (scope != ScopeSubgroup)
9591 SPIRV_CROSS_THROW("Only subgroup scope is supported.");
9592 }
9593
9594 switch (op)
9595 {
9596 case OpGroupNonUniformElect:
9597 emit_op(result_type, id, "subgroupElect()", true);
9598 break;
9599
9600 case OpGroupNonUniformBroadcast:
9601 emit_binary_func_op(result_type, id, ops[3], ops[4], "subgroupBroadcast");
9602 break;
9603
9604 case OpGroupNonUniformBroadcastFirst:
9605 emit_unary_func_op(result_type, id, ops[3], "subgroupBroadcastFirst");
9606 break;
9607
9608 case OpGroupNonUniformBallot:
9609 emit_unary_func_op(result_type, id, ops[3], "subgroupBallot");
9610 break;
9611
9612 case OpGroupNonUniformInverseBallot:
9613 emit_unary_func_op(result_type, id, ops[3], "subgroupInverseBallot");
9614 break;
9615
9616 case OpGroupNonUniformBallotBitExtract:
9617 emit_binary_func_op(result_type, id, ops[3], ops[4], "subgroupBallotBitExtract");
9618 break;
9619
9620 case OpGroupNonUniformBallotFindLSB:
9621 emit_unary_func_op(result_type, id, ops[3], "subgroupBallotFindLSB");
9622 break;
9623
9624 case OpGroupNonUniformBallotFindMSB:
9625 emit_unary_func_op(result_type, id, ops[3], "subgroupBallotFindMSB");
9626 break;
9627
9628 case OpGroupNonUniformBallotBitCount:
9629 {
9630 auto operation = static_cast<GroupOperation>(ops[3]);
9631 if (operation == GroupOperationReduce)
9632 emit_unary_func_op(result_type, id, ops[4], "subgroupBallotBitCount");
9633 else if (operation == GroupOperationInclusiveScan)
9634 emit_unary_func_op(result_type, id, ops[4], "subgroupBallotInclusiveBitCount");
9635 else if (operation == GroupOperationExclusiveScan)
9636 emit_unary_func_op(result_type, id, ops[4], "subgroupBallotExclusiveBitCount");
9637 else
9638 SPIRV_CROSS_THROW("Invalid BitCount operation.");
9639 break;
9640 }
9641
9642 case OpGroupNonUniformShuffle:
9643 emit_binary_func_op(result_type, id, ops[3], ops[4], "subgroupShuffle");
9644 break;
9645
9646 case OpGroupNonUniformShuffleXor:
9647 emit_binary_func_op(result_type, id, ops[3], ops[4], "subgroupShuffleXor");
9648 break;
9649
9650 case OpGroupNonUniformShuffleUp:
9651 emit_binary_func_op(result_type, id, ops[3], ops[4], "subgroupShuffleUp");
9652 break;
9653
9654 case OpGroupNonUniformShuffleDown:
9655 emit_binary_func_op(result_type, id, ops[3], ops[4], "subgroupShuffleDown");
9656 break;
9657
9658 case OpGroupNonUniformRotateKHR:
9659 if (i.length > 5)
9660 emit_trinary_func_op(result_type, id, ops[3], ops[4], ops[5], "subgroupClusteredRotate");
9661 else
9662 emit_binary_func_op(result_type, id, ops[3], ops[4], "subgroupRotate");
9663 break;
9664
9665 case OpGroupNonUniformAll:
9666 emit_unary_func_op(result_type, id, ops[3], "subgroupAll");
9667 break;
9668
9669 case OpGroupNonUniformAny:
9670 emit_unary_func_op(result_type, id, ops[3], "subgroupAny");
9671 break;
9672
9673 case OpGroupNonUniformAllEqual:
9674 emit_unary_func_op(result_type, id, ops[3], "subgroupAllEqual");
9675 break;
9676
9677 // clang-format off
9678 #define GLSL_GROUP_OP(op, glsl_op) \
9679 case OpGroupNonUniform##op: \
9680 { \
9681 auto operation = static_cast<GroupOperation>(ops[3]); \
9682 if (operation == GroupOperationReduce) \
9683 emit_unary_func_op(result_type, id, ops[4], "subgroup" #glsl_op); \
9684 else if (operation == GroupOperationInclusiveScan) \
9685 emit_unary_func_op(result_type, id, ops[4], "subgroupInclusive" #glsl_op); \
9686 else if (operation == GroupOperationExclusiveScan) \
9687 emit_unary_func_op(result_type, id, ops[4], "subgroupExclusive" #glsl_op); \
9688 else if (operation == GroupOperationClusteredReduce) \
9689 emit_binary_func_op(result_type, id, ops[4], ops[5], "subgroupClustered" #glsl_op); \
9690 else \
9691 SPIRV_CROSS_THROW("Invalid group operation."); \
9692 break; \
9693 }
9694
9695 #define GLSL_GROUP_OP_CAST(op, glsl_op, type) \
9696 case OpGroupNonUniform##op: \
9697 { \
9698 auto operation = static_cast<GroupOperation>(ops[3]); \
9699 if (operation == GroupOperationReduce) \
9700 emit_unary_func_op_cast(result_type, id, ops[4], "subgroup" #glsl_op, type, type); \
9701 else if (operation == GroupOperationInclusiveScan) \
9702 emit_unary_func_op_cast(result_type, id, ops[4], "subgroupInclusive" #glsl_op, type, type); \
9703 else if (operation == GroupOperationExclusiveScan) \
9704 emit_unary_func_op_cast(result_type, id, ops[4], "subgroupExclusive" #glsl_op, type, type); \
9705 else if (operation == GroupOperationClusteredReduce) \
9706 emit_binary_func_op_cast_clustered(result_type, id, ops[4], ops[5], "subgroupClustered" #glsl_op, type); \
9707 else \
9708 SPIRV_CROSS_THROW("Invalid group operation."); \
9709 break; \
9710 }
9711
9712 GLSL_GROUP_OP(FAdd, Add)
9713 GLSL_GROUP_OP(FMul, Mul)
9714 GLSL_GROUP_OP(FMin, Min)
9715 GLSL_GROUP_OP(FMax, Max)
9716 GLSL_GROUP_OP(IAdd, Add)
9717 GLSL_GROUP_OP(IMul, Mul)
9718 GLSL_GROUP_OP_CAST(SMin, Min, int_type)
9719 GLSL_GROUP_OP_CAST(SMax, Max, int_type)
9720 GLSL_GROUP_OP_CAST(UMin, Min, uint_type)
9721 GLSL_GROUP_OP_CAST(UMax, Max, uint_type)
9722 GLSL_GROUP_OP(BitwiseAnd, And)
9723 GLSL_GROUP_OP(BitwiseOr, Or)
9724 GLSL_GROUP_OP(BitwiseXor, Xor)
9725 GLSL_GROUP_OP(LogicalAnd, And)
9726 GLSL_GROUP_OP(LogicalOr, Or)
9727 GLSL_GROUP_OP(LogicalXor, Xor)
9728 #undef GLSL_GROUP_OP
9729 #undef GLSL_GROUP_OP_CAST
9730 // clang-format on
9731
9732 case OpGroupNonUniformQuadSwap:
9733 {
9734 uint32_t direction = evaluate_constant_u32(ops[4]);
9735 if (direction == 0)
9736 emit_unary_func_op(result_type, id, ops[3], "subgroupQuadSwapHorizontal");
9737 else if (direction == 1)
9738 emit_unary_func_op(result_type, id, ops[3], "subgroupQuadSwapVertical");
9739 else if (direction == 2)
9740 emit_unary_func_op(result_type, id, ops[3], "subgroupQuadSwapDiagonal");
9741 else
9742 SPIRV_CROSS_THROW("Invalid quad swap direction.");
9743 break;
9744 }
9745
9746 case OpGroupNonUniformQuadBroadcast:
9747 {
9748 emit_binary_func_op(result_type, id, ops[3], ops[4], "subgroupQuadBroadcast");
9749 break;
9750 }
9751
9752 case OpGroupNonUniformQuadAllKHR:
9753 emit_unary_func_op(result_type, id, ops[2], "subgroupQuadAll");
9754 break;
9755
9756 case OpGroupNonUniformQuadAnyKHR:
9757 emit_unary_func_op(result_type, id, ops[2], "subgroupQuadAny");
9758 break;
9759
9760 default:
9761 SPIRV_CROSS_THROW("Invalid opcode for subgroup.");
9762 }
9763
9764 register_control_dependent_expression(id);
9765 }
9766
9767 string CompilerGLSL::bitcast_glsl_op(const SPIRType &out_type, const SPIRType &in_type)
9768 {
9769 // OpBitcast can deal with pointers.
9770 if (out_type.pointer || in_type.pointer)
9771 {
9772 if (out_type.vecsize == 2 || in_type.vecsize == 2)
9773 require_extension_internal("GL_EXT_buffer_reference_uvec2");
9774 return type_to_glsl(out_type);
9775 }
9776
9777 if (out_type.basetype == in_type.basetype)
9778 return "";
9779
9780 assert(out_type.basetype != SPIRType::Boolean);
9781 assert(in_type.basetype != SPIRType::Boolean);
9782
9783 bool integral_cast = type_is_integral(out_type) && type_is_integral(in_type);
9784 bool same_size_cast = out_type.width == in_type.width;
9785
9786 // Trivial bitcast case, casts between integers.
9787 if (integral_cast && same_size_cast)
9788 return type_to_glsl(out_type);
9789
9790 // Catch-all 8-bit arithmetic casts (GL_EXT_shader_explicit_arithmetic_types).
9791 if (out_type.width == 8 && in_type.width >= 16 && integral_cast && in_type.vecsize == 1)
9792 return "unpack8";
9793 else if (in_type.width == 8 && out_type.width == 16 && integral_cast && out_type.vecsize == 1)
9794 return "pack16";
9795 else if (in_type.width == 8 && out_type.width == 32 && integral_cast && out_type.vecsize == 1)
9796 return "pack32";
9797
9798 // Floating <-> Integer special casts. Just have to enumerate all cases. :(
9799 // 16-bit, 32-bit and 64-bit floats.
9800 if (out_type.basetype == SPIRType::UInt && in_type.basetype == SPIRType::Float)
9801 {
9802 if (is_legacy_es())
9803 SPIRV_CROSS_THROW("Float -> Uint bitcast not supported on legacy ESSL.");
9804 else if (!options.es && options.version < 330)
9805 require_extension_internal("GL_ARB_shader_bit_encoding");
9806 return "floatBitsToUint";
9807 }
9808 else if (out_type.basetype == SPIRType::Int && in_type.basetype == SPIRType::Float)
9809 {
9810 if (is_legacy_es())
9811 SPIRV_CROSS_THROW("Float -> Int bitcast not supported on legacy ESSL.");
9812 else if (!options.es && options.version < 330)
9813 require_extension_internal("GL_ARB_shader_bit_encoding");
9814 return "floatBitsToInt";
9815 }
9816 else if (out_type.basetype == SPIRType::Float && in_type.basetype == SPIRType::UInt)
9817 {
9818 if (is_legacy_es())
9819 SPIRV_CROSS_THROW("Uint -> Float bitcast not supported on legacy ESSL.");
9820 else if (!options.es && options.version < 330)
9821 require_extension_internal("GL_ARB_shader_bit_encoding");
9822 return "uintBitsToFloat";
9823 }
9824 else if (out_type.basetype == SPIRType::Float && in_type.basetype == SPIRType::Int)
9825 {
9826 if (is_legacy_es())
9827 SPIRV_CROSS_THROW("Int -> Float bitcast not supported on legacy ESSL.");
9828 else if (!options.es && options.version < 330)
9829 require_extension_internal("GL_ARB_shader_bit_encoding");
9830 return "intBitsToFloat";
9831 }
9832
9833 else if (out_type.basetype == SPIRType::Int64 && in_type.basetype == SPIRType::Double)
9834 return "doubleBitsToInt64";
9835 else if (out_type.basetype == SPIRType::UInt64 && in_type.basetype == SPIRType::Double)
9836 return "doubleBitsToUint64";
9837 else if (out_type.basetype == SPIRType::Double && in_type.basetype == SPIRType::Int64)
9838 return "int64BitsToDouble";
9839 else if (out_type.basetype == SPIRType::Double && in_type.basetype == SPIRType::UInt64)
9840 return "uint64BitsToDouble";
9841 else if (out_type.basetype == SPIRType::Short && in_type.basetype == SPIRType::Half)
9842 return "float16BitsToInt16";
9843 else if (out_type.basetype == SPIRType::UShort && in_type.basetype == SPIRType::Half)
9844 return "float16BitsToUint16";
9845 else if (out_type.basetype == SPIRType::Half && in_type.basetype == SPIRType::Short)
9846 return "int16BitsToFloat16";
9847 else if (out_type.basetype == SPIRType::Half && in_type.basetype == SPIRType::UShort)
9848 return "uint16BitsToFloat16";
9849
9850 // And finally, some even more special purpose casts.
9851 if (out_type.basetype == SPIRType::UInt64 && in_type.basetype == SPIRType::UInt && in_type.vecsize == 2)
9852 return "packUint2x32";
9853 else if (out_type.basetype == SPIRType::UInt && in_type.basetype == SPIRType::UInt64 && out_type.vecsize == 2)
9854 return "unpackUint2x32";
9855 else if (out_type.basetype == SPIRType::Half && in_type.basetype == SPIRType::UInt && in_type.vecsize == 1)
9856 return "unpackFloat2x16";
9857 else if (out_type.basetype == SPIRType::UInt && in_type.basetype == SPIRType::Half && in_type.vecsize == 2)
9858 return "packFloat2x16";
9859 else if (out_type.basetype == SPIRType::Int && in_type.basetype == SPIRType::Short && in_type.vecsize == 2)
9860 return "packInt2x16";
9861 else if (out_type.basetype == SPIRType::Short && in_type.basetype == SPIRType::Int && in_type.vecsize == 1)
9862 return "unpackInt2x16";
9863 else if (out_type.basetype == SPIRType::UInt && in_type.basetype == SPIRType::UShort && in_type.vecsize == 2)
9864 return "packUint2x16";
9865 else if (out_type.basetype == SPIRType::UShort && in_type.basetype == SPIRType::UInt && in_type.vecsize == 1)
9866 return "unpackUint2x16";
9867 else if (out_type.basetype == SPIRType::Int64 && in_type.basetype == SPIRType::Short && in_type.vecsize == 4)
9868 return "packInt4x16";
9869 else if (out_type.basetype == SPIRType::Short && in_type.basetype == SPIRType::Int64 && in_type.vecsize == 1)
9870 return "unpackInt4x16";
9871 else if (out_type.basetype == SPIRType::UInt64 && in_type.basetype == SPIRType::UShort && in_type.vecsize == 4)
9872 return "packUint4x16";
9873 else if (out_type.basetype == SPIRType::UShort && in_type.basetype == SPIRType::UInt64 && in_type.vecsize == 1)
9874 return "unpackUint4x16";
9875 else if (out_type.basetype == SPIRType::BFloat16 && in_type.basetype == SPIRType::UShort)
9876 return "uintBitsToBFloat16EXT";
9877 else if (out_type.basetype == SPIRType::BFloat16 && in_type.basetype == SPIRType::Short)
9878 return "intBitsToBFloat16EXT";
9879 else if (out_type.basetype == SPIRType::UShort && in_type.basetype == SPIRType::BFloat16)
9880 return "bfloat16BitsToUintEXT";
9881 else if (out_type.basetype == SPIRType::Short && in_type.basetype == SPIRType::BFloat16)
9882 return "bfloat16BitsToIntEXT";
9883 else if (out_type.basetype == SPIRType::FloatE4M3 && in_type.basetype == SPIRType::UByte)
9884 return "uintBitsToFloate4m3EXT";
9885 else if (out_type.basetype == SPIRType::FloatE4M3 && in_type.basetype == SPIRType::SByte)
9886 return "intBitsToFloate4m3EXT";
9887 else if (out_type.basetype == SPIRType::UByte && in_type.basetype == SPIRType::FloatE4M3)
9888 return "floate4m3BitsToUintEXT";
9889 else if (out_type.basetype == SPIRType::SByte && in_type.basetype == SPIRType::FloatE4M3)
9890 return "floate4m3BitsToIntEXT";
9891 else if (out_type.basetype == SPIRType::FloatE5M2 && in_type.basetype == SPIRType::UByte)
9892 return "uintBitsToFloate5m2EXT";
9893 else if (out_type.basetype == SPIRType::FloatE5M2 && in_type.basetype == SPIRType::SByte)
9894 return "intBitsToFloate5m2EXT";
9895 else if (out_type.basetype == SPIRType::UByte && in_type.basetype == SPIRType::FloatE5M2)
9896 return "floate5m2BitsToUintEXT";
9897 else if (out_type.basetype == SPIRType::SByte && in_type.basetype == SPIRType::FloatE5M2)
9898 return "floate5m2BitsToIntEXT";
9899
9900 return "";
9901 }
9902
9903 string CompilerGLSL::bitcast_glsl(const SPIRType &result_type, uint32_t argument)
9904 {
9905 auto op = bitcast_glsl_op(result_type, expression_type(argument));
9906 if (op.empty())
9907 return to_enclosed_unpacked_expression(argument);
9908 else
9909 return join(op, "(", to_unpacked_expression(argument), ")");
9910 }
9911
9912 std::string CompilerGLSL::bitcast_expression(SPIRType::BaseType target_type, uint32_t arg)
9913 {
9914 auto expr = to_expression(arg);
9915 auto &src_type = expression_type(arg);
9916 if (src_type.basetype != target_type)
9917 {
9918 auto target = src_type;
9919 target.basetype = target_type;
9920 expr = join(bitcast_glsl_op(target, src_type), "(", expr, ")");
9921 }
9922
9923 return expr;
9924 }
9925
9926 std::string CompilerGLSL::bitcast_expression(const SPIRType &target_type, SPIRType::BaseType expr_type,
9927 const std::string &expr)
9928 {
9929 if (target_type.basetype == expr_type)
9930 return expr;
9931
9932 auto src_type = target_type;
9933 src_type.basetype = expr_type;
9934 return join(bitcast_glsl_op(target_type, src_type), "(", expr, ")");
9935 }
9936
9937 string CompilerGLSL::builtin_to_glsl(BuiltIn builtin, StorageClass storage)
9938 {
9939 switch (builtin)
9940 {
9941 case BuiltInPosition:
9942 return "gl_Position";
9943 case BuiltInPointSize:
9944 return "gl_PointSize";
9945 case BuiltInClipDistance:
9946 {
9947 if (options.es)
9948 require_extension_internal("GL_EXT_clip_cull_distance");
9949 return "gl_ClipDistance";
9950 }
9951 case BuiltInCullDistance:
9952 {
9953 if (options.es)
9954 require_extension_internal("GL_EXT_clip_cull_distance");
9955 return "gl_CullDistance";
9956 }
9957 case BuiltInVertexId:
9958 if (options.vulkan_semantics)
9959 SPIRV_CROSS_THROW("Cannot implement gl_VertexID in Vulkan GLSL. This shader was created "
9960 "with GL semantics.");
9961 return "gl_VertexID";
9962 case BuiltInInstanceId:
9963 if (options.vulkan_semantics)
9964 {
9965 auto model = get_entry_point().model;
9966 switch (model)
9967 {
9968 case spv::ExecutionModelIntersectionKHR:
9969 case spv::ExecutionModelAnyHitKHR:
9970 case spv::ExecutionModelClosestHitKHR:
9971 // gl_InstanceID is allowed in these shaders.
9972 break;
9973
9974 default:
9975 SPIRV_CROSS_THROW("Cannot implement gl_InstanceID in Vulkan GLSL. This shader was "
9976 "created with GL semantics.");
9977 }
9978 }
9979 if (!options.es && options.version < 140)
9980 {
9981 require_extension_internal("GL_ARB_draw_instanced");
9982 }
9983 return "gl_InstanceID";
9984 case BuiltInVertexIndex:
9985 if (options.vulkan_semantics)
9986 return "gl_VertexIndex";
9987 else
9988 return "gl_VertexID"; // gl_VertexID already has the base offset applied.
9989 case BuiltInInstanceIndex:
9990 if (options.vulkan_semantics)
9991 return "gl_InstanceIndex";
9992
9993 if (!options.es && options.version < 140)
9994 {
9995 require_extension_internal("GL_ARB_draw_instanced");
9996 }
9997
9998 if (options.vertex.support_nonzero_base_instance)
9999 {
10000 if (!options.vulkan_semantics)
10001 {
10002 // This is a soft-enable. We will opt-in to using gl_BaseInstanceARB if supported.
10003 require_extension_internal("GL_ARB_shader_draw_parameters");
10004 }
10005 return "(gl_InstanceID + SPIRV_Cross_BaseInstance)"; // ... but not gl_InstanceID.
10006 }
10007 else
10008 return "gl_InstanceID";
10009 case BuiltInPrimitiveId:
10010 if (storage == StorageClassInput && get_entry_point().model == ExecutionModelGeometry)
10011 return "gl_PrimitiveIDIn";
10012 else
10013 return "gl_PrimitiveID";
10014 case BuiltInInvocationId:
10015 return "gl_InvocationID";
10016 case BuiltInLayer:
10017 {
10018 auto model = get_execution_model();
10019 if (model == ExecutionModelVertex || model == ExecutionModelTessellationEvaluation)
10020 {
10021 if (options.es)
10022 require_extension_internal("GL_NV_viewport_array2");
10023 else
10024 require_extension_internal("GL_ARB_shader_viewport_layer_array");
10025 }
10026 return "gl_Layer";
10027 }
10028 case BuiltInViewportIndex:
10029 return "gl_ViewportIndex";
10030 case BuiltInTessLevelOuter:
10031 return "gl_TessLevelOuter";
10032 case BuiltInTessLevelInner:
10033 return "gl_TessLevelInner";
10034 case BuiltInTessCoord:
10035 return "gl_TessCoord";
10036 case BuiltInPatchVertices:
10037 return "gl_PatchVerticesIn";
10038 case BuiltInFragCoord:
10039 return "gl_FragCoord";
10040 case BuiltInPointCoord:
10041 return "gl_PointCoord";
10042 case BuiltInFrontFacing:
10043 return "gl_FrontFacing";
10044 case BuiltInFragDepth:
10045 return "gl_FragDepth";
10046 case BuiltInNumWorkgroups:
10047 return "gl_NumWorkGroups";
10048 case BuiltInWorkgroupSize:
10049 return "gl_WorkGroupSize";
10050 case BuiltInWorkgroupId:
10051 return "gl_WorkGroupID";
10052 case BuiltInLocalInvocationId:
10053 return "gl_LocalInvocationID";
10054 case BuiltInGlobalInvocationId:
10055 return "gl_GlobalInvocationID";
10056 case BuiltInLocalInvocationIndex:
10057 return "gl_LocalInvocationIndex";
10058 case BuiltInHelperInvocation:
10059 return "gl_HelperInvocation";
10060
10061 case BuiltInBaseVertex:
10062 if (options.es)
10063 SPIRV_CROSS_THROW("BaseVertex not supported in ES profile.");
10064
10065 if (options.vulkan_semantics)
10066 {
10067 if (options.version < 460)
10068 {
10069 require_extension_internal("GL_ARB_shader_draw_parameters");
10070 return "gl_BaseVertexARB";
10071 }
10072 return "gl_BaseVertex";
10073 }
10074 // On regular GL, this is soft-enabled and we emit ifdefs in code.
10075 require_extension_internal("GL_ARB_shader_draw_parameters");
10076 return "SPIRV_Cross_BaseVertex";
10077
10078 case BuiltInBaseInstance:
10079 if (options.es)
10080 SPIRV_CROSS_THROW("BaseInstance not supported in ES profile.");
10081
10082 if (options.vulkan_semantics)
10083 {
10084 if (options.version < 460)
10085 {
10086 require_extension_internal("GL_ARB_shader_draw_parameters");
10087 return "gl_BaseInstanceARB";
10088 }
10089 return "gl_BaseInstance";
10090 }
10091 // On regular GL, this is soft-enabled and we emit ifdefs in code.
10092 require_extension_internal("GL_ARB_shader_draw_parameters");
10093 return "SPIRV_Cross_BaseInstance";
10094
10095 case BuiltInDrawIndex:
10096 if (options.es)
10097 SPIRV_CROSS_THROW("DrawIndex not supported in ES profile.");
10098
10099 if (options.vulkan_semantics)
10100 {
10101 if (options.version < 460)
10102 {
10103 require_extension_internal("GL_ARB_shader_draw_parameters");
10104 return "gl_DrawIDARB";
10105 }
10106 return "gl_DrawID";
10107 }
10108 // On regular GL, this is soft-enabled and we emit ifdefs in code.
10109 require_extension_internal("GL_ARB_shader_draw_parameters");
10110 return "gl_DrawIDARB";
10111
10112 case BuiltInSampleId:
10113 if (is_legacy())
10114 SPIRV_CROSS_THROW("Sample variables not supported in legacy GLSL.");
10115 else if (options.es && options.version < 320)
10116 require_extension_internal("GL_OES_sample_variables");
10117 else if (!options.es && options.version < 400)
10118 require_extension_internal("GL_ARB_sample_shading");
10119 return "gl_SampleID";
10120
10121 case BuiltInSampleMask:
10122 if (is_legacy())
10123 SPIRV_CROSS_THROW("Sample variables not supported in legacy GLSL.");
10124 else if (options.es && options.version < 320)
10125 require_extension_internal("GL_OES_sample_variables");
10126 else if (!options.es && options.version < 400)
10127 require_extension_internal("GL_ARB_sample_shading");
10128
10129 if (storage == StorageClassInput)
10130 return "gl_SampleMaskIn";
10131 else
10132 return "gl_SampleMask";
10133
10134 case BuiltInSamplePosition:
10135 if (is_legacy())
10136 SPIRV_CROSS_THROW("Sample variables not supported in legacy GLSL.");
10137 else if (options.es && options.version < 320)
10138 require_extension_internal("GL_OES_sample_variables");
10139 else if (!options.es && options.version < 400)
10140 require_extension_internal("GL_ARB_sample_shading");
10141 return "gl_SamplePosition";
10142
10143 case BuiltInViewIndex:
10144 if (options.vulkan_semantics)
10145 return "gl_ViewIndex";
10146 else
10147 return "gl_ViewID_OVR";
10148
10149 case BuiltInNumSubgroups:
10150 request_subgroup_feature(ShaderSubgroupSupportHelper::NumSubgroups);
10151 return "gl_NumSubgroups";
10152
10153 case BuiltInSubgroupId:
10154 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupID);
10155 return "gl_SubgroupID";
10156
10157 case BuiltInSubgroupSize:
10158 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupSize);
10159 return "gl_SubgroupSize";
10160
10161 case BuiltInSubgroupLocalInvocationId:
10162 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupInvocationID);
10163 return "gl_SubgroupInvocationID";
10164
10165 case BuiltInSubgroupEqMask:
10166 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupMask);
10167 return "gl_SubgroupEqMask";
10168
10169 case BuiltInSubgroupGeMask:
10170 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupMask);
10171 return "gl_SubgroupGeMask";
10172
10173 case BuiltInSubgroupGtMask:
10174 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupMask);
10175 return "gl_SubgroupGtMask";
10176
10177 case BuiltInSubgroupLeMask:
10178 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupMask);
10179 return "gl_SubgroupLeMask";
10180
10181 case BuiltInSubgroupLtMask:
10182 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupMask);
10183 return "gl_SubgroupLtMask";
10184
10185 case BuiltInLaunchIdKHR:
10186 return ray_tracing_is_khr ? "gl_LaunchIDEXT" : "gl_LaunchIDNV";
10187 case BuiltInLaunchSizeKHR:
10188 return ray_tracing_is_khr ? "gl_LaunchSizeEXT" : "gl_LaunchSizeNV";
10189 case BuiltInWorldRayOriginKHR:
10190 return ray_tracing_is_khr ? "gl_WorldRayOriginEXT" : "gl_WorldRayOriginNV";
10191 case BuiltInWorldRayDirectionKHR:
10192 return ray_tracing_is_khr ? "gl_WorldRayDirectionEXT" : "gl_WorldRayDirectionNV";
10193 case BuiltInObjectRayOriginKHR:
10194 return ray_tracing_is_khr ? "gl_ObjectRayOriginEXT" : "gl_ObjectRayOriginNV";
10195 case BuiltInObjectRayDirectionKHR:
10196 return ray_tracing_is_khr ? "gl_ObjectRayDirectionEXT" : "gl_ObjectRayDirectionNV";
10197 case BuiltInRayTminKHR:
10198 return ray_tracing_is_khr ? "gl_RayTminEXT" : "gl_RayTminNV";
10199 case BuiltInRayTmaxKHR:
10200 return ray_tracing_is_khr ? "gl_RayTmaxEXT" : "gl_RayTmaxNV";
10201 case BuiltInInstanceCustomIndexKHR:
10202 return ray_tracing_is_khr ? "gl_InstanceCustomIndexEXT" : "gl_InstanceCustomIndexNV";
10203 case BuiltInObjectToWorldKHR:
10204 return ray_tracing_is_khr ? "gl_ObjectToWorldEXT" : "gl_ObjectToWorldNV";
10205 case BuiltInWorldToObjectKHR:
10206 return ray_tracing_is_khr ? "gl_WorldToObjectEXT" : "gl_WorldToObjectNV";
10207 case BuiltInHitTNV:
10208 // gl_HitTEXT is an alias of RayTMax in KHR.
10209 return "gl_HitTNV";
10210 case BuiltInHitKindKHR:
10211 return ray_tracing_is_khr ? "gl_HitKindEXT" : "gl_HitKindNV";
10212 case BuiltInIncomingRayFlagsKHR:
10213 return ray_tracing_is_khr ? "gl_IncomingRayFlagsEXT" : "gl_IncomingRayFlagsNV";
10214
10215 case BuiltInBaryCoordKHR:
10216 {
10217 if (options.es && options.version < 320)
10218 SPIRV_CROSS_THROW("gl_BaryCoordEXT requires ESSL 320.");
10219 else if (!options.es && options.version < 450)
10220 SPIRV_CROSS_THROW("gl_BaryCoordEXT requires GLSL 450.");
10221
10222 if (barycentric_is_nv)
10223 {
10224 require_extension_internal("GL_NV_fragment_shader_barycentric");
10225 return "gl_BaryCoordNV";
10226 }
10227 else
10228 {
10229 require_extension_internal("GL_EXT_fragment_shader_barycentric");
10230 return "gl_BaryCoordEXT";
10231 }
10232 }
10233
10234 case BuiltInBaryCoordNoPerspNV:
10235 {
10236 if (options.es && options.version < 320)
10237 SPIRV_CROSS_THROW("gl_BaryCoordNoPerspEXT requires ESSL 320.");
10238 else if (!options.es && options.version < 450)
10239 SPIRV_CROSS_THROW("gl_BaryCoordNoPerspEXT requires GLSL 450.");
10240
10241 if (barycentric_is_nv)
10242 {
10243 require_extension_internal("GL_NV_fragment_shader_barycentric");
10244 return "gl_BaryCoordNoPerspNV";
10245 }
10246 else
10247 {
10248 require_extension_internal("GL_EXT_fragment_shader_barycentric");
10249 return "gl_BaryCoordNoPerspEXT";
10250 }
10251 }
10252
10253 case BuiltInFragStencilRefEXT:
10254 {
10255 if (!options.es)
10256 {
10257 require_extension_internal("GL_ARB_shader_stencil_export");
10258 return "gl_FragStencilRefARB";
10259 }
10260 else
10261 SPIRV_CROSS_THROW("Stencil export not supported in GLES.");
10262 }
10263
10264 case BuiltInPrimitiveShadingRateKHR:
10265 {
10266 if (!options.vulkan_semantics)
10267 SPIRV_CROSS_THROW("Can only use PrimitiveShadingRateKHR in Vulkan GLSL.");
10268 require_extension_internal("GL_EXT_fragment_shading_rate");
10269 return "gl_PrimitiveShadingRateEXT";
10270 }
10271
10272 case BuiltInShadingRateKHR:
10273 {
10274 if (!options.vulkan_semantics)
10275 SPIRV_CROSS_THROW("Can only use ShadingRateKHR in Vulkan GLSL.");
10276 require_extension_internal("GL_EXT_fragment_shading_rate");
10277 return "gl_ShadingRateEXT";
10278 }
10279
10280 case BuiltInDeviceIndex:
10281 if (!options.vulkan_semantics)
10282 SPIRV_CROSS_THROW("Need Vulkan semantics for device group support.");
10283 require_extension_internal("GL_EXT_device_group");
10284 return "gl_DeviceIndex";
10285
10286 case BuiltInFullyCoveredEXT:
10287 if (!options.es)
10288 require_extension_internal("GL_NV_conservative_raster_underestimation");
10289 else
10290 SPIRV_CROSS_THROW("Need desktop GL to use GL_NV_conservative_raster_underestimation.");
10291 return "gl_FragFullyCoveredNV";
10292
10293 case BuiltInPrimitiveTriangleIndicesEXT:
10294 return "gl_PrimitiveTriangleIndicesEXT";
10295 case BuiltInPrimitiveLineIndicesEXT:
10296 return "gl_PrimitiveLineIndicesEXT";
10297 case BuiltInPrimitivePointIndicesEXT:
10298 return "gl_PrimitivePointIndicesEXT";
10299 case BuiltInCullPrimitiveEXT:
10300 return "gl_CullPrimitiveEXT";
10301
10302 default:
10303 return join("gl_BuiltIn_", convert_to_string(builtin));
10304 }
10305 }
10306
10307 const char *CompilerGLSL::index_to_swizzle(uint32_t index)
10308 {
10309 switch (index)
10310 {
10311 case 0:
10312 return "x";
10313 case 1:
10314 return "y";
10315 case 2:
10316 return "z";
10317 case 3:
10318 return "w";
10319 default:
10320 return "x"; // Don't crash, but engage the "undefined behavior" described for out-of-bounds logical addressing in spec.
10321 }
10322 }
10323
10324 void CompilerGLSL::access_chain_internal_append_index(std::string &expr, uint32_t /*base*/, const SPIRType * /*type*/,
10325 AccessChainFlags flags, bool &access_chain_is_arrayed,
10326 uint32_t index)
10327 {
10328 bool index_is_literal = (flags & ACCESS_CHAIN_INDEX_IS_LITERAL_BIT) != 0;
10329 bool ptr_chain = (flags & ACCESS_CHAIN_PTR_CHAIN_BIT) != 0;
10330 bool register_expression_read = (flags & ACCESS_CHAIN_SKIP_REGISTER_EXPRESSION_READ_BIT) == 0;
10331
10332 string idx_expr = index_is_literal ? convert_to_string(index) : to_unpacked_expression(index, register_expression_read);
10333
10334 // For the case where the base of an OpPtrAccessChain already ends in [n],
10335 // we need to use the index as an offset to the existing index, otherwise,
10336 // we can just use the index directly.
10337 if (ptr_chain && access_chain_is_arrayed)
10338 {
10339 size_t split_pos = expr.find_last_of(']');
10340 size_t enclose_split = expr.find_last_of(')');
10341
10342 // If we have already enclosed the expression, don't try to be clever, it will break.
10343 if (split_pos > enclose_split || enclose_split == string::npos)
10344 {
10345 string expr_front = expr.substr(0, split_pos);
10346 string expr_back = expr.substr(split_pos);
10347 expr = expr_front + " + " + enclose_expression(idx_expr) + expr_back;
10348 return;
10349 }
10350 }
10351
10352 expr += "[";
10353 expr += idx_expr;
10354 expr += "]";
10355 }
10356
10357 bool CompilerGLSL::access_chain_needs_stage_io_builtin_translation(uint32_t)
10358 {
10359 return true;
10360 }
10361
10362 string CompilerGLSL::access_chain_internal(uint32_t base, const uint32_t *indices, uint32_t count,
10363 AccessChainFlags flags, AccessChainMeta *meta)
10364 {
10365 string expr;
10366
10367 bool index_is_literal = (flags & ACCESS_CHAIN_INDEX_IS_LITERAL_BIT) != 0;
10368 bool msb_is_id = (flags & ACCESS_CHAIN_LITERAL_MSB_FORCE_ID) != 0;
10369 bool chain_only = (flags & ACCESS_CHAIN_CHAIN_ONLY_BIT) != 0;
10370 bool ptr_chain = (flags & ACCESS_CHAIN_PTR_CHAIN_BIT) != 0;
10371 bool register_expression_read = (flags & ACCESS_CHAIN_SKIP_REGISTER_EXPRESSION_READ_BIT) == 0;
10372 bool flatten_member_reference = (flags & ACCESS_CHAIN_FLATTEN_ALL_MEMBERS_BIT) != 0;
10373
10374 if (!chain_only)
10375 {
10376 // We handle transpose explicitly, so don't resolve that here.
10377 auto *e = maybe_get<SPIRExpression>(base);
10378 bool old_transpose = e && e->need_transpose;
10379 if (e)
10380 e->need_transpose = false;
10381 expr = to_enclosed_expression(base, register_expression_read);
10382 if (e)
10383 e->need_transpose = old_transpose;
10384 }
10385
10386 // Start traversing type hierarchy at the proper non-pointer types,
10387 // but keep type_id referencing the original pointer for use below.
10388 uint32_t type_id = expression_type_id(base);
10389 const auto *type = &get_pointee_type(type_id);
10390
10391 if (!backend.native_pointers)
10392 {
10393 if (ptr_chain)
10394 SPIRV_CROSS_THROW("Backend does not support native pointers and does not support OpPtrAccessChain.");
10395
10396 // Wrapped buffer reference pointer types will need to poke into the internal "value" member before
10397 // continuing the access chain.
10398 if (should_dereference(base))
10399 expr = dereference_expression(get<SPIRType>(type_id), expr);
10400 }
10401 else if (should_dereference(base) && type->basetype != SPIRType::Struct && !ptr_chain)
10402 expr = join("(", dereference_expression(*type, expr), ")");
10403
10404 bool access_chain_is_arrayed = expr.find_first_of('[') != string::npos;
10405 bool row_major_matrix_needs_conversion = is_non_native_row_major_matrix(base);
10406 bool is_packed = has_extended_decoration(base, SPIRVCrossDecorationPhysicalTypePacked);
10407 uint32_t physical_type = get_extended_decoration(base, SPIRVCrossDecorationPhysicalTypeID);
10408 bool is_invariant = has_decoration(base, DecorationInvariant);
10409 bool relaxed_precision = has_decoration(base, DecorationRelaxedPrecision);
10410 bool pending_array_enclose = false;
10411 bool dimension_flatten = false;
10412 bool access_meshlet_position_y = false;
10413 bool chain_is_builtin = false;
10414 spv::BuiltIn chained_builtin = {};
10415
10416 if (auto *base_expr = maybe_get<SPIRExpression>(base))
10417 {
10418 access_meshlet_position_y = base_expr->access_meshlet_position_y;
10419 }
10420
10421 // If we are translating access to a structured buffer, the first subscript '._m0' must be hidden
10422 bool hide_first_subscript = count > 1 && is_user_type_structured(base);
10423
10424 const auto append_index = [&](uint32_t index, bool is_literal, bool is_ptr_chain = false) {
10425 AccessChainFlags mod_flags = flags;
10426 if (!is_literal)
10427 mod_flags &= ~ACCESS_CHAIN_INDEX_IS_LITERAL_BIT;
10428 if (!is_ptr_chain)
10429 mod_flags &= ~ACCESS_CHAIN_PTR_CHAIN_BIT;
10430 access_chain_internal_append_index(expr, base, type, mod_flags, access_chain_is_arrayed, index);
10431 if (check_physical_type_cast(expr, type, physical_type))
10432 physical_type = 0;
10433 };
10434
10435 for (uint32_t i = 0; i < count; i++)
10436 {
10437 uint32_t index = indices[i];
10438
10439 bool is_literal = index_is_literal;
10440 if (is_literal && msb_is_id && (index >> 31u) != 0u)
10441 {
10442 is_literal = false;
10443 index &= 0x7fffffffu;
10444 }
10445
10446 bool ptr_chain_array_entry = ptr_chain && i == 0 && is_array(*type);
10447
10448 if (ptr_chain_array_entry)
10449 {
10450 // This is highly unusual code, since normally we'd use plain AccessChain, but it's still allowed.
10451 // We are considered to have a pointer to array and one element shifts by one array at a time.
10452 // If we use normal array indexing, we'll first decay to pointer, and lose the array-ness,
10453 // so we have to take pointer to array explicitly.
10454 if (!should_dereference(base))
10455 expr = enclose_expression(address_of_expression(expr));
10456 }
10457
10458 if (ptr_chain && i == 0)
10459 {
10460 // Pointer chains
10461 // If we are flattening multidimensional arrays, only create opening bracket on first
10462 // array index.
10463 if (options.flatten_multidimensional_arrays)
10464 {
10465 dimension_flatten = type->array.size() >= 1;
10466 pending_array_enclose = dimension_flatten;
10467 if (pending_array_enclose)
10468 expr += "[";
10469 }
10470
10471 if (options.flatten_multidimensional_arrays && dimension_flatten)
10472 {
10473 // If we are flattening multidimensional arrays, do manual stride computation.
10474 if (is_literal)
10475 expr += convert_to_string(index);
10476 else
10477 expr += to_enclosed_expression(index, register_expression_read);
10478
10479 for (auto j = uint32_t(type->array.size()); j; j--)
10480 {
10481 expr += " * ";
10482 expr += enclose_expression(to_array_size(*type, j - 1));
10483 }
10484
10485 if (type->array.empty())
10486 pending_array_enclose = false;
10487 else
10488 expr += " + ";
10489
10490 if (!pending_array_enclose)
10491 expr += "]";
10492 }
10493 else
10494 {
10495 if (flags & ACCESS_CHAIN_PTR_CHAIN_POINTER_ARITH_BIT)
10496 {
10497 SPIRType tmp_type(OpTypeInt);
10498 tmp_type.basetype = SPIRType::UInt64;
10499 tmp_type.width = 64;
10500 tmp_type.vecsize = 1;
10501 tmp_type.columns = 1;
10502
10503 TypeID ptr_type_id = expression_type_id(base);
10504 const SPIRType &ptr_type = get<SPIRType>(ptr_type_id);
10505 const SPIRType &pointee_type = get_pointee_type(ptr_type);
10506
10507 // This only runs in native pointer backends.
10508 // Can replace reinterpret_cast with a backend string if ever needed.
10509 // We expect this to count as a de-reference.
10510 // This leaks some MSL details, but feels slightly overkill to
10511 // add yet another virtual interface just for this.
10512 auto intptr_expr = join("reinterpret_cast<", type_to_glsl(tmp_type), ">(", expr, ")");
10513 intptr_expr += join(" + ", to_enclosed_unpacked_expression(index), " * ",
10514 get_decoration(ptr_type_id, DecorationArrayStride));
10515
10516 if (flags & ACCESS_CHAIN_PTR_CHAIN_CAST_TO_SCALAR_BIT)
10517 {
10518 is_packed = true;
10519 expr = join("*reinterpret_cast<device packed_", type_to_glsl(pointee_type),
10520 " *>(", intptr_expr, ")");
10521 }
10522 else
10523 {
10524 expr = join("*reinterpret_cast<", type_to_glsl(ptr_type), ">(", intptr_expr, ")");
10525 }
10526 }
10527 else
10528 append_index(index, is_literal, true);
10529 }
10530
10531 if (type->basetype == SPIRType::ControlPointArray)
10532 {
10533 type_id = type->parent_type;
10534 type = &get<SPIRType>(type_id);
10535 }
10536
10537 access_chain_is_arrayed = true;
10538
10539 // Explicitly enclose the expression if this is one of the weird pointer-to-array cases.
10540 // We don't want any future indexing to add to this array dereference.
10541 // Enclosing the expression blocks that and avoids any shenanigans with operand priority.
10542 if (ptr_chain_array_entry)
10543 expr = join("(", expr, ")");
10544 }
10545 // Arrays
10546 else if (!type->array.empty())
10547 {
10548 // If we are flattening multidimensional arrays, only create opening bracket on first
10549 // array index.
10550 if (options.flatten_multidimensional_arrays && !pending_array_enclose)
10551 {
10552 dimension_flatten = type->array.size() > 1;
10553 pending_array_enclose = dimension_flatten;
10554 if (pending_array_enclose)
10555 expr += "[";
10556 }
10557
10558 assert(type->parent_type);
10559
10560 auto *var = maybe_get<SPIRVariable>(base);
10561 if (backend.force_gl_in_out_block && i == 0 && var && is_builtin_variable(*var) &&
10562 !has_decoration(type->self, DecorationBlock))
10563 {
10564 // This deals with scenarios for tesc/geom where arrays of gl_Position[] are declared.
10565 // Normally, these variables live in blocks when compiled from GLSL,
10566 // but HLSL seems to just emit straight arrays here.
10567 // We must pretend this access goes through gl_in/gl_out arrays
10568 // to be able to access certain builtins as arrays.
10569 // Similar concerns apply for mesh shaders where we have to redirect to gl_MeshVerticesEXT or MeshPrimitivesEXT.
10570 auto builtin = ir.meta[base].decoration.builtin_type;
10571 bool mesh_shader = get_execution_model() == ExecutionModelMeshEXT;
10572
10573 chain_is_builtin = true;
10574 chained_builtin = builtin;
10575
10576 switch (builtin)
10577 {
10578 case BuiltInCullDistance:
10579 case BuiltInClipDistance:
10580 if (type->array.size() == 1) // Red herring. Only consider block IO for two-dimensional arrays here.
10581 {
10582 append_index(index, is_literal);
10583 break;
10584 }
10585 // fallthrough
10586 case BuiltInPosition:
10587 case BuiltInPointSize:
10588 if (mesh_shader)
10589 expr = join("gl_MeshVerticesEXT[", to_expression(index, register_expression_read), "].", expr);
10590 else if (var->storage == StorageClassInput)
10591 expr = join("gl_in[", to_expression(index, register_expression_read), "].", expr);
10592 else if (var->storage == StorageClassOutput)
10593 expr = join("gl_out[", to_expression(index, register_expression_read), "].", expr);
10594 else
10595 append_index(index, is_literal);
10596 break;
10597
10598 case BuiltInPrimitiveId:
10599 case BuiltInLayer:
10600 case BuiltInViewportIndex:
10601 case BuiltInCullPrimitiveEXT:
10602 case BuiltInPrimitiveShadingRateKHR:
10603 if (mesh_shader)
10604 expr = join("gl_MeshPrimitivesEXT[", to_expression(index, register_expression_read), "].", expr);
10605 else
10606 append_index(index, is_literal);
10607 break;
10608
10609 default:
10610 append_index(index, is_literal);
10611 break;
10612 }
10613 }
10614 else if (backend.force_merged_mesh_block && i == 0 && var &&
10615 !is_builtin_variable(*var) && var->storage == StorageClassOutput)
10616 {
10617 if (is_per_primitive_variable(*var))
10618 expr = join("gl_MeshPrimitivesEXT[", to_expression(index, register_expression_read), "].", expr);
10619 else
10620 expr = join("gl_MeshVerticesEXT[", to_expression(index, register_expression_read), "].", expr);
10621 }
10622 else if (options.flatten_multidimensional_arrays && dimension_flatten)
10623 {
10624 // If we are flattening multidimensional arrays, do manual stride computation.
10625 auto &parent_type = get<SPIRType>(type->parent_type);
10626
10627 if (is_literal)
10628 expr += convert_to_string(index);
10629 else
10630 expr += to_enclosed_expression(index, register_expression_read);
10631
10632 for (auto j = uint32_t(parent_type.array.size()); j; j--)
10633 {
10634 expr += " * ";
10635 expr += enclose_expression(to_array_size(parent_type, j - 1));
10636 }
10637
10638 if (parent_type.array.empty())
10639 pending_array_enclose = false;
10640 else
10641 expr += " + ";
10642
10643 if (!pending_array_enclose)
10644 expr += "]";
10645 }
10646 else if (index_is_literal || !builtin_translates_to_nonarray(BuiltIn(get_decoration(base, DecorationBuiltIn))))
10647 {
10648 // Some builtins are arrays in SPIR-V but not in other languages, e.g. gl_SampleMask[] is an array in SPIR-V but not in Metal.
10649 // By throwing away the index, we imply the index was 0, which it must be for gl_SampleMask.
10650 // For literal indices we are working on composites, so we ignore this since we have already converted to proper array.
10651 append_index(index, is_literal);
10652 }
10653
10654 if (var && has_decoration(var->self, DecorationBuiltIn) &&
10655 get_decoration(var->self, DecorationBuiltIn) == BuiltInPosition &&
10656 get_execution_model() == ExecutionModelMeshEXT)
10657 {
10658 access_meshlet_position_y = true;
10659 }
10660
10661 type_id = type->parent_type;
10662 type = &get<SPIRType>(type_id);
10663
10664 // If the physical type has an unnatural vecsize,
10665 // we must assume it's a faked struct where the .data member
10666 // is used for the real payload.
10667 if (physical_type && (is_vector(*type) || is_scalar(*type)))
10668 {
10669 auto &phys = get<SPIRType>(physical_type);
10670 if (phys.vecsize > 4)
10671 expr += ".data";
10672 }
10673
10674 access_chain_is_arrayed = true;
10675 }
10676 // For structs, the index refers to a constant, which indexes into the members, possibly through a redirection mapping.
10677 // We also check if this member is a builtin, since we then replace the entire expression with the builtin one.
10678 else if (type->basetype == SPIRType::Struct)
10679 {
10680 if (!is_literal)
10681 index = evaluate_constant_u32(index);
10682
10683 if (index < uint32_t(type->member_type_index_redirection.size()))
10684 index = type->member_type_index_redirection[index];
10685
10686 if (index >= type->member_types.size())
10687 SPIRV_CROSS_THROW("Member index is out of bounds!");
10688
10689 if (hide_first_subscript)
10690 {
10691 // First "._m0" subscript has been hidden, subsequent fields must be emitted even for structured buffers
10692 hide_first_subscript = false;
10693 }
10694 else
10695 {
10696 BuiltIn builtin = BuiltInMax;
10697 if (is_member_builtin(*type, index, &builtin) && access_chain_needs_stage_io_builtin_translation(base))
10698 {
10699 if (access_chain_is_arrayed)
10700 {
10701 expr += ".";
10702 expr += builtin_to_glsl(builtin, type->storage);
10703 }
10704 else
10705 expr = builtin_to_glsl(builtin, type->storage);
10706
10707 if (builtin == BuiltInPosition && get_execution_model() == ExecutionModelMeshEXT)
10708 {
10709 access_meshlet_position_y = true;
10710 }
10711
10712 chain_is_builtin = true;
10713 chained_builtin = builtin;
10714 }
10715 else
10716 {
10717 // If the member has a qualified name, use it as the entire chain
10718 string qual_mbr_name = get_member_qualified_name(type_id, index);
10719 if (!qual_mbr_name.empty())
10720 expr = qual_mbr_name;
10721 else if (flatten_member_reference)
10722 expr += join("_", to_member_name(*type, index));
10723 else
10724 {
10725 // Any pointer de-refences for values are handled in the first access chain.
10726 // For pointer chains, the pointer-ness is resolved through an array access.
10727 // The only time this is not true is when accessing array of SSBO/UBO.
10728 // This case is explicitly handled.
10729 expr += to_member_reference(base, *type, index, ptr_chain || i != 0);
10730 }
10731 }
10732 }
10733
10734 if (has_member_decoration(type->self, index, DecorationInvariant))
10735 is_invariant = true;
10736 if (has_member_decoration(type->self, index, DecorationRelaxedPrecision))
10737 relaxed_precision = true;
10738
10739 is_packed = member_is_packed_physical_type(*type, index);
10740 if (member_is_remapped_physical_type(*type, index))
10741 physical_type = get_extended_member_decoration(type->self, index, SPIRVCrossDecorationPhysicalTypeID);
10742 else
10743 physical_type = 0;
10744
10745 row_major_matrix_needs_conversion = member_is_non_native_row_major_matrix(*type, index);
10746 type = &get<SPIRType>(type->member_types[index]);
10747 }
10748 // Matrix -> Vector
10749 else if (type->columns > 1)
10750 {
10751 // If we have a row-major matrix here, we need to defer any transpose in case this access chain
10752 // is used to store a column. We can resolve it right here and now if we access a scalar directly,
10753 // by flipping indexing order of the matrix.
10754
10755 expr += "[";
10756 if (is_literal)
10757 expr += convert_to_string(index);
10758 else
10759 expr += to_unpacked_expression(index, register_expression_read);
10760 expr += "]";
10761
10762 // If the physical type has an unnatural vecsize,
10763 // we must assume it's a faked struct where the .data member
10764 // is used for the real payload.
10765 if (physical_type)
10766 {
10767 auto &phys = get<SPIRType>(physical_type);
10768 if (phys.vecsize > 4 || phys.columns > 4)
10769 expr += ".data";
10770 }
10771
10772 type_id = type->parent_type;
10773 type = &get<SPIRType>(type_id);
10774 }
10775 // Vector -> Scalar
10776 else if (type->op == OpTypeCooperativeMatrixKHR || type->vecsize > 1)
10777 {
10778 string deferred_index;
10779 if (row_major_matrix_needs_conversion)
10780 {
10781 // Flip indexing order.
10782 auto column_index = expr.find_last_of('[');
10783 if (column_index != string::npos)
10784 {
10785 deferred_index = expr.substr(column_index);
10786
10787 auto end_deferred_index = deferred_index.find_last_of(']');
10788 if (end_deferred_index != string::npos && end_deferred_index + 1 != deferred_index.size())
10789 {
10790 // If we have any data member fixups, it must be transposed so that it refers to this index.
10791 // E.g. [0].data followed by [1] would be shuffled to [1][0].data which is wrong,
10792 // and needs to be [1].data[0] instead.
10793 end_deferred_index++;
10794 deferred_index = deferred_index.substr(end_deferred_index) +
10795 deferred_index.substr(0, end_deferred_index);
10796 }
10797
10798 expr.resize(column_index);
10799 }
10800 }
10801
10802 // Internally, access chain implementation can also be used on composites,
10803 // ignore scalar access workarounds in this case.
10804 StorageClass effective_storage = StorageClassGeneric;
10805 bool ignore_potential_sliced_writes = false;
10806 if ((flags & ACCESS_CHAIN_FORCE_COMPOSITE_BIT) == 0)
10807 {
10808 if (expression_type(base).pointer)
10809 effective_storage = get_expression_effective_storage_class(base);
10810
10811 // Special consideration for control points.
10812 // Control points can only be written by InvocationID, so there is no need
10813 // to consider scalar access chains here.
10814 // Cleans up some cases where it's very painful to determine the accurate storage class
10815 // since blocks can be partially masked ...
10816 auto *var = maybe_get_backing_variable(base);
10817 if (var && var->storage == StorageClassOutput &&
10818 get_execution_model() == ExecutionModelTessellationControl &&
10819 !has_decoration(var->self, DecorationPatch))
10820 {
10821 ignore_potential_sliced_writes = true;
10822 }
10823 }
10824 else
10825 ignore_potential_sliced_writes = true;
10826
10827 if (!row_major_matrix_needs_conversion && !ignore_potential_sliced_writes)
10828 {
10829 // On some backends, we might not be able to safely access individual scalars in a vector.
10830 // To work around this, we might have to cast the access chain reference to something which can,
10831 // like a pointer to scalar, which we can then index into.
10832 prepare_access_chain_for_scalar_access(expr, get<SPIRType>(type->parent_type), effective_storage,
10833 is_packed);
10834 }
10835
10836 if (is_literal)
10837 {
10838 bool out_of_bounds = index >= type->vecsize && type->op != OpTypeCooperativeMatrixKHR;
10839
10840 if (!is_packed && !row_major_matrix_needs_conversion && type->op != OpTypeCooperativeMatrixKHR)
10841 {
10842 expr += ".";
10843 expr += index_to_swizzle(out_of_bounds ? 0 : index);
10844 }
10845 else
10846 {
10847 // For packed vectors, we can only access them as an array, not by swizzle.
10848 expr += join("[", out_of_bounds ? 0 : index, "]");
10849 }
10850 }
10851 else if (ir.ids[index].get_type() == TypeConstant && !is_packed && !row_major_matrix_needs_conversion)
10852 {
10853 auto &c = get<SPIRConstant>(index);
10854 bool out_of_bounds = (c.scalar() >= type->vecsize);
10855
10856 if (c.specialization)
10857 {
10858 // If the index is a spec constant, we cannot turn extract into a swizzle.
10859 expr += join("[", out_of_bounds ? "0" : to_expression(index), "]");
10860 }
10861 else
10862 {
10863 expr += ".";
10864 expr += index_to_swizzle(out_of_bounds ? 0 : c.scalar());
10865 }
10866 }
10867 else
10868 {
10869 expr += "[";
10870 expr += to_unpacked_expression(index, register_expression_read);
10871 expr += "]";
10872 }
10873
10874 if (row_major_matrix_needs_conversion && !ignore_potential_sliced_writes)
10875 {
10876 if (prepare_access_chain_for_scalar_access(expr, get<SPIRType>(type->parent_type), effective_storage,
10877 is_packed))
10878 {
10879 // We're in a pointer context now, so just remove any member dereference.
10880 auto first_index = deferred_index.find_first_of('[');
10881 if (first_index != string::npos && first_index != 0)
10882 deferred_index = deferred_index.substr(first_index);
10883 }
10884 }
10885
10886 if (access_meshlet_position_y)
10887 {
10888 if (is_literal)
10889 {
10890 access_meshlet_position_y = index == 1;
10891 }
10892 else
10893 {
10894 const auto *c = maybe_get<SPIRConstant>(index);
10895 if (c)
10896 access_meshlet_position_y = c->scalar() == 1;
10897 else
10898 {
10899 // We don't know, but we have to assume no.
10900 // Flip Y in mesh shaders is an opt-in horrible hack, so we'll have to assume shaders try to behave.
10901 access_meshlet_position_y = false;
10902 }
10903 }
10904 }
10905
10906 expr += deferred_index;
10907 row_major_matrix_needs_conversion = false;
10908
10909 is_packed = false;
10910 physical_type = 0;
10911 type_id = type->parent_type;
10912 type = &get<SPIRType>(type_id);
10913 }
10914 else if (!backend.allow_truncated_access_chain)
10915 SPIRV_CROSS_THROW("Cannot subdivide a scalar value!");
10916 }
10917
10918 if (pending_array_enclose)
10919 {
10920 SPIRV_CROSS_THROW("Flattening of multidimensional arrays were enabled, "
10921 "but the access chain was terminated in the middle of a multidimensional array. "
10922 "This is not supported.");
10923 }
10924
10925 if (meta)
10926 {
10927 meta->need_transpose = row_major_matrix_needs_conversion;
10928 meta->storage_is_packed = is_packed;
10929 meta->storage_is_invariant = is_invariant;
10930 meta->storage_physical_type = physical_type;
10931 meta->relaxed_precision = relaxed_precision;
10932 meta->access_meshlet_position_y = access_meshlet_position_y;
10933 meta->chain_is_builtin = chain_is_builtin;
10934 meta->builtin = chained_builtin;
10935 }
10936
10937 return expr;
10938 }
10939
10940 bool CompilerGLSL::check_physical_type_cast(std::string &, const SPIRType *, uint32_t)
10941 {
10942 return false;
10943 }
10944
10945 bool CompilerGLSL::prepare_access_chain_for_scalar_access(std::string &, const SPIRType &, spv::StorageClass, bool &)
10946 {
10947 return false;
10948 }
10949
10950 string CompilerGLSL::to_flattened_struct_member(const string &basename, const SPIRType &type, uint32_t index)
10951 {
10952 auto ret = join(basename, "_", to_member_name(type, index));
10953 ParsedIR::sanitize_underscores(ret);
10954 return ret;
10955 }
10956
10957 uint32_t CompilerGLSL::get_physical_type_stride(const SPIRType &) const
10958 {
10959 SPIRV_CROSS_THROW("Invalid to call get_physical_type_stride on a backend without native pointer support.");
10960 }
10961
10962 string CompilerGLSL::access_chain(uint32_t base, const uint32_t *indices, uint32_t count, const SPIRType &target_type,
10963 AccessChainMeta *meta, bool ptr_chain)
10964 {
10965 if (flattened_buffer_blocks.count(base))
10966 {
10967 uint32_t matrix_stride = 0;
10968 uint32_t array_stride = 0;
10969 bool need_transpose = false;
10970 flattened_access_chain_offset(expression_type(base), indices, count, 0, 16, &need_transpose, &matrix_stride,
10971 &array_stride, ptr_chain);
10972
10973 if (meta)
10974 {
10975 meta->need_transpose = target_type.columns > 1 && need_transpose;
10976 meta->storage_is_packed = false;
10977 }
10978
10979 return flattened_access_chain(base, indices, count, target_type, 0, matrix_stride, array_stride,
10980 need_transpose);
10981 }
10982 else if (flattened_structs.count(base) && count > 0)
10983 {
10984 AccessChainFlags flags = ACCESS_CHAIN_CHAIN_ONLY_BIT | ACCESS_CHAIN_SKIP_REGISTER_EXPRESSION_READ_BIT;
10985 if (ptr_chain)
10986 flags |= ACCESS_CHAIN_PTR_CHAIN_BIT;
10987
10988 if (flattened_structs[base])
10989 {
10990 flags |= ACCESS_CHAIN_FLATTEN_ALL_MEMBERS_BIT;
10991 if (meta)
10992 meta->flattened_struct = target_type.basetype == SPIRType::Struct;
10993 }
10994
10995 auto chain = access_chain_internal(base, indices, count, flags, nullptr).substr(1);
10996 if (meta)
10997 {
10998 meta->need_transpose = false;
10999 meta->storage_is_packed = false;
11000 }
11001
11002 auto basename = to_flattened_access_chain_expression(base);
11003 auto ret = join(basename, "_", chain);
11004 ParsedIR::sanitize_underscores(ret);
11005 return ret;
11006 }
11007 else
11008 {
11009 AccessChainFlags flags = ACCESS_CHAIN_SKIP_REGISTER_EXPRESSION_READ_BIT;
11010 if (ptr_chain)
11011 {
11012 flags |= ACCESS_CHAIN_PTR_CHAIN_BIT;
11013 // PtrAccessChain could get complicated.
11014 TypeID type_id = expression_type_id(base);
11015 if (backend.native_pointers && has_decoration(type_id, DecorationArrayStride))
11016 {
11017 // If there is a mismatch we have to go via 64-bit pointer arithmetic :'(
11018 // Using packed hacks only gets us so far, and is not designed to deal with pointer to
11019 // random values. It works for structs though.
11020 auto &pointee_type = get_pointee_type(get<SPIRType>(type_id));
11021 uint32_t physical_stride = get_physical_type_stride(pointee_type);
11022 uint32_t requested_stride = get_decoration(type_id, DecorationArrayStride);
11023 if (physical_stride != requested_stride)
11024 {
11025 flags |= ACCESS_CHAIN_PTR_CHAIN_POINTER_ARITH_BIT;
11026 if (is_vector(pointee_type))
11027 flags |= ACCESS_CHAIN_PTR_CHAIN_CAST_TO_SCALAR_BIT;
11028 }
11029 }
11030 }
11031
11032 return access_chain_internal(base, indices, count, flags, meta);
11033 }
11034 }
11035
11036 string CompilerGLSL::load_flattened_struct(const string &basename, const SPIRType &type)
11037 {
11038 auto expr = type_to_glsl_constructor(type);
11039 expr += '(';
11040
11041 for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
11042 {
11043 if (i)
11044 expr += ", ";
11045
11046 auto &member_type = get<SPIRType>(type.member_types[i]);
11047 if (member_type.basetype == SPIRType::Struct)
11048 expr += load_flattened_struct(to_flattened_struct_member(basename, type, i), member_type);
11049 else
11050 expr += to_flattened_struct_member(basename, type, i);
11051 }
11052 expr += ')';
11053 return expr;
11054 }
11055
11056 std::string CompilerGLSL::to_flattened_access_chain_expression(uint32_t id)
11057 {
11058 // Do not use to_expression as that will unflatten access chains.
11059 string basename;
11060 if (const auto *var = maybe_get<SPIRVariable>(id))
11061 basename = to_name(var->self);
11062 else if (const auto *expr = maybe_get<SPIRExpression>(id))
11063 basename = expr->expression;
11064 else
11065 basename = to_expression(id);
11066
11067 return basename;
11068 }
11069
11070 void CompilerGLSL::store_flattened_struct(const string &basename, uint32_t rhs_id, const SPIRType &type,
11071 const SmallVector<uint32_t> &indices)
11072 {
11073 SmallVector<uint32_t> sub_indices = indices;
11074 sub_indices.push_back(0);
11075
11076 auto *member_type = &type;
11077 for (auto &index : indices)
11078 member_type = &get<SPIRType>(member_type->member_types[index]);
11079
11080 for (uint32_t i = 0; i < uint32_t(member_type->member_types.size()); i++)
11081 {
11082 sub_indices.back() = i;
11083 auto lhs = join(basename, "_", to_member_name(*member_type, i));
11084 ParsedIR::sanitize_underscores(lhs);
11085
11086 if (get<SPIRType>(member_type->member_types[i]).basetype == SPIRType::Struct)
11087 {
11088 store_flattened_struct(lhs, rhs_id, type, sub_indices);
11089 }
11090 else
11091 {
11092 auto rhs = to_expression(rhs_id) + to_multi_member_reference(type, sub_indices);
11093 statement(lhs, " = ", rhs, ";");
11094 }
11095 }
11096 }
11097
11098 void CompilerGLSL::store_flattened_struct(uint32_t lhs_id, uint32_t value)
11099 {
11100 auto &type = expression_type(lhs_id);
11101 auto basename = to_flattened_access_chain_expression(lhs_id);
11102 store_flattened_struct(basename, value, type, {});
11103 }
11104
11105 std::string CompilerGLSL::flattened_access_chain(uint32_t base, const uint32_t *indices, uint32_t count,
11106 const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
11107 uint32_t /* array_stride */, bool need_transpose)
11108 {
11109 if (!target_type.array.empty())
11110 SPIRV_CROSS_THROW("Access chains that result in an array can not be flattened");
11111 else if (target_type.basetype == SPIRType::Struct)
11112 return flattened_access_chain_struct(base, indices, count, target_type, offset);
11113 else if (target_type.columns > 1)
11114 return flattened_access_chain_matrix(base, indices, count, target_type, offset, matrix_stride, need_transpose);
11115 else
11116 return flattened_access_chain_vector(base, indices, count, target_type, offset, matrix_stride, need_transpose);
11117 }
11118
11119 std::string CompilerGLSL::flattened_access_chain_struct(uint32_t base, const uint32_t *indices, uint32_t count,
11120 const SPIRType &target_type, uint32_t offset)
11121 {
11122 std::string expr;
11123
11124 if (backend.can_declare_struct_inline)
11125 {
11126 expr += type_to_glsl_constructor(target_type);
11127 expr += "(";
11128 }
11129 else
11130 expr += "{";
11131
11132 for (uint32_t i = 0; i < uint32_t(target_type.member_types.size()); ++i)
11133 {
11134 if (i != 0)
11135 expr += ", ";
11136
11137 const SPIRType &member_type = get<SPIRType>(target_type.member_types[i]);
11138 uint32_t member_offset = type_struct_member_offset(target_type, i);
11139
11140 // The access chain terminates at the struct, so we need to find matrix strides and row-major information
11141 // ahead of time.
11142 bool need_transpose = false;
11143 bool relaxed = false;
11144 uint32_t matrix_stride = 0;
11145 if (member_type.columns > 1)
11146 {
11147 auto decorations = combined_decoration_for_member(target_type, i);
11148 need_transpose = decorations.get(DecorationRowMajor);
11149 relaxed = decorations.get(DecorationRelaxedPrecision);
11150 matrix_stride = type_struct_member_matrix_stride(target_type, i);
11151 }
11152
11153 auto tmp = flattened_access_chain(base, indices, count, member_type, offset + member_offset, matrix_stride,
11154 0 /* array_stride */, need_transpose);
11155
11156 // Cannot forward transpositions, so resolve them here.
11157 if (need_transpose)
11158 expr += convert_row_major_matrix(tmp, member_type, 0, false, relaxed);
11159 else
11160 expr += tmp;
11161 }
11162
11163 expr += backend.can_declare_struct_inline ? ")" : "}";
11164
11165 return expr;
11166 }
11167
11168 std::string CompilerGLSL::flattened_access_chain_matrix(uint32_t base, const uint32_t *indices, uint32_t count,
11169 const SPIRType &target_type, uint32_t offset,
11170 uint32_t matrix_stride, bool need_transpose)
11171 {
11172 assert(matrix_stride);
11173 SPIRType tmp_type = target_type;
11174 if (need_transpose)
11175 swap(tmp_type.vecsize, tmp_type.columns);
11176
11177 std::string expr;
11178
11179 expr += type_to_glsl_constructor(tmp_type);
11180 expr += "(";
11181
11182 for (uint32_t i = 0; i < tmp_type.columns; i++)
11183 {
11184 if (i != 0)
11185 expr += ", ";
11186
11187 expr += flattened_access_chain_vector(base, indices, count, tmp_type, offset + i * matrix_stride, matrix_stride,
11188 /* need_transpose= */ false);
11189 }
11190
11191 expr += ")";
11192
11193 return expr;
11194 }
11195
11196 std::string CompilerGLSL::flattened_access_chain_vector(uint32_t base, const uint32_t *indices, uint32_t count,
11197 const SPIRType &target_type, uint32_t offset,
11198 uint32_t matrix_stride, bool need_transpose)
11199 {
11200 auto result = flattened_access_chain_offset(expression_type(base), indices, count, offset, 16);
11201
11202 auto buffer_name = to_name(expression_type(base).self);
11203
11204 if (need_transpose)
11205 {
11206 std::string expr;
11207
11208 if (target_type.vecsize > 1)
11209 {
11210 expr += type_to_glsl_constructor(target_type);
11211 expr += "(";
11212 }
11213
11214 for (uint32_t i = 0; i < target_type.vecsize; ++i)
11215 {
11216 if (i != 0)
11217 expr += ", ";
11218
11219 uint32_t component_offset = result.second + i * matrix_stride;
11220
11221 assert(component_offset % (target_type.width / 8) == 0);
11222 uint32_t index = component_offset / (target_type.width / 8);
11223
11224 expr += buffer_name;
11225 expr += "[";
11226 expr += result.first; // this is a series of N1 * k1 + N2 * k2 + ... that is either empty or ends with a +
11227 expr += convert_to_string(index / 4);
11228 expr += "]";
11229
11230 expr += vector_swizzle(1, index % 4);
11231 }
11232
11233 if (target_type.vecsize > 1)
11234 {
11235 expr += ")";
11236 }
11237
11238 return expr;
11239 }
11240 else
11241 {
11242 assert(result.second % (target_type.width / 8) == 0);
11243 uint32_t index = result.second / (target_type.width / 8);
11244
11245 std::string expr;
11246
11247 expr += buffer_name;
11248 expr += "[";
11249 expr += result.first; // this is a series of N1 * k1 + N2 * k2 + ... that is either empty or ends with a +
11250 expr += convert_to_string(index / 4);
11251 expr += "]";
11252
11253 expr += vector_swizzle(target_type.vecsize, index % 4);
11254
11255 return expr;
11256 }
11257 }
11258
11259 std::pair<std::string, uint32_t> CompilerGLSL::flattened_access_chain_offset(
11260 const SPIRType &basetype, const uint32_t *indices, uint32_t count, uint32_t offset, uint32_t word_stride,
11261 bool *need_transpose, uint32_t *out_matrix_stride, uint32_t *out_array_stride, bool ptr_chain)
11262 {
11263 // Start traversing type hierarchy at the proper non-pointer types.
11264 const auto *type = &get_pointee_type(basetype);
11265
11266 std::string expr;
11267
11268 // Inherit matrix information in case we are access chaining a vector which might have come from a row major layout.
11269 bool row_major_matrix_needs_conversion = need_transpose ? *need_transpose : false;
11270 uint32_t matrix_stride = out_matrix_stride ? *out_matrix_stride : 0;
11271 uint32_t array_stride = out_array_stride ? *out_array_stride : 0;
11272
11273 for (uint32_t i = 0; i < count; i++)
11274 {
11275 uint32_t index = indices[i];
11276
11277 // Pointers
11278 if (ptr_chain && i == 0)
11279 {
11280 // Here, the pointer type will be decorated with an array stride.
11281 array_stride = get_decoration(basetype.self, DecorationArrayStride);
11282 if (!array_stride)
11283 SPIRV_CROSS_THROW("SPIR-V does not define ArrayStride for buffer block.");
11284
11285 auto *constant = maybe_get<SPIRConstant>(index);
11286 if (constant)
11287 {
11288 // Constant array access.
11289 offset += constant->scalar() * array_stride;
11290 }
11291 else
11292 {
11293 // Dynamic array access.
11294 if (array_stride % word_stride)
11295 {
11296 SPIRV_CROSS_THROW("Array stride for dynamic indexing must be divisible by the size "
11297 "of a 4-component vector. "
11298 "Likely culprit here is a float or vec2 array inside a push "
11299 "constant block which is std430. "
11300 "This cannot be flattened. Try using std140 layout instead.");
11301 }
11302
11303 expr += to_enclosed_expression(index);
11304 expr += " * ";
11305 expr += convert_to_string(array_stride / word_stride);
11306 expr += " + ";
11307 }
11308 }
11309 // Arrays
11310 else if (!type->array.empty())
11311 {
11312 auto *constant = maybe_get<SPIRConstant>(index);
11313 if (constant)
11314 {
11315 // Constant array access.
11316 offset += constant->scalar() * array_stride;
11317 }
11318 else
11319 {
11320 // Dynamic array access.
11321 if (array_stride % word_stride)
11322 {
11323 SPIRV_CROSS_THROW("Array stride for dynamic indexing must be divisible by the size "
11324 "of a 4-component vector. "
11325 "Likely culprit here is a float or vec2 array inside a push "
11326 "constant block which is std430. "
11327 "This cannot be flattened. Try using std140 layout instead.");
11328 }
11329
11330 expr += to_enclosed_expression(index, false);
11331 expr += " * ";
11332 expr += convert_to_string(array_stride / word_stride);
11333 expr += " + ";
11334 }
11335
11336 uint32_t parent_type = type->parent_type;
11337 type = &get<SPIRType>(parent_type);
11338
11339 if (!type->array.empty())
11340 array_stride = get_decoration(parent_type, DecorationArrayStride);
11341 }
11342 // For structs, the index refers to a constant, which indexes into the members.
11343 // We also check if this member is a builtin, since we then replace the entire expression with the builtin one.
11344 else if (type->basetype == SPIRType::Struct)
11345 {
11346 index = evaluate_constant_u32(index);
11347
11348 if (index >= type->member_types.size())
11349 SPIRV_CROSS_THROW("Member index is out of bounds!");
11350
11351 offset += type_struct_member_offset(*type, index);
11352
11353 auto &struct_type = *type;
11354 type = &get<SPIRType>(type->member_types[index]);
11355
11356 if (type->columns > 1)
11357 {
11358 matrix_stride = type_struct_member_matrix_stride(struct_type, index);
11359 row_major_matrix_needs_conversion =
11360 combined_decoration_for_member(struct_type, index).get(DecorationRowMajor);
11361 }
11362 else
11363 row_major_matrix_needs_conversion = false;
11364
11365 if (!type->array.empty())
11366 array_stride = type_struct_member_array_stride(struct_type, index);
11367 }
11368 // Matrix -> Vector
11369 else if (type->columns > 1)
11370 {
11371 auto *constant = maybe_get<SPIRConstant>(index);
11372 if (constant)
11373 {
11374 index = evaluate_constant_u32(index);
11375 offset += index * (row_major_matrix_needs_conversion ? (type->width / 8) : matrix_stride);
11376 }
11377 else
11378 {
11379 uint32_t indexing_stride = row_major_matrix_needs_conversion ? (type->width / 8) : matrix_stride;
11380 // Dynamic array access.
11381 if (indexing_stride % word_stride)
11382 {
11383 SPIRV_CROSS_THROW("Matrix stride for dynamic indexing must be divisible by the size of a "
11384 "4-component vector. "
11385 "Likely culprit here is a row-major matrix being accessed dynamically. "
11386 "This cannot be flattened. Try using std140 layout instead.");
11387 }
11388
11389 expr += to_enclosed_expression(index, false);
11390 expr += " * ";
11391 expr += convert_to_string(indexing_stride / word_stride);
11392 expr += " + ";
11393 }
11394
11395 type = &get<SPIRType>(type->parent_type);
11396 }
11397 // Vector -> Scalar
11398 else if (type->vecsize > 1)
11399 {
11400 auto *constant = maybe_get<SPIRConstant>(index);
11401 if (constant)
11402 {
11403 index = evaluate_constant_u32(index);
11404 offset += index * (row_major_matrix_needs_conversion ? matrix_stride : (type->width / 8));
11405 }
11406 else
11407 {
11408 uint32_t indexing_stride = row_major_matrix_needs_conversion ? matrix_stride : (type->width / 8);
11409
11410 // Dynamic array access.
11411 if (indexing_stride % word_stride)
11412 {
11413 SPIRV_CROSS_THROW("Stride for dynamic vector indexing must be divisible by the "
11414 "size of a 4-component vector. "
11415 "This cannot be flattened in legacy targets.");
11416 }
11417
11418 expr += to_enclosed_expression(index, false);
11419 expr += " * ";
11420 expr += convert_to_string(indexing_stride / word_stride);
11421 expr += " + ";
11422 }
11423
11424 type = &get<SPIRType>(type->parent_type);
11425 }
11426 else
11427 SPIRV_CROSS_THROW("Cannot subdivide a scalar value!");
11428 }
11429
11430 if (need_transpose)
11431 *need_transpose = row_major_matrix_needs_conversion;
11432 if (out_matrix_stride)
11433 *out_matrix_stride = matrix_stride;
11434 if (out_array_stride)
11435 *out_array_stride = array_stride;
11436
11437 return std::make_pair(expr, offset);
11438 }
11439
11440 bool CompilerGLSL::should_dereference(uint32_t id)
11441 {
11442 const auto &type = expression_type(id);
11443 // Non-pointer expressions don't need to be dereferenced.
11444 if (!is_pointer(type))
11445 return false;
11446
11447 // Handles shouldn't be dereferenced either.
11448 if (!expression_is_lvalue(id))
11449 return false;
11450
11451 // If id is a variable but not a phi variable, we should not dereference it.
11452 // BDA passed around as parameters are always pointers.
11453 if (auto *var = maybe_get<SPIRVariable>(id))
11454 return (var->parameter && is_physical_pointer(type)) || var->phi_variable;
11455
11456 if (auto *expr = maybe_get<SPIRExpression>(id))
11457 {
11458 // If id is an access chain, we should not dereference it.
11459 if (expr->access_chain)
11460 return false;
11461
11462 // If id is a forwarded copy of a variable pointer, we should not dereference it.
11463 SPIRVariable *var = nullptr;
11464 while (expr->loaded_from && expression_is_forwarded(expr->self))
11465 {
11466 auto &src_type = expression_type(expr->loaded_from);
11467 // To be a copy, the pointer and its source expression must be the
11468 // same type. Can't check type.self, because for some reason that's
11469 // usually the base type with pointers stripped off. This check is
11470 // complex enough that I've hoisted it out of the while condition.
11471 if (src_type.pointer != type.pointer || src_type.pointer_depth != type.pointer_depth ||
11472 src_type.parent_type != type.parent_type)
11473 break;
11474 if ((var = maybe_get<SPIRVariable>(expr->loaded_from)))
11475 break;
11476 if (!(expr = maybe_get<SPIRExpression>(expr->loaded_from)))
11477 break;
11478 }
11479
11480 return !var || var->phi_variable;
11481 }
11482
11483 // Otherwise, we should dereference this pointer expression.
11484 return true;
11485 }
11486
11487 bool CompilerGLSL::should_dereference_caller_param(uint32_t id)
11488 {
11489 const auto &type = expression_type(id);
11490 // BDA is always passed around as pointers.
11491 if (is_physical_pointer(type))
11492 return false;
11493
11494 return should_dereference(id);
11495 }
11496
11497 bool CompilerGLSL::should_forward(uint32_t id) const
11498 {
11499 // If id is a variable we will try to forward it regardless of force_temporary check below
11500 // This is important because otherwise we'll get local sampler copies (highp sampler2D foo = bar) that are invalid in OpenGL GLSL
11501
11502 auto *var = maybe_get<SPIRVariable>(id);
11503 if (var)
11504 {
11505 // Never forward volatile builtin variables, e.g. SPIR-V 1.6 HelperInvocation.
11506 return !(has_decoration(id, DecorationBuiltIn) && has_decoration(id, DecorationVolatile));
11507 }
11508
11509 // For debugging emit temporary variables for all expressions
11510 if (options.force_temporary)
11511 return false;
11512
11513 // If an expression carries enough dependencies we need to stop forwarding at some point,
11514 // or we explode compilers. There are usually limits to how much we can nest expressions.
11515 auto *expr = maybe_get<SPIRExpression>(id);
11516 const uint32_t max_expression_dependencies = 64;
11517 if (expr && expr->expression_dependencies.size() >= max_expression_dependencies)
11518 return false;
11519
11520 if (expr && expr->loaded_from
11521 && has_decoration(expr->loaded_from, DecorationBuiltIn)
11522 && has_decoration(expr->loaded_from, DecorationVolatile))
11523 {
11524 // Never forward volatile builtin variables, e.g. SPIR-V 1.6 HelperInvocation.
11525 return false;
11526 }
11527
11528 // Immutable expression can always be forwarded.
11529 if (is_immutable(id))
11530 return true;
11531
11532 return false;
11533 }
11534
11535 bool CompilerGLSL::should_suppress_usage_tracking(uint32_t id) const
11536 {
11537 // Used only by opcodes which don't do any real "work", they just swizzle data in some fashion.
11538 return !expression_is_forwarded(id) || expression_suppresses_usage_tracking(id);
11539 }
11540
11541 void CompilerGLSL::track_expression_read(uint32_t id)
11542 {
11543 switch (ir.ids[id].get_type())
11544 {
11545 case TypeExpression:
11546 {
11547 auto &e = get<SPIRExpression>(id);
11548 for (auto implied_read : e.implied_read_expressions)
11549 track_expression_read(implied_read);
11550 break;
11551 }
11552
11553 case TypeAccessChain:
11554 {
11555 auto &e = get<SPIRAccessChain>(id);
11556 for (auto implied_read : e.implied_read_expressions)
11557 track_expression_read(implied_read);
11558 break;
11559 }
11560
11561 default:
11562 break;
11563 }
11564
11565 // If we try to read a forwarded temporary more than once we will stamp out possibly complex code twice.
11566 // In this case, it's better to just bind the complex expression to the temporary and read that temporary twice.
11567 if (expression_is_forwarded(id) && !expression_suppresses_usage_tracking(id))
11568 {
11569 auto &v = expression_usage_counts[id];
11570 v++;
11571
11572 // If we create an expression outside a loop,
11573 // but access it inside a loop, we're implicitly reading it multiple times.
11574 // If the expression in question is expensive, we should hoist it out to avoid relying on loop-invariant code motion
11575 // working inside the backend compiler.
11576 if (expression_read_implies_multiple_reads(id))
11577 v++;
11578
11579 if (v >= 2)
11580 {
11581 //if (v == 2)
11582 // fprintf(stderr, "ID %u was forced to temporary due to more than 1 expression use!\n", id);
11583
11584 // Force a recompile after this pass to avoid forwarding this variable.
11585 force_temporary_and_recompile(id);
11586 }
11587 }
11588 }
11589
11590 bool CompilerGLSL::args_will_forward(uint32_t id, const uint32_t *args, uint32_t num_args, bool pure)
11591 {
11592 if (forced_temporaries.find(id) != end(forced_temporaries))
11593 return false;
11594
11595 for (uint32_t i = 0; i < num_args; i++)
11596 if (!should_forward(args[i]))
11597 return false;
11598
11599 // We need to forward globals as well.
11600 if (!pure)
11601 {
11602 for (auto global : global_variables)
11603 if (!should_forward(global))
11604 return false;
11605 for (auto aliased : aliased_variables)
11606 if (!should_forward(aliased))
11607 return false;
11608 }
11609
11610 return true;
11611 }
11612
11613 void CompilerGLSL::register_impure_function_call()
11614 {
11615 // Impure functions can modify globals and aliased variables, so invalidate them as well.
11616 for (auto global : global_variables)
11617 flush_dependees(get<SPIRVariable>(global));
11618 for (auto aliased : aliased_variables)
11619 flush_dependees(get<SPIRVariable>(aliased));
11620 }
11621
11622 void CompilerGLSL::register_call_out_argument(uint32_t id)
11623 {
11624 register_write(id);
11625
11626 auto *var = maybe_get<SPIRVariable>(id);
11627 if (var)
11628 flush_variable_declaration(var->self);
11629 }
11630
11631 string CompilerGLSL::variable_decl_function_local(SPIRVariable &var)
11632 {
11633 // These variables are always function local,
11634 // so make sure we emit the variable without storage qualifiers.
11635 // Some backends will inject custom variables locally in a function
11636 // with a storage qualifier which is not function-local.
11637 auto old_storage = var.storage;
11638 var.storage = StorageClassFunction;
11639 auto expr = variable_decl(var);
11640 var.storage = old_storage;
11641 return expr;
11642 }
11643
11644 void CompilerGLSL::emit_variable_temporary_copies(const SPIRVariable &var)
11645 {
11646 // Ensure that we declare phi-variable copies even if the original declaration isn't deferred
11647 if (var.allocate_temporary_copy && !flushed_phi_variables.count(var.self))
11648 {
11649 auto &type = get<SPIRType>(var.basetype);
11650 auto &flags = get_decoration_bitset(var.self);
11651 statement(flags_to_qualifiers_glsl(type, flags), variable_decl(type, join("_", var.self, "_copy")), ";");
11652 flushed_phi_variables.insert(var.self);
11653 }
11654 }
11655
11656 void CompilerGLSL::flush_variable_declaration(uint32_t id)
11657 {
11658 // Ensure that we declare phi-variable copies even if the original declaration isn't deferred
11659 auto *var = maybe_get<SPIRVariable>(id);
11660 if (var && var->deferred_declaration)
11661 {
11662 string initializer;
11663 if (options.force_zero_initialized_variables &&
11664 (var->storage == StorageClassFunction || var->storage == StorageClassGeneric ||
11665 var->storage == StorageClassPrivate) &&
11666 !var->initializer && type_can_zero_initialize(get_variable_data_type(*var)))
11667 {
11668 initializer = join(" = ", to_zero_initialized_expression(get_variable_data_type_id(*var)));
11669 }
11670
11671 statement(variable_decl_function_local(*var), initializer, ";");
11672 var->deferred_declaration = false;
11673 }
11674 if (var)
11675 {
11676 emit_variable_temporary_copies(*var);
11677 }
11678 }
11679
11680 bool CompilerGLSL::remove_duplicate_swizzle(string &op)
11681 {
11682 auto pos = op.find_last_of('.');
11683 if (pos == string::npos || pos == 0)
11684 return false;
11685
11686 string final_swiz = op.substr(pos + 1, string::npos);
11687
11688 if (backend.swizzle_is_function)
11689 {
11690 if (final_swiz.size() < 2)
11691 return false;
11692
11693 if (final_swiz.substr(final_swiz.size() - 2, string::npos) == "()")
11694 final_swiz.erase(final_swiz.size() - 2, string::npos);
11695 else
11696 return false;
11697 }
11698
11699 // Check if final swizzle is of form .x, .xy, .xyz, .xyzw or similar.
11700 // If so, and previous swizzle is of same length,
11701 // we can drop the final swizzle altogether.
11702 for (uint32_t i = 0; i < final_swiz.size(); i++)
11703 {
11704 static const char expected[] = { 'x', 'y', 'z', 'w' };
11705 if (i >= 4 || final_swiz[i] != expected[i])
11706 return false;
11707 }
11708
11709 auto prevpos = op.find_last_of('.', pos - 1);
11710 if (prevpos == string::npos)
11711 return false;
11712
11713 prevpos++;
11714
11715 // Make sure there are only swizzles here ...
11716 for (auto i = prevpos; i < pos; i++)
11717 {
11718 if (op[i] < 'w' || op[i] > 'z')
11719 {
11720 // If swizzles are foo.xyz() like in C++ backend for example, check for that.
11721 if (backend.swizzle_is_function && i + 2 == pos && op[i] == '(' && op[i + 1] == ')')
11722 break;
11723 return false;
11724 }
11725 }
11726
11727 // If original swizzle is large enough, just carve out the components we need.
11728 // E.g. foobar.wyx.xy will turn into foobar.wy.
11729 if (pos - prevpos >= final_swiz.size())
11730 {
11731 op.erase(prevpos + final_swiz.size(), string::npos);
11732
11733 // Add back the function call ...
11734 if (backend.swizzle_is_function)
11735 op += "()";
11736 }
11737 return true;
11738 }
11739
11740 // Optimizes away vector swizzles where we have something like
11741 // vec3 foo;
11742 // foo.xyz <-- swizzle expression does nothing.
11743 // This is a very common pattern after OpCompositeCombine.
11744 bool CompilerGLSL::remove_unity_swizzle(uint32_t base, string &op)
11745 {
11746 auto pos = op.find_last_of('.');
11747 if (pos == string::npos || pos == 0)
11748 return false;
11749
11750 string final_swiz = op.substr(pos + 1, string::npos);
11751
11752 if (backend.swizzle_is_function)
11753 {
11754 if (final_swiz.size() < 2)
11755 return false;
11756
11757 if (final_swiz.substr(final_swiz.size() - 2, string::npos) == "()")
11758 final_swiz.erase(final_swiz.size() - 2, string::npos);
11759 else
11760 return false;
11761 }
11762
11763 // Check if final swizzle is of form .x, .xy, .xyz, .xyzw or similar.
11764 // If so, and previous swizzle is of same length,
11765 // we can drop the final swizzle altogether.
11766 for (uint32_t i = 0; i < final_swiz.size(); i++)
11767 {
11768 static const char expected[] = { 'x', 'y', 'z', 'w' };
11769 if (i >= 4 || final_swiz[i] != expected[i])
11770 return false;
11771 }
11772
11773 auto &type = expression_type(base);
11774
11775 // Sanity checking ...
11776 assert(type.columns == 1 && type.array.empty());
11777
11778 if (type.vecsize == final_swiz.size())
11779 op.erase(pos, string::npos);
11780 return true;
11781 }
11782
11783 string CompilerGLSL::build_composite_combiner(uint32_t return_type, const uint32_t *elems, uint32_t length)
11784 {
11785 ID base = 0;
11786 string op;
11787 string subop;
11788
11789 // Can only merge swizzles for vectors.
11790 auto &type = get<SPIRType>(return_type);
11791 bool can_apply_swizzle_opt = type.basetype != SPIRType::Struct && type.array.empty() && type.columns == 1 &&
11792 type.op != spv::OpTypeCooperativeMatrixKHR;
11793 bool swizzle_optimization = false;
11794
11795 for (uint32_t i = 0; i < length; i++)
11796 {
11797 auto *e = maybe_get<SPIRExpression>(elems[i]);
11798
11799 // If we're merging another scalar which belongs to the same base
11800 // object, just merge the swizzles to avoid triggering more than 1 expression read as much as possible!
11801 if (can_apply_swizzle_opt && e && e->base_expression && e->base_expression == base)
11802 {
11803 // Only supposed to be used for vector swizzle -> scalar.
11804 assert(!e->expression.empty() && e->expression.front() == '.');
11805 subop += e->expression.substr(1, string::npos);
11806 swizzle_optimization = true;
11807 }
11808 else
11809 {
11810 // We'll likely end up with duplicated swizzles, e.g.
11811 // foobar.xyz.xyz from patterns like
11812 // OpVectorShuffle
11813 // OpCompositeExtract x 3
11814 // OpCompositeConstruct 3x + other scalar.
11815 // Just modify op in-place.
11816 if (swizzle_optimization)
11817 {
11818 if (backend.swizzle_is_function)
11819 subop += "()";
11820
11821 // Don't attempt to remove unity swizzling if we managed to remove duplicate swizzles.
11822 // The base "foo" might be vec4, while foo.xyz is vec3 (OpVectorShuffle) and looks like a vec3 due to the .xyz tacked on.
11823 // We only want to remove the swizzles if we're certain that the resulting base will be the same vecsize.
11824 // Essentially, we can only remove one set of swizzles, since that's what we have control over ...
11825 // Case 1:
11826 // foo.yxz.xyz: Duplicate swizzle kicks in, giving foo.yxz, we are done.
11827 // foo.yxz was the result of OpVectorShuffle and we don't know the type of foo.
11828 // Case 2:
11829 // foo.xyz: Duplicate swizzle won't kick in.
11830 // If foo is vec3, we can remove xyz, giving just foo.
11831 if (!remove_duplicate_swizzle(subop))
11832 remove_unity_swizzle(base, subop);
11833
11834 // Strips away redundant parens if we created them during component extraction.
11835 strip_enclosed_expression(subop);
11836 swizzle_optimization = false;
11837 op += subop;
11838 }
11839 else
11840 op += subop;
11841
11842 if (i)
11843 op += ", ";
11844
11845 bool uses_buffer_offset =
11846 type.basetype == SPIRType::Struct && has_member_decoration(type.self, i, DecorationOffset);
11847 subop = to_composite_constructor_expression(type, elems[i], uses_buffer_offset);
11848 }
11849
11850 base = e ? e->base_expression : ID(0);
11851 }
11852
11853 if (swizzle_optimization)
11854 {
11855 if (backend.swizzle_is_function)
11856 subop += "()";
11857
11858 if (!remove_duplicate_swizzle(subop))
11859 remove_unity_swizzle(base, subop);
11860 // Strips away redundant parens if we created them during component extraction.
11861 strip_enclosed_expression(subop);
11862 }
11863
11864 op += subop;
11865 return op;
11866 }
11867
11868 bool CompilerGLSL::skip_argument(uint32_t id) const
11869 {
11870 if (!combined_image_samplers.empty() || !options.vulkan_semantics)
11871 {
11872 auto &type = expression_type(id);
11873 if (type.basetype == SPIRType::Sampler || (type.basetype == SPIRType::Image && type.image.sampled == 1))
11874 return true;
11875 }
11876 return false;
11877 }
11878
11879 bool CompilerGLSL::optimize_read_modify_write(const SPIRType &type, const string &lhs, const string &rhs)
11880 {
11881 // Do this with strings because we have a very clear pattern we can check for and it avoids
11882 // adding lots of special cases to the code emission.
11883 if (rhs.size() < lhs.size() + 3)
11884 return false;
11885
11886 // Do not optimize matrices. They are a bit awkward to reason about in general
11887 // (in which order does operation happen?), and it does not work on MSL anyways.
11888 if (type.vecsize > 1 && type.columns > 1)
11889 return false;
11890
11891 auto index = rhs.find(lhs);
11892 if (index != 0)
11893 return false;
11894
11895 // TODO: Shift operators, but it's not important for now.
11896 auto op = rhs.find_first_of("+-/*%|&^", lhs.size() + 1);
11897 if (op != lhs.size() + 1)
11898 return false;
11899
11900 // Check that the op is followed by space. This excludes && and ||.
11901 if (rhs[op + 1] != ' ')
11902 return false;
11903
11904 char bop = rhs[op];
11905 auto expr = rhs.substr(lhs.size() + 3);
11906
11907 // Avoids false positives where we get a = a * b + c.
11908 // Normally, these expressions are always enclosed, but unexpected code paths may end up hitting this.
11909 if (needs_enclose_expression(expr))
11910 return false;
11911
11912 // Try to find increments and decrements. Makes it look neater as += 1, -= 1 is fairly rare to see in real code.
11913 // Find some common patterns which are equivalent.
11914 if ((bop == '+' || bop == '-') && (expr == "1" || expr == "uint(1)" || expr == "1u" || expr == "int(1u)"))
11915 statement(lhs, bop, bop, ";");
11916 else
11917 statement(lhs, " ", bop, "= ", expr, ";");
11918 return true;
11919 }
11920
11921 void CompilerGLSL::register_control_dependent_expression(uint32_t expr)
11922 {
11923 if (forwarded_temporaries.find(expr) == end(forwarded_temporaries))
11924 return;
11925
11926 assert(current_emitting_block);
11927 current_emitting_block->invalidate_expressions.push_back(expr);
11928 }
11929
11930 void CompilerGLSL::emit_block_instructions(SPIRBlock &block)
11931 {
11932 current_emitting_block = &block;
11933
11934 if (backend.requires_relaxed_precision_analysis)
11935 {
11936 // If PHI variables are consumed in unexpected precision contexts, copy them here.
11937 for (size_t i = 0, n = block.phi_variables.size(); i < n; i++)
11938 {
11939 auto &phi = block.phi_variables[i];
11940
11941 // Ensure we only copy once. We know a-priori that this array will lay out
11942 // the same function variables together.
11943 if (i && block.phi_variables[i - 1].function_variable == phi.function_variable)
11944 continue;
11945
11946 auto itr = temporary_to_mirror_precision_alias.find(phi.function_variable);
11947 if (itr != temporary_to_mirror_precision_alias.end())
11948 {
11949 // Explicitly, we don't want to inherit RelaxedPrecision state in this CopyObject,
11950 // so it helps to have handle_instruction_precision() on the outside of emit_instruction().
11951 EmbeddedInstruction inst;
11952 inst.op = OpCopyObject;
11953 inst.length = 3;
11954 inst.ops.push_back(expression_type_id(itr->first));
11955 inst.ops.push_back(itr->second);
11956 inst.ops.push_back(itr->first);
11957 emit_instruction(inst);
11958 }
11959 }
11960 }
11961
11962 for (auto &op : block.ops)
11963 {
11964 auto temporary_copy = handle_instruction_precision(op);
11965 emit_instruction(op);
11966 if (temporary_copy.dst_id)
11967 {
11968 // Explicitly, we don't want to inherit RelaxedPrecision state in this CopyObject,
11969 // so it helps to have handle_instruction_precision() on the outside of emit_instruction().
11970 EmbeddedInstruction inst;
11971 inst.op = OpCopyObject;
11972 inst.length = 3;
11973 inst.ops.push_back(expression_type_id(temporary_copy.src_id));
11974 inst.ops.push_back(temporary_copy.dst_id);
11975 inst.ops.push_back(temporary_copy.src_id);
11976
11977 // Never attempt to hoist mirrored temporaries.
11978 // They are hoisted in lock-step with their parents.
11979 block_temporary_hoisting = true;
11980 emit_instruction(inst);
11981 block_temporary_hoisting = false;
11982 }
11983 }
11984
11985 current_emitting_block = nullptr;
11986 }
11987
11988 void CompilerGLSL::disallow_forwarding_in_expression_chain(const SPIRExpression &expr)
11989 {
11990 // Allow trivially forwarded expressions like OpLoad or trivial shuffles,
11991 // these will be marked as having suppressed usage tracking.
11992 // Our only concern is to make sure arithmetic operations are done in similar ways.
11993 if (forced_invariant_temporaries.count(expr.self) == 0)
11994 {
11995 if (!expression_suppresses_usage_tracking(expr.self))
11996 force_temporary_and_recompile(expr.self);
11997 forced_invariant_temporaries.insert(expr.self);
11998
11999 for (auto &dependent : expr.invariance_dependencies)
12000 disallow_forwarding_in_expression_chain(get<SPIRExpression>(dependent));
12001 }
12002 }
12003
12004 void CompilerGLSL::handle_store_to_invariant_variable(uint32_t store_id, uint32_t value_id)
12005 {
12006 // Variables or access chains marked invariant are complicated. We will need to make sure the code-gen leading up to
12007 // this variable is consistent. The failure case for SPIRV-Cross is when an expression is forced to a temporary
12008 // in one translation unit, but not another, e.g. due to multiple use of an expression.
12009 // This causes variance despite the output variable being marked invariant, so the solution here is to force all dependent
12010 // expressions to be temporaries.
12011 // It is uncertain if this is enough to support invariant in all possible cases, but it should be good enough
12012 // for all reasonable uses of invariant.
12013 if (!has_decoration(store_id, DecorationInvariant))
12014 return;
12015
12016 auto *expr = maybe_get<SPIRExpression>(value_id);
12017 if (!expr)
12018 return;
12019
12020 disallow_forwarding_in_expression_chain(*expr);
12021 }
12022
12023 void CompilerGLSL::emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression)
12024 {
12025 auto rhs = to_pointer_expression(rhs_expression);
12026
12027 // Statements to OpStore may be empty if it is a struct with zero members. Just forward the store to /dev/null.
12028 if (!rhs.empty())
12029 {
12030 handle_store_to_invariant_variable(lhs_expression, rhs_expression);
12031
12032 if (!unroll_array_to_complex_store(lhs_expression, rhs_expression))
12033 {
12034 auto lhs = to_dereferenced_expression(lhs_expression);
12035 if (has_decoration(lhs_expression, DecorationNonUniform))
12036 convert_non_uniform_expression(lhs, lhs_expression);
12037
12038 // We might need to cast in order to store to a builtin.
12039 cast_to_variable_store(lhs_expression, rhs, expression_type(rhs_expression));
12040
12041 // Tries to optimize assignments like "<lhs> = <lhs> op expr".
12042 // While this is purely cosmetic, this is important for legacy ESSL where loop
12043 // variable increments must be in either i++ or i += const-expr.
12044 // Without this, we end up with i = i + 1, which is correct GLSL, but not correct GLES 2.0.
12045 if (!optimize_read_modify_write(expression_type(rhs_expression), lhs, rhs))
12046 statement(lhs, " = ", rhs, ";");
12047 }
12048 register_write(lhs_expression);
12049 }
12050 }
12051
12052 uint32_t CompilerGLSL::get_integer_width_for_instruction(const Instruction &instr) const
12053 {
12054 if (instr.length < 3)
12055 return 32;
12056
12057 auto *ops = stream(instr);
12058
12059 switch (instr.op)
12060 {
12061 case OpSConvert:
12062 case OpConvertSToF:
12063 case OpUConvert:
12064 case OpConvertUToF:
12065 case OpIEqual:
12066 case OpINotEqual:
12067 case OpSLessThan:
12068 case OpSLessThanEqual:
12069 case OpSGreaterThan:
12070 case OpSGreaterThanEqual:
12071 case OpULessThan:
12072 case OpULessThanEqual:
12073 case OpUGreaterThan:
12074 case OpUGreaterThanEqual:
12075 return expression_type(ops[2]).width;
12076
12077 case OpSMulExtended:
12078 case OpUMulExtended:
12079 return get<SPIRType>(get<SPIRType>(ops[0]).member_types[0]).width;
12080
12081 default:
12082 {
12083 // We can look at result type which is more robust.
12084 auto *type = maybe_get<SPIRType>(ops[0]);
12085 if (type && type_is_integral(*type))
12086 return type->width;
12087 else
12088 return 32;
12089 }
12090 }
12091 }
12092
12093 uint32_t CompilerGLSL::get_integer_width_for_glsl_instruction(GLSLstd450 op, const uint32_t *ops, uint32_t length) const
12094 {
12095 if (length < 1)
12096 return 32;
12097
12098 switch (op)
12099 {
12100 case GLSLstd450SAbs:
12101 case GLSLstd450SSign:
12102 case GLSLstd450UMin:
12103 case GLSLstd450SMin:
12104 case GLSLstd450UMax:
12105 case GLSLstd450SMax:
12106 case GLSLstd450UClamp:
12107 case GLSLstd450SClamp:
12108 case GLSLstd450FindSMsb:
12109 case GLSLstd450FindUMsb:
12110 return expression_type(ops[0]).width;
12111
12112 default:
12113 {
12114 // We don't need to care about other opcodes, just return 32.
12115 return 32;
12116 }
12117 }
12118 }
12119
12120 void CompilerGLSL::forward_relaxed_precision(uint32_t dst_id, const uint32_t *args, uint32_t length)
12121 {
12122 // Only GLSL supports RelaxedPrecision directly.
12123 // We cannot implement this in HLSL or MSL because it is tied to the type system.
12124 // In SPIR-V, everything must masquerade as 32-bit.
12125 if (!backend.requires_relaxed_precision_analysis)
12126 return;
12127
12128 auto input_precision = analyze_expression_precision(args, length);
12129
12130 // For expressions which are loaded or directly forwarded, we inherit mediump implicitly.
12131 // For dst_id to be analyzed properly, it must inherit any relaxed precision decoration from src_id.
12132 if (input_precision == Options::Mediump)
12133 set_decoration(dst_id, DecorationRelaxedPrecision);
12134 }
12135
12136 CompilerGLSL::Options::Precision CompilerGLSL::analyze_expression_precision(const uint32_t *args, uint32_t length) const
12137 {
12138 // Now, analyze the precision at which the arguments would run.
12139 // GLSL rules are such that the precision used to evaluate an expression is equal to the highest precision
12140 // for the inputs. Constants do not have inherent precision and do not contribute to this decision.
12141 // If all inputs are constants, they inherit precision from outer expressions, including an l-value.
12142 // In this case, we'll have to force a temporary for dst_id so that we can bind the constant expression with
12143 // correct precision.
12144 bool expression_has_highp = false;
12145 bool expression_has_mediump = false;
12146
12147 for (uint32_t i = 0; i < length; i++)
12148 {
12149 uint32_t arg = args[i];
12150
12151 auto handle_type = ir.ids[arg].get_type();
12152 if (handle_type == TypeConstant || handle_type == TypeConstantOp || handle_type == TypeUndef)
12153 continue;
12154
12155 if (has_decoration(arg, DecorationRelaxedPrecision))
12156 expression_has_mediump = true;
12157 else
12158 expression_has_highp = true;
12159 }
12160
12161 if (expression_has_highp)
12162 return Options::Highp;
12163 else if (expression_has_mediump)
12164 return Options::Mediump;
12165 else
12166 return Options::DontCare;
12167 }
12168
12169 void CompilerGLSL::analyze_precision_requirements(uint32_t type_id, uint32_t dst_id, uint32_t *args, uint32_t length)
12170 {
12171 if (!backend.requires_relaxed_precision_analysis)
12172 return;
12173
12174 auto &type = get<SPIRType>(type_id);
12175
12176 // RelaxedPrecision only applies to 32-bit values.
12177 if (type.basetype != SPIRType::Float && type.basetype != SPIRType::Int && type.basetype != SPIRType::UInt)
12178 return;
12179
12180 bool operation_is_highp = !has_decoration(dst_id, DecorationRelaxedPrecision);
12181
12182 auto input_precision = analyze_expression_precision(args, length);
12183 if (input_precision == Options::DontCare)
12184 {
12185 consume_temporary_in_precision_context(type_id, dst_id, input_precision);
12186 return;
12187 }
12188
12189 // In SPIR-V and GLSL, the semantics are flipped for how relaxed precision is determined.
12190 // In SPIR-V, the operation itself marks RelaxedPrecision, meaning that inputs can be truncated to 16-bit.
12191 // However, if the expression is not, inputs must be expanded to 32-bit first,
12192 // since the operation must run at high precision.
12193 // This is the awkward part, because if we have mediump inputs, or expressions which derived from mediump,
12194 // we might have to forcefully bind the source IDs to highp temporaries. This is done by clearing decorations
12195 // and forcing temporaries. Similarly for mediump operations. We bind highp expressions to mediump variables.
12196 if ((operation_is_highp && input_precision == Options::Mediump) ||
12197 (!operation_is_highp && input_precision == Options::Highp))
12198 {
12199 auto precision = operation_is_highp ? Options::Highp : Options::Mediump;
12200 for (uint32_t i = 0; i < length; i++)
12201 {
12202 // Rewrites the opcode so that we consume an ID in correct precision context.
12203 // This is pretty hacky, but it's the most straight forward way of implementing this without adding
12204 // lots of extra passes to rewrite all code blocks.
12205 args[i] = consume_temporary_in_precision_context(expression_type_id(args[i]), args[i], precision);
12206 }
12207 }
12208 }
12209
12210 // This is probably not exhaustive ...
12211 static bool opcode_is_precision_sensitive_operation(Op op)
12212 {
12213 switch (op)
12214 {
12215 case OpFAdd:
12216 case OpFSub:
12217 case OpFMul:
12218 case OpFNegate:
12219 case OpIAdd:
12220 case OpISub:
12221 case OpIMul:
12222 case OpSNegate:
12223 case OpFMod:
12224 case OpFDiv:
12225 case OpFRem:
12226 case OpSMod:
12227 case OpSDiv:
12228 case OpSRem:
12229 case OpUMod:
12230 case OpUDiv:
12231 case OpVectorTimesMatrix:
12232 case OpMatrixTimesVector:
12233 case OpMatrixTimesMatrix:
12234 case OpDPdx:
12235 case OpDPdy:
12236 case OpDPdxCoarse:
12237 case OpDPdyCoarse:
12238 case OpDPdxFine:
12239 case OpDPdyFine:
12240 case OpFwidth:
12241 case OpFwidthCoarse:
12242 case OpFwidthFine:
12243 case OpVectorTimesScalar:
12244 case OpMatrixTimesScalar:
12245 case OpOuterProduct:
12246 case OpFConvert:
12247 case OpSConvert:
12248 case OpUConvert:
12249 case OpConvertSToF:
12250 case OpConvertUToF:
12251 case OpConvertFToU:
12252 case OpConvertFToS:
12253 return true;
12254
12255 default:
12256 return false;
12257 }
12258 }
12259
12260 // Instructions which just load data but don't do any arithmetic operation should just inherit the decoration.
12261 // SPIR-V doesn't require this, but it's somewhat implied it has to work this way, relaxed precision is only
12262 // relevant when operating on the IDs, not when shuffling things around.
12263 static bool opcode_is_precision_forwarding_instruction(Op op, uint32_t &arg_count)
12264 {
12265 switch (op)
12266 {
12267 case OpLoad:
12268 case OpAccessChain:
12269 case OpInBoundsAccessChain:
12270 case OpCompositeExtract:
12271 case OpVectorExtractDynamic:
12272 case OpSampledImage:
12273 case OpImage:
12274 case OpCopyObject:
12275
12276 case OpImageRead:
12277 case OpImageFetch:
12278 case OpImageSampleImplicitLod:
12279 case OpImageSampleProjImplicitLod:
12280 case OpImageSampleDrefImplicitLod:
12281 case OpImageSampleProjDrefImplicitLod:
12282 case OpImageSampleExplicitLod:
12283 case OpImageSampleProjExplicitLod:
12284 case OpImageSampleDrefExplicitLod:
12285 case OpImageSampleProjDrefExplicitLod:
12286 case OpImageGather:
12287 case OpImageDrefGather:
12288 case OpImageSparseRead:
12289 case OpImageSparseFetch:
12290 case OpImageSparseSampleImplicitLod:
12291 case OpImageSparseSampleProjImplicitLod:
12292 case OpImageSparseSampleDrefImplicitLod:
12293 case OpImageSparseSampleProjDrefImplicitLod:
12294 case OpImageSparseSampleExplicitLod:
12295 case OpImageSparseSampleProjExplicitLod:
12296 case OpImageSparseSampleDrefExplicitLod:
12297 case OpImageSparseSampleProjDrefExplicitLod:
12298 case OpImageSparseGather:
12299 case OpImageSparseDrefGather:
12300 arg_count = 1;
12301 return true;
12302
12303 case OpVectorShuffle:
12304 arg_count = 2;
12305 return true;
12306
12307 case OpCompositeConstruct:
12308 return true;
12309
12310 default:
12311 break;
12312 }
12313
12314 return false;
12315 }
12316
12317 CompilerGLSL::TemporaryCopy CompilerGLSL::handle_instruction_precision(const Instruction &instruction)
12318 {
12319 auto ops = stream_mutable(instruction);
12320 auto opcode = static_cast<Op>(instruction.op);
12321 uint32_t length = instruction.length;
12322
12323 if (backend.requires_relaxed_precision_analysis)
12324 {
12325 if (length > 2)
12326 {
12327 uint32_t forwarding_length = length - 2;
12328
12329 if (opcode_is_precision_sensitive_operation(opcode))
12330 analyze_precision_requirements(ops[0], ops[1], &ops[2], forwarding_length);
12331 else if (opcode == OpExtInst && length >= 5 && get<SPIRExtension>(ops[2]).ext == SPIRExtension::GLSL)
12332 analyze_precision_requirements(ops[0], ops[1], &ops[4], forwarding_length - 2);
12333 else if (opcode_is_precision_forwarding_instruction(opcode, forwarding_length))
12334 forward_relaxed_precision(ops[1], &ops[2], forwarding_length);
12335 }
12336
12337 uint32_t result_type = 0, result_id = 0;
12338 if (instruction_to_result_type(result_type, result_id, opcode, ops, length))
12339 {
12340 auto itr = temporary_to_mirror_precision_alias.find(ops[1]);
12341 if (itr != temporary_to_mirror_precision_alias.end())
12342 return { itr->second, itr->first };
12343 }
12344 }
12345
12346 return {};
12347 }
12348
12349 static pair<string, string> split_coopmat_pointer(const string &expr)
12350 {
12351 auto ptr_expr = expr;
12352 string index_expr;
12353
12354 if (ptr_expr.back() != ']')
12355 SPIRV_CROSS_THROW("Access chain for coopmat must be indexed into an array.");
12356
12357 // Strip the access chain.
12358 ptr_expr.pop_back();
12359 uint32_t counter = 1;
12360 while (counter && !ptr_expr.empty())
12361 {
12362 if (ptr_expr.back() == ']')
12363 counter++;
12364 else if (ptr_expr.back() == '[')
12365 counter--;
12366 ptr_expr.pop_back();
12367 }
12368
12369 if (ptr_expr.empty())
12370 SPIRV_CROSS_THROW("Invalid pointer expression for coopmat.");
12371
12372 index_expr = expr.substr(ptr_expr.size() + 1, expr.size() - (ptr_expr.size() + 1) - 1);
12373 return { std::move(ptr_expr), std::move(index_expr) };
12374 }
12375
12376 void CompilerGLSL::emit_instruction(const Instruction &instruction)
12377 {
12378 auto ops = stream(instruction);
12379 auto opcode = static_cast<Op>(instruction.op);
12380 uint32_t length = instruction.length;
12381
12382 #define GLSL_BOP(op) emit_binary_op(ops[0], ops[1], ops[2], ops[3], #op)
12383 #define GLSL_BOP_CAST(op, type) \
12384 emit_binary_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, \
12385 opcode_is_sign_invariant(opcode), implicit_integer_promotion)
12386 #define GLSL_UOP(op) emit_unary_op(ops[0], ops[1], ops[2], #op)
12387 #define GLSL_UOP_CAST(op) emit_unary_op_cast(ops[0], ops[1], ops[2], #op)
12388 #define GLSL_QFOP(op) emit_quaternary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], #op)
12389 #define GLSL_TFOP(op) emit_trinary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], #op)
12390 #define GLSL_BFOP(op) emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], #op)
12391 #define GLSL_BFOP_CAST(op, type) \
12392 emit_binary_func_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode))
12393 #define GLSL_BFOP(op) emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], #op)
12394 #define GLSL_UFOP(op) emit_unary_func_op(ops[0], ops[1], ops[2], #op)
12395
12396 // If we need to do implicit bitcasts, make sure we do it with the correct type.
12397 uint32_t integer_width = get_integer_width_for_instruction(instruction);
12398 auto int_type = to_signed_basetype(integer_width);
12399 auto uint_type = to_unsigned_basetype(integer_width);
12400
12401 // Handle C implicit integer promotion rules.
12402 // If we get implicit promotion to int, need to make sure we cast by value to intended return type,
12403 // otherwise, future sign-dependent operations and bitcasts will break.
12404 bool implicit_integer_promotion = integer_width < 32 && backend.implicit_c_integer_promotion_rules &&
12405 opcode_can_promote_integer_implicitly(opcode) &&
12406 get<SPIRType>(ops[0]).vecsize == 1;
12407
12408 opcode = get_remapped_spirv_op(opcode);
12409
12410 switch (opcode)
12411 {
12412 // Dealing with memory
12413 case OpLoad:
12414 {
12415 uint32_t result_type = ops[0];
12416 uint32_t id = ops[1];
12417 uint32_t ptr = ops[2];
12418
12419 flush_variable_declaration(ptr);
12420
12421 // If we're loading from memory that cannot be changed by the shader,
12422 // just forward the expression directly to avoid needless temporaries.
12423 // If an expression is mutable and forwardable, we speculate that it is immutable.
12424 bool forward = should_forward(ptr) && forced_temporaries.find(id) == end(forced_temporaries);
12425
12426 // If loading a non-native row-major matrix, mark the expression as need_transpose.
12427 bool need_transpose = false;
12428 bool old_need_transpose = false;
12429
12430 auto *ptr_expression = maybe_get<SPIRExpression>(ptr);
12431
12432 if (forward)
12433 {
12434 // If we're forwarding the load, we're also going to forward transpose state, so don't transpose while
12435 // taking the expression.
12436 if (ptr_expression && ptr_expression->need_transpose)
12437 {
12438 old_need_transpose = true;
12439 ptr_expression->need_transpose = false;
12440 need_transpose = true;
12441 }
12442 else if (is_non_native_row_major_matrix(ptr))
12443 need_transpose = true;
12444 }
12445
12446 // If we are forwarding this load,
12447 // don't register the read to access chain here, defer that to when we actually use the expression,
12448 // using the add_implied_read_expression mechanism.
12449 string expr;
12450
12451 bool is_packed = has_extended_decoration(ptr, SPIRVCrossDecorationPhysicalTypePacked);
12452 bool is_remapped = has_extended_decoration(ptr, SPIRVCrossDecorationPhysicalTypeID);
12453 if (forward || (!is_packed && !is_remapped))
12454 {
12455 // For the simple case, we do not need to deal with repacking.
12456 expr = to_dereferenced_expression(ptr, false);
12457 }
12458 else
12459 {
12460 // If we are not forwarding the expression, we need to unpack and resolve any physical type remapping here before
12461 // storing the expression to a temporary.
12462 expr = to_unpacked_expression(ptr);
12463 }
12464
12465 auto &type = get<SPIRType>(result_type);
12466 auto &expr_type = expression_type(ptr);
12467
12468 // If the expression has more vector components than the result type, insert
12469 // a swizzle. This shouldn't happen normally on valid SPIR-V, but it might
12470 // happen with e.g. the MSL backend replacing the type of an input variable.
12471 if (expr_type.vecsize > type.vecsize)
12472 expr = enclose_expression(expr + vector_swizzle(type.vecsize, 0));
12473
12474 if (forward && ptr_expression)
12475 ptr_expression->need_transpose = old_need_transpose;
12476
12477 // We might need to cast in order to load from a builtin.
12478 cast_from_variable_load(ptr, expr, type);
12479
12480 if (forward && ptr_expression)
12481 ptr_expression->need_transpose = false;
12482
12483 // We might be trying to load a gl_Position[N], where we should be
12484 // doing float4[](gl_in[i].gl_Position, ...) instead.
12485 // Similar workarounds are required for input arrays in tessellation.
12486 // Also, loading from gl_SampleMask array needs special unroll.
12487 unroll_array_from_complex_load(id, ptr, expr);
12488
12489 if (!type_is_opaque_value(type) && has_decoration(ptr, DecorationNonUniform))
12490 {
12491 // If we're loading something non-opaque, we need to handle non-uniform descriptor access.
12492 convert_non_uniform_expression(expr, ptr);
12493 }
12494
12495 if (forward && ptr_expression)
12496 ptr_expression->need_transpose = old_need_transpose;
12497
12498 bool flattened = ptr_expression && flattened_buffer_blocks.count(ptr_expression->loaded_from) != 0;
12499
12500 if (backend.needs_row_major_load_workaround && !is_non_native_row_major_matrix(ptr) && !flattened)
12501 rewrite_load_for_wrapped_row_major(expr, result_type, ptr);
12502
12503 // By default, suppress usage tracking since using same expression multiple times does not imply any extra work.
12504 // However, if we try to load a complex, composite object from a flattened buffer,
12505 // we should avoid emitting the same code over and over and lower the result to a temporary.
12506 bool usage_tracking = flattened && (type.basetype == SPIRType::Struct || (type.columns > 1));
12507
12508 SPIRExpression *e = nullptr;
12509 if (!forward && expression_is_non_value_type_array(ptr))
12510 {
12511 // Complicated load case where we need to make a copy of ptr, but we cannot, because
12512 // it is an array, and our backend does not support arrays as value types.
12513 // Emit the temporary, and copy it explicitly.
12514 e = &emit_uninitialized_temporary_expression(result_type, id);
12515 emit_array_copy(nullptr, id, ptr, StorageClassFunction, get_expression_effective_storage_class(ptr));
12516 }
12517 else
12518 e = &emit_op(result_type, id, expr, forward, !usage_tracking);
12519
12520 e->need_transpose = need_transpose;
12521 register_read(id, ptr, forward);
12522
12523 if (forward)
12524 {
12525 // Pass through whether the result is of a packed type and the physical type ID.
12526 if (has_extended_decoration(ptr, SPIRVCrossDecorationPhysicalTypePacked))
12527 set_extended_decoration(id, SPIRVCrossDecorationPhysicalTypePacked);
12528 if (has_extended_decoration(ptr, SPIRVCrossDecorationPhysicalTypeID))
12529 {
12530 set_extended_decoration(id, SPIRVCrossDecorationPhysicalTypeID,
12531 get_extended_decoration(ptr, SPIRVCrossDecorationPhysicalTypeID));
12532 }
12533 }
12534 else
12535 {
12536 // This might have been set on an earlier compilation iteration, force it to be unset.
12537 unset_extended_decoration(id, SPIRVCrossDecorationPhysicalTypePacked);
12538 unset_extended_decoration(id, SPIRVCrossDecorationPhysicalTypeID);
12539 }
12540
12541 inherit_expression_dependencies(id, ptr);
12542 if (forward)
12543 add_implied_read_expression(*e, ptr);
12544 break;
12545 }
12546
12547 case OpInBoundsAccessChain:
12548 case OpAccessChain:
12549 case OpPtrAccessChain:
12550 {
12551 auto *var = maybe_get<SPIRVariable>(ops[2]);
12552 if (var)
12553 flush_variable_declaration(var->self);
12554
12555 // If the base is immutable, the access chain pointer must also be.
12556 // If an expression is mutable and forwardable, we speculate that it is immutable.
12557 AccessChainMeta meta;
12558 bool ptr_chain = opcode == OpPtrAccessChain;
12559 auto &target_type = get<SPIRType>(ops[0]);
12560 auto e = access_chain(ops[2], &ops[3], length - 3, target_type, &meta, ptr_chain);
12561
12562 // If the base is flattened UBO of struct type, the expression has to be a composite.
12563 // In that case, backends which do not support inline syntax need it to be bound to a temporary.
12564 // Otherwise, invalid expressions like ({UBO[0].xyz, UBO[0].w, UBO[1]}).member are emitted.
12565 bool requires_temporary = false;
12566 if (flattened_buffer_blocks.count(ops[2]) && target_type.basetype == SPIRType::Struct)
12567 requires_temporary = !backend.can_declare_struct_inline;
12568
12569 auto &expr = requires_temporary ?
12570 emit_op(ops[0], ops[1], std::move(e), false) :
12571 set<SPIRExpression>(ops[1], std::move(e), ops[0], should_forward(ops[2]));
12572
12573 auto *backing_variable = maybe_get_backing_variable(ops[2]);
12574 expr.loaded_from = backing_variable ? backing_variable->self : ID(ops[2]);
12575 expr.need_transpose = meta.need_transpose;
12576 expr.access_chain = true;
12577 expr.access_meshlet_position_y = meta.access_meshlet_position_y;
12578
12579 // Mark the result as being packed. Some platforms handled packed vectors differently than non-packed.
12580 if (meta.storage_is_packed)
12581 set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypePacked);
12582 if (meta.storage_physical_type != 0)
12583 set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypeID, meta.storage_physical_type);
12584 if (meta.storage_is_invariant)
12585 set_decoration(ops[1], DecorationInvariant);
12586 if (meta.flattened_struct)
12587 flattened_structs[ops[1]] = true;
12588 if (meta.relaxed_precision && backend.requires_relaxed_precision_analysis)
12589 set_decoration(ops[1], DecorationRelaxedPrecision);
12590 if (meta.chain_is_builtin)
12591 set_decoration(ops[1], DecorationBuiltIn, meta.builtin);
12592
12593 // If we have some expression dependencies in our access chain, this access chain is technically a forwarded
12594 // temporary which could be subject to invalidation.
12595 // Need to assume we're forwarded while calling inherit_expression_depdendencies.
12596 forwarded_temporaries.insert(ops[1]);
12597 // The access chain itself is never forced to a temporary, but its dependencies might.
12598 suppressed_usage_tracking.insert(ops[1]);
12599
12600 for (uint32_t i = 2; i < length; i++)
12601 {
12602 inherit_expression_dependencies(ops[1], ops[i]);
12603 add_implied_read_expression(expr, ops[i]);
12604 }
12605
12606 // If we have no dependencies after all, i.e., all indices in the access chain are immutable temporaries,
12607 // we're not forwarded after all.
12608 if (expr.expression_dependencies.empty())
12609 forwarded_temporaries.erase(ops[1]);
12610
12611 break;
12612 }
12613
12614 case OpStore:
12615 {
12616 auto *var = maybe_get<SPIRVariable>(ops[0]);
12617
12618 if (var && var->statically_assigned)
12619 var->static_expression = ops[1];
12620 else if (var && var->loop_variable && !var->loop_variable_enable)
12621 var->static_expression = ops[1];
12622 else if (var && var->remapped_variable && var->static_expression)
12623 {
12624 // Skip the write.
12625 }
12626 else if (flattened_structs.count(ops[0]))
12627 {
12628 store_flattened_struct(ops[0], ops[1]);
12629 register_write(ops[0]);
12630 }
12631 else
12632 {
12633 emit_store_statement(ops[0], ops[1]);
12634 }
12635
12636 // Storing a pointer results in a variable pointer, so we must conservatively assume
12637 // we can write through it.
12638 if (expression_type(ops[1]).pointer)
12639 register_write(ops[1]);
12640 break;
12641 }
12642
12643 case OpArrayLength:
12644 {
12645 uint32_t result_type = ops[0];
12646 uint32_t id = ops[1];
12647 auto e = access_chain_internal(ops[2], &ops[3], length - 3, ACCESS_CHAIN_INDEX_IS_LITERAL_BIT, nullptr);
12648 if (has_decoration(ops[2], DecorationNonUniform))
12649 convert_non_uniform_expression(e, ops[2]);
12650 set<SPIRExpression>(id, join(type_to_glsl(get<SPIRType>(result_type)), "(", e, ".length())"), result_type,
12651 true);
12652 break;
12653 }
12654
12655 // Function calls
12656 case OpFunctionCall:
12657 {
12658 uint32_t result_type = ops[0];
12659 uint32_t id = ops[1];
12660 uint32_t func = ops[2];
12661 const auto *arg = &ops[3];
12662 length -= 3;
12663
12664 auto &callee = get<SPIRFunction>(func);
12665 auto &return_type = get<SPIRType>(callee.return_type);
12666 bool pure = function_is_pure(callee);
12667 bool control_dependent = function_is_control_dependent(callee);
12668
12669 bool callee_has_out_variables = false;
12670 bool emit_return_value_as_argument = false;
12671
12672 // Invalidate out variables passed to functions since they can be OpStore'd to.
12673 for (uint32_t i = 0; i < length; i++)
12674 {
12675 if (callee.arguments[i].write_count)
12676 {
12677 register_call_out_argument(arg[i]);
12678 callee_has_out_variables = true;
12679 }
12680
12681 flush_variable_declaration(arg[i]);
12682 }
12683
12684 if (!return_type.array.empty() && !backend.can_return_array)
12685 {
12686 callee_has_out_variables = true;
12687 emit_return_value_as_argument = true;
12688 }
12689
12690 if (!pure)
12691 register_impure_function_call();
12692
12693 string funexpr;
12694 SmallVector<string> arglist;
12695 funexpr += to_name(func) + "(";
12696
12697 if (emit_return_value_as_argument)
12698 {
12699 statement(type_to_glsl(return_type), " ", to_name(id), type_to_array_glsl(return_type, 0), ";");
12700 arglist.push_back(to_name(id));
12701 }
12702
12703 for (uint32_t i = 0; i < length; i++)
12704 {
12705 // Do not pass in separate images or samplers if we're remapping
12706 // to combined image samplers.
12707 if (skip_argument(arg[i]))
12708 continue;
12709
12710 arglist.push_back(to_func_call_arg(callee.arguments[i], arg[i]));
12711 }
12712
12713 for (auto &combined : callee.combined_parameters)
12714 {
12715 auto image_id = combined.global_image ? combined.image_id : VariableID(arg[combined.image_id]);
12716 auto sampler_id = combined.global_sampler ? combined.sampler_id : VariableID(arg[combined.sampler_id]);
12717 arglist.push_back(to_combined_image_sampler(image_id, sampler_id));
12718 }
12719
12720 append_global_func_args(callee, length, arglist);
12721
12722 funexpr += merge(arglist);
12723 funexpr += ")";
12724
12725 // Check for function call constraints.
12726 check_function_call_constraints(arg, length);
12727
12728 if (return_type.basetype != SPIRType::Void)
12729 {
12730 // If the function actually writes to an out variable,
12731 // take the conservative route and do not forward.
12732 // The problem is that we might not read the function
12733 // result (and emit the function) before an out variable
12734 // is read (common case when return value is ignored!
12735 // In order to avoid start tracking invalid variables,
12736 // just avoid the forwarding problem altogether.
12737 bool forward = args_will_forward(id, arg, length, pure) && !callee_has_out_variables && pure &&
12738 (forced_temporaries.find(id) == end(forced_temporaries));
12739
12740 if (emit_return_value_as_argument)
12741 {
12742 statement(funexpr, ";");
12743 set<SPIRExpression>(id, to_name(id), result_type, true);
12744 }
12745 else
12746 emit_op(result_type, id, funexpr, forward);
12747
12748 // Function calls are implicit loads from all variables in question.
12749 // Set dependencies for them.
12750 for (uint32_t i = 0; i < length; i++)
12751 register_read(id, arg[i], forward);
12752
12753 // If we're going to forward the temporary result,
12754 // put dependencies on every variable that must not change.
12755 if (forward)
12756 register_global_read_dependencies(callee, id);
12757 }
12758 else
12759 statement(funexpr, ";");
12760
12761 if (control_dependent)
12762 register_control_dependent_expression(id);
12763
12764 break;
12765 }
12766
12767 // Composite munging
12768 case OpCompositeConstruct:
12769 {
12770 uint32_t result_type = ops[0];
12771 uint32_t id = ops[1];
12772 const auto *const elems = &ops[2];
12773 length -= 2;
12774
12775 bool forward = true;
12776 for (uint32_t i = 0; i < length; i++)
12777 forward = forward && should_forward(elems[i]);
12778
12779 auto &out_type = get<SPIRType>(result_type);
12780 auto *in_type = length > 0 ? &expression_type(elems[0]) : nullptr;
12781
12782 // Only splat if we have vector constructors.
12783 // Arrays and structs must be initialized properly in full.
12784 bool composite = !out_type.array.empty() || out_type.basetype == SPIRType::Struct;
12785
12786 bool splat = false;
12787 bool swizzle_splat = false;
12788
12789 if (in_type)
12790 {
12791 splat = in_type->vecsize == 1 && in_type->columns == 1 && !composite && backend.use_constructor_splatting;
12792 swizzle_splat = in_type->vecsize == 1 && in_type->columns == 1 && backend.can_swizzle_scalar;
12793
12794 if (ir.ids[elems[0]].get_type() == TypeConstant && !type_is_floating_point(*in_type))
12795 {
12796 // Cannot swizzle literal integers as a special case.
12797 swizzle_splat = false;
12798 }
12799 }
12800
12801 if (splat || swizzle_splat)
12802 {
12803 uint32_t input = elems[0];
12804 for (uint32_t i = 0; i < length; i++)
12805 {
12806 if (input != elems[i])
12807 {
12808 splat = false;
12809 swizzle_splat = false;
12810 }
12811 }
12812 }
12813
12814 if (out_type.basetype == SPIRType::Struct && !backend.can_declare_struct_inline)
12815 forward = false;
12816 if (!out_type.array.empty() && !backend.can_declare_arrays_inline)
12817 forward = false;
12818 if (type_is_empty(out_type) && !backend.supports_empty_struct)
12819 forward = false;
12820
12821 string constructor_op;
12822 if (backend.use_initializer_list && composite)
12823 {
12824 bool needs_trailing_tracket = false;
12825 // Only use this path if we are building composites.
12826 // This path cannot be used for arithmetic.
12827 if (backend.use_typed_initializer_list && out_type.basetype == SPIRType::Struct && out_type.array.empty())
12828 constructor_op += type_to_glsl_constructor(get<SPIRType>(result_type));
12829 else if (backend.use_typed_initializer_list && backend.array_is_value_type && !out_type.array.empty())
12830 {
12831 // MSL path. Array constructor is baked into type here, do not use _constructor variant.
12832 constructor_op += type_to_glsl_constructor(get<SPIRType>(result_type)) + "(";
12833 needs_trailing_tracket = true;
12834 }
12835 constructor_op += "{ ";
12836
12837 if (type_is_empty(out_type) && !backend.supports_empty_struct)
12838 constructor_op += "0";
12839 else if (splat)
12840 constructor_op += to_unpacked_expression(elems[0]);
12841 else
12842 constructor_op += build_composite_combiner(result_type, elems, length);
12843 constructor_op += " }";
12844 if (needs_trailing_tracket)
12845 constructor_op += ")";
12846 }
12847 else if (swizzle_splat && !composite)
12848 {
12849 constructor_op = remap_swizzle(get<SPIRType>(result_type), 1, to_unpacked_expression(elems[0]));
12850 }
12851 else
12852 {
12853 constructor_op = type_to_glsl_constructor(get<SPIRType>(result_type)) + "(";
12854 if (type_is_empty(out_type) && !backend.supports_empty_struct)
12855 constructor_op += "0";
12856 else if (splat)
12857 constructor_op += to_unpacked_expression(elems[0]);
12858 else
12859 constructor_op += build_composite_combiner(result_type, elems, length);
12860 constructor_op += ")";
12861 }
12862
12863 if (!constructor_op.empty())
12864 {
12865 emit_op(result_type, id, constructor_op, forward);
12866 for (uint32_t i = 0; i < length; i++)
12867 inherit_expression_dependencies(id, elems[i]);
12868 }
12869 break;
12870 }
12871
12872 case OpVectorInsertDynamic:
12873 {
12874 uint32_t result_type = ops[0];
12875 uint32_t id = ops[1];
12876 uint32_t vec = ops[2];
12877 uint32_t comp = ops[3];
12878 uint32_t index = ops[4];
12879
12880 flush_variable_declaration(vec);
12881
12882 // Make a copy, then use access chain to store the variable.
12883 statement(declare_temporary(result_type, id), to_expression(vec), ";");
12884 set<SPIRExpression>(id, to_name(id), result_type, true);
12885 auto chain = access_chain_internal(id, &index, 1, 0, nullptr);
12886 statement(chain, " = ", to_unpacked_expression(comp), ";");
12887 break;
12888 }
12889
12890 case OpVectorExtractDynamic:
12891 {
12892 uint32_t result_type = ops[0];
12893 uint32_t id = ops[1];
12894
12895 auto expr = access_chain_internal(ops[2], &ops[3], 1, 0, nullptr);
12896 emit_op(result_type, id, expr, should_forward(ops[2]));
12897 inherit_expression_dependencies(id, ops[2]);
12898 inherit_expression_dependencies(id, ops[3]);
12899 break;
12900 }
12901
12902 case OpCompositeExtract:
12903 {
12904 uint32_t result_type = ops[0];
12905 uint32_t id = ops[1];
12906 length -= 3;
12907
12908 auto &type = get<SPIRType>(result_type);
12909
12910 // We can only split the expression here if our expression is forwarded as a temporary.
12911 bool allow_base_expression = forced_temporaries.find(id) == end(forced_temporaries);
12912
12913 // Do not allow base expression for struct members. We risk doing "swizzle" optimizations in this case.
12914 auto &composite_type = expression_type(ops[2]);
12915 bool composite_type_is_complex = composite_type.basetype == SPIRType::Struct || !composite_type.array.empty();
12916 if (composite_type_is_complex)
12917 allow_base_expression = false;
12918
12919 if (composite_type.op == spv::OpTypeCooperativeMatrixKHR)
12920 allow_base_expression = false;
12921
12922 // Packed expressions or physical ID mapped expressions cannot be split up.
12923 if (has_extended_decoration(ops[2], SPIRVCrossDecorationPhysicalTypePacked) ||
12924 has_extended_decoration(ops[2], SPIRVCrossDecorationPhysicalTypeID))
12925 allow_base_expression = false;
12926
12927 // Cannot use base expression for row-major matrix row-extraction since we need to interleave access pattern
12928 // into the base expression.
12929 if (is_non_native_row_major_matrix(ops[2]))
12930 allow_base_expression = false;
12931
12932 AccessChainMeta meta;
12933 SPIRExpression *e = nullptr;
12934 auto *c = maybe_get<SPIRConstant>(ops[2]);
12935
12936 if (c && !c->specialization && !composite_type_is_complex)
12937 {
12938 auto expr = to_extract_constant_composite_expression(result_type, *c, ops + 3, length);
12939 e = &emit_op(result_type, id, expr, true, true);
12940 }
12941 else if (allow_base_expression && should_forward(ops[2]) && type.vecsize == 1 && type.columns == 1 && length == 1)
12942 {
12943 // Only apply this optimization if result is scalar.
12944
12945 // We want to split the access chain from the base.
12946 // This is so we can later combine different CompositeExtract results
12947 // with CompositeConstruct without emitting code like
12948 //
12949 // vec3 temp = texture(...).xyz
12950 // vec4(temp.x, temp.y, temp.z, 1.0).
12951 //
12952 // when we actually wanted to emit this
12953 // vec4(texture(...).xyz, 1.0).
12954 //
12955 // Including the base will prevent this and would trigger multiple reads
12956 // from expression causing it to be forced to an actual temporary in GLSL.
12957 auto expr = access_chain_internal(ops[2], &ops[3], length,
12958 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_CHAIN_ONLY_BIT |
12959 ACCESS_CHAIN_FORCE_COMPOSITE_BIT, &meta);
12960 e = &emit_op(result_type, id, expr, true, should_suppress_usage_tracking(ops[2]));
12961 inherit_expression_dependencies(id, ops[2]);
12962 e->base_expression = ops[2];
12963
12964 if (meta.relaxed_precision && backend.requires_relaxed_precision_analysis)
12965 set_decoration(ops[1], DecorationRelaxedPrecision);
12966 }
12967 else
12968 {
12969 auto expr = access_chain_internal(ops[2], &ops[3], length,
12970 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_FORCE_COMPOSITE_BIT, &meta);
12971 e = &emit_op(result_type, id, expr, should_forward(ops[2]), should_suppress_usage_tracking(ops[2]));
12972 inherit_expression_dependencies(id, ops[2]);
12973 }
12974
12975 // Pass through some meta information to the loaded expression.
12976 // We can still end up loading a buffer type to a variable, then CompositeExtract from it
12977 // instead of loading everything through an access chain.
12978 e->need_transpose = meta.need_transpose;
12979 if (meta.storage_is_packed)
12980 set_extended_decoration(id, SPIRVCrossDecorationPhysicalTypePacked);
12981 if (meta.storage_physical_type != 0)
12982 set_extended_decoration(id, SPIRVCrossDecorationPhysicalTypeID, meta.storage_physical_type);
12983 if (meta.storage_is_invariant)
12984 set_decoration(id, DecorationInvariant);
12985
12986 break;
12987 }
12988
12989 case OpCompositeInsert:
12990 {
12991 uint32_t result_type = ops[0];
12992 uint32_t id = ops[1];
12993 uint32_t obj = ops[2];
12994 uint32_t composite = ops[3];
12995 const auto *elems = &ops[4];
12996 length -= 4;
12997
12998 flush_variable_declaration(composite);
12999
13000 // CompositeInsert requires a copy + modification, but this is very awkward code in HLL.
13001 // Speculate that the input composite is no longer used, and we can modify it in-place.
13002 // There are various scenarios where this is not possible to satisfy.
13003 bool can_modify_in_place = true;
13004 forced_temporaries.insert(id);
13005
13006 // Cannot safely RMW PHI variables since they have no way to be invalidated,
13007 // forcing temporaries is not going to help.
13008 // This is similar for Constant and Undef inputs.
13009 // The only safe thing to RMW is SPIRExpression.
13010 // If the expression has already been used (i.e. used in a continue block), we have to keep using
13011 // that loop variable, since we won't be able to override the expression after the fact.
13012 // If the composite is hoisted, we might never be able to properly invalidate any usage
13013 // of that composite in a subsequent loop iteration.
13014 if (invalid_expressions.count(composite) ||
13015 block_composite_insert_overwrite.count(composite) ||
13016 hoisted_temporaries.count(id) || hoisted_temporaries.count(composite) ||
13017 maybe_get<SPIRExpression>(composite) == nullptr)
13018 {
13019 can_modify_in_place = false;
13020 }
13021 else if (backend.requires_relaxed_precision_analysis &&
13022 has_decoration(composite, DecorationRelaxedPrecision) !=
13023 has_decoration(id, DecorationRelaxedPrecision) &&
13024 get<SPIRType>(result_type).basetype != SPIRType::Struct)
13025 {
13026 // Similarly, if precision does not match for input and output,
13027 // we cannot alias them. If we write a composite into a relaxed precision
13028 // ID, we might get a false truncation.
13029 can_modify_in_place = false;
13030 }
13031
13032 if (can_modify_in_place)
13033 {
13034 // Have to make sure the modified SSA value is bound to a temporary so we can modify it in-place.
13035 if (!forced_temporaries.count(composite))
13036 force_temporary_and_recompile(composite);
13037
13038 auto chain = access_chain_internal(composite, elems, length, ACCESS_CHAIN_INDEX_IS_LITERAL_BIT, nullptr);
13039 statement(chain, " = ", to_unpacked_expression(obj), ";");
13040 set<SPIRExpression>(id, to_expression(composite), result_type, true);
13041 invalid_expressions.insert(composite);
13042 composite_insert_overwritten.insert(composite);
13043 }
13044 else
13045 {
13046 if (maybe_get<SPIRUndef>(composite) != nullptr)
13047 {
13048 emit_uninitialized_temporary_expression(result_type, id);
13049 }
13050 else
13051 {
13052 // Make a copy, then use access chain to store the variable.
13053 statement(declare_temporary(result_type, id), to_expression(composite), ";");
13054 set<SPIRExpression>(id, to_name(id), result_type, true);
13055 }
13056
13057 auto chain = access_chain_internal(id, elems, length, ACCESS_CHAIN_INDEX_IS_LITERAL_BIT, nullptr);
13058 statement(chain, " = ", to_unpacked_expression(obj), ";");
13059 }
13060
13061 break;
13062 }
13063
13064 case OpCopyMemory:
13065 {
13066 uint32_t lhs = ops[0];
13067 uint32_t rhs = ops[1];
13068 if (lhs != rhs)
13069 {
13070 uint32_t &tmp_id = extra_sub_expressions[instruction.offset | EXTRA_SUB_EXPRESSION_TYPE_STREAM_OFFSET];
13071 if (!tmp_id)
13072 tmp_id = ir.increase_bound_by(1);
13073 uint32_t tmp_type_id = expression_type(rhs).parent_type;
13074
13075 EmbeddedInstruction fake_load, fake_store;
13076 fake_load.op = OpLoad;
13077 fake_load.length = 3;
13078 fake_load.ops.push_back(tmp_type_id);
13079 fake_load.ops.push_back(tmp_id);
13080 fake_load.ops.push_back(rhs);
13081
13082 fake_store.op = OpStore;
13083 fake_store.length = 2;
13084 fake_store.ops.push_back(lhs);
13085 fake_store.ops.push_back(tmp_id);
13086
13087 // Load and Store do a *lot* of workarounds, and we'd like to reuse them as much as possible.
13088 // Synthesize a fake Load and Store pair for CopyMemory.
13089 emit_instruction(fake_load);
13090 emit_instruction(fake_store);
13091 }
13092 break;
13093 }
13094
13095 case OpCopyLogical:
13096 {
13097 // This is used for copying object of different types, arrays and structs.
13098 // We need to unroll the copy, element-by-element.
13099 uint32_t result_type = ops[0];
13100 uint32_t id = ops[1];
13101 uint32_t rhs = ops[2];
13102
13103 emit_uninitialized_temporary_expression(result_type, id);
13104 emit_copy_logical_type(id, result_type, rhs, expression_type_id(rhs), {});
13105 break;
13106 }
13107
13108 case OpCopyObject:
13109 {
13110 uint32_t result_type = ops[0];
13111 uint32_t id = ops[1];
13112 uint32_t rhs = ops[2];
13113 bool pointer = get<SPIRType>(result_type).pointer;
13114
13115 auto *chain = maybe_get<SPIRAccessChain>(rhs);
13116 auto *imgsamp = maybe_get<SPIRCombinedImageSampler>(rhs);
13117 if (chain)
13118 {
13119 // Cannot lower to a SPIRExpression, just copy the object.
13120 auto &e = set<SPIRAccessChain>(id, *chain);
13121 e.self = id;
13122 }
13123 else if (imgsamp)
13124 {
13125 // Cannot lower to a SPIRExpression, just copy the object.
13126 // GLSL does not currently use this type and will never get here, but MSL does.
13127 // Handled here instead of CompilerMSL for better integration and general handling,
13128 // and in case GLSL or other subclasses require it in the future.
13129 auto &e = set<SPIRCombinedImageSampler>(id, *imgsamp);
13130 e.self = id;
13131 }
13132 else if (expression_is_lvalue(rhs) && !pointer)
13133 {
13134 // Need a copy.
13135 // For pointer types, we copy the pointer itself.
13136 emit_op(result_type, id, to_unpacked_expression(rhs), false);
13137 }
13138 else
13139 {
13140 // RHS expression is immutable, so just forward it.
13141 // Copying these things really make no sense, but
13142 // seems to be allowed anyways.
13143 auto &e = emit_op(result_type, id, to_expression(rhs), true, true);
13144 if (pointer)
13145 {
13146 auto *var = maybe_get_backing_variable(rhs);
13147 e.loaded_from = var ? var->self : ID(0);
13148 }
13149
13150 // If we're copying an access chain, need to inherit the read expressions.
13151 auto *rhs_expr = maybe_get<SPIRExpression>(rhs);
13152 if (rhs_expr)
13153 {
13154 e.implied_read_expressions = rhs_expr->implied_read_expressions;
13155 e.expression_dependencies = rhs_expr->expression_dependencies;
13156 }
13157 }
13158 break;
13159 }
13160
13161 case OpVectorShuffle:
13162 {
13163 uint32_t result_type = ops[0];
13164 uint32_t id = ops[1];
13165 uint32_t vec0 = ops[2];
13166 uint32_t vec1 = ops[3];
13167 const auto *elems = &ops[4];
13168 length -= 4;
13169
13170 auto &type0 = expression_type(vec0);
13171
13172 // If we have the undefined swizzle index -1, we need to swizzle in undefined data,
13173 // or in our case, T(0).
13174 bool shuffle = false;
13175 for (uint32_t i = 0; i < length; i++)
13176 if (elems[i] >= type0.vecsize || elems[i] == 0xffffffffu)
13177 shuffle = true;
13178
13179 // Cannot use swizzles with packed expressions, force shuffle path.
13180 if (!shuffle && has_extended_decoration(vec0, SPIRVCrossDecorationPhysicalTypePacked))
13181 shuffle = true;
13182
13183 string expr;
13184 bool should_fwd, trivial_forward;
13185
13186 if (shuffle)
13187 {
13188 should_fwd = should_forward(vec0) && should_forward(vec1);
13189 trivial_forward = should_suppress_usage_tracking(vec0) && should_suppress_usage_tracking(vec1);
13190
13191 // Constructor style and shuffling from two different vectors.
13192 SmallVector<string> args;
13193 for (uint32_t i = 0; i < length; i++)
13194 {
13195 if (elems[i] == 0xffffffffu)
13196 {
13197 // Use a constant 0 here.
13198 // We could use the first component or similar, but then we risk propagating
13199 // a value we might not need, and bog down codegen.
13200 SPIRConstant c;
13201 c.constant_type = type0.parent_type;
13202 assert(type0.parent_type != ID(0));
13203 args.push_back(constant_expression(c));
13204 }
13205 else if (elems[i] >= type0.vecsize)
13206 args.push_back(to_extract_component_expression(vec1, elems[i] - type0.vecsize));
13207 else
13208 args.push_back(to_extract_component_expression(vec0, elems[i]));
13209 }
13210 expr += join(type_to_glsl_constructor(get<SPIRType>(result_type)), "(", merge(args), ")");
13211 }
13212 else
13213 {
13214 should_fwd = should_forward(vec0);
13215 trivial_forward = should_suppress_usage_tracking(vec0);
13216
13217 // We only source from first vector, so can use swizzle.
13218 // If the vector is packed, unpack it before applying a swizzle (needed for MSL)
13219 expr += to_enclosed_unpacked_expression(vec0);
13220 expr += ".";
13221 for (uint32_t i = 0; i < length; i++)
13222 {
13223 assert(elems[i] != 0xffffffffu);
13224 expr += index_to_swizzle(elems[i]);
13225 }
13226
13227 if (backend.swizzle_is_function && length > 1)
13228 expr += "()";
13229 }
13230
13231 // A shuffle is trivial in that it doesn't actually *do* anything.
13232 // We inherit the forwardedness from our arguments to avoid flushing out to temporaries when it's not really needed.
13233
13234 emit_op(result_type, id, expr, should_fwd, trivial_forward);
13235
13236 inherit_expression_dependencies(id, vec0);
13237 if (vec0 != vec1)
13238 inherit_expression_dependencies(id, vec1);
13239 break;
13240 }
13241
13242 // ALU
13243 case OpIsNan:
13244 if (!is_legacy())
13245 GLSL_UFOP(isnan);
13246 else
13247 {
13248 // Check if the number doesn't equal itself
13249 auto &type = get<SPIRType>(ops[0]);
13250 if (type.vecsize > 1)
13251 emit_binary_func_op(ops[0], ops[1], ops[2], ops[2], "notEqual");
13252 else
13253 emit_binary_op(ops[0], ops[1], ops[2], ops[2], "!=");
13254 }
13255 break;
13256
13257 case OpIsInf:
13258 if (!is_legacy())
13259 GLSL_UFOP(isinf);
13260 else
13261 {
13262 // inf * 2 == inf by IEEE 754 rules, note this also applies to 0.0
13263 // This is more reliable than checking if product with zero is NaN
13264 uint32_t result_type = ops[0];
13265 uint32_t result_id = ops[1];
13266 uint32_t operand = ops[2];
13267
13268 auto &type = get<SPIRType>(result_type);
13269 std::string expr;
13270 if (type.vecsize > 1)
13271 {
13272 expr = type_to_glsl_constructor(type);
13273 expr += '(';
13274 for (uint32_t i = 0; i < type.vecsize; i++)
13275 {
13276 auto comp = to_extract_component_expression(operand, i);
13277 expr += join(comp, " != 0.0 && 2.0 * ", comp, " == ", comp);
13278
13279 if (i + 1 < type.vecsize)
13280 expr += ", ";
13281 }
13282 expr += ')';
13283 }
13284 else
13285 {
13286 // Register an extra read to force writing out a temporary
13287 auto oper = to_enclosed_expression(operand);
13288 track_expression_read(operand);
13289 expr += join(oper, " != 0.0 && 2.0 * ", oper, " == ", oper);
13290 }
13291 emit_op(result_type, result_id, expr, should_forward(operand));
13292
13293 inherit_expression_dependencies(result_id, operand);
13294 }
13295 break;
13296
13297 case OpSNegate:
13298 if (implicit_integer_promotion || expression_type_id(ops[2]) != ops[0])
13299 GLSL_UOP_CAST(-);
13300 else
13301 GLSL_UOP(-);
13302 break;
13303
13304 case OpFNegate:
13305 GLSL_UOP(-);
13306 break;
13307
13308 case OpIAdd:
13309 {
13310 // For simple arith ops, prefer the output type if there's a mismatch to avoid extra bitcasts.
13311 auto type = get<SPIRType>(ops[0]).basetype;
13312 GLSL_BOP_CAST(+, type);
13313 break;
13314 }
13315
13316 case OpFAdd:
13317 GLSL_BOP(+);
13318 break;
13319
13320 case OpISub:
13321 {
13322 auto type = get<SPIRType>(ops[0]).basetype;
13323 GLSL_BOP_CAST(-, type);
13324 break;
13325 }
13326
13327 case OpFSub:
13328 GLSL_BOP(-);
13329 break;
13330
13331 case OpIMul:
13332 {
13333 auto type = get<SPIRType>(ops[0]).basetype;
13334 GLSL_BOP_CAST(*, type);
13335 break;
13336 }
13337
13338 case OpVectorTimesMatrix:
13339 case OpMatrixTimesVector:
13340 {
13341 // If the matrix needs transpose, just flip the multiply order.
13342 auto *e = maybe_get<SPIRExpression>(ops[opcode == OpMatrixTimesVector ? 2 : 3]);
13343 if (e && e->need_transpose)
13344 {
13345 e->need_transpose = false;
13346 string expr;
13347
13348 if (opcode == OpMatrixTimesVector)
13349 expr = join(to_enclosed_unpacked_expression(ops[3]), " * ",
13350 enclose_expression(to_unpacked_row_major_matrix_expression(ops[2])));
13351 else
13352 expr = join(enclose_expression(to_unpacked_row_major_matrix_expression(ops[3])), " * ",
13353 to_enclosed_unpacked_expression(ops[2]));
13354
13355 bool forward = should_forward(ops[2]) && should_forward(ops[3]);
13356 emit_op(ops[0], ops[1], expr, forward);
13357 e->need_transpose = true;
13358 inherit_expression_dependencies(ops[1], ops[2]);
13359 inherit_expression_dependencies(ops[1], ops[3]);
13360 }
13361 else
13362 GLSL_BOP(*);
13363 break;
13364 }
13365
13366 case OpMatrixTimesMatrix:
13367 {
13368 auto *a = maybe_get<SPIRExpression>(ops[2]);
13369 auto *b = maybe_get<SPIRExpression>(ops[3]);
13370
13371 // If both matrices need transpose, we can multiply in flipped order and tag the expression as transposed.
13372 // a^T * b^T = (b * a)^T.
13373 if (a && b && a->need_transpose && b->need_transpose)
13374 {
13375 a->need_transpose = false;
13376 b->need_transpose = false;
13377 auto expr = join(enclose_expression(to_unpacked_row_major_matrix_expression(ops[3])), " * ",
13378 enclose_expression(to_unpacked_row_major_matrix_expression(ops[2])));
13379 bool forward = should_forward(ops[2]) && should_forward(ops[3]);
13380 auto &e = emit_op(ops[0], ops[1], expr, forward);
13381 e.need_transpose = true;
13382 a->need_transpose = true;
13383 b->need_transpose = true;
13384 inherit_expression_dependencies(ops[1], ops[2]);
13385 inherit_expression_dependencies(ops[1], ops[3]);
13386 }
13387 else
13388 GLSL_BOP(*);
13389
13390 break;
13391 }
13392
13393 case OpMatrixTimesScalar:
13394 {
13395 auto *a = maybe_get<SPIRExpression>(ops[2]);
13396
13397 // If the matrix need transpose, just mark the result as needing so.
13398 if (a && a->need_transpose)
13399 {
13400 a->need_transpose = false;
13401 auto expr = join(enclose_expression(to_unpacked_row_major_matrix_expression(ops[2])), " * ",
13402 to_enclosed_unpacked_expression(ops[3]));
13403 bool forward = should_forward(ops[2]) && should_forward(ops[3]);
13404 auto &e = emit_op(ops[0], ops[1], expr, forward);
13405 e.need_transpose = true;
13406 a->need_transpose = true;
13407 inherit_expression_dependencies(ops[1], ops[2]);
13408 inherit_expression_dependencies(ops[1], ops[3]);
13409 }
13410 else
13411 GLSL_BOP(*);
13412 break;
13413 }
13414
13415 case OpFMul:
13416 case OpVectorTimesScalar:
13417 GLSL_BOP(*);
13418 break;
13419
13420 case OpOuterProduct:
13421 if (options.version < 120) // Matches GLSL 1.10 / ESSL 1.00
13422 {
13423 uint32_t result_type = ops[0];
13424 uint32_t id = ops[1];
13425 uint32_t a = ops[2];
13426 uint32_t b = ops[3];
13427
13428 auto &type = get<SPIRType>(result_type);
13429 string expr = type_to_glsl_constructor(type);
13430 expr += "(";
13431 for (uint32_t col = 0; col < type.columns; col++)
13432 {
13433 expr += to_enclosed_expression(a);
13434 expr += " * ";
13435 expr += to_extract_component_expression(b, col);
13436 if (col + 1 < type.columns)
13437 expr += ", ";
13438 }
13439 expr += ")";
13440 emit_op(result_type, id, expr, should_forward(a) && should_forward(b));
13441 inherit_expression_dependencies(id, a);
13442 inherit_expression_dependencies(id, b);
13443 }
13444 else
13445 GLSL_BFOP(outerProduct);
13446 break;
13447
13448 case OpDot:
13449 GLSL_BFOP(dot);
13450 break;
13451
13452 case OpTranspose:
13453 if (options.version < 120) // Matches GLSL 1.10 / ESSL 1.00
13454 {
13455 // transpose() is not available, so instead, flip need_transpose,
13456 // which can later be turned into an emulated transpose op by
13457 // convert_row_major_matrix(), if necessary.
13458 uint32_t result_type = ops[0];
13459 uint32_t result_id = ops[1];
13460 uint32_t input = ops[2];
13461
13462 // Force need_transpose to false temporarily to prevent
13463 // to_expression() from doing the transpose.
13464 bool need_transpose = false;
13465 auto *input_e = maybe_get<SPIRExpression>(input);
13466 if (input_e)
13467 swap(need_transpose, input_e->need_transpose);
13468
13469 bool forward = should_forward(input);
13470 auto &e = emit_op(result_type, result_id, to_expression(input), forward);
13471 e.need_transpose = !need_transpose;
13472
13473 // Restore the old need_transpose flag.
13474 if (input_e)
13475 input_e->need_transpose = need_transpose;
13476 }
13477 else
13478 GLSL_UFOP(transpose);
13479 break;
13480
13481 case OpSRem:
13482 {
13483 uint32_t result_type = ops[0];
13484 uint32_t result_id = ops[1];
13485 uint32_t op0 = ops[2];
13486 uint32_t op1 = ops[3];
13487
13488 auto &out_type = get<SPIRType>(result_type);
13489
13490 bool forward = should_forward(op0) && should_forward(op1);
13491 string cast_op0, cast_op1;
13492 auto expected_type = binary_op_bitcast_helper(cast_op0, cast_op1, int_type, op0, op1, false);
13493
13494 // Needs special handling.
13495 auto expr = join(cast_op0, " - ", cast_op1, " * ", "(", cast_op0, " / ", cast_op1, ")");
13496
13497 if (implicit_integer_promotion)
13498 {
13499 expr = join(type_to_glsl(get<SPIRType>(result_type)), '(', expr, ')');
13500 }
13501 else if (out_type.basetype != int_type)
13502 {
13503 expected_type.basetype = int_type;
13504 expr = join(bitcast_glsl_op(out_type, expected_type), '(', expr, ')');
13505 }
13506
13507 emit_op(result_type, result_id, expr, forward);
13508 inherit_expression_dependencies(result_id, op0);
13509 inherit_expression_dependencies(result_id, op1);
13510 break;
13511 }
13512
13513 case OpSDiv:
13514 GLSL_BOP_CAST(/, int_type);
13515 break;
13516
13517 case OpUDiv:
13518 GLSL_BOP_CAST(/, uint_type);
13519 break;
13520
13521 case OpIAddCarry:
13522 case OpISubBorrow:
13523 {
13524 if (options.es && options.version < 310)
13525 SPIRV_CROSS_THROW("Extended arithmetic is only available from ESSL 310.");
13526 else if (!options.es && options.version < 400)
13527 SPIRV_CROSS_THROW("Extended arithmetic is only available from GLSL 400.");
13528
13529 uint32_t result_type = ops[0];
13530 uint32_t result_id = ops[1];
13531 uint32_t op0 = ops[2];
13532 uint32_t op1 = ops[3];
13533 auto &type = get<SPIRType>(result_type);
13534 emit_uninitialized_temporary_expression(result_type, result_id);
13535 const char *op = opcode == OpIAddCarry ? "uaddCarry" : "usubBorrow";
13536
13537 statement(to_expression(result_id), ".", to_member_name(type, 0), " = ", op, "(", to_expression(op0), ", ",
13538 to_expression(op1), ", ", to_expression(result_id), ".", to_member_name(type, 1), ");");
13539 break;
13540 }
13541
13542 case OpUMulExtended:
13543 case OpSMulExtended:
13544 {
13545 if (options.es && options.version < 310)
13546 SPIRV_CROSS_THROW("Extended arithmetic is only available from ESSL 310.");
13547 else if (!options.es && options.version < 400)
13548 SPIRV_CROSS_THROW("Extended arithmetic is only available from GLSL 4000.");
13549
13550 uint32_t result_type = ops[0];
13551 uint32_t result_id = ops[1];
13552 uint32_t op0 = ops[2];
13553 uint32_t op1 = ops[3];
13554 auto &type = get<SPIRType>(result_type);
13555 emit_uninitialized_temporary_expression(result_type, result_id);
13556 const char *op = opcode == OpUMulExtended ? "umulExtended" : "imulExtended";
13557
13558 statement(op, "(", to_expression(op0), ", ", to_expression(op1), ", ", to_expression(result_id), ".",
13559 to_member_name(type, 1), ", ", to_expression(result_id), ".", to_member_name(type, 0), ");");
13560 break;
13561 }
13562
13563 case OpFDiv:
13564 GLSL_BOP(/);
13565 break;
13566
13567 case OpShiftRightLogical:
13568 GLSL_BOP_CAST(>>, uint_type);
13569 break;
13570
13571 case OpShiftRightArithmetic:
13572 GLSL_BOP_CAST(>>, int_type);
13573 break;
13574
13575 case OpShiftLeftLogical:
13576 {
13577 auto type = get<SPIRType>(ops[0]).basetype;
13578 GLSL_BOP_CAST(<<, type);
13579 break;
13580 }
13581
13582 case OpBitwiseOr:
13583 {
13584 auto type = get<SPIRType>(ops[0]).basetype;
13585 GLSL_BOP_CAST(|, type);
13586 break;
13587 }
13588
13589 case OpBitwiseXor:
13590 {
13591 auto type = get<SPIRType>(ops[0]).basetype;
13592 GLSL_BOP_CAST(^, type);
13593 break;
13594 }
13595
13596 case OpBitwiseAnd:
13597 {
13598 auto type = get<SPIRType>(ops[0]).basetype;
13599 GLSL_BOP_CAST(&, type);
13600 break;
13601 }
13602
13603 case OpNot:
13604 if (implicit_integer_promotion || expression_type_id(ops[2]) != ops[0])
13605 GLSL_UOP_CAST(~);
13606 else
13607 GLSL_UOP(~);
13608 break;
13609
13610 case OpUMod:
13611 GLSL_BOP_CAST(%, uint_type);
13612 break;
13613
13614 case OpSMod:
13615 GLSL_BOP_CAST(%, int_type);
13616 break;
13617
13618 case OpFMod:
13619 GLSL_BFOP(mod);
13620 break;
13621
13622 case OpFRem:
13623 {
13624 uint32_t result_type = ops[0];
13625 uint32_t result_id = ops[1];
13626 uint32_t op0 = ops[2];
13627 uint32_t op1 = ops[3];
13628
13629 // Needs special handling.
13630 bool forward = should_forward(op0) && should_forward(op1);
13631 std::string expr;
13632 if (!is_legacy())
13633 {
13634 expr = join(to_enclosed_expression(op0), " - ", to_enclosed_expression(op1), " * ", "trunc(",
13635 to_enclosed_expression(op0), " / ", to_enclosed_expression(op1), ")");
13636 }
13637 else
13638 {
13639 // Legacy GLSL has no trunc, emulate by casting to int and back
13640 auto &op0_type = expression_type(op0);
13641 auto via_type = op0_type;
13642 via_type.basetype = SPIRType::Int;
13643 expr = join(to_enclosed_expression(op0), " - ", to_enclosed_expression(op1), " * ",
13644 type_to_glsl(op0_type), "(", type_to_glsl(via_type), "(",
13645 to_enclosed_expression(op0), " / ", to_enclosed_expression(op1), "))");
13646 }
13647
13648 emit_op(result_type, result_id, expr, forward);
13649 inherit_expression_dependencies(result_id, op0);
13650 inherit_expression_dependencies(result_id, op1);
13651 break;
13652 }
13653
13654 // Relational
13655 case OpAny:
13656 GLSL_UFOP(any);
13657 break;
13658
13659 case OpAll:
13660 GLSL_UFOP(all);
13661 break;
13662
13663 case OpSelect:
13664 emit_mix_op(ops[0], ops[1], ops[4], ops[3], ops[2]);
13665 break;
13666
13667 case OpLogicalOr:
13668 {
13669 // No vector variant in GLSL for logical OR.
13670 auto result_type = ops[0];
13671 auto id = ops[1];
13672 auto &type = get<SPIRType>(result_type);
13673
13674 if (type.vecsize > 1)
13675 emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "||", false, SPIRType::Unknown);
13676 else
13677 GLSL_BOP(||);
13678 break;
13679 }
13680
13681 case OpLogicalAnd:
13682 {
13683 // No vector variant in GLSL for logical AND.
13684 auto result_type = ops[0];
13685 auto id = ops[1];
13686 auto &type = get<SPIRType>(result_type);
13687
13688 if (type.vecsize > 1)
13689 emit_unrolled_binary_op(result_type, id, ops[2], ops[3], "&&", false, SPIRType::Unknown);
13690 else
13691 GLSL_BOP(&&);
13692 break;
13693 }
13694
13695 case OpLogicalNot:
13696 {
13697 auto &type = get<SPIRType>(ops[0]);
13698 if (type.vecsize > 1)
13699 GLSL_UFOP(not );
13700 else
13701 GLSL_UOP(!);
13702 break;
13703 }
13704
13705 case OpIEqual:
13706 {
13707 if (expression_type(ops[2]).vecsize > 1)
13708 GLSL_BFOP_CAST(equal, int_type);
13709 else
13710 GLSL_BOP_CAST(==, int_type);
13711 break;
13712 }
13713
13714 case OpLogicalEqual:
13715 case OpFOrdEqual:
13716 {
13717 if (expression_type(ops[2]).vecsize > 1)
13718 GLSL_BFOP(equal);
13719 else
13720 GLSL_BOP(==);
13721 break;
13722 }
13723
13724 case OpINotEqual:
13725 {
13726 if (expression_type(ops[2]).vecsize > 1)
13727 GLSL_BFOP_CAST(notEqual, int_type);
13728 else
13729 GLSL_BOP_CAST(!=, int_type);
13730 break;
13731 }
13732
13733 case OpLogicalNotEqual:
13734 case OpFOrdNotEqual:
13735 case OpFUnordNotEqual:
13736 {
13737 // GLSL is fuzzy on what to do with ordered vs unordered not equal.
13738 // glslang started emitting UnorderedNotEqual some time ago to harmonize with IEEE,
13739 // but this means we have no easy way of implementing ordered not equal.
13740 if (expression_type(ops[2]).vecsize > 1)
13741 GLSL_BFOP(notEqual);
13742 else
13743 GLSL_BOP(!=);
13744 break;
13745 }
13746
13747 case OpUGreaterThan:
13748 case OpSGreaterThan:
13749 {
13750 auto type = opcode == OpUGreaterThan ? uint_type : int_type;
13751 if (expression_type(ops[2]).vecsize > 1)
13752 GLSL_BFOP_CAST(greaterThan, type);
13753 else
13754 GLSL_BOP_CAST(>, type);
13755 break;
13756 }
13757
13758 case OpFOrdGreaterThan:
13759 {
13760 if (expression_type(ops[2]).vecsize > 1)
13761 GLSL_BFOP(greaterThan);
13762 else
13763 GLSL_BOP(>);
13764 break;
13765 }
13766
13767 case OpUGreaterThanEqual:
13768 case OpSGreaterThanEqual:
13769 {
13770 auto type = opcode == OpUGreaterThanEqual ? uint_type : int_type;
13771 if (expression_type(ops[2]).vecsize > 1)
13772 GLSL_BFOP_CAST(greaterThanEqual, type);
13773 else
13774 GLSL_BOP_CAST(>=, type);
13775 break;
13776 }
13777
13778 case OpFOrdGreaterThanEqual:
13779 {
13780 if (expression_type(ops[2]).vecsize > 1)
13781 GLSL_BFOP(greaterThanEqual);
13782 else
13783 GLSL_BOP(>=);
13784 break;
13785 }
13786
13787 case OpULessThan:
13788 case OpSLessThan:
13789 {
13790 auto type = opcode == OpULessThan ? uint_type : int_type;
13791 if (expression_type(ops[2]).vecsize > 1)
13792 GLSL_BFOP_CAST(lessThan, type);
13793 else
13794 GLSL_BOP_CAST(<, type);
13795 break;
13796 }
13797
13798 case OpFOrdLessThan:
13799 {
13800 if (expression_type(ops[2]).vecsize > 1)
13801 GLSL_BFOP(lessThan);
13802 else
13803 GLSL_BOP(<);
13804 break;
13805 }
13806
13807 case OpULessThanEqual:
13808 case OpSLessThanEqual:
13809 {
13810 auto type = opcode == OpULessThanEqual ? uint_type : int_type;
13811 if (expression_type(ops[2]).vecsize > 1)
13812 GLSL_BFOP_CAST(lessThanEqual, type);
13813 else
13814 GLSL_BOP_CAST(<=, type);
13815 break;
13816 }
13817
13818 case OpFOrdLessThanEqual:
13819 {
13820 if (expression_type(ops[2]).vecsize > 1)
13821 GLSL_BFOP(lessThanEqual);
13822 else
13823 GLSL_BOP(<=);
13824 break;
13825 }
13826
13827 // Conversion
13828 case OpSConvert:
13829 case OpConvertSToF:
13830 case OpUConvert:
13831 case OpConvertUToF:
13832 {
13833 auto input_type = opcode == OpSConvert || opcode == OpConvertSToF ? int_type : uint_type;
13834 uint32_t result_type = ops[0];
13835 uint32_t id = ops[1];
13836
13837 auto &type = get<SPIRType>(result_type);
13838 auto &arg_type = expression_type(ops[2]);
13839 auto func = type_to_glsl_constructor(type);
13840
13841 if (arg_type.width < type.width || type_is_floating_point(type))
13842 emit_unary_func_op_cast(result_type, id, ops[2], func.c_str(), input_type, type.basetype);
13843 else
13844 emit_unary_func_op(result_type, id, ops[2], func.c_str());
13845 break;
13846 }
13847
13848 case OpConvertFToU:
13849 case OpConvertFToS:
13850 {
13851 // Cast to expected arithmetic type, then potentially bitcast away to desired signedness.
13852 uint32_t result_type = ops[0];
13853 uint32_t id = ops[1];
13854 auto &type = get<SPIRType>(result_type);
13855 auto expected_type = type;
13856 auto &float_type = expression_type(ops[2]);
13857 expected_type.basetype =
13858 opcode == OpConvertFToS ? to_signed_basetype(type.width) : to_unsigned_basetype(type.width);
13859
13860 auto func = type_to_glsl_constructor(expected_type);
13861 emit_unary_func_op_cast(result_type, id, ops[2], func.c_str(), float_type.basetype, expected_type.basetype);
13862 break;
13863 }
13864
13865 case OpCooperativeMatrixConvertNV:
13866 if (!options.vulkan_semantics)
13867 SPIRV_CROSS_THROW("CooperativeMatrixConvertNV requires vulkan semantics.");
13868 require_extension_internal("GL_NV_cooperative_matrix2");
13869 // fallthrough
13870 case OpFConvert:
13871 {
13872 uint32_t result_type = ops[0];
13873 uint32_t id = ops[1];
13874
13875 auto &type = get<SPIRType>(result_type);
13876
13877 if (type.op == OpTypeCooperativeMatrixKHR && opcode == OpFConvert)
13878 {
13879 auto &expr_type = expression_type(ops[2]);
13880 if (get<SPIRConstant>(type.cooperative.use_id).scalar() !=
13881 get<SPIRConstant>(expr_type.cooperative.use_id).scalar())
13882 {
13883 // Somewhat questionable with spec constant uses.
13884 if (!options.vulkan_semantics)
13885 SPIRV_CROSS_THROW("NV_cooperative_matrix2 requires vulkan semantics.");
13886 require_extension_internal("GL_NV_cooperative_matrix2");
13887 }
13888 }
13889
13890 if ((type.basetype == SPIRType::FloatE4M3 || type.basetype == SPIRType::FloatE5M2) &&
13891 has_decoration(id, spv::DecorationSaturatedToLargestFloat8NormalConversionEXT))
13892 {
13893 emit_uninitialized_temporary_expression(result_type, id);
13894 statement("saturatedConvertEXT(", to_expression(id), ", ", to_unpacked_expression(ops[2]), ");");
13895 }
13896 else
13897 {
13898 auto func = type_to_glsl_constructor(type);
13899 emit_unary_func_op(result_type, id, ops[2], func.c_str());
13900 }
13901 break;
13902 }
13903
13904 case OpBitcast:
13905 {
13906 uint32_t result_type = ops[0];
13907 uint32_t id = ops[1];
13908 uint32_t arg = ops[2];
13909
13910 if (!emit_complex_bitcast(result_type, id, arg))
13911 {
13912 auto op = bitcast_glsl_op(get<SPIRType>(result_type), expression_type(arg));
13913 emit_unary_func_op(result_type, id, arg, op.c_str());
13914 }
13915 break;
13916 }
13917
13918 case OpQuantizeToF16:
13919 {
13920 uint32_t result_type = ops[0];
13921 uint32_t id = ops[1];
13922 uint32_t arg = ops[2];
13923
13924 string op;
13925 auto &type = get<SPIRType>(result_type);
13926
13927 switch (type.vecsize)
13928 {
13929 case 1:
13930 op = join("unpackHalf2x16(packHalf2x16(vec2(", to_expression(arg), "))).x");
13931 break;
13932 case 2:
13933 op = join("unpackHalf2x16(packHalf2x16(", to_expression(arg), "))");
13934 break;
13935 case 3:
13936 {
13937 auto op0 = join("unpackHalf2x16(packHalf2x16(", to_expression(arg), ".xy))");
13938 auto op1 = join("unpackHalf2x16(packHalf2x16(", to_expression(arg), ".zz)).x");
13939 op = join("vec3(", op0, ", ", op1, ")");
13940 break;
13941 }
13942 case 4:
13943 {
13944 auto op0 = join("unpackHalf2x16(packHalf2x16(", to_expression(arg), ".xy))");
13945 auto op1 = join("unpackHalf2x16(packHalf2x16(", to_expression(arg), ".zw))");
13946 op = join("vec4(", op0, ", ", op1, ")");
13947 break;
13948 }
13949 default:
13950 SPIRV_CROSS_THROW("Illegal argument to OpQuantizeToF16.");
13951 }
13952
13953 emit_op(result_type, id, op, should_forward(arg));
13954 inherit_expression_dependencies(id, arg);
13955 break;
13956 }
13957
13958 // Derivatives
13959 case OpDPdx:
13960 GLSL_UFOP(dFdx);
13961 if (is_legacy_es())
13962 require_extension_internal("GL_OES_standard_derivatives");
13963 register_control_dependent_expression(ops[1]);
13964 break;
13965
13966 case OpDPdy:
13967 GLSL_UFOP(dFdy);
13968 if (is_legacy_es())
13969 require_extension_internal("GL_OES_standard_derivatives");
13970 register_control_dependent_expression(ops[1]);
13971 break;
13972
13973 case OpDPdxFine:
13974 GLSL_UFOP(dFdxFine);
13975 if (options.es)
13976 {
13977 SPIRV_CROSS_THROW("GL_ARB_derivative_control is unavailable in OpenGL ES.");
13978 }
13979 if (options.version < 450)
13980 require_extension_internal("GL_ARB_derivative_control");
13981 register_control_dependent_expression(ops[1]);
13982 break;
13983
13984 case OpDPdyFine:
13985 GLSL_UFOP(dFdyFine);
13986 if (options.es)
13987 {
13988 SPIRV_CROSS_THROW("GL_ARB_derivative_control is unavailable in OpenGL ES.");
13989 }
13990 if (options.version < 450)
13991 require_extension_internal("GL_ARB_derivative_control");
13992 register_control_dependent_expression(ops[1]);
13993 break;
13994
13995 case OpDPdxCoarse:
13996 if (options.es)
13997 {
13998 SPIRV_CROSS_THROW("GL_ARB_derivative_control is unavailable in OpenGL ES.");
13999 }
14000 GLSL_UFOP(dFdxCoarse);
14001 if (options.version < 450)
14002 require_extension_internal("GL_ARB_derivative_control");
14003 register_control_dependent_expression(ops[1]);
14004 break;
14005
14006 case OpDPdyCoarse:
14007 GLSL_UFOP(dFdyCoarse);
14008 if (options.es)
14009 {
14010 SPIRV_CROSS_THROW("GL_ARB_derivative_control is unavailable in OpenGL ES.");
14011 }
14012 if (options.version < 450)
14013 require_extension_internal("GL_ARB_derivative_control");
14014 register_control_dependent_expression(ops[1]);
14015 break;
14016
14017 case OpFwidth:
14018 GLSL_UFOP(fwidth);
14019 if (is_legacy_es())
14020 require_extension_internal("GL_OES_standard_derivatives");
14021 register_control_dependent_expression(ops[1]);
14022 break;
14023
14024 case OpFwidthCoarse:
14025 GLSL_UFOP(fwidthCoarse);
14026 if (options.es)
14027 {
14028 SPIRV_CROSS_THROW("GL_ARB_derivative_control is unavailable in OpenGL ES.");
14029 }
14030 if (options.version < 450)
14031 require_extension_internal("GL_ARB_derivative_control");
14032 register_control_dependent_expression(ops[1]);
14033 break;
14034
14035 case OpFwidthFine:
14036 GLSL_UFOP(fwidthFine);
14037 if (options.es)
14038 {
14039 SPIRV_CROSS_THROW("GL_ARB_derivative_control is unavailable in OpenGL ES.");
14040 }
14041 if (options.version < 450)
14042 require_extension_internal("GL_ARB_derivative_control");
14043 register_control_dependent_expression(ops[1]);
14044 break;
14045
14046 // Bitfield
14047 case OpBitFieldInsert:
14048 {
14049 emit_bitfield_insert_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], "bitfieldInsert", SPIRType::Int);
14050 break;
14051 }
14052
14053 case OpBitFieldSExtract:
14054 {
14055 emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "bitfieldExtract", int_type, int_type,
14056 SPIRType::Int, SPIRType::Int);
14057 break;
14058 }
14059
14060 case OpBitFieldUExtract:
14061 {
14062 emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "bitfieldExtract", uint_type, uint_type,
14063 SPIRType::Int, SPIRType::Int);
14064 break;
14065 }
14066
14067 case OpBitReverse:
14068 // BitReverse does not have issues with sign since result type must match input type.
14069 GLSL_UFOP(bitfieldReverse);
14070 break;
14071
14072 case OpBitCount:
14073 {
14074 auto basetype = expression_type(ops[2]).basetype;
14075 emit_unary_func_op_cast(ops[0], ops[1], ops[2], "bitCount", basetype, int_type);
14076 break;
14077 }
14078
14079 // Atomics
14080 case OpAtomicExchange:
14081 {
14082 uint32_t result_type = ops[0];
14083 uint32_t id = ops[1];
14084 uint32_t ptr = ops[2];
14085 // Ignore semantics for now, probably only relevant to CL.
14086 uint32_t val = ops[5];
14087 const char *op = check_atomic_image(ptr) ? "imageAtomicExchange" : "atomicExchange";
14088
14089 emit_atomic_func_op(result_type, id, ptr, val, op);
14090 break;
14091 }
14092
14093 case OpAtomicCompareExchange:
14094 {
14095 uint32_t result_type = ops[0];
14096 uint32_t id = ops[1];
14097 uint32_t ptr = ops[2];
14098 uint32_t val = ops[6];
14099 uint32_t comp = ops[7];
14100 const char *op = check_atomic_image(ptr) ? "imageAtomicCompSwap" : "atomicCompSwap";
14101
14102 emit_atomic_func_op(result_type, id, ptr, comp, val, op);
14103 break;
14104 }
14105
14106 case OpAtomicLoad:
14107 {
14108 // In plain GLSL, we have no atomic loads, so emulate this by fetch adding by 0 and hope compiler figures it out.
14109 // Alternatively, we could rely on KHR_memory_model, but that's not very helpful for GL.
14110 auto &type = expression_type(ops[2]);
14111 forced_temporaries.insert(ops[1]);
14112 bool atomic_image = check_atomic_image(ops[2]);
14113 bool unsigned_type = (type.basetype == SPIRType::UInt) ||
14114 (atomic_image && get<SPIRType>(type.image.type).basetype == SPIRType::UInt);
14115 const char *op = atomic_image ? "imageAtomicAdd" : "atomicAdd";
14116 const char *increment = unsigned_type ? "0u" : "0";
14117 emit_op(ops[0], ops[1],
14118 join(op, "(",
14119 to_atomic_ptr_expression(ops[2]), ", ", increment, ")"), false);
14120 flush_all_atomic_capable_variables();
14121
14122 if (type.basetype == SPIRType::UInt64 || type.basetype == SPIRType::Int64)
14123 require_extension_internal("GL_EXT_shader_atomic_int64");
14124 break;
14125 }
14126
14127 case OpAtomicStore:
14128 {
14129 // In plain GLSL, we have no atomic stores, so emulate this with an atomic exchange where we don't consume the result.
14130 // Alternatively, we could rely on KHR_memory_model, but that's not very helpful for GL.
14131 uint32_t ptr = ops[0];
14132 // Ignore semantics for now, probably only relevant to CL.
14133 uint32_t val = ops[3];
14134 const char *op = check_atomic_image(ptr) ? "imageAtomicExchange" : "atomicExchange";
14135 statement(op, "(", to_atomic_ptr_expression(ptr), ", ", to_expression(val), ");");
14136 flush_all_atomic_capable_variables();
14137
14138 auto &type = expression_type(ptr);
14139 if (type.basetype == SPIRType::UInt64 || type.basetype == SPIRType::Int64)
14140 require_extension_internal("GL_EXT_shader_atomic_int64");
14141 break;
14142 }
14143
14144 case OpAtomicIIncrement:
14145 case OpAtomicIDecrement:
14146 {
14147 forced_temporaries.insert(ops[1]);
14148 auto &type = expression_type(ops[2]);
14149 if (type.storage == StorageClassAtomicCounter)
14150 {
14151 // Legacy GLSL stuff, not sure if this is relevant to support.
14152 if (opcode == OpAtomicIIncrement)
14153 GLSL_UFOP(atomicCounterIncrement);
14154 else
14155 GLSL_UFOP(atomicCounterDecrement);
14156 }
14157 else
14158 {
14159 bool atomic_image = check_atomic_image(ops[2]);
14160 bool unsigned_type = (type.basetype == SPIRType::UInt) ||
14161 (atomic_image && get<SPIRType>(type.image.type).basetype == SPIRType::UInt);
14162 const char *op = atomic_image ? "imageAtomicAdd" : "atomicAdd";
14163
14164 const char *increment = nullptr;
14165 if (opcode == OpAtomicIIncrement && unsigned_type)
14166 increment = "1u";
14167 else if (opcode == OpAtomicIIncrement)
14168 increment = "1";
14169 else if (unsigned_type)
14170 increment = "uint(-1)";
14171 else
14172 increment = "-1";
14173
14174 emit_op(ops[0], ops[1],
14175 join(op, "(", to_atomic_ptr_expression(ops[2]), ", ", increment, ")"), false);
14176
14177 if (type.basetype == SPIRType::UInt64 || type.basetype == SPIRType::Int64)
14178 require_extension_internal("GL_EXT_shader_atomic_int64");
14179 }
14180
14181 flush_all_atomic_capable_variables();
14182 break;
14183 }
14184
14185 case OpAtomicIAdd:
14186 case OpAtomicFAddEXT:
14187 {
14188 const char *op = check_atomic_image(ops[2]) ? "imageAtomicAdd" : "atomicAdd";
14189 emit_atomic_func_op(ops[0], ops[1], ops[2], ops[5], op);
14190 break;
14191 }
14192
14193 case OpAtomicISub:
14194 {
14195 const char *op = check_atomic_image(ops[2]) ? "imageAtomicAdd" : "atomicAdd";
14196 forced_temporaries.insert(ops[1]);
14197 auto expr = join(op, "(", to_atomic_ptr_expression(ops[2]), ", -", to_enclosed_expression(ops[5]), ")");
14198 emit_op(ops[0], ops[1], expr, should_forward(ops[2]) && should_forward(ops[5]));
14199 flush_all_atomic_capable_variables();
14200
14201 auto &type = get<SPIRType>(ops[0]);
14202 if (type.basetype == SPIRType::UInt64 || type.basetype == SPIRType::Int64)
14203 require_extension_internal("GL_EXT_shader_atomic_int64");
14204 break;
14205 }
14206
14207 case OpAtomicSMin:
14208 case OpAtomicUMin:
14209 {
14210 const char *op = check_atomic_image(ops[2]) ? "imageAtomicMin" : "atomicMin";
14211 emit_atomic_func_op(ops[0], ops[1], ops[2], ops[5], op);
14212 break;
14213 }
14214
14215 case OpAtomicSMax:
14216 case OpAtomicUMax:
14217 {
14218 const char *op = check_atomic_image(ops[2]) ? "imageAtomicMax" : "atomicMax";
14219 emit_atomic_func_op(ops[0], ops[1], ops[2], ops[5], op);
14220 break;
14221 }
14222
14223 case OpAtomicAnd:
14224 {
14225 const char *op = check_atomic_image(ops[2]) ? "imageAtomicAnd" : "atomicAnd";
14226 emit_atomic_func_op(ops[0], ops[1], ops[2], ops[5], op);
14227 break;
14228 }
14229
14230 case OpAtomicOr:
14231 {
14232 const char *op = check_atomic_image(ops[2]) ? "imageAtomicOr" : "atomicOr";
14233 emit_atomic_func_op(ops[0], ops[1], ops[2], ops[5], op);
14234 break;
14235 }
14236
14237 case OpAtomicXor:
14238 {
14239 const char *op = check_atomic_image(ops[2]) ? "imageAtomicXor" : "atomicXor";
14240 emit_atomic_func_op(ops[0], ops[1], ops[2], ops[5], op);
14241 break;
14242 }
14243
14244 // Geometry shaders
14245 case OpEmitVertex:
14246 statement("EmitVertex();");
14247 break;
14248
14249 case OpEndPrimitive:
14250 statement("EndPrimitive();");
14251 break;
14252
14253 case OpEmitStreamVertex:
14254 {
14255 if (options.es)
14256 SPIRV_CROSS_THROW("Multi-stream geometry shaders not supported in ES.");
14257 else if (!options.es && options.version < 400)
14258 SPIRV_CROSS_THROW("Multi-stream geometry shaders only supported in GLSL 400.");
14259
14260 auto stream_expr = to_expression(ops[0]);
14261 if (expression_type(ops[0]).basetype != SPIRType::Int)
14262 stream_expr = join("int(", stream_expr, ")");
14263 statement("EmitStreamVertex(", stream_expr, ");");
14264 break;
14265 }
14266
14267 case OpEndStreamPrimitive:
14268 {
14269 if (options.es)
14270 SPIRV_CROSS_THROW("Multi-stream geometry shaders not supported in ES.");
14271 else if (!options.es && options.version < 400)
14272 SPIRV_CROSS_THROW("Multi-stream geometry shaders only supported in GLSL 400.");
14273
14274 auto stream_expr = to_expression(ops[0]);
14275 if (expression_type(ops[0]).basetype != SPIRType::Int)
14276 stream_expr = join("int(", stream_expr, ")");
14277 statement("EndStreamPrimitive(", stream_expr, ");");
14278 break;
14279 }
14280
14281 // Textures
14282 case OpImageSampleExplicitLod:
14283 case OpImageSampleProjExplicitLod:
14284 case OpImageSampleDrefExplicitLod:
14285 case OpImageSampleProjDrefExplicitLod:
14286 case OpImageSampleImplicitLod:
14287 case OpImageSampleProjImplicitLod:
14288 case OpImageSampleDrefImplicitLod:
14289 case OpImageSampleProjDrefImplicitLod:
14290 case OpImageFetch:
14291 case OpImageGather:
14292 case OpImageDrefGather:
14293 // Gets a bit hairy, so move this to a separate instruction.
14294 emit_texture_op(instruction, false);
14295 break;
14296
14297 case OpImageSparseSampleExplicitLod:
14298 case OpImageSparseSampleProjExplicitLod:
14299 case OpImageSparseSampleDrefExplicitLod:
14300 case OpImageSparseSampleProjDrefExplicitLod:
14301 case OpImageSparseSampleImplicitLod:
14302 case OpImageSparseSampleProjImplicitLod:
14303 case OpImageSparseSampleDrefImplicitLod:
14304 case OpImageSparseSampleProjDrefImplicitLod:
14305 case OpImageSparseFetch:
14306 case OpImageSparseGather:
14307 case OpImageSparseDrefGather:
14308 // Gets a bit hairy, so move this to a separate instruction.
14309 emit_texture_op(instruction, true);
14310 break;
14311
14312 case OpImageSparseTexelsResident:
14313 if (options.es)
14314 SPIRV_CROSS_THROW("Sparse feedback is not supported in GLSL.");
14315 require_extension_internal("GL_ARB_sparse_texture2");
14316 emit_unary_func_op_cast(ops[0], ops[1], ops[2], "sparseTexelsResidentARB", int_type, SPIRType::Boolean);
14317 break;
14318
14319 case OpImage:
14320 {
14321 uint32_t result_type = ops[0];
14322 uint32_t id = ops[1];
14323
14324 // Suppress usage tracking.
14325 auto &e = emit_op(result_type, id, to_expression(ops[2]), true, true);
14326
14327 // When using the image, we need to know which variable it is actually loaded from.
14328 auto *var = maybe_get_backing_variable(ops[2]);
14329 e.loaded_from = var ? var->self : ID(0);
14330 break;
14331 }
14332
14333 case OpImageQueryLod:
14334 {
14335 const char *op = nullptr;
14336 if (!options.es && options.version < 400)
14337 {
14338 require_extension_internal("GL_ARB_texture_query_lod");
14339 // For some reason, the ARB spec is all-caps.
14340 op = "textureQueryLOD";
14341 }
14342 else if (options.es)
14343 {
14344 if (options.version < 300)
14345 SPIRV_CROSS_THROW("textureQueryLod not supported in legacy ES");
14346 require_extension_internal("GL_EXT_texture_query_lod");
14347 op = "textureQueryLOD";
14348 }
14349 else
14350 op = "textureQueryLod";
14351
14352 auto sampler_expr = to_expression(ops[2]);
14353 if (has_decoration(ops[2], DecorationNonUniform))
14354 {
14355 if (maybe_get_backing_variable(ops[2]))
14356 convert_non_uniform_expression(sampler_expr, ops[2]);
14357 else if (*backend.nonuniform_qualifier != '\0')
14358 sampler_expr = join(backend.nonuniform_qualifier, "(", sampler_expr, ")");
14359 }
14360
14361 bool forward = should_forward(ops[3]);
14362 emit_op(ops[0], ops[1],
14363 join(op, "(", sampler_expr, ", ", to_unpacked_expression(ops[3]), ")"),
14364 forward);
14365 inherit_expression_dependencies(ops[1], ops[2]);
14366 inherit_expression_dependencies(ops[1], ops[3]);
14367 register_control_dependent_expression(ops[1]);
14368 break;
14369 }
14370
14371 case OpImageQueryLevels:
14372 {
14373 uint32_t result_type = ops[0];
14374 uint32_t id = ops[1];
14375
14376 if (!options.es && options.version < 430)
14377 require_extension_internal("GL_ARB_texture_query_levels");
14378 if (options.es)
14379 SPIRV_CROSS_THROW("textureQueryLevels not supported in ES profile.");
14380
14381 auto expr = join("textureQueryLevels(", convert_separate_image_to_expression(ops[2]), ")");
14382 auto &restype = get<SPIRType>(ops[0]);
14383 expr = bitcast_expression(restype, SPIRType::Int, expr);
14384 emit_op(result_type, id, expr, true);
14385 break;
14386 }
14387
14388 case OpImageQuerySamples:
14389 {
14390 auto &type = expression_type(ops[2]);
14391 uint32_t result_type = ops[0];
14392 uint32_t id = ops[1];
14393
14394 if (options.es)
14395 SPIRV_CROSS_THROW("textureSamples and imageSamples not supported in ES profile.");
14396 else if (options.version < 450)
14397 require_extension_internal("GL_ARB_texture_query_samples");
14398
14399 string expr;
14400 if (type.image.sampled == 2)
14401 expr = join("imageSamples(", to_non_uniform_aware_expression(ops[2]), ")");
14402 else
14403 expr = join("textureSamples(", convert_separate_image_to_expression(ops[2]), ")");
14404
14405 auto &restype = get<SPIRType>(ops[0]);
14406 expr = bitcast_expression(restype, SPIRType::Int, expr);
14407 emit_op(result_type, id, expr, true);
14408 break;
14409 }
14410
14411 case OpSampledImage:
14412 {
14413 uint32_t result_type = ops[0];
14414 uint32_t id = ops[1];
14415 emit_sampled_image_op(result_type, id, ops[2], ops[3]);
14416 inherit_expression_dependencies(id, ops[2]);
14417 inherit_expression_dependencies(id, ops[3]);
14418 break;
14419 }
14420
14421 case OpImageQuerySizeLod:
14422 {
14423 uint32_t result_type = ops[0];
14424 uint32_t id = ops[1];
14425 uint32_t img = ops[2];
14426 auto &type = expression_type(img);
14427 auto &imgtype = get<SPIRType>(type.self);
14428
14429 std::string fname = "textureSize";
14430 if (is_legacy_desktop())
14431 {
14432 fname = legacy_tex_op(fname, imgtype, img);
14433 }
14434 else if (is_legacy_es())
14435 SPIRV_CROSS_THROW("textureSize is not supported in ESSL 100.");
14436
14437 auto expr = join(fname, "(", convert_separate_image_to_expression(img), ", ",
14438 bitcast_expression(SPIRType::Int, ops[3]), ")");
14439
14440 // ES needs to emulate 1D images as 2D.
14441 if (type.image.dim == Dim1D && options.es)
14442 expr = join(expr, ".x");
14443
14444 auto &restype = get<SPIRType>(ops[0]);
14445 expr = bitcast_expression(restype, SPIRType::Int, expr);
14446 emit_op(result_type, id, expr, true);
14447 break;
14448 }
14449
14450 // Image load/store
14451 case OpImageRead:
14452 case OpImageSparseRead:
14453 {
14454 // We added Nonreadable speculatively to the OpImage variable due to glslangValidator
14455 // not adding the proper qualifiers.
14456 // If it turns out we need to read the image after all, remove the qualifier and recompile.
14457 auto *var = maybe_get_backing_variable(ops[2]);
14458 if (var)
14459 {
14460 auto &flags = get_decoration_bitset(var->self);
14461 if (flags.get(DecorationNonReadable))
14462 {
14463 unset_decoration(var->self, DecorationNonReadable);
14464 force_recompile();
14465 }
14466 }
14467
14468 uint32_t result_type = ops[0];
14469 uint32_t id = ops[1];
14470
14471 bool pure;
14472 string imgexpr;
14473 auto &type = expression_type(ops[2]);
14474
14475 if (var && var->remapped_variable) // Remapped input, just read as-is without any op-code
14476 {
14477 if (type.image.ms)
14478 SPIRV_CROSS_THROW("Trying to remap multisampled image to variable, this is not possible.");
14479
14480 auto itr =
14481 find_if(begin(pls_inputs), end(pls_inputs), [var](const PlsRemap &pls) { return pls.id == var->self; });
14482
14483 if (itr == end(pls_inputs))
14484 {
14485 // For non-PLS inputs, we rely on subpass type remapping information to get it right
14486 // since ImageRead always returns 4-component vectors and the backing type is opaque.
14487 if (!var->remapped_components)
14488 SPIRV_CROSS_THROW("subpassInput was remapped, but remap_components is not set correctly.");
14489 imgexpr = remap_swizzle(get<SPIRType>(result_type), var->remapped_components, to_expression(ops[2]));
14490 }
14491 else
14492 {
14493 // PLS input could have different number of components than what the SPIR expects, swizzle to
14494 // the appropriate vector size.
14495 uint32_t components = pls_format_to_components(itr->format);
14496 imgexpr = remap_swizzle(get<SPIRType>(result_type), components, to_expression(ops[2]));
14497 }
14498 pure = true;
14499 }
14500 else if (type.image.dim == DimSubpassData)
14501 {
14502 if (var && subpass_input_is_framebuffer_fetch(var->self))
14503 {
14504 imgexpr = to_expression(var->self);
14505 }
14506 else if (options.vulkan_semantics)
14507 {
14508 // With Vulkan semantics, use the proper Vulkan GLSL construct.
14509 if (type.image.ms)
14510 {
14511 uint32_t operands = ops[4];
14512 if (operands != ImageOperandsSampleMask || length != 6)
14513 SPIRV_CROSS_THROW("Multisampled image used in OpImageRead, but unexpected "
14514 "operand mask was used.");
14515
14516 uint32_t samples = ops[5];
14517 imgexpr = join("subpassLoad(", to_non_uniform_aware_expression(ops[2]), ", ", to_expression(samples), ")");
14518 }
14519 else
14520 imgexpr = join("subpassLoad(", to_non_uniform_aware_expression(ops[2]), ")");
14521 }
14522 else
14523 {
14524 if (type.image.ms)
14525 {
14526 uint32_t operands = ops[4];
14527 if (operands != ImageOperandsSampleMask || length != 6)
14528 SPIRV_CROSS_THROW("Multisampled image used in OpImageRead, but unexpected "
14529 "operand mask was used.");
14530
14531 uint32_t samples = ops[5];
14532 imgexpr = join("texelFetch(", to_non_uniform_aware_expression(ops[2]), ", ivec2(gl_FragCoord.xy), ",
14533 to_expression(samples), ")");
14534 }
14535 else
14536 {
14537 // Implement subpass loads via texture barrier style sampling.
14538 imgexpr = join("texelFetch(", to_non_uniform_aware_expression(ops[2]), ", ivec2(gl_FragCoord.xy), 0)");
14539 }
14540 }
14541 imgexpr = remap_swizzle(get<SPIRType>(result_type), 4, imgexpr);
14542 pure = true;
14543 }
14544 else
14545 {
14546 bool sparse = opcode == OpImageSparseRead;
14547 uint32_t sparse_code_id = 0;
14548 uint32_t sparse_texel_id = 0;
14549 if (sparse)
14550 emit_sparse_feedback_temporaries(ops[0], ops[1], sparse_code_id, sparse_texel_id);
14551
14552 // imageLoad only accepts int coords, not uint.
14553 auto coord_expr = to_expression(ops[3]);
14554 auto target_coord_type = expression_type(ops[3]);
14555 target_coord_type.basetype = SPIRType::Int;
14556 coord_expr = bitcast_expression(target_coord_type, expression_type(ops[3]).basetype, coord_expr);
14557
14558 // ES needs to emulate 1D images as 2D.
14559 if (type.image.dim == Dim1D && options.es)
14560 coord_expr = join("ivec2(", coord_expr, ", 0)");
14561
14562 // Plain image load/store.
14563 if (sparse)
14564 {
14565 if (type.image.ms)
14566 {
14567 uint32_t operands = ops[4];
14568 if (operands != ImageOperandsSampleMask || length != 6)
14569 SPIRV_CROSS_THROW("Multisampled image used in OpImageRead, but unexpected "
14570 "operand mask was used.");
14571
14572 uint32_t samples = ops[5];
14573 statement(to_expression(sparse_code_id), " = sparseImageLoadARB(", to_non_uniform_aware_expression(ops[2]), ", ",
14574 coord_expr, ", ", to_expression(samples), ", ", to_expression(sparse_texel_id), ");");
14575 }
14576 else
14577 {
14578 statement(to_expression(sparse_code_id), " = sparseImageLoadARB(", to_non_uniform_aware_expression(ops[2]), ", ",
14579 coord_expr, ", ", to_expression(sparse_texel_id), ");");
14580 }
14581 imgexpr = join(type_to_glsl(get<SPIRType>(result_type)), "(", to_expression(sparse_code_id), ", ",
14582 to_expression(sparse_texel_id), ")");
14583 }
14584 else
14585 {
14586 if (type.image.ms)
14587 {
14588 uint32_t operands = ops[4];
14589 if (operands != ImageOperandsSampleMask || length != 6)
14590 SPIRV_CROSS_THROW("Multisampled image used in OpImageRead, but unexpected "
14591 "operand mask was used.");
14592
14593 uint32_t samples = ops[5];
14594 imgexpr =
14595 join("imageLoad(", to_non_uniform_aware_expression(ops[2]), ", ", coord_expr, ", ", to_expression(samples), ")");
14596 }
14597 else
14598 imgexpr = join("imageLoad(", to_non_uniform_aware_expression(ops[2]), ", ", coord_expr, ")");
14599 }
14600
14601 if (!sparse)
14602 imgexpr = remap_swizzle(get<SPIRType>(result_type), 4, imgexpr);
14603 pure = false;
14604 }
14605
14606 if (var)
14607 {
14608 bool forward = forced_temporaries.find(id) == end(forced_temporaries);
14609 auto &e = emit_op(result_type, id, imgexpr, forward);
14610
14611 // We only need to track dependencies if we're reading from image load/store.
14612 if (!pure)
14613 {
14614 e.loaded_from = var->self;
14615 if (forward)
14616 var->dependees.push_back(id);
14617 }
14618 }
14619 else
14620 emit_op(result_type, id, imgexpr, false);
14621
14622 inherit_expression_dependencies(id, ops[2]);
14623 if (type.image.ms)
14624 inherit_expression_dependencies(id, ops[5]);
14625 break;
14626 }
14627
14628 case OpImageTexelPointer:
14629 {
14630 uint32_t result_type = ops[0];
14631 uint32_t id = ops[1];
14632
14633 auto coord_expr = to_expression(ops[3]);
14634 auto target_coord_type = expression_type(ops[3]);
14635 target_coord_type.basetype = SPIRType::Int;
14636 coord_expr = bitcast_expression(target_coord_type, expression_type(ops[3]).basetype, coord_expr);
14637
14638 auto expr = join(to_expression(ops[2]), ", ", coord_expr);
14639 auto &e = set<SPIRExpression>(id, expr, result_type, true);
14640
14641 // When using the pointer, we need to know which variable it is actually loaded from.
14642 auto *var = maybe_get_backing_variable(ops[2]);
14643 e.loaded_from = var ? var->self : ID(0);
14644 inherit_expression_dependencies(id, ops[3]);
14645 break;
14646 }
14647
14648 case OpImageWrite:
14649 {
14650 // We added Nonwritable speculatively to the OpImage variable due to glslangValidator
14651 // not adding the proper qualifiers.
14652 // If it turns out we need to write to the image after all, remove the qualifier and recompile.
14653 auto *var = maybe_get_backing_variable(ops[0]);
14654 if (var)
14655 {
14656 if (has_decoration(var->self, DecorationNonWritable))
14657 {
14658 unset_decoration(var->self, DecorationNonWritable);
14659 force_recompile();
14660 }
14661 }
14662
14663 auto &type = expression_type(ops[0]);
14664 auto &value_type = expression_type(ops[2]);
14665 auto store_type = value_type;
14666 store_type.vecsize = 4;
14667
14668 // imageStore only accepts int coords, not uint.
14669 auto coord_expr = to_expression(ops[1]);
14670 auto target_coord_type = expression_type(ops[1]);
14671 target_coord_type.basetype = SPIRType::Int;
14672 coord_expr = bitcast_expression(target_coord_type, expression_type(ops[1]).basetype, coord_expr);
14673
14674 // ES needs to emulate 1D images as 2D.
14675 if (type.image.dim == Dim1D && options.es)
14676 coord_expr = join("ivec2(", coord_expr, ", 0)");
14677
14678 if (type.image.ms)
14679 {
14680 uint32_t operands = ops[3];
14681 if (operands != ImageOperandsSampleMask || length != 5)
14682 SPIRV_CROSS_THROW("Multisampled image used in OpImageWrite, but unexpected operand mask was used.");
14683 uint32_t samples = ops[4];
14684 statement("imageStore(", to_non_uniform_aware_expression(ops[0]), ", ", coord_expr, ", ", to_expression(samples), ", ",
14685 remap_swizzle(store_type, value_type.vecsize, to_expression(ops[2])), ");");
14686 }
14687 else
14688 statement("imageStore(", to_non_uniform_aware_expression(ops[0]), ", ", coord_expr, ", ",
14689 remap_swizzle(store_type, value_type.vecsize, to_expression(ops[2])), ");");
14690
14691 if (var && variable_storage_is_aliased(*var))
14692 flush_all_aliased_variables();
14693 break;
14694 }
14695
14696 case OpImageQuerySize:
14697 {
14698 auto &type = expression_type(ops[2]);
14699 uint32_t result_type = ops[0];
14700 uint32_t id = ops[1];
14701
14702 if (type.basetype == SPIRType::Image)
14703 {
14704 string expr;
14705 if (type.image.sampled == 2)
14706 {
14707 if (!options.es && options.version < 430)
14708 require_extension_internal("GL_ARB_shader_image_size");
14709 else if (options.es && options.version < 310)
14710 SPIRV_CROSS_THROW("At least ESSL 3.10 required for imageSize.");
14711
14712 // The size of an image is always constant.
14713 expr = join("imageSize(", to_non_uniform_aware_expression(ops[2]), ")");
14714 }
14715 else
14716 {
14717 // This path is hit for samplerBuffers and multisampled images which do not have LOD.
14718 std::string fname = "textureSize";
14719 if (is_legacy())
14720 {
14721 auto &imgtype = get<SPIRType>(type.self);
14722 fname = legacy_tex_op(fname, imgtype, ops[2]);
14723 }
14724 expr = join(fname, "(", convert_separate_image_to_expression(ops[2]), ")");
14725 }
14726
14727 auto &restype = get<SPIRType>(ops[0]);
14728 expr = bitcast_expression(restype, SPIRType::Int, expr);
14729 emit_op(result_type, id, expr, true);
14730 }
14731 else
14732 SPIRV_CROSS_THROW("Invalid type for OpImageQuerySize.");
14733 break;
14734 }
14735
14736 case OpImageSampleWeightedQCOM:
14737 case OpImageBoxFilterQCOM:
14738 case OpImageBlockMatchSSDQCOM:
14739 case OpImageBlockMatchSADQCOM:
14740 {
14741 require_extension_internal("GL_QCOM_image_processing");
14742 uint32_t result_type_id = ops[0];
14743 uint32_t id = ops[1];
14744 string expr;
14745 switch (opcode)
14746 {
14747 case OpImageSampleWeightedQCOM:
14748 expr = "textureWeightedQCOM";
14749 break;
14750 case OpImageBoxFilterQCOM:
14751 expr = "textureBoxFilterQCOM";
14752 break;
14753 case OpImageBlockMatchSSDQCOM:
14754 expr = "textureBlockMatchSSDQCOM";
14755 break;
14756 case OpImageBlockMatchSADQCOM:
14757 expr = "textureBlockMatchSADQCOM";
14758 break;
14759 default:
14760 SPIRV_CROSS_THROW("Invalid opcode for QCOM_image_processing.");
14761 }
14762 expr += "(";
14763
14764 bool forward = false;
14765 expr += to_expression(ops[2]);
14766 expr += ", " + to_expression(ops[3]);
14767
14768 switch (opcode)
14769 {
14770 case OpImageSampleWeightedQCOM:
14771 expr += ", " + to_non_uniform_aware_expression(ops[4]);
14772 break;
14773 case OpImageBoxFilterQCOM:
14774 expr += ", " + to_expression(ops[4]);
14775 break;
14776 case OpImageBlockMatchSSDQCOM:
14777 case OpImageBlockMatchSADQCOM:
14778 expr += ", " + to_non_uniform_aware_expression(ops[4]);
14779 expr += ", " + to_expression(ops[5]);
14780 expr += ", " + to_expression(ops[6]);
14781 break;
14782 default:
14783 SPIRV_CROSS_THROW("Invalid opcode for QCOM_image_processing.");
14784 }
14785
14786 expr += ")";
14787 emit_op(result_type_id, id, expr, forward);
14788
14789 inherit_expression_dependencies(id, ops[3]);
14790 if (opcode == OpImageBlockMatchSSDQCOM || opcode == OpImageBlockMatchSADQCOM)
14791 inherit_expression_dependencies(id, ops[5]);
14792
14793 break;
14794 }
14795
14796 case OpImageBlockMatchWindowSSDQCOM:
14797 case OpImageBlockMatchWindowSADQCOM:
14798 case OpImageBlockMatchGatherSSDQCOM:
14799 case OpImageBlockMatchGatherSADQCOM:
14800 {
14801 require_extension_internal("GL_QCOM_image_processing2");
14802 uint32_t result_type_id = ops[0];
14803 uint32_t id = ops[1];
14804 string expr;
14805 switch (opcode)
14806 {
14807 case OpImageBlockMatchWindowSSDQCOM:
14808 expr = "textureBlockMatchWindowSSDQCOM";
14809 break;
14810 case OpImageBlockMatchWindowSADQCOM:
14811 expr = "textureBlockMatchWindowSADQCOM";
14812 break;
14813 case OpImageBlockMatchGatherSSDQCOM:
14814 expr = "textureBlockMatchGatherSSDQCOM";
14815 break;
14816 case OpImageBlockMatchGatherSADQCOM:
14817 expr = "textureBlockMatchGatherSADQCOM";
14818 break;
14819 default:
14820 SPIRV_CROSS_THROW("Invalid opcode for QCOM_image_processing2.");
14821 }
14822 expr += "(";
14823
14824 bool forward = false;
14825 expr += to_expression(ops[2]);
14826 expr += ", " + to_expression(ops[3]);
14827
14828 expr += ", " + to_non_uniform_aware_expression(ops[4]);
14829 expr += ", " + to_expression(ops[5]);
14830 expr += ", " + to_expression(ops[6]);
14831
14832 expr += ")";
14833 emit_op(result_type_id, id, expr, forward);
14834
14835 inherit_expression_dependencies(id, ops[3]);
14836 inherit_expression_dependencies(id, ops[5]);
14837 break;
14838 }
14839
14840 // Compute
14841 case OpControlBarrier:
14842 case OpMemoryBarrier:
14843 {
14844 uint32_t execution_scope = 0;
14845 uint32_t memory;
14846 uint32_t semantics;
14847
14848 if (opcode == OpMemoryBarrier)
14849 {
14850 memory = evaluate_constant_u32(ops[0]);
14851 semantics = evaluate_constant_u32(ops[1]);
14852 }
14853 else
14854 {
14855 execution_scope = evaluate_constant_u32(ops[0]);
14856 memory = evaluate_constant_u32(ops[1]);
14857 semantics = evaluate_constant_u32(ops[2]);
14858 }
14859
14860 if (execution_scope == ScopeSubgroup || memory == ScopeSubgroup)
14861 {
14862 // OpControlBarrier with ScopeSubgroup is subgroupBarrier()
14863 if (opcode != OpControlBarrier)
14864 {
14865 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupMemBarrier);
14866 }
14867 else
14868 {
14869 request_subgroup_feature(ShaderSubgroupSupportHelper::SubgroupBarrier);
14870 }
14871 }
14872
14873 if (execution_scope != ScopeSubgroup && get_entry_point().model == ExecutionModelTessellationControl)
14874 {
14875 // Control shaders only have barriers, and it implies memory barriers.
14876 if (opcode == OpControlBarrier)
14877 statement("barrier();");
14878 break;
14879 }
14880
14881 // We only care about these flags, acquire/release and friends are not relevant to GLSL.
14882 semantics = mask_relevant_memory_semantics(semantics);
14883
14884 if (opcode == OpMemoryBarrier)
14885 {
14886 // If we are a memory barrier, and the next instruction is a control barrier, check if that memory barrier
14887 // does what we need, so we avoid redundant barriers.
14888 const Instruction *next = get_next_instruction_in_block(instruction);
14889 if (next && next->op == OpControlBarrier)
14890 {
14891 auto *next_ops = stream(*next);
14892 uint32_t next_memory = evaluate_constant_u32(next_ops[1]);
14893 uint32_t next_semantics = evaluate_constant_u32(next_ops[2]);
14894 next_semantics = mask_relevant_memory_semantics(next_semantics);
14895
14896 bool memory_scope_covered = false;
14897 if (next_memory == memory)
14898 memory_scope_covered = true;
14899 else if (next_semantics == MemorySemanticsWorkgroupMemoryMask)
14900 {
14901 // If we only care about workgroup memory, either Device or Workgroup scope is fine,
14902 // scope does not have to match.
14903 if ((next_memory == ScopeDevice || next_memory == ScopeWorkgroup) &&
14904 (memory == ScopeDevice || memory == ScopeWorkgroup))
14905 {
14906 memory_scope_covered = true;
14907 }
14908 }
14909 else if (memory == ScopeWorkgroup && next_memory == ScopeDevice)
14910 {
14911 // The control barrier has device scope, but the memory barrier just has workgroup scope.
14912 memory_scope_covered = true;
14913 }
14914
14915 // If we have the same memory scope, and all memory types are covered, we're good.
14916 if (memory_scope_covered && (semantics & next_semantics) == semantics)
14917 break;
14918 }
14919 }
14920
14921 // We are synchronizing some memory or syncing execution,
14922 // so we cannot forward any loads beyond the memory barrier.
14923 if (semantics || opcode == OpControlBarrier)
14924 {
14925 assert(current_emitting_block);
14926 flush_control_dependent_expressions(current_emitting_block->self);
14927 flush_all_active_variables();
14928 }
14929
14930 if (memory == ScopeWorkgroup) // Only need to consider memory within a group
14931 {
14932 if (semantics == MemorySemanticsWorkgroupMemoryMask)
14933 {
14934 // OpControlBarrier implies a memory barrier for shared memory as well.
14935 bool implies_shared_barrier = opcode == OpControlBarrier && execution_scope == ScopeWorkgroup;
14936 if (!implies_shared_barrier)
14937 statement("memoryBarrierShared();");
14938 }
14939 else if (semantics != 0)
14940 statement("groupMemoryBarrier();");
14941 }
14942 else if (memory == ScopeSubgroup)
14943 {
14944 const uint32_t all_barriers =
14945 MemorySemanticsWorkgroupMemoryMask | MemorySemanticsUniformMemoryMask | MemorySemanticsImageMemoryMask;
14946
14947 if (semantics & (MemorySemanticsCrossWorkgroupMemoryMask | MemorySemanticsSubgroupMemoryMask))
14948 {
14949 // These are not relevant for GLSL, but assume it means memoryBarrier().
14950 // memoryBarrier() does everything, so no need to test anything else.
14951 statement("subgroupMemoryBarrier();");
14952 }
14953 else if ((semantics & all_barriers) == all_barriers)
14954 {
14955 // Short-hand instead of emitting 3 barriers.
14956 statement("subgroupMemoryBarrier();");
14957 }
14958 else
14959 {
14960 // Pick out individual barriers.
14961 if (semantics & MemorySemanticsWorkgroupMemoryMask)
14962 statement("subgroupMemoryBarrierShared();");
14963 if (semantics & MemorySemanticsUniformMemoryMask)
14964 statement("subgroupMemoryBarrierBuffer();");
14965 if (semantics & MemorySemanticsImageMemoryMask)
14966 statement("subgroupMemoryBarrierImage();");
14967 }
14968 }
14969 else
14970 {
14971 const uint32_t all_barriers =
14972 MemorySemanticsWorkgroupMemoryMask | MemorySemanticsUniformMemoryMask | MemorySemanticsImageMemoryMask;
14973
14974 if (semantics & (MemorySemanticsCrossWorkgroupMemoryMask | MemorySemanticsSubgroupMemoryMask))
14975 {
14976 // These are not relevant for GLSL, but assume it means memoryBarrier().
14977 // memoryBarrier() does everything, so no need to test anything else.
14978 statement("memoryBarrier();");
14979 }
14980 else if ((semantics & all_barriers) == all_barriers)
14981 {
14982 // Short-hand instead of emitting 4 barriers.
14983 statement("memoryBarrier();");
14984 }
14985 else
14986 {
14987 // Pick out individual barriers.
14988 if (semantics & MemorySemanticsWorkgroupMemoryMask)
14989 statement("memoryBarrierShared();");
14990 if (semantics & MemorySemanticsUniformMemoryMask)
14991 statement("memoryBarrierBuffer();");
14992 if (semantics & MemorySemanticsImageMemoryMask)
14993 statement("memoryBarrierImage();");
14994 }
14995 }
14996
14997 if (opcode == OpControlBarrier)
14998 {
14999 if (execution_scope == ScopeSubgroup)
15000 statement("subgroupBarrier();");
15001 else
15002 statement("barrier();");
15003 }
15004 break;
15005 }
15006
15007 case OpExtInstWithForwardRefsKHR:
15008 {
15009 uint32_t extension_set = ops[2];
15010 auto ext = get<SPIRExtension>(extension_set).ext;
15011 if (ext != SPIRExtension::SPV_debug_info &&
15012 ext != SPIRExtension::NonSemanticShaderDebugInfo &&
15013 ext != SPIRExtension::NonSemanticGeneric)
15014 {
15015 SPIRV_CROSS_THROW("Unexpected use of ExtInstWithForwardRefsKHR.");
15016 }
15017
15018 break;
15019 }
15020
15021 case OpExtInst:
15022 {
15023 uint32_t extension_set = ops[2];
15024 auto ext = get<SPIRExtension>(extension_set).ext;
15025
15026 if (ext == SPIRExtension::GLSL)
15027 {
15028 emit_glsl_op(ops[0], ops[1], ops[3], &ops[4], length - 4);
15029 }
15030 else if (ext == SPIRExtension::SPV_AMD_shader_ballot)
15031 {
15032 emit_spv_amd_shader_ballot_op(ops[0], ops[1], ops[3], &ops[4], length - 4);
15033 }
15034 else if (ext == SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter)
15035 {
15036 emit_spv_amd_shader_explicit_vertex_parameter_op(ops[0], ops[1], ops[3], &ops[4], length - 4);
15037 }
15038 else if (ext == SPIRExtension::SPV_AMD_shader_trinary_minmax)
15039 {
15040 emit_spv_amd_shader_trinary_minmax_op(ops[0], ops[1], ops[3], &ops[4], length - 4);
15041 }
15042 else if (ext == SPIRExtension::SPV_AMD_gcn_shader)
15043 {
15044 emit_spv_amd_gcn_shader_op(ops[0], ops[1], ops[3], &ops[4], length - 4);
15045 }
15046 else if (ext == SPIRExtension::SPV_debug_info ||
15047 ext == SPIRExtension::NonSemanticShaderDebugInfo ||
15048 ext == SPIRExtension::NonSemanticGeneric)
15049 {
15050 break; // Ignore SPIR-V debug information extended instructions.
15051 }
15052 else if (ext == SPIRExtension::NonSemanticDebugPrintf)
15053 {
15054 // Operation 1 is printf.
15055 if (ops[3] == 1)
15056 {
15057 if (!options.vulkan_semantics)
15058 SPIRV_CROSS_THROW("Debug printf is only supported in Vulkan GLSL.\n");
15059 require_extension_internal("GL_EXT_debug_printf");
15060 auto &format_string = get<SPIRString>(ops[4]).str;
15061 string expr = join(backend.printf_function, "(\"", format_string, "\"");
15062 for (uint32_t i = 5; i < length; i++)
15063 {
15064 expr += ", ";
15065 expr += to_expression(ops[i]);
15066 }
15067 statement(expr, ");");
15068 }
15069 }
15070 else
15071 {
15072 statement("// unimplemented ext op ", instruction.op);
15073 break;
15074 }
15075
15076 break;
15077 }
15078
15079 // Legacy sub-group stuff ...
15080 case OpSubgroupBallotKHR:
15081 {
15082 uint32_t result_type = ops[0];
15083 uint32_t id = ops[1];
15084 string expr;
15085 expr = join("uvec4(unpackUint2x32(ballotARB(" + to_expression(ops[2]) + ")), 0u, 0u)");
15086 emit_op(result_type, id, expr, should_forward(ops[2]));
15087
15088 require_extension_internal("GL_ARB_shader_ballot");
15089 inherit_expression_dependencies(id, ops[2]);
15090 register_control_dependent_expression(ops[1]);
15091 break;
15092 }
15093
15094 case OpSubgroupFirstInvocationKHR:
15095 {
15096 uint32_t result_type = ops[0];
15097 uint32_t id = ops[1];
15098 emit_unary_func_op(result_type, id, ops[2], "readFirstInvocationARB");
15099
15100 require_extension_internal("GL_ARB_shader_ballot");
15101 register_control_dependent_expression(ops[1]);
15102 break;
15103 }
15104
15105 case OpSubgroupReadInvocationKHR:
15106 {
15107 uint32_t result_type = ops[0];
15108 uint32_t id = ops[1];
15109 emit_binary_func_op(result_type, id, ops[2], ops[3], "readInvocationARB");
15110
15111 require_extension_internal("GL_ARB_shader_ballot");
15112 register_control_dependent_expression(ops[1]);
15113 break;
15114 }
15115
15116 case OpSubgroupAllKHR:
15117 {
15118 uint32_t result_type = ops[0];
15119 uint32_t id = ops[1];
15120 emit_unary_func_op(result_type, id, ops[2], "allInvocationsARB");
15121
15122 require_extension_internal("GL_ARB_shader_group_vote");
15123 register_control_dependent_expression(ops[1]);
15124 break;
15125 }
15126
15127 case OpSubgroupAnyKHR:
15128 {
15129 uint32_t result_type = ops[0];
15130 uint32_t id = ops[1];
15131 emit_unary_func_op(result_type, id, ops[2], "anyInvocationARB");
15132
15133 require_extension_internal("GL_ARB_shader_group_vote");
15134 register_control_dependent_expression(ops[1]);
15135 break;
15136 }
15137
15138 case OpSubgroupAllEqualKHR:
15139 {
15140 uint32_t result_type = ops[0];
15141 uint32_t id = ops[1];
15142 emit_unary_func_op(result_type, id, ops[2], "allInvocationsEqualARB");
15143
15144 require_extension_internal("GL_ARB_shader_group_vote");
15145 register_control_dependent_expression(ops[1]);
15146 break;
15147 }
15148
15149 case OpGroupIAddNonUniformAMD:
15150 case OpGroupFAddNonUniformAMD:
15151 {
15152 uint32_t result_type = ops[0];
15153 uint32_t id = ops[1];
15154 emit_unary_func_op(result_type, id, ops[4], "addInvocationsNonUniformAMD");
15155
15156 require_extension_internal("GL_AMD_shader_ballot");
15157 register_control_dependent_expression(ops[1]);
15158 break;
15159 }
15160
15161 case OpGroupFMinNonUniformAMD:
15162 case OpGroupUMinNonUniformAMD:
15163 case OpGroupSMinNonUniformAMD:
15164 {
15165 uint32_t result_type = ops[0];
15166 uint32_t id = ops[1];
15167 emit_unary_func_op(result_type, id, ops[4], "minInvocationsNonUniformAMD");
15168
15169 require_extension_internal("GL_AMD_shader_ballot");
15170 register_control_dependent_expression(ops[1]);
15171 break;
15172 }
15173
15174 case OpGroupFMaxNonUniformAMD:
15175 case OpGroupUMaxNonUniformAMD:
15176 case OpGroupSMaxNonUniformAMD:
15177 {
15178 uint32_t result_type = ops[0];
15179 uint32_t id = ops[1];
15180 emit_unary_func_op(result_type, id, ops[4], "maxInvocationsNonUniformAMD");
15181
15182 require_extension_internal("GL_AMD_shader_ballot");
15183 register_control_dependent_expression(ops[1]);
15184 break;
15185 }
15186
15187 case OpFragmentMaskFetchAMD:
15188 {
15189 auto &type = expression_type(ops[2]);
15190 uint32_t result_type = ops[0];
15191 uint32_t id = ops[1];
15192
15193 if (type.image.dim == spv::DimSubpassData)
15194 {
15195 emit_unary_func_op(result_type, id, ops[2], "fragmentMaskFetchAMD");
15196 }
15197 else
15198 {
15199 emit_binary_func_op(result_type, id, ops[2], ops[3], "fragmentMaskFetchAMD");
15200 }
15201
15202 require_extension_internal("GL_AMD_shader_fragment_mask");
15203 break;
15204 }
15205
15206 case OpFragmentFetchAMD:
15207 {
15208 auto &type = expression_type(ops[2]);
15209 uint32_t result_type = ops[0];
15210 uint32_t id = ops[1];
15211
15212 if (type.image.dim == spv::DimSubpassData)
15213 {
15214 emit_binary_func_op(result_type, id, ops[2], ops[4], "fragmentFetchAMD");
15215 }
15216 else
15217 {
15218 emit_trinary_func_op(result_type, id, ops[2], ops[3], ops[4], "fragmentFetchAMD");
15219 }
15220
15221 require_extension_internal("GL_AMD_shader_fragment_mask");
15222 break;
15223 }
15224
15225 // Vulkan 1.1 sub-group stuff ...
15226 case OpGroupNonUniformElect:
15227 case OpGroupNonUniformBroadcast:
15228 case OpGroupNonUniformBroadcastFirst:
15229 case OpGroupNonUniformBallot:
15230 case OpGroupNonUniformInverseBallot:
15231 case OpGroupNonUniformBallotBitExtract:
15232 case OpGroupNonUniformBallotBitCount:
15233 case OpGroupNonUniformBallotFindLSB:
15234 case OpGroupNonUniformBallotFindMSB:
15235 case OpGroupNonUniformShuffle:
15236 case OpGroupNonUniformShuffleXor:
15237 case OpGroupNonUniformShuffleUp:
15238 case OpGroupNonUniformShuffleDown:
15239 case OpGroupNonUniformAll:
15240 case OpGroupNonUniformAny:
15241 case OpGroupNonUniformAllEqual:
15242 case OpGroupNonUniformFAdd:
15243 case OpGroupNonUniformIAdd:
15244 case OpGroupNonUniformFMul:
15245 case OpGroupNonUniformIMul:
15246 case OpGroupNonUniformFMin:
15247 case OpGroupNonUniformFMax:
15248 case OpGroupNonUniformSMin:
15249 case OpGroupNonUniformSMax:
15250 case OpGroupNonUniformUMin:
15251 case OpGroupNonUniformUMax:
15252 case OpGroupNonUniformBitwiseAnd:
15253 case OpGroupNonUniformBitwiseOr:
15254 case OpGroupNonUniformBitwiseXor:
15255 case OpGroupNonUniformLogicalAnd:
15256 case OpGroupNonUniformLogicalOr:
15257 case OpGroupNonUniformLogicalXor:
15258 case OpGroupNonUniformQuadSwap:
15259 case OpGroupNonUniformQuadBroadcast:
15260 case OpGroupNonUniformQuadAllKHR:
15261 case OpGroupNonUniformQuadAnyKHR:
15262 case OpGroupNonUniformRotateKHR:
15263 emit_subgroup_op(instruction);
15264 break;
15265
15266 case OpFUnordEqual:
15267 case OpFUnordLessThan:
15268 case OpFUnordGreaterThan:
15269 case OpFUnordLessThanEqual:
15270 case OpFUnordGreaterThanEqual:
15271 {
15272 // GLSL doesn't specify if floating point comparisons are ordered or unordered,
15273 // but glslang always emits ordered floating point compares for GLSL.
15274 // To get unordered compares, we can test the opposite thing and invert the result.
15275 // This way, we force true when there is any NaN present.
15276 uint32_t op0 = ops[2];
15277 uint32_t op1 = ops[3];
15278
15279 string expr;
15280 if (expression_type(op0).vecsize > 1)
15281 {
15282 const char *comp_op = nullptr;
15283 switch (opcode)
15284 {
15285 case OpFUnordEqual:
15286 comp_op = "notEqual";
15287 break;
15288
15289 case OpFUnordLessThan:
15290 comp_op = "greaterThanEqual";
15291 break;
15292
15293 case OpFUnordLessThanEqual:
15294 comp_op = "greaterThan";
15295 break;
15296
15297 case OpFUnordGreaterThan:
15298 comp_op = "lessThanEqual";
15299 break;
15300
15301 case OpFUnordGreaterThanEqual:
15302 comp_op = "lessThan";
15303 break;
15304
15305 default:
15306 assert(0);
15307 break;
15308 }
15309
15310 expr = join("not(", comp_op, "(", to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), "))");
15311 }
15312 else
15313 {
15314 const char *comp_op = nullptr;
15315 switch (opcode)
15316 {
15317 case OpFUnordEqual:
15318 comp_op = " != ";
15319 break;
15320
15321 case OpFUnordLessThan:
15322 comp_op = " >= ";
15323 break;
15324
15325 case OpFUnordLessThanEqual:
15326 comp_op = " > ";
15327 break;
15328
15329 case OpFUnordGreaterThan:
15330 comp_op = " <= ";
15331 break;
15332
15333 case OpFUnordGreaterThanEqual:
15334 comp_op = " < ";
15335 break;
15336
15337 default:
15338 assert(0);
15339 break;
15340 }
15341
15342 expr = join("!(", to_enclosed_unpacked_expression(op0), comp_op, to_enclosed_unpacked_expression(op1), ")");
15343 }
15344
15345 emit_op(ops[0], ops[1], expr, should_forward(op0) && should_forward(op1));
15346 inherit_expression_dependencies(ops[1], op0);
15347 inherit_expression_dependencies(ops[1], op1);
15348 break;
15349 }
15350
15351 case OpReportIntersectionKHR:
15352 // NV is same opcode.
15353 forced_temporaries.insert(ops[1]);
15354 if (ray_tracing_is_khr)
15355 GLSL_BFOP(reportIntersectionEXT);
15356 else
15357 GLSL_BFOP(reportIntersectionNV);
15358 flush_control_dependent_expressions(current_emitting_block->self);
15359 break;
15360 case OpIgnoreIntersectionNV:
15361 // KHR variant is a terminator.
15362 statement("ignoreIntersectionNV();");
15363 flush_control_dependent_expressions(current_emitting_block->self);
15364 break;
15365 case OpTerminateRayNV:
15366 // KHR variant is a terminator.
15367 statement("terminateRayNV();");
15368 flush_control_dependent_expressions(current_emitting_block->self);
15369 break;
15370 case OpTraceNV:
15371 statement("traceNV(", to_non_uniform_aware_expression(ops[0]), ", ", to_expression(ops[1]), ", ", to_expression(ops[2]), ", ",
15372 to_expression(ops[3]), ", ", to_expression(ops[4]), ", ", to_expression(ops[5]), ", ",
15373 to_expression(ops[6]), ", ", to_expression(ops[7]), ", ", to_expression(ops[8]), ", ",
15374 to_expression(ops[9]), ", ", to_expression(ops[10]), ");");
15375 flush_control_dependent_expressions(current_emitting_block->self);
15376 break;
15377 case OpTraceRayKHR:
15378 if (!has_decoration(ops[10], DecorationLocation))
15379 SPIRV_CROSS_THROW("A memory declaration object must be used in TraceRayKHR.");
15380 statement("traceRayEXT(", to_non_uniform_aware_expression(ops[0]), ", ", to_expression(ops[1]), ", ", to_expression(ops[2]), ", ",
15381 to_expression(ops[3]), ", ", to_expression(ops[4]), ", ", to_expression(ops[5]), ", ",
15382 to_expression(ops[6]), ", ", to_expression(ops[7]), ", ", to_expression(ops[8]), ", ",
15383 to_expression(ops[9]), ", ", get_decoration(ops[10], DecorationLocation), ");");
15384 flush_control_dependent_expressions(current_emitting_block->self);
15385 break;
15386 case OpExecuteCallableNV:
15387 statement("executeCallableNV(", to_expression(ops[0]), ", ", to_expression(ops[1]), ");");
15388 flush_control_dependent_expressions(current_emitting_block->self);
15389 break;
15390 case OpExecuteCallableKHR:
15391 if (!has_decoration(ops[1], DecorationLocation))
15392 SPIRV_CROSS_THROW("A memory declaration object must be used in ExecuteCallableKHR.");
15393 statement("executeCallableEXT(", to_expression(ops[0]), ", ", get_decoration(ops[1], DecorationLocation), ");");
15394 flush_control_dependent_expressions(current_emitting_block->self);
15395 break;
15396
15397 // Don't bother forwarding temporaries. Avoids having to test expression invalidation with ray query objects.
15398 case OpRayQueryInitializeKHR:
15399 flush_variable_declaration(ops[0]);
15400 statement("rayQueryInitializeEXT(",
15401 to_expression(ops[0]), ", ", to_expression(ops[1]), ", ",
15402 to_expression(ops[2]), ", ", to_expression(ops[3]), ", ",
15403 to_expression(ops[4]), ", ", to_expression(ops[5]), ", ",
15404 to_expression(ops[6]), ", ", to_expression(ops[7]), ");");
15405 break;
15406 case OpRayQueryProceedKHR:
15407 flush_variable_declaration(ops[0]);
15408 emit_op(ops[0], ops[1], join("rayQueryProceedEXT(", to_expression(ops[2]), ")"), false);
15409 break;
15410 case OpRayQueryTerminateKHR:
15411 flush_variable_declaration(ops[0]);
15412 statement("rayQueryTerminateEXT(", to_expression(ops[0]), ");");
15413 break;
15414 case OpRayQueryGenerateIntersectionKHR:
15415 flush_variable_declaration(ops[0]);
15416 statement("rayQueryGenerateIntersectionEXT(", to_expression(ops[0]), ", ", to_expression(ops[1]), ");");
15417 break;
15418 case OpRayQueryConfirmIntersectionKHR:
15419 flush_variable_declaration(ops[0]);
15420 statement("rayQueryConfirmIntersectionEXT(", to_expression(ops[0]), ");");
15421 break;
15422 #define GLSL_RAY_QUERY_GET_OP(op) \
15423 case OpRayQueryGet##op##KHR: \
15424 flush_variable_declaration(ops[2]); \
15425 emit_op(ops[0], ops[1], join("rayQueryGet" #op "EXT(", to_expression(ops[2]), ")"), false); \
15426 break
15427 #define GLSL_RAY_QUERY_GET_OP2(op) \
15428 case OpRayQueryGet##op##KHR: \
15429 flush_variable_declaration(ops[2]); \
15430 emit_op(ops[0], ops[1], join("rayQueryGet" #op "EXT(", to_expression(ops[2]), ", ", "bool(", to_expression(ops[3]), "))"), false); \
15431 break
15432 GLSL_RAY_QUERY_GET_OP(RayTMin);
15433 GLSL_RAY_QUERY_GET_OP(RayFlags);
15434 GLSL_RAY_QUERY_GET_OP(WorldRayOrigin);
15435 GLSL_RAY_QUERY_GET_OP(WorldRayDirection);
15436 GLSL_RAY_QUERY_GET_OP(IntersectionCandidateAABBOpaque);
15437 GLSL_RAY_QUERY_GET_OP2(IntersectionType);
15438 GLSL_RAY_QUERY_GET_OP2(IntersectionT);
15439 GLSL_RAY_QUERY_GET_OP2(IntersectionInstanceCustomIndex);
15440 GLSL_RAY_QUERY_GET_OP2(IntersectionInstanceId);
15441 GLSL_RAY_QUERY_GET_OP2(IntersectionInstanceShaderBindingTableRecordOffset);
15442 GLSL_RAY_QUERY_GET_OP2(IntersectionGeometryIndex);
15443 GLSL_RAY_QUERY_GET_OP2(IntersectionPrimitiveIndex);
15444 GLSL_RAY_QUERY_GET_OP2(IntersectionBarycentrics);
15445 GLSL_RAY_QUERY_GET_OP2(IntersectionFrontFace);
15446 GLSL_RAY_QUERY_GET_OP2(IntersectionObjectRayDirection);
15447 GLSL_RAY_QUERY_GET_OP2(IntersectionObjectRayOrigin);
15448 GLSL_RAY_QUERY_GET_OP2(IntersectionObjectToWorld);
15449 GLSL_RAY_QUERY_GET_OP2(IntersectionWorldToObject);
15450 #undef GLSL_RAY_QUERY_GET_OP
15451 #undef GLSL_RAY_QUERY_GET_OP2
15452
15453 case OpConvertUToAccelerationStructureKHR:
15454 {
15455 require_extension_internal("GL_EXT_ray_tracing");
15456
15457 bool elide_temporary = should_forward(ops[2]) && forced_temporaries.count(ops[1]) == 0 &&
15458 !hoisted_temporaries.count(ops[1]);
15459
15460 if (elide_temporary)
15461 {
15462 GLSL_UFOP(accelerationStructureEXT);
15463 }
15464 else
15465 {
15466 // Force this path in subsequent iterations.
15467 forced_temporaries.insert(ops[1]);
15468
15469 // We cannot declare a temporary acceleration structure in GLSL.
15470 // If we get to this point, we'll have to emit a temporary uvec2,
15471 // and cast to RTAS on demand.
15472 statement(declare_temporary(expression_type_id(ops[2]), ops[1]), to_unpacked_expression(ops[2]), ";");
15473 // Use raw SPIRExpression interface to block all usage tracking.
15474 set<SPIRExpression>(ops[1], join("accelerationStructureEXT(", to_name(ops[1]), ")"), ops[0], true);
15475 }
15476 break;
15477 }
15478
15479 case OpConvertUToPtr:
15480 {
15481 auto &type = get<SPIRType>(ops[0]);
15482 if (type.storage != StorageClassPhysicalStorageBuffer)
15483 SPIRV_CROSS_THROW("Only StorageClassPhysicalStorageBuffer is supported by OpConvertUToPtr.");
15484
15485 auto &in_type = expression_type(ops[2]);
15486 if (in_type.vecsize == 2)
15487 require_extension_internal("GL_EXT_buffer_reference_uvec2");
15488
15489 auto op = type_to_glsl(type);
15490 emit_unary_func_op(ops[0], ops[1], ops[2], op.c_str());
15491 break;
15492 }
15493
15494 case OpConvertPtrToU:
15495 {
15496 auto &type = get<SPIRType>(ops[0]);
15497 auto &ptr_type = expression_type(ops[2]);
15498 if (ptr_type.storage != StorageClassPhysicalStorageBuffer)
15499 SPIRV_CROSS_THROW("Only StorageClassPhysicalStorageBuffer is supported by OpConvertPtrToU.");
15500
15501 if (type.vecsize == 2)
15502 require_extension_internal("GL_EXT_buffer_reference_uvec2");
15503
15504 auto op = type_to_glsl(type);
15505 emit_unary_func_op(ops[0], ops[1], ops[2], op.c_str());
15506 break;
15507 }
15508
15509 case OpUndef:
15510 // Undefined value has been declared.
15511 break;
15512
15513 case OpLine:
15514 {
15515 emit_line_directive(ops[0], ops[1]);
15516 break;
15517 }
15518
15519 case OpNoLine:
15520 break;
15521
15522 case OpDemoteToHelperInvocationEXT:
15523 if (!options.vulkan_semantics)
15524 SPIRV_CROSS_THROW("GL_EXT_demote_to_helper_invocation is only supported in Vulkan GLSL.");
15525 require_extension_internal("GL_EXT_demote_to_helper_invocation");
15526 statement(backend.demote_literal, ";");
15527 break;
15528
15529 case OpIsHelperInvocationEXT:
15530 if (!options.vulkan_semantics)
15531 SPIRV_CROSS_THROW("GL_EXT_demote_to_helper_invocation is only supported in Vulkan GLSL.");
15532 require_extension_internal("GL_EXT_demote_to_helper_invocation");
15533 // Helper lane state with demote is volatile by nature.
15534 // Do not forward this.
15535 emit_op(ops[0], ops[1], "helperInvocationEXT()", false);
15536 break;
15537
15538 case OpBeginInvocationInterlockEXT:
15539 // If the interlock is complex, we emit this elsewhere.
15540 if (!interlocked_is_complex)
15541 {
15542 statement("SPIRV_Cross_beginInvocationInterlock();");
15543 flush_all_active_variables();
15544 // Make sure forwarding doesn't propagate outside interlock region.
15545 }
15546 break;
15547
15548 case OpEndInvocationInterlockEXT:
15549 // If the interlock is complex, we emit this elsewhere.
15550 if (!interlocked_is_complex)
15551 {
15552 statement("SPIRV_Cross_endInvocationInterlock();");
15553 flush_all_active_variables();
15554 // Make sure forwarding doesn't propagate outside interlock region.
15555 }
15556 break;
15557
15558 case OpSetMeshOutputsEXT:
15559 statement("SetMeshOutputsEXT(", to_unpacked_expression(ops[0]), ", ", to_unpacked_expression(ops[1]), ");");
15560 break;
15561
15562 case OpReadClockKHR:
15563 {
15564 auto &type = get<SPIRType>(ops[0]);
15565 auto scope = static_cast<Scope>(evaluate_constant_u32(ops[2]));
15566 const char *op = nullptr;
15567 // Forwarding clock statements leads to a scenario where an SSA value can take on different
15568 // values every time it's evaluated. Block any forwarding attempt.
15569 // We also might want to invalidate all expressions to function as a sort of optimization
15570 // barrier, but might be overkill for now.
15571 if (scope == ScopeDevice)
15572 {
15573 require_extension_internal("GL_EXT_shader_realtime_clock");
15574 if (type.basetype == SPIRType::BaseType::UInt64)
15575 op = "clockRealtimeEXT()";
15576 else if (type.basetype == SPIRType::BaseType::UInt && type.vecsize == 2)
15577 op = "clockRealtime2x32EXT()";
15578 else
15579 SPIRV_CROSS_THROW("Unsupported result type for OpReadClockKHR opcode.");
15580 }
15581 else if (scope == ScopeSubgroup)
15582 {
15583 require_extension_internal("GL_ARB_shader_clock");
15584 if (type.basetype == SPIRType::BaseType::UInt64)
15585 op = "clockARB()";
15586 else if (type.basetype == SPIRType::BaseType::UInt && type.vecsize == 2)
15587 op = "clock2x32ARB()";
15588 else
15589 SPIRV_CROSS_THROW("Unsupported result type for OpReadClockKHR opcode.");
15590 }
15591 else
15592 SPIRV_CROSS_THROW("Unsupported scope for OpReadClockKHR opcode.");
15593
15594 emit_op(ops[0], ops[1], op, false);
15595 break;
15596 }
15597
15598 case OpCooperativeMatrixLengthKHR:
15599 {
15600 // Need to synthesize a dummy temporary, since the SPIR-V opcode is based on the type.
15601 uint32_t result_type = ops[0];
15602 uint32_t id = ops[1];
15603 set<SPIRExpression>(
15604 id, join(type_to_glsl(get<SPIRType>(result_type)),
15605 "(", type_to_glsl(get<SPIRType>(ops[2])), "(0).length())"),
15606 result_type, true);
15607 break;
15608 }
15609
15610 case OpCooperativeMatrixLoadKHR:
15611 {
15612 // Spec contradicts itself if stride is optional or not.
15613 if (length < 5)
15614 SPIRV_CROSS_THROW("Stride is not provided.");
15615
15616 uint32_t result_type = ops[0];
15617 uint32_t id = ops[1];
15618 emit_uninitialized_temporary_expression(result_type, id);
15619
15620 auto expr = to_expression(ops[2]);
15621 pair<string, string> split_expr;
15622 if (!is_forcing_recompilation())
15623 split_expr = split_coopmat_pointer(expr);
15624
15625 string layout_expr;
15626 if (const auto *layout = maybe_get<SPIRConstant>(ops[3]))
15627 {
15628 if (!layout->specialization)
15629 {
15630 if (layout->scalar() == spv::CooperativeMatrixLayoutColumnMajorKHR)
15631 layout_expr = "gl_CooperativeMatrixLayoutColumnMajor";
15632 else
15633 layout_expr = "gl_CooperativeMatrixLayoutRowMajor";
15634 }
15635 }
15636
15637 if (layout_expr.empty())
15638 layout_expr = join("int(", to_expression(ops[3]), ")");
15639
15640 statement("coopMatLoad(",
15641 to_expression(id), ", ",
15642 split_expr.first, ", ",
15643 split_expr.second, ", ",
15644 to_expression(ops[4]), ", ",
15645 layout_expr, ");");
15646
15647 register_read(id, ops[2], false);
15648 break;
15649 }
15650
15651 case OpCooperativeMatrixStoreKHR:
15652 {
15653 // Spec contradicts itself if stride is optional or not.
15654 if (length < 4)
15655 SPIRV_CROSS_THROW("Stride is not provided.");
15656
15657 // SPIR-V and GLSL don't agree how to pass the expression.
15658 // In SPIR-V it's a pointer, but in GLSL it's reference to array + index.
15659
15660 auto expr = to_expression(ops[0]);
15661 pair<string, string> split_expr;
15662 if (!is_forcing_recompilation())
15663 split_expr = split_coopmat_pointer(expr);
15664
15665 string layout_expr;
15666 if (const auto *layout = maybe_get<SPIRConstant>(ops[2]))
15667 {
15668 if (!layout->specialization)
15669 {
15670 if (layout->scalar() == spv::CooperativeMatrixLayoutColumnMajorKHR)
15671 layout_expr = "gl_CooperativeMatrixLayoutColumnMajor";
15672 else
15673 layout_expr = "gl_CooperativeMatrixLayoutRowMajor";
15674 }
15675 }
15676
15677 if (layout_expr.empty())
15678 layout_expr = join("int(", to_expression(ops[2]), ")");
15679
15680 statement("coopMatStore(",
15681 to_expression(ops[1]), ", ",
15682 split_expr.first, ", ",
15683 split_expr.second, ", ",
15684 to_expression(ops[3]), ", ",
15685 layout_expr, ");");
15686
15687 // TODO: Do we care about memory operands?
15688
15689 register_write(ops[0]);
15690 break;
15691 }
15692
15693 case OpCooperativeMatrixMulAddKHR:
15694 {
15695 uint32_t result_type = ops[0];
15696 uint32_t id = ops[1];
15697 uint32_t A = ops[2];
15698 uint32_t B = ops[3];
15699 uint32_t C = ops[4];
15700 bool forward = should_forward(A) && should_forward(B) && should_forward(C);
15701 emit_op(result_type, id,
15702 join("coopMatMulAdd(",
15703 to_unpacked_expression(A), ", ",
15704 to_unpacked_expression(B), ", ",
15705 to_unpacked_expression(C), ", ",
15706 (length >= 6 ? ops[5] : 0),
15707 ")"),
15708 forward);
15709
15710 inherit_expression_dependencies(id, A);
15711 inherit_expression_dependencies(id, B);
15712 inherit_expression_dependencies(id, C);
15713 break;
15714 }
15715
15716 case OpCompositeConstructReplicateEXT:
15717 {
15718 uint32_t result_type = ops[0];
15719 uint32_t id = ops[1];
15720
15721 auto &type = get<SPIRType>(result_type);
15722 auto value_to_replicate = to_expression(ops[2]);
15723 std::string rhs;
15724 // Matrices don't have a replicating constructor for vectors. Need to manually replicate
15725 if (type.op == spv::OpTypeMatrix || type.op == spv::OpTypeArray)
15726 {
15727 if (type.op == spv::OpTypeArray && type.array.size() != 1)
15728 {
15729 SPIRV_CROSS_THROW(
15730 "Multi-dimensional arrays currently not supported for OpCompositeConstructReplicateEXT");
15731 }
15732 uint32_t num_elements = type.op == spv::OpTypeMatrix ? type.columns : type.array[0];
15733 if (backend.use_initializer_list && type.op == spv::OpTypeArray)
15734 {
15735 rhs += "{";
15736 }
15737 else
15738 {
15739 rhs += type_to_glsl_constructor(type);
15740 rhs += "(";
15741 }
15742 for (uint32_t i = 0; i < num_elements; i++)
15743 {
15744 rhs += value_to_replicate;
15745 if (i < num_elements - 1)
15746 rhs += ", ";
15747 }
15748 if (backend.use_initializer_list && type.op == spv::OpTypeArray)
15749 rhs += "}";
15750 else
15751 rhs += ")";
15752 }
15753 else
15754 {
15755 rhs = join(type_to_glsl(type), "(", to_expression(ops[2]), ")");
15756 }
15757 emit_op(result_type, id, rhs, true);
15758 break;
15759 }
15760
15761 default:
15762 statement("// unimplemented op ", instruction.op);
15763 break;
15764 }
15765 }
15766
15767 // Appends function arguments, mapped from global variables, beyond the specified arg index.
15768 // This is used when a function call uses fewer arguments than the function defines.
15769 // This situation may occur if the function signature has been dynamically modified to
15770 // extract global variables referenced from within the function, and convert them to
15771 // function arguments. This is necessary for shader languages that do not support global
15772 // access to shader input content from within a function (eg. Metal). Each additional
15773 // function args uses the name of the global variable. Function nesting will modify the
15774 // functions and function calls all the way up the nesting chain.
15775 void CompilerGLSL::append_global_func_args(const SPIRFunction &func, uint32_t index, SmallVector<string> &arglist)
15776 {
15777 auto &args = func.arguments;
15778 uint32_t arg_cnt = uint32_t(args.size());
15779 for (uint32_t arg_idx = index; arg_idx < arg_cnt; arg_idx++)
15780 {
15781 auto &arg = args[arg_idx];
15782 assert(arg.alias_global_variable);
15783
15784 // If the underlying variable needs to be declared
15785 // (ie. a local variable with deferred declaration), do so now.
15786 uint32_t var_id = get<SPIRVariable>(arg.id).basevariable;
15787 if (var_id)
15788 flush_variable_declaration(var_id);
15789
15790 arglist.push_back(to_func_call_arg(arg, arg.id));
15791 }
15792 }
15793
15794 string CompilerGLSL::to_member_name(const SPIRType &type, uint32_t index)
15795 {
15796 if (type.type_alias != TypeID(0) &&
15797 !has_extended_decoration(type.type_alias, SPIRVCrossDecorationBufferBlockRepacked))
15798 {
15799 return to_member_name(get<SPIRType>(type.type_alias), index);
15800 }
15801
15802 auto &memb = ir.meta[type.self].members;
15803 if (index < memb.size() && !memb[index].alias.empty())
15804 return memb[index].alias;
15805 else
15806 return join("_m", index);
15807 }
15808
15809 string CompilerGLSL::to_member_reference(uint32_t, const SPIRType &type, uint32_t index, bool)
15810 {
15811 return join(".", to_member_name(type, index));
15812 }
15813
15814 string CompilerGLSL::to_multi_member_reference(const SPIRType &type, const SmallVector<uint32_t> &indices)
15815 {
15816 string ret;
15817 auto *member_type = &type;
15818 for (auto &index : indices)
15819 {
15820 ret += join(".", to_member_name(*member_type, index));
15821 member_type = &get<SPIRType>(member_type->member_types[index]);
15822 }
15823 return ret;
15824 }
15825
15826 void CompilerGLSL::add_member_name(SPIRType &type, uint32_t index)
15827 {
15828 auto &memb = ir.meta[type.self].members;
15829 if (index < memb.size() && !memb[index].alias.empty())
15830 {
15831 auto &name = memb[index].alias;
15832 if (name.empty())
15833 return;
15834
15835 ParsedIR::sanitize_identifier(name, true, true);
15836 update_name_cache(type.member_name_cache, name);
15837 }
15838 }
15839
15840 // Checks whether the ID is a row_major matrix that requires conversion before use
15841 bool CompilerGLSL::is_non_native_row_major_matrix(uint32_t id)
15842 {
15843 // Natively supported row-major matrices do not need to be converted.
15844 // Legacy targets do not support row major.
15845 if (backend.native_row_major_matrix && !is_legacy())
15846 return false;
15847
15848 auto *e = maybe_get<SPIRExpression>(id);
15849 if (e)
15850 return e->need_transpose;
15851 else
15852 return has_decoration(id, DecorationRowMajor);
15853 }
15854
15855 // Checks whether the member is a row_major matrix that requires conversion before use
15856 bool CompilerGLSL::member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index)
15857 {
15858 // Natively supported row-major matrices do not need to be converted.
15859 if (backend.native_row_major_matrix && !is_legacy())
15860 return false;
15861
15862 // Non-matrix or column-major matrix types do not need to be converted.
15863 if (!has_member_decoration(type.self, index, DecorationRowMajor))
15864 return false;
15865
15866 // Only square row-major matrices can be converted at this time.
15867 // Converting non-square matrices will require defining custom GLSL function that
15868 // swaps matrix elements while retaining the original dimensional form of the matrix.
15869 const auto mbr_type = get<SPIRType>(type.member_types[index]);
15870 if (mbr_type.columns != mbr_type.vecsize)
15871 SPIRV_CROSS_THROW("Row-major matrices must be square on this platform.");
15872
15873 return true;
15874 }
15875
15876 // Checks if we need to remap physical type IDs when declaring the type in a buffer.
15877 bool CompilerGLSL::member_is_remapped_physical_type(const SPIRType &type, uint32_t index) const
15878 {
15879 return has_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID);
15880 }
15881
15882 // Checks whether the member is in packed data type, that might need to be unpacked.
15883 bool CompilerGLSL::member_is_packed_physical_type(const SPIRType &type, uint32_t index) const
15884 {
15885 return has_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
15886 }
15887
15888 // Wraps the expression string in a function call that converts the
15889 // row_major matrix result of the expression to a column_major matrix.
15890 // Base implementation uses the standard library transpose() function.
15891 // Subclasses may override to use a different function.
15892 string CompilerGLSL::convert_row_major_matrix(string exp_str, const SPIRType &exp_type, uint32_t /* physical_type_id */,
15893 bool /*is_packed*/, bool relaxed)
15894 {
15895 strip_enclosed_expression(exp_str);
15896 if (!is_matrix(exp_type))
15897 {
15898 auto column_index = exp_str.find_last_of('[');
15899 if (column_index == string::npos)
15900 return exp_str;
15901
15902 auto column_expr = exp_str.substr(column_index);
15903 exp_str.resize(column_index);
15904
15905 auto end_deferred_index = column_expr.find_last_of(']');
15906 if (end_deferred_index != string::npos && end_deferred_index + 1 != column_expr.size())
15907 {
15908 // If we have any data member fixups, it must be transposed so that it refers to this index.
15909 // E.g. [0].data followed by [1] would be shuffled to [1][0].data which is wrong,
15910 // and needs to be [1].data[0] instead.
15911 end_deferred_index++;
15912 column_expr = column_expr.substr(end_deferred_index) +
15913 column_expr.substr(0, end_deferred_index);
15914 }
15915
15916 auto transposed_expr = type_to_glsl_constructor(exp_type) + "(";
15917
15918 // Loading a column from a row-major matrix. Unroll the load.
15919 for (uint32_t c = 0; c < exp_type.vecsize; c++)
15920 {
15921 transposed_expr += join(exp_str, '[', c, ']', column_expr);
15922 if (c + 1 < exp_type.vecsize)
15923 transposed_expr += ", ";
15924 }
15925
15926 transposed_expr += ")";
15927 return transposed_expr;
15928 }
15929 else if (options.version < 120)
15930 {
15931 // GLSL 110, ES 100 do not have transpose(), so emulate it. Note that
15932 // these GLSL versions do not support non-square matrices.
15933 if (exp_type.vecsize == 2 && exp_type.columns == 2)
15934 require_polyfill(PolyfillTranspose2x2, relaxed);
15935 else if (exp_type.vecsize == 3 && exp_type.columns == 3)
15936 require_polyfill(PolyfillTranspose3x3, relaxed);
15937 else if (exp_type.vecsize == 4 && exp_type.columns == 4)
15938 require_polyfill(PolyfillTranspose4x4, relaxed);
15939 else
15940 SPIRV_CROSS_THROW("Non-square matrices are not supported in legacy GLSL, cannot transpose.");
15941 return join("spvTranspose", (options.es && relaxed) ? "MP" : "", "(", exp_str, ")");
15942 }
15943 else
15944 return join("transpose(", exp_str, ")");
15945 }
15946
15947 string CompilerGLSL::variable_decl(const SPIRType &type, const string &name, uint32_t id)
15948 {
15949 string type_name = type_to_glsl(type, id);
15950 remap_variable_type_name(type, name, type_name);
15951 return join(type_name, " ", name, type_to_array_glsl(type, id));
15952 }
15953
15954 bool CompilerGLSL::variable_decl_is_remapped_storage(const SPIRVariable &var, StorageClass storage) const
15955 {
15956 return var.storage == storage;
15957 }
15958
15959 // Emit a structure member. Subclasses may override to modify output,
15960 // or to dynamically add a padding member if needed.
15961 void CompilerGLSL::emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
15962 const string &qualifier, uint32_t)
15963 {
15964 auto &membertype = get<SPIRType>(member_type_id);
15965
15966 Bitset memberflags;
15967 auto &memb = ir.meta[type.self].members;
15968 if (index < memb.size())
15969 memberflags = memb[index].decoration_flags;
15970
15971 string qualifiers;
15972 bool is_block = ir.meta[type.self].decoration.decoration_flags.get(DecorationBlock) ||
15973 ir.meta[type.self].decoration.decoration_flags.get(DecorationBufferBlock);
15974
15975 if (is_block)
15976 qualifiers = to_interpolation_qualifiers(memberflags);
15977
15978 statement(layout_for_member(type, index), qualifiers, qualifier, flags_to_qualifiers_glsl(membertype, memberflags),
15979 variable_decl(membertype, to_member_name(type, index)), ";");
15980 }
15981
15982 void CompilerGLSL::emit_struct_padding_target(const SPIRType &)
15983 {
15984 }
15985
15986 string CompilerGLSL::flags_to_qualifiers_glsl(const SPIRType &type, const Bitset &flags)
15987 {
15988 // GL_EXT_buffer_reference variables can be marked as restrict.
15989 if (flags.get(DecorationRestrictPointerEXT))
15990 return "restrict ";
15991
15992 string qual;
15993
15994 if (type_is_floating_point(type) && flags.get(DecorationNoContraction) && backend.support_precise_qualifier)
15995 qual = "precise ";
15996
15997 // Structs do not have precision qualifiers, neither do doubles (desktop only anyways, so no mediump/highp).
15998 bool type_supports_precision =
15999 type.basetype == SPIRType::Float || type.basetype == SPIRType::Int || type.basetype == SPIRType::UInt ||
16000 type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage ||
16001 type.basetype == SPIRType::Sampler;
16002
16003 if (!type_supports_precision)
16004 return qual;
16005
16006 if (options.es)
16007 {
16008 auto &execution = get_entry_point();
16009
16010 if (type.basetype == SPIRType::UInt && is_legacy_es())
16011 {
16012 // HACK: This is a bool. See comment in type_to_glsl().
16013 qual += "lowp ";
16014 }
16015 else if (flags.get(DecorationRelaxedPrecision))
16016 {
16017 bool implied_fmediump = type.basetype == SPIRType::Float &&
16018 options.fragment.default_float_precision == Options::Mediump &&
16019 execution.model == ExecutionModelFragment;
16020
16021 bool implied_imediump = (type.basetype == SPIRType::Int || type.basetype == SPIRType::UInt) &&
16022 options.fragment.default_int_precision == Options::Mediump &&
16023 execution.model == ExecutionModelFragment;
16024
16025 qual += (implied_fmediump || implied_imediump) ? "" : "mediump ";
16026 }
16027 else
16028 {
16029 bool implied_fhighp =
16030 type.basetype == SPIRType::Float && ((options.fragment.default_float_precision == Options::Highp &&
16031 execution.model == ExecutionModelFragment) ||
16032 (execution.model != ExecutionModelFragment));
16033
16034 bool implied_ihighp = (type.basetype == SPIRType::Int || type.basetype == SPIRType::UInt) &&
16035 ((options.fragment.default_int_precision == Options::Highp &&
16036 execution.model == ExecutionModelFragment) ||
16037 (execution.model != ExecutionModelFragment));
16038
16039 qual += (implied_fhighp || implied_ihighp) ? "" : "highp ";
16040 }
16041 }
16042 else if (backend.allow_precision_qualifiers)
16043 {
16044 // Vulkan GLSL supports precision qualifiers, even in desktop profiles, which is convenient.
16045 // The default is highp however, so only emit mediump in the rare case that a shader has these.
16046 if (flags.get(DecorationRelaxedPrecision))
16047 qual += "mediump ";
16048 }
16049
16050 return qual;
16051 }
16052
16053 string CompilerGLSL::to_precision_qualifiers_glsl(uint32_t id)
16054 {
16055 auto &type = expression_type(id);
16056 bool use_precision_qualifiers = backend.allow_precision_qualifiers;
16057 if (use_precision_qualifiers && (type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage))
16058 {
16059 // Force mediump for the sampler type. We cannot declare 16-bit or smaller image types.
16060 auto &result_type = get<SPIRType>(type.image.type);
16061 if (result_type.width < 32)
16062 return "mediump ";
16063 }
16064 return flags_to_qualifiers_glsl(type, ir.meta[id].decoration.decoration_flags);
16065 }
16066
16067 void CompilerGLSL::fixup_io_block_patch_primitive_qualifiers(const SPIRVariable &var)
16068 {
16069 // Works around weird behavior in glslangValidator where
16070 // a patch out block is translated to just block members getting the decoration.
16071 // To make glslang not complain when we compile again, we have to transform this back to a case where
16072 // the variable itself has Patch decoration, and not members.
16073 // Same for perprimitiveEXT.
16074 auto &type = get<SPIRType>(var.basetype);
16075 if (has_decoration(type.self, DecorationBlock))
16076 {
16077 uint32_t member_count = uint32_t(type.member_types.size());
16078 Decoration promoted_decoration = {};
16079 bool do_promote_decoration = false;
16080 for (uint32_t i = 0; i < member_count; i++)
16081 {
16082 if (has_member_decoration(type.self, i, DecorationPatch))
16083 {
16084 promoted_decoration = DecorationPatch;
16085 do_promote_decoration = true;
16086 break;
16087 }
16088 else if (has_member_decoration(type.self, i, DecorationPerPrimitiveEXT))
16089 {
16090 promoted_decoration = DecorationPerPrimitiveEXT;
16091 do_promote_decoration = true;
16092 break;
16093 }
16094 }
16095
16096 if (do_promote_decoration)
16097 {
16098 set_decoration(var.self, promoted_decoration);
16099 for (uint32_t i = 0; i < member_count; i++)
16100 unset_member_decoration(type.self, i, promoted_decoration);
16101 }
16102 }
16103 }
16104
16105 string CompilerGLSL::to_qualifiers_glsl(uint32_t id)
16106 {
16107 auto &flags = get_decoration_bitset(id);
16108 string res;
16109
16110 auto *var = maybe_get<SPIRVariable>(id);
16111
16112 if (var && var->storage == StorageClassWorkgroup && !backend.shared_is_implied)
16113 res += "shared ";
16114 else if (var && var->storage == StorageClassTaskPayloadWorkgroupEXT && !backend.shared_is_implied)
16115 res += "taskPayloadSharedEXT ";
16116
16117 res += to_interpolation_qualifiers(flags);
16118 if (var)
16119 res += to_storage_qualifiers_glsl(*var);
16120
16121 auto &type = expression_type(id);
16122 if (type.image.dim != DimSubpassData && type.image.sampled == 2)
16123 {
16124 if (flags.get(DecorationCoherent))
16125 res += "coherent ";
16126 if (flags.get(DecorationRestrict))
16127 res += "restrict ";
16128
16129 if (flags.get(DecorationNonWritable))
16130 res += "readonly ";
16131
16132 bool formatted_load = type.image.format == ImageFormatUnknown;
16133 if (flags.get(DecorationNonReadable))
16134 {
16135 res += "writeonly ";
16136 formatted_load = false;
16137 }
16138
16139 if (formatted_load)
16140 {
16141 if (!options.es)
16142 require_extension_internal("GL_EXT_shader_image_load_formatted");
16143 else
16144 SPIRV_CROSS_THROW("Cannot use GL_EXT_shader_image_load_formatted in ESSL.");
16145 }
16146 }
16147
16148 res += to_precision_qualifiers_glsl(id);
16149
16150 return res;
16151 }
16152
16153 string CompilerGLSL::argument_decl(const SPIRFunction::Parameter &arg)
16154 {
16155 // glslangValidator seems to make all arguments pointer no matter what which is rather bizarre ...
16156 auto &type = expression_type(arg.id);
16157 const char *direction = "";
16158
16159 if (is_pointer(type) &&
16160 (type.storage == StorageClassFunction ||
16161 type.storage == StorageClassPrivate ||
16162 type.storage == StorageClassOutput))
16163 {
16164 // If we're passing around block types to function, we really mean reference in a pointer sense,
16165 // but DXC does not like inout for mesh blocks, so workaround that. out is technically not correct,
16166 // but it works in practice due to legalization. It's ... not great, but you gotta do what you gotta do.
16167 // GLSL will never hit this case since it's not valid.
16168 if (type.storage == StorageClassOutput && get_execution_model() == ExecutionModelMeshEXT &&
16169 has_decoration(type.self, DecorationBlock) && is_builtin_type(type) && arg.write_count)
16170 {
16171 direction = "out ";
16172 }
16173 else if (arg.write_count && arg.read_count)
16174 direction = "inout ";
16175 else if (arg.write_count)
16176 direction = "out ";
16177 }
16178
16179 return join(direction, to_qualifiers_glsl(arg.id), variable_decl(type, to_name(arg.id), arg.id));
16180 }
16181
16182 string CompilerGLSL::to_initializer_expression(const SPIRVariable &var)
16183 {
16184 return to_unpacked_expression(var.initializer);
16185 }
16186
16187 string CompilerGLSL::to_zero_initialized_expression(uint32_t type_id)
16188 {
16189 #ifndef NDEBUG
16190 auto &type = get<SPIRType>(type_id);
16191 assert(type.storage == StorageClassPrivate || type.storage == StorageClassFunction ||
16192 type.storage == StorageClassGeneric);
16193 #endif
16194 uint32_t id = ir.increase_bound_by(1);
16195 ir.make_constant_null(id, type_id, false);
16196 return constant_expression(get<SPIRConstant>(id));
16197 }
16198
16199 bool CompilerGLSL::type_can_zero_initialize(const SPIRType &type) const
16200 {
16201 if (type.pointer)
16202 return false;
16203
16204 if (!type.array.empty() && options.flatten_multidimensional_arrays)
16205 return false;
16206
16207 for (auto &literal : type.array_size_literal)
16208 if (!literal)
16209 return false;
16210
16211 for (auto &memb : type.member_types)
16212 if (!type_can_zero_initialize(get<SPIRType>(memb)))
16213 return false;
16214
16215 return true;
16216 }
16217
16218 string CompilerGLSL::variable_decl(const SPIRVariable &variable)
16219 {
16220 // Ignore the pointer type since GLSL doesn't have pointers.
16221 auto &type = get_variable_data_type(variable);
16222
16223 if (type.pointer_depth > 1 && !backend.support_pointer_to_pointer)
16224 SPIRV_CROSS_THROW("Cannot declare pointer-to-pointer types.");
16225
16226 auto res = join(to_qualifiers_glsl(variable.self), variable_decl(type, to_name(variable.self), variable.self));
16227
16228 if (variable.loop_variable && variable.static_expression)
16229 {
16230 uint32_t expr = variable.static_expression;
16231 if (ir.ids[expr].get_type() != TypeUndef)
16232 res += join(" = ", to_unpacked_expression(variable.static_expression));
16233 else if (options.force_zero_initialized_variables && type_can_zero_initialize(type))
16234 res += join(" = ", to_zero_initialized_expression(get_variable_data_type_id(variable)));
16235 }
16236 else if (variable.initializer)
16237 {
16238 if (!variable_decl_is_remapped_storage(variable, StorageClassWorkgroup))
16239 {
16240 uint32_t expr = variable.initializer;
16241 if (ir.ids[expr].get_type() != TypeUndef)
16242 res += join(" = ", to_initializer_expression(variable));
16243 else if (options.force_zero_initialized_variables && type_can_zero_initialize(type))
16244 res += join(" = ", to_zero_initialized_expression(get_variable_data_type_id(variable)));
16245 }
16246 else
16247 {
16248 // Workgroup memory requires special handling. First, it can only be Null-Initialized.
16249 // GLSL will handle this with null initializer, while others require more work after the decl
16250 require_extension_internal("GL_EXT_null_initializer");
16251 if (!backend.constant_null_initializer.empty())
16252 res += join(" = ", backend.constant_null_initializer);
16253 }
16254 }
16255
16256 return res;
16257 }
16258
16259 const char *CompilerGLSL::to_pls_qualifiers_glsl(const SPIRVariable &variable)
16260 {
16261 auto &flags = get_decoration_bitset(variable.self);
16262 if (flags.get(DecorationRelaxedPrecision))
16263 return "mediump ";
16264 else
16265 return "highp ";
16266 }
16267
16268 string CompilerGLSL::pls_decl(const PlsRemap &var)
16269 {
16270 auto &variable = get<SPIRVariable>(var.id);
16271
16272 auto op_and_basetype = pls_format_to_basetype(var.format);
16273
16274 SPIRType type { op_and_basetype.first };
16275 type.basetype = op_and_basetype.second;
16276 auto vecsize = pls_format_to_components(var.format);
16277 if (vecsize > 1)
16278 {
16279 type.op = OpTypeVector;
16280 type.vecsize = vecsize;
16281 }
16282
16283 return join(to_pls_layout(var.format), to_pls_qualifiers_glsl(variable), type_to_glsl(type), " ",
16284 to_name(variable.self));
16285 }
16286
16287 uint32_t CompilerGLSL::to_array_size_literal(const SPIRType &type) const
16288 {
16289 return to_array_size_literal(type, uint32_t(type.array.size() - 1));
16290 }
16291
16292 uint32_t CompilerGLSL::to_array_size_literal(const SPIRType &type, uint32_t index) const
16293 {
16294 assert(type.array.size() == type.array_size_literal.size());
16295
16296 if (type.array_size_literal[index])
16297 {
16298 return type.array[index];
16299 }
16300 else
16301 {
16302 // Use the default spec constant value.
16303 // This is the best we can do.
16304 return evaluate_constant_u32(type.array[index]);
16305 }
16306 }
16307
16308 string CompilerGLSL::to_array_size(const SPIRType &type, uint32_t index)
16309 {
16310 assert(type.array.size() == type.array_size_literal.size());
16311
16312 auto &size = type.array[index];
16313 if (!type.array_size_literal[index])
16314 return to_expression(size);
16315 else if (size)
16316 return convert_to_string(size);
16317 else if (!backend.unsized_array_supported)
16318 {
16319 // For runtime-sized arrays, we can work around
16320 // lack of standard support for this by simply having
16321 // a single element array.
16322 //
16323 // Runtime length arrays must always be the last element
16324 // in an interface block.
16325 return "1";
16326 }
16327 else
16328 return "";
16329 }
16330
16331 string CompilerGLSL::type_to_array_glsl(const SPIRType &type, uint32_t)
16332 {
16333 if (type.pointer && type.storage == StorageClassPhysicalStorageBuffer && type.basetype != SPIRType::Struct)
16334 {
16335 // We are using a wrapped pointer type, and we should not emit any array declarations here.
16336 return "";
16337 }
16338
16339 if (type.array.empty())
16340 return "";
16341
16342 if (options.flatten_multidimensional_arrays)
16343 {
16344 string res;
16345 res += "[";
16346 for (auto i = uint32_t(type.array.size()); i; i--)
16347 {
16348 res += enclose_expression(to_array_size(type, i - 1));
16349 if (i > 1)
16350 res += " * ";
16351 }
16352 res += "]";
16353 return res;
16354 }
16355 else
16356 {
16357 if (type.array.size() > 1)
16358 {
16359 if (!options.es && options.version < 430)
16360 require_extension_internal("GL_ARB_arrays_of_arrays");
16361 else if (options.es && options.version < 310)
16362 SPIRV_CROSS_THROW("Arrays of arrays not supported before ESSL version 310. "
16363 "Try using --flatten-multidimensional-arrays or set "
16364 "options.flatten_multidimensional_arrays to true.");
16365 }
16366
16367 string res;
16368 for (auto i = uint32_t(type.array.size()); i; i--)
16369 {
16370 res += "[";
16371 res += to_array_size(type, i - 1);
16372 res += "]";
16373 }
16374 return res;
16375 }
16376 }
16377
16378 string CompilerGLSL::image_type_glsl(const SPIRType &type, uint32_t id, bool /*member*/)
16379 {
16380 auto &imagetype = get<SPIRType>(type.image.type);
16381 string res;
16382
16383 switch (imagetype.basetype)
16384 {
16385 case SPIRType::Int64:
16386 res = "i64";
16387 require_extension_internal("GL_EXT_shader_image_int64");
16388 break;
16389 case SPIRType::UInt64:
16390 res = "u64";
16391 require_extension_internal("GL_EXT_shader_image_int64");
16392 break;
16393 case SPIRType::Int:
16394 case SPIRType::Short:
16395 case SPIRType::SByte:
16396 res = "i";
16397 break;
16398 case SPIRType::UInt:
16399 case SPIRType::UShort:
16400 case SPIRType::UByte:
16401 res = "u";
16402 break;
16403 default:
16404 break;
16405 }
16406
16407 // For half image types, we will force mediump for the sampler, and cast to f16 after any sampling operation.
16408 // We cannot express a true half texture type in GLSL. Neither for short integer formats for that matter.
16409
16410 if (type.basetype == SPIRType::Image && type.image.dim == DimSubpassData && options.vulkan_semantics)
16411 return res + "subpassInput" + (type.image.ms ? "MS" : "");
16412 else if (type.basetype == SPIRType::Image && type.image.dim == DimSubpassData &&
16413 subpass_input_is_framebuffer_fetch(id))
16414 {
16415 SPIRType sampled_type = get<SPIRType>(type.image.type);
16416 sampled_type.vecsize = 4;
16417 return type_to_glsl(sampled_type);
16418 }
16419
16420 // If we're emulating subpassInput with samplers, force sampler2D
16421 // so we don't have to specify format.
16422 if (type.basetype == SPIRType::Image && type.image.dim != DimSubpassData)
16423 {
16424 // Sampler buffers are always declared as samplerBuffer even though they might be separate images in the SPIR-V.
16425 if (type.image.dim == DimBuffer && type.image.sampled == 1)
16426 res += "sampler";
16427 else
16428 res += type.image.sampled == 2 ? "image" : "texture";
16429 }
16430 else
16431 res += "sampler";
16432
16433 switch (type.image.dim)
16434 {
16435 case Dim1D:
16436 // ES doesn't support 1D. Fake it with 2D.
16437 res += options.es ? "2D" : "1D";
16438 break;
16439 case Dim2D:
16440 res += "2D";
16441 break;
16442 case Dim3D:
16443 res += "3D";
16444 break;
16445 case DimCube:
16446 res += "Cube";
16447 break;
16448 case DimRect:
16449 if (options.es)
16450 SPIRV_CROSS_THROW("Rectangle textures are not supported on OpenGL ES.");
16451
16452 if (is_legacy_desktop())
16453 require_extension_internal("GL_ARB_texture_rectangle");
16454
16455 res += "2DRect";
16456 break;
16457
16458 case DimBuffer:
16459 if (options.es && options.version < 320)
16460 require_extension_internal("GL_EXT_texture_buffer");
16461 else if (!options.es && options.version < 140)
16462 require_extension_internal("GL_EXT_texture_buffer_object");
16463 res += "Buffer";
16464 break;
16465
16466 case DimSubpassData:
16467 res += "2D";
16468 break;
16469 default:
16470 SPIRV_CROSS_THROW("Only 1D, 2D, 2DRect, 3D, Buffer, InputTarget and Cube textures supported.");
16471 }
16472
16473 if (type.image.ms)
16474 res += "MS";
16475 if (type.image.arrayed)
16476 {
16477 if (is_legacy_desktop())
16478 require_extension_internal("GL_EXT_texture_array");
16479 res += "Array";
16480 }
16481
16482 // "Shadow" state in GLSL only exists for samplers and combined image samplers.
16483 if (((type.basetype == SPIRType::SampledImage) || (type.basetype == SPIRType::Sampler)) &&
16484 is_depth_image(type, id))
16485 {
16486 res += "Shadow";
16487
16488 if (type.image.dim == DimCube && is_legacy())
16489 {
16490 if (!options.es)
16491 require_extension_internal("GL_EXT_gpu_shader4");
16492 else
16493 {
16494 require_extension_internal("GL_NV_shadow_samplers_cube");
16495 res += "NV";
16496 }
16497 }
16498 }
16499
16500 return res;
16501 }
16502
16503 string CompilerGLSL::type_to_glsl_constructor(const SPIRType &type)
16504 {
16505 if (backend.use_array_constructor && type.array.size() > 1)
16506 {
16507 if (options.flatten_multidimensional_arrays)
16508 SPIRV_CROSS_THROW("Cannot flatten constructors of multidimensional array constructors, "
16509 "e.g. float[][]().");
16510 else if (!options.es && options.version < 430)
16511 require_extension_internal("GL_ARB_arrays_of_arrays");
16512 else if (options.es && options.version < 310)
16513 SPIRV_CROSS_THROW("Arrays of arrays not supported before ESSL version 310.");
16514 }
16515
16516 auto e = type_to_glsl(type);
16517 if (backend.use_array_constructor)
16518 {
16519 for (uint32_t i = 0; i < type.array.size(); i++)
16520 e += "[]";
16521 }
16522 return e;
16523 }
16524
16525 // The optional id parameter indicates the object whose type we are trying
16526 // to find the description for. It is optional. Most type descriptions do not
16527 // depend on a specific object's use of that type.
16528 string CompilerGLSL::type_to_glsl(const SPIRType &type, uint32_t id)
16529 {
16530 if (is_physical_pointer(type) && !is_physical_pointer_to_buffer_block(type))
16531 {
16532 // Need to create a magic type name which compacts the entire type information.
16533 auto *parent = &get_pointee_type(type);
16534 string name = type_to_glsl(*parent);
16535
16536 uint32_t array_stride = get_decoration(type.parent_type, DecorationArrayStride);
16537
16538 // Resolve all array dimensions in one go since once we lose the pointer type,
16539 // array information is left to to_array_type_glsl. The base type loses array information.
16540 while (is_array(*parent))
16541 {
16542 if (parent->array_size_literal.back())
16543 name += join(type.array.back(), "_");
16544 else
16545 name += join("id", type.array.back(), "_");
16546
16547 name += "stride_" + std::to_string(array_stride);
16548
16549 array_stride = get_decoration(parent->parent_type, DecorationArrayStride);
16550 parent = &get<SPIRType>(parent->parent_type);
16551 }
16552
16553 name += "Pointer";
16554 return name;
16555 }
16556
16557 switch (type.basetype)
16558 {
16559 case SPIRType::Struct:
16560 // Need OpName lookup here to get a "sensible" name for a struct.
16561 if (backend.explicit_struct_type)
16562 return join("struct ", to_name(type.self));
16563 else
16564 return to_name(type.self);
16565
16566 case SPIRType::Image:
16567 case SPIRType::SampledImage:
16568 return image_type_glsl(type, id);
16569
16570 case SPIRType::Sampler:
16571 // The depth field is set by calling code based on the variable ID of the sampler, effectively reintroducing
16572 // this distinction into the type system.
16573 return comparison_ids.count(id) ? "samplerShadow" : "sampler";
16574
16575 case SPIRType::AccelerationStructure:
16576 return ray_tracing_is_khr ? "accelerationStructureEXT" : "accelerationStructureNV";
16577
16578 case SPIRType::RayQuery:
16579 return "rayQueryEXT";
16580
16581 case SPIRType::Void:
16582 return "void";
16583
16584 default:
16585 break;
16586 }
16587
16588 if (type.basetype == SPIRType::UInt && is_legacy())
16589 {
16590 if (options.es)
16591 // HACK: spirv-cross changes bools into uints and generates code which compares them to
16592 // zero. Input code will have already been validated as not to have contained any uints,
16593 // so any remaining uints must in fact be bools. However, simply returning "bool" here
16594 // will result in invalid code. Instead, return an int.
16595 return backend.basic_int_type;
16596 else
16597 require_extension_internal("GL_EXT_gpu_shader4");
16598 }
16599
16600 if (type.basetype == SPIRType::AtomicCounter)
16601 {
16602 if (options.es && options.version < 310)
16603 SPIRV_CROSS_THROW("At least ESSL 3.10 required for atomic counters.");
16604 else if (!options.es && options.version < 420)
16605 require_extension_internal("GL_ARB_shader_atomic_counters");
16606 }
16607
16608 const SPIRType *coop_type = &type;
16609 while (is_pointer(*coop_type) || is_array(*coop_type))
16610 coop_type = &get<SPIRType>(coop_type->parent_type);
16611
16612 if (coop_type->op == spv::OpTypeCooperativeMatrixKHR)
16613 {
16614 require_extension_internal("GL_KHR_cooperative_matrix");
16615 if (!options.vulkan_semantics)
16616 SPIRV_CROSS_THROW("Cooperative matrix only available in Vulkan.");
16617 // GLSL doesn't support this as spec constant, which makes sense ...
16618 uint32_t use_type = get<SPIRConstant>(coop_type->cooperative.use_id).scalar();
16619
16620 const char *use = nullptr;
16621 switch (use_type)
16622 {
16623 case CooperativeMatrixUseMatrixAKHR:
16624 use = "gl_MatrixUseA";
16625 break;
16626
16627 case CooperativeMatrixUseMatrixBKHR:
16628 use = "gl_MatrixUseB";
16629 break;
16630
16631 case CooperativeMatrixUseMatrixAccumulatorKHR:
16632 use = "gl_MatrixUseAccumulator";
16633 break;
16634
16635 default:
16636 SPIRV_CROSS_THROW("Invalid matrix use.");
16637 }
16638
16639 string scope_expr;
16640 if (const auto *scope = maybe_get<SPIRConstant>(coop_type->cooperative.scope_id))
16641 {
16642 if (!scope->specialization)
16643 {
16644 require_extension_internal("GL_KHR_memory_scope_semantics");
16645 if (scope->scalar() == spv::ScopeSubgroup)
16646 scope_expr = "gl_ScopeSubgroup";
16647 else if (scope->scalar() == spv::ScopeWorkgroup)
16648 scope_expr = "gl_ScopeWorkgroup";
16649 else
16650 SPIRV_CROSS_THROW("Invalid scope for cooperative matrix.");
16651 }
16652 }
16653
16654 if (scope_expr.empty())
16655 scope_expr = to_expression(coop_type->cooperative.scope_id);
16656
16657 return join("coopmat<", type_to_glsl(get<SPIRType>(coop_type->parent_type)), ", ",
16658 scope_expr, ", ",
16659 to_expression(coop_type->cooperative.rows_id), ", ",
16660 to_expression(coop_type->cooperative.columns_id), ", ", use, ">");
16661 }
16662
16663 if (type.vecsize == 1 && type.columns == 1) // Scalar builtin
16664 {
16665 switch (type.basetype)
16666 {
16667 case SPIRType::Boolean:
16668 return "bool";
16669 case SPIRType::SByte:
16670 return backend.basic_int8_type;
16671 case SPIRType::UByte:
16672 return backend.basic_uint8_type;
16673 case SPIRType::Short:
16674 return backend.basic_int16_type;
16675 case SPIRType::UShort:
16676 return backend.basic_uint16_type;
16677 case SPIRType::Int:
16678 return backend.basic_int_type;
16679 case SPIRType::UInt:
16680 return backend.basic_uint_type;
16681 case SPIRType::AtomicCounter:
16682 return "atomic_uint";
16683 case SPIRType::Half:
16684 return "float16_t";
16685 case SPIRType::BFloat16:
16686 if (!options.vulkan_semantics)
16687 SPIRV_CROSS_THROW("bfloat16 requires Vulkan semantics.");
16688 require_extension_internal("GL_EXT_bfloat16");
16689 return "bfloat16_t";
16690 case SPIRType::FloatE4M3:
16691 if (!options.vulkan_semantics)
16692 SPIRV_CROSS_THROW("floate4m3_t requires Vulkan semantics.");
16693 require_extension_internal("GL_EXT_float_e4m3");
16694 return "floate4m3_t";
16695 case SPIRType::FloatE5M2:
16696 if (!options.vulkan_semantics)
16697 SPIRV_CROSS_THROW("floate5m2_t requires Vulkan semantics.");
16698 require_extension_internal("GL_EXT_float_e5m2");
16699 return "floate5m2_t";
16700 case SPIRType::Float:
16701 return "float";
16702 case SPIRType::Double:
16703 return "double";
16704 case SPIRType::Int64:
16705 return "int64_t";
16706 case SPIRType::UInt64:
16707 return "uint64_t";
16708 default:
16709 return "???";
16710 }
16711 }
16712 else if (type.vecsize > 1 && type.columns == 1) // Vector builtin
16713 {
16714 switch (type.basetype)
16715 {
16716 case SPIRType::Boolean:
16717 return join("bvec", type.vecsize);
16718 case SPIRType::SByte:
16719 return join("i8vec", type.vecsize);
16720 case SPIRType::UByte:
16721 return join("u8vec", type.vecsize);
16722 case SPIRType::Short:
16723 return join("i16vec", type.vecsize);
16724 case SPIRType::UShort:
16725 return join("u16vec", type.vecsize);
16726 case SPIRType::Int:
16727 return join("ivec", type.vecsize);
16728 case SPIRType::UInt:
16729 return join("uvec", type.vecsize);
16730 case SPIRType::Half:
16731 return join("f16vec", type.vecsize);
16732 case SPIRType::BFloat16:
16733 if (!options.vulkan_semantics)
16734 SPIRV_CROSS_THROW("bfloat16 requires Vulkan semantics.");
16735 require_extension_internal("GL_EXT_bfloat16");
16736 return join("bf16vec", type.vecsize);
16737 case SPIRType::FloatE4M3:
16738 if (!options.vulkan_semantics)
16739 SPIRV_CROSS_THROW("floate4m3_t requires Vulkan semantics.");
16740 require_extension_internal("GL_EXT_float_e4m3");
16741 return join("fe4m3vec", type.vecsize);
16742 case SPIRType::FloatE5M2:
16743 if (!options.vulkan_semantics)
16744 SPIRV_CROSS_THROW("floate5m2_t requires Vulkan semantics.");
16745 require_extension_internal("GL_EXT_float_e5m2");
16746 return join("fe5m2vec", type.vecsize);
16747 case SPIRType::Float:
16748 return join("vec", type.vecsize);
16749 case SPIRType::Double:
16750 return join("dvec", type.vecsize);
16751 case SPIRType::Int64:
16752 return join("i64vec", type.vecsize);
16753 case SPIRType::UInt64:
16754 return join("u64vec", type.vecsize);
16755 default:
16756 return "???";
16757 }
16758 }
16759 else if (type.vecsize == type.columns) // Simple Matrix builtin
16760 {
16761 switch (type.basetype)
16762 {
16763 case SPIRType::Boolean:
16764 return join("bmat", type.vecsize);
16765 case SPIRType::Int:
16766 return join("imat", type.vecsize);
16767 case SPIRType::UInt:
16768 return join("umat", type.vecsize);
16769 case SPIRType::Half:
16770 return join("f16mat", type.vecsize);
16771 case SPIRType::Float:
16772 return join("mat", type.vecsize);
16773 case SPIRType::Double:
16774 return join("dmat", type.vecsize);
16775 // Matrix types not supported for int64/uint64.
16776 default:
16777 return "???";
16778 }
16779 }
16780 else
16781 {
16782 switch (type.basetype)
16783 {
16784 case SPIRType::Boolean:
16785 return join("bmat", type.columns, "x", type.vecsize);
16786 case SPIRType::Int:
16787 return join("imat", type.columns, "x", type.vecsize);
16788 case SPIRType::UInt:
16789 return join("umat", type.columns, "x", type.vecsize);
16790 case SPIRType::Half:
16791 return join("f16mat", type.columns, "x", type.vecsize);
16792 case SPIRType::Float:
16793 return join("mat", type.columns, "x", type.vecsize);
16794 case SPIRType::Double:
16795 return join("dmat", type.columns, "x", type.vecsize);
16796 // Matrix types not supported for int64/uint64.
16797 default:
16798 return "???";
16799 }
16800 }
16801 }
16802
16803 void CompilerGLSL::add_variable(unordered_set<string> &variables_primary,
16804 const unordered_set<string> &variables_secondary, string &name)
16805 {
16806 if (name.empty())
16807 return;
16808
16809 ParsedIR::sanitize_underscores(name);
16810 if (ParsedIR::is_globally_reserved_identifier(name, true))
16811 {
16812 name.clear();
16813 return;
16814 }
16815
16816 update_name_cache(variables_primary, variables_secondary, name);
16817 }
16818
16819 void CompilerGLSL::add_local_variable_name(uint32_t id)
16820 {
16821 add_variable(local_variable_names, block_names, ir.meta[id].decoration.alias);
16822 }
16823
16824 void CompilerGLSL::add_resource_name(uint32_t id)
16825 {
16826 add_variable(resource_names, block_names, ir.meta[id].decoration.alias);
16827 }
16828
16829 void CompilerGLSL::add_header_line(const std::string &line)
16830 {
16831 header_lines.push_back(line);
16832 }
16833
16834 bool CompilerGLSL::has_extension(const std::string &ext) const
16835 {
16836 auto itr = find(begin(forced_extensions), end(forced_extensions), ext);
16837 return itr != end(forced_extensions);
16838 }
16839
16840 void CompilerGLSL::require_extension(const std::string &ext)
16841 {
16842 if (!has_extension(ext))
16843 forced_extensions.push_back(ext);
16844 }
16845
16846 const SmallVector<std::string> &CompilerGLSL::get_required_extensions() const
16847 {
16848 return forced_extensions;
16849 }
16850
16851 void CompilerGLSL::require_extension_internal(const string &ext)
16852 {
16853 if (backend.supports_extensions && !has_extension(ext))
16854 {
16855 forced_extensions.push_back(ext);
16856 force_recompile();
16857 }
16858 }
16859
16860 void CompilerGLSL::flatten_buffer_block(VariableID id)
16861 {
16862 auto &var = get<SPIRVariable>(id);
16863 auto &type = get<SPIRType>(var.basetype);
16864 auto name = to_name(type.self, false);
16865 auto &flags = get_decoration_bitset(type.self);
16866
16867 if (!type.array.empty())
16868 SPIRV_CROSS_THROW(name + " is an array of UBOs.");
16869 if (type.basetype != SPIRType::Struct)
16870 SPIRV_CROSS_THROW(name + " is not a struct.");
16871 if (!flags.get(DecorationBlock))
16872 SPIRV_CROSS_THROW(name + " is not a block.");
16873 if (type.member_types.empty())
16874 SPIRV_CROSS_THROW(name + " is an empty struct.");
16875
16876 flattened_buffer_blocks.insert(id);
16877 }
16878
16879 bool CompilerGLSL::builtin_translates_to_nonarray(spv::BuiltIn /*builtin*/) const
16880 {
16881 return false; // GLSL itself does not need to translate array builtin types to non-array builtin types
16882 }
16883
16884 bool CompilerGLSL::is_user_type_structured(uint32_t /*id*/) const
16885 {
16886 return false; // GLSL itself does not have structured user type, but HLSL does with StructuredBuffer and RWStructuredBuffer resources.
16887 }
16888
16889 bool CompilerGLSL::check_atomic_image(uint32_t id)
16890 {
16891 auto &type = expression_type(id);
16892 if (type.storage == StorageClassImage)
16893 {
16894 if (options.es && options.version < 320)
16895 require_extension_internal("GL_OES_shader_image_atomic");
16896
16897 auto *var = maybe_get_backing_variable(id);
16898 if (var)
16899 {
16900 if (has_decoration(var->self, DecorationNonWritable) || has_decoration(var->self, DecorationNonReadable))
16901 {
16902 unset_decoration(var->self, DecorationNonWritable);
16903 unset_decoration(var->self, DecorationNonReadable);
16904 force_recompile();
16905 }
16906 }
16907 return true;
16908 }
16909 else
16910 return false;
16911 }
16912
16913 void CompilerGLSL::add_function_overload(const SPIRFunction &func)
16914 {
16915 Hasher hasher;
16916 for (auto &arg : func.arguments)
16917 {
16918 // Parameters can vary with pointer type or not,
16919 // but that will not change the signature in GLSL/HLSL,
16920 // so strip the pointer type before hashing.
16921 uint32_t type_id = get_pointee_type_id(arg.type);
16922
16923 // Workaround glslang bug. It seems to only consider the base type when resolving overloads.
16924 if (get<SPIRType>(type_id).op == spv::OpTypeCooperativeMatrixKHR)
16925 type_id = get<SPIRType>(type_id).parent_type;
16926
16927 auto &type = get<SPIRType>(type_id);
16928
16929 if (!combined_image_samplers.empty())
16930 {
16931 // If we have combined image samplers, we cannot really trust the image and sampler arguments
16932 // we pass down to callees, because they may be shuffled around.
16933 // Ignore these arguments, to make sure that functions need to differ in some other way
16934 // to be considered different overloads.
16935 if (type.basetype == SPIRType::SampledImage ||
16936 (type.basetype == SPIRType::Image && type.image.sampled == 1) || type.basetype == SPIRType::Sampler)
16937 {
16938 continue;
16939 }
16940 }
16941
16942 hasher.u32(type_id);
16943 }
16944 uint64_t types_hash = hasher.get();
16945
16946 auto function_name = to_name(func.self);
16947 auto itr = function_overloads.find(function_name);
16948 if (itr != end(function_overloads))
16949 {
16950 // There exists a function with this name already.
16951 auto &overloads = itr->second;
16952 if (overloads.count(types_hash) != 0)
16953 {
16954 // Overload conflict, assign a new name.
16955 add_resource_name(func.self);
16956 function_overloads[to_name(func.self)].insert(types_hash);
16957 }
16958 else
16959 {
16960 // Can reuse the name.
16961 overloads.insert(types_hash);
16962 }
16963 }
16964 else
16965 {
16966 // First time we see this function name.
16967 add_resource_name(func.self);
16968 function_overloads[to_name(func.self)].insert(types_hash);
16969 }
16970 }
16971
16972 void CompilerGLSL::emit_function_prototype(SPIRFunction &func, const Bitset &return_flags)
16973 {
16974 if (func.self != ir.default_entry_point)
16975 add_function_overload(func);
16976
16977 // Avoid shadow declarations.
16978 local_variable_names = resource_names;
16979
16980 string decl;
16981
16982 auto &type = get<SPIRType>(func.return_type);
16983 decl += flags_to_qualifiers_glsl(type, return_flags);
16984 decl += type_to_glsl(type);
16985 decl += type_to_array_glsl(type, 0);
16986 decl += " ";
16987
16988 if (func.self == ir.default_entry_point)
16989 {
16990 // If we need complex fallback in GLSL, we just wrap main() in a function
16991 // and interlock the entire shader ...
16992 if (interlocked_is_complex)
16993 decl += "spvMainInterlockedBody";
16994 else
16995 decl += "main";
16996
16997 processing_entry_point = true;
16998 }
16999 else
17000 decl += to_name(func.self);
17001
17002 decl += "(";
17003 SmallVector<string> arglist;
17004 for (auto &arg : func.arguments)
17005 {
17006 // Do not pass in separate images or samplers if we're remapping
17007 // to combined image samplers.
17008 if (skip_argument(arg.id))
17009 continue;
17010
17011 // Might change the variable name if it already exists in this function.
17012 // SPIRV OpName doesn't have any semantic effect, so it's valid for an implementation
17013 // to use same name for variables.
17014 // Since we want to make the GLSL debuggable and somewhat sane, use fallback names for variables which are duplicates.
17015 add_local_variable_name(arg.id);
17016
17017 arglist.push_back(argument_decl(arg));
17018
17019 // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
17020 auto *var = maybe_get<SPIRVariable>(arg.id);
17021 if (var)
17022 var->parameter = &arg;
17023 }
17024
17025 for (auto &arg : func.shadow_arguments)
17026 {
17027 // Might change the variable name if it already exists in this function.
17028 // SPIRV OpName doesn't have any semantic effect, so it's valid for an implementation
17029 // to use same name for variables.
17030 // Since we want to make the GLSL debuggable and somewhat sane, use fallback names for variables which are duplicates.
17031 add_local_variable_name(arg.id);
17032
17033 arglist.push_back(argument_decl(arg));
17034
17035 // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
17036 auto *var = maybe_get<SPIRVariable>(arg.id);
17037 if (var)
17038 var->parameter = &arg;
17039 }
17040
17041 decl += merge(arglist);
17042 decl += ")";
17043 statement(decl);
17044 }
17045
17046 void CompilerGLSL::emit_function(SPIRFunction &func, const Bitset &return_flags)
17047 {
17048 // Avoid potential cycles.
17049 if (func.active)
17050 return;
17051 func.active = true;
17052
17053 // If we depend on a function, emit that function before we emit our own function.
17054 for (auto block : func.blocks)
17055 {
17056 auto &b = get<SPIRBlock>(block);
17057 for (auto &i : b.ops)
17058 {
17059 auto ops = stream(i);
17060 auto op = static_cast<Op>(i.op);
17061
17062 if (op == OpFunctionCall)
17063 {
17064 // Recursively emit functions which are called.
17065 uint32_t id = ops[2];
17066
17067 emit_function(get<SPIRFunction>(id), ir.meta[ops[1]].decoration.decoration_flags);
17068 }
17069 }
17070 }
17071
17072 if (func.entry_line.file_id != 0)
17073 emit_line_directive(func.entry_line.file_id, func.entry_line.line_literal);
17074 emit_function_prototype(func, return_flags);
17075 begin_scope();
17076
17077 if (func.self == ir.default_entry_point)
17078 emit_entry_point_declarations();
17079
17080 current_function = &func;
17081 auto &entry_block = get<SPIRBlock>(func.entry_block);
17082
17083 sort(begin(func.constant_arrays_needed_on_stack), end(func.constant_arrays_needed_on_stack));
17084 for (auto &array : func.constant_arrays_needed_on_stack)
17085 {
17086 auto &c = get<SPIRConstant>(array);
17087 auto &type = get<SPIRType>(c.constant_type);
17088 statement(variable_decl(type, join("_", array, "_array_copy")), " = ", constant_expression(c), ";");
17089 }
17090
17091 for (auto &v : func.local_variables)
17092 {
17093 auto &var = get<SPIRVariable>(v);
17094 var.deferred_declaration = false;
17095 if (var.storage == StorageClassTaskPayloadWorkgroupEXT)
17096 continue;
17097
17098 if (variable_decl_is_remapped_storage(var, StorageClassWorkgroup))
17099 {
17100 // Special variable type which cannot have initializer,
17101 // need to be declared as standalone variables.
17102 // Comes from MSL which can push global variables as local variables in main function.
17103 add_local_variable_name(var.self);
17104 statement(variable_decl(var), ";");
17105
17106 // "Real" workgroup variables in compute shaders needs extra caretaking.
17107 // They need to be initialized with an extra routine as they come in arbitrary form.
17108 if (var.storage == StorageClassWorkgroup && var.initializer)
17109 emit_workgroup_initialization(var);
17110
17111 var.deferred_declaration = false;
17112 }
17113 else if (var.storage == StorageClassPrivate)
17114 {
17115 // These variables will not have had their CFG usage analyzed, so move it to the entry block.
17116 // Comes from MSL which can push global variables as local variables in main function.
17117 // We could just declare them right now, but we would miss out on an important initialization case which is
17118 // LUT declaration in MSL.
17119 // If we don't declare the variable when it is assigned we're forced to go through a helper function
17120 // which copies elements one by one.
17121 add_local_variable_name(var.self);
17122
17123 if (var.initializer)
17124 {
17125 statement(variable_decl(var), ";");
17126 var.deferred_declaration = false;
17127 }
17128 else
17129 {
17130 auto &dominated = entry_block.dominated_variables;
17131 if (find(begin(dominated), end(dominated), var.self) == end(dominated))
17132 entry_block.dominated_variables.push_back(var.self);
17133 var.deferred_declaration = true;
17134 }
17135 }
17136 else if (var.storage == StorageClassFunction && var.remapped_variable && var.static_expression)
17137 {
17138 // No need to declare this variable, it has a static expression.
17139 var.deferred_declaration = false;
17140 }
17141 else if (expression_is_lvalue(v))
17142 {
17143 add_local_variable_name(var.self);
17144
17145 // Loop variables should never be declared early, they are explicitly emitted in a loop.
17146 if (var.initializer && !var.loop_variable)
17147 statement(variable_decl_function_local(var), ";");
17148 else
17149 {
17150 // Don't declare variable until first use to declutter the GLSL output quite a lot.
17151 // If we don't touch the variable before first branch,
17152 // declare it then since we need variable declaration to be in top scope.
17153 var.deferred_declaration = true;
17154 }
17155 }
17156 else
17157 {
17158 // HACK: SPIR-V in older glslang output likes to use samplers and images as local variables, but GLSL does not allow this.
17159 // For these types (non-lvalue), we enforce forwarding through a shadowed variable.
17160 // This means that when we OpStore to these variables, we just write in the expression ID directly.
17161 // This breaks any kind of branching, since the variable must be statically assigned.
17162 // Branching on samplers and images would be pretty much impossible to fake in GLSL.
17163 var.statically_assigned = true;
17164 }
17165
17166 var.loop_variable_enable = false;
17167
17168 // Loop variables are never declared outside their for-loop, so block any implicit declaration.
17169 if (var.loop_variable)
17170 {
17171 var.deferred_declaration = false;
17172 // Need to reset the static expression so we can fallback to initializer if need be.
17173 var.static_expression = 0;
17174 }
17175 }
17176
17177 // Enforce declaration order for regression testing purposes.
17178 for (auto &block_id : func.blocks)
17179 {
17180 auto &block = get<SPIRBlock>(block_id);
17181 sort(begin(block.dominated_variables), end(block.dominated_variables));
17182 }
17183
17184 for (auto &line : current_function->fixup_hooks_in)
17185 line();
17186
17187 emit_block_chain(entry_block);
17188
17189 end_scope();
17190 processing_entry_point = false;
17191 statement("");
17192
17193 // Make sure deferred declaration state for local variables is cleared when we are done with function.
17194 // We risk declaring Private/Workgroup variables in places we are not supposed to otherwise.
17195 for (auto &v : func.local_variables)
17196 {
17197 auto &var = get<SPIRVariable>(v);
17198 var.deferred_declaration = false;
17199 }
17200 }
17201
17202 void CompilerGLSL::emit_fixup()
17203 {
17204 if (is_vertex_like_shader())
17205 {
17206 if (options.vertex.fixup_clipspace)
17207 {
17208 const char *suffix = backend.float_literal_suffix ? "f" : "";
17209 statement("gl_Position.z = 2.0", suffix, " * gl_Position.z - gl_Position.w;");
17210 }
17211
17212 if (options.vertex.flip_vert_y)
17213 statement("gl_Position.y = -gl_Position.y;");
17214 }
17215 }
17216
17217 void CompilerGLSL::emit_workgroup_initialization(const SPIRVariable &)
17218 {
17219 }
17220
17221 void CompilerGLSL::flush_phi(BlockID from, BlockID to)
17222 {
17223 auto &child = get<SPIRBlock>(to);
17224 if (child.ignore_phi_from_block == from)
17225 return;
17226
17227 unordered_set<uint32_t> temporary_phi_variables;
17228
17229 for (auto itr = begin(child.phi_variables); itr != end(child.phi_variables); ++itr)
17230 {
17231 auto &phi = *itr;
17232
17233 if (phi.parent == from)
17234 {
17235 auto &var = get<SPIRVariable>(phi.function_variable);
17236
17237 // A Phi variable might be a loop variable, so flush to static expression.
17238 if (var.loop_variable && !var.loop_variable_enable)
17239 var.static_expression = phi.local_variable;
17240 else
17241 {
17242 flush_variable_declaration(phi.function_variable);
17243
17244 // Check if we are going to write to a Phi variable that another statement will read from
17245 // as part of another Phi node in our target block.
17246 // For this case, we will need to copy phi.function_variable to a temporary, and use that for future reads.
17247 // This is judged to be extremely rare, so deal with it here using a simple, but suboptimal algorithm.
17248 bool need_saved_temporary =
17249 find_if(itr + 1, end(child.phi_variables), [&](const SPIRBlock::Phi &future_phi) -> bool {
17250 return future_phi.local_variable == ID(phi.function_variable) && future_phi.parent == from;
17251 }) != end(child.phi_variables);
17252
17253 if (need_saved_temporary)
17254 {
17255 // Need to make sure we declare the phi variable with a copy at the right scope.
17256 // We cannot safely declare a temporary here since we might be inside a continue block.
17257 if (!var.allocate_temporary_copy)
17258 {
17259 var.allocate_temporary_copy = true;
17260 force_recompile();
17261 }
17262 statement("_", phi.function_variable, "_copy", " = ", to_name(phi.function_variable), ";");
17263 temporary_phi_variables.insert(phi.function_variable);
17264 }
17265
17266 // This might be called in continue block, so make sure we
17267 // use this to emit ESSL 1.0 compliant increments/decrements.
17268 auto lhs = to_expression(phi.function_variable);
17269
17270 string rhs;
17271 if (temporary_phi_variables.count(phi.local_variable))
17272 rhs = join("_", phi.local_variable, "_copy");
17273 else
17274 rhs = to_pointer_expression(phi.local_variable);
17275
17276 if (!optimize_read_modify_write(get<SPIRType>(var.basetype), lhs, rhs))
17277 statement(lhs, " = ", rhs, ";");
17278 }
17279
17280 register_write(phi.function_variable);
17281 }
17282 }
17283 }
17284
17285 void CompilerGLSL::branch_to_continue(BlockID from, BlockID to)
17286 {
17287 auto &to_block = get<SPIRBlock>(to);
17288 if (from == to)
17289 return;
17290
17291 assert(is_continue(to));
17292 if (to_block.complex_continue)
17293 {
17294 // Just emit the whole block chain as is.
17295 auto usage_counts = expression_usage_counts;
17296
17297 emit_block_chain(to_block);
17298
17299 // Expression usage counts are moot after returning from the continue block.
17300 expression_usage_counts = usage_counts;
17301 }
17302 else
17303 {
17304 auto &from_block = get<SPIRBlock>(from);
17305 bool outside_control_flow = false;
17306 uint32_t loop_dominator = 0;
17307
17308 // FIXME: Refactor this to not use the old loop_dominator tracking.
17309 if (from_block.merge_block)
17310 {
17311 // If we are a loop header, we don't set the loop dominator,
17312 // so just use "self" here.
17313 loop_dominator = from;
17314 }
17315 else if (from_block.loop_dominator != BlockID(SPIRBlock::NoDominator))
17316 {
17317 loop_dominator = from_block.loop_dominator;
17318 }
17319
17320 if (loop_dominator != 0)
17321 {
17322 auto &cfg = get_cfg_for_current_function();
17323
17324 // For non-complex continue blocks, we implicitly branch to the continue block
17325 // by having the continue block be part of the loop header in for (; ; continue-block).
17326 outside_control_flow = cfg.node_terminates_control_flow_in_sub_graph(loop_dominator, from);
17327 }
17328
17329 // Some simplification for for-loops. We always end up with a useless continue;
17330 // statement since we branch to a loop block.
17331 // Walk the CFG, if we unconditionally execute the block calling continue assuming we're in the loop block,
17332 // we can avoid writing out an explicit continue statement.
17333 // Similar optimization to return statements if we know we're outside flow control.
17334 if (!outside_control_flow)
17335 statement("continue;");
17336 }
17337 }
17338
17339 void CompilerGLSL::branch(BlockID from, BlockID to)
17340 {
17341 flush_phi(from, to);
17342 flush_control_dependent_expressions(from);
17343
17344 bool to_is_continue = is_continue(to);
17345
17346 // This is only a continue if we branch to our loop dominator.
17347 if ((ir.block_meta[to] & ParsedIR::BLOCK_META_LOOP_HEADER_BIT) != 0 && get<SPIRBlock>(from).loop_dominator == to)
17348 {
17349 // This can happen if we had a complex continue block which was emitted.
17350 // Once the continue block tries to branch to the loop header, just emit continue;
17351 // and end the chain here.
17352 statement("continue;");
17353 }
17354 else if (from != to && is_break(to))
17355 {
17356 // We cannot break to ourselves, so check explicitly for from != to.
17357 // This case can trigger if a loop header is all three of these things:
17358 // - Continue block
17359 // - Loop header
17360 // - Break merge target all at once ...
17361
17362 // Very dirty workaround.
17363 // Switch constructs are able to break, but they cannot break out of a loop at the same time,
17364 // yet SPIR-V allows it.
17365 // Only sensible solution is to make a ladder variable, which we declare at the top of the switch block,
17366 // write to the ladder here, and defer the break.
17367 // The loop we're breaking out of must dominate the switch block, or there is no ladder breaking case.
17368 if (is_loop_break(to))
17369 {
17370 for (size_t n = current_emitting_switch_stack.size(); n; n--)
17371 {
17372 auto *current_emitting_switch = current_emitting_switch_stack[n - 1];
17373
17374 if (current_emitting_switch &&
17375 current_emitting_switch->loop_dominator != BlockID(SPIRBlock::NoDominator) &&
17376 get<SPIRBlock>(current_emitting_switch->loop_dominator).merge_block == to)
17377 {
17378 if (!current_emitting_switch->need_ladder_break)
17379 {
17380 force_recompile();
17381 current_emitting_switch->need_ladder_break = true;
17382 }
17383
17384 statement("_", current_emitting_switch->self, "_ladder_break = true;");
17385 }
17386 else
17387 break;
17388 }
17389 }
17390 statement("break;");
17391 }
17392 else if (to_is_continue || from == to)
17393 {
17394 // For from == to case can happen for a do-while loop which branches into itself.
17395 // We don't mark these cases as continue blocks, but the only possible way to branch into
17396 // ourselves is through means of continue blocks.
17397
17398 // If we are merging to a continue block, there is no need to emit the block chain for continue here.
17399 // We can branch to the continue block after we merge execution.
17400
17401 // Here we make use of structured control flow rules from spec:
17402 // 2.11: - the merge block declared by a header block cannot be a merge block declared by any other header block
17403 // - each header block must strictly dominate its merge block, unless the merge block is unreachable in the CFG
17404 // If we are branching to a merge block, we must be inside a construct which dominates the merge block.
17405 auto &block_meta = ir.block_meta[to];
17406 bool branching_to_merge =
17407 (block_meta & (ParsedIR::BLOCK_META_SELECTION_MERGE_BIT | ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT |
17408 ParsedIR::BLOCK_META_LOOP_MERGE_BIT)) != 0;
17409 if (!to_is_continue || !branching_to_merge)
17410 branch_to_continue(from, to);
17411 }
17412 else if (!is_conditional(to))
17413 emit_block_chain(get<SPIRBlock>(to));
17414
17415 // It is important that we check for break before continue.
17416 // A block might serve two purposes, a break block for the inner scope, and
17417 // a continue block in the outer scope.
17418 // Inner scope always takes precedence.
17419 }
17420
17421 void CompilerGLSL::branch(BlockID from, uint32_t cond, BlockID true_block, BlockID false_block)
17422 {
17423 auto &from_block = get<SPIRBlock>(from);
17424 BlockID merge_block = from_block.merge == SPIRBlock::MergeSelection ? from_block.next_block : BlockID(0);
17425
17426 // If we branch directly to our selection merge target, we don't need a code path.
17427 bool true_block_needs_code = true_block != merge_block || flush_phi_required(from, true_block);
17428 bool false_block_needs_code = false_block != merge_block || flush_phi_required(from, false_block);
17429
17430 if (!true_block_needs_code && !false_block_needs_code)
17431 return;
17432
17433 // We might have a loop merge here. Only consider selection flattening constructs.
17434 // Loop hints are handled explicitly elsewhere.
17435 if (from_block.hint == SPIRBlock::HintFlatten || from_block.hint == SPIRBlock::HintDontFlatten)
17436 emit_block_hints(from_block);
17437
17438 if (true_block_needs_code)
17439 {
17440 statement("if (", to_expression(cond), ")");
17441 begin_scope();
17442 branch(from, true_block);
17443 end_scope();
17444
17445 if (false_block_needs_code)
17446 {
17447 statement("else");
17448 begin_scope();
17449 branch(from, false_block);
17450 end_scope();
17451 }
17452 }
17453 else if (false_block_needs_code)
17454 {
17455 // Only need false path, use negative conditional.
17456 statement("if (!", to_enclosed_expression(cond), ")");
17457 begin_scope();
17458 branch(from, false_block);
17459 end_scope();
17460 }
17461 }
17462
17463 // FIXME: This currently cannot handle complex continue blocks
17464 // as in do-while.
17465 // This should be seen as a "trivial" continue block.
17466 string CompilerGLSL::emit_continue_block(uint32_t continue_block, bool follow_true_block, bool follow_false_block)
17467 {
17468 auto *block = &get<SPIRBlock>(continue_block);
17469
17470 // While emitting the continue block, declare_temporary will check this
17471 // if we have to emit temporaries.
17472 current_continue_block = block;
17473
17474 SmallVector<string> statements;
17475
17476 // Capture all statements into our list.
17477 auto *old = redirect_statement;
17478 redirect_statement = &statements;
17479
17480 // Stamp out all blocks one after each other.
17481 while ((ir.block_meta[block->self] & ParsedIR::BLOCK_META_LOOP_HEADER_BIT) == 0)
17482 {
17483 // Write out all instructions we have in this block.
17484 emit_block_instructions(*block);
17485
17486 // For plain branchless for/while continue blocks.
17487 if (block->next_block)
17488 {
17489 flush_phi(continue_block, block->next_block);
17490 block = &get<SPIRBlock>(block->next_block);
17491 }
17492 // For do while blocks. The last block will be a select block.
17493 else if (block->true_block && follow_true_block)
17494 {
17495 flush_phi(continue_block, block->true_block);
17496 block = &get<SPIRBlock>(block->true_block);
17497 }
17498 else if (block->false_block && follow_false_block)
17499 {
17500 flush_phi(continue_block, block->false_block);
17501 block = &get<SPIRBlock>(block->false_block);
17502 }
17503 else
17504 {
17505 SPIRV_CROSS_THROW("Invalid continue block detected!");
17506 }
17507 }
17508
17509 // Restore old pointer.
17510 redirect_statement = old;
17511
17512 // Somewhat ugly, strip off the last ';' since we use ',' instead.
17513 // Ideally, we should select this behavior in statement().
17514 for (auto &s : statements)
17515 {
17516 if (!s.empty() && s.back() == ';')
17517 s.erase(s.size() - 1, 1);
17518 }
17519
17520 current_continue_block = nullptr;
17521 return merge(statements);
17522 }
17523
17524 void CompilerGLSL::emit_while_loop_initializers(const SPIRBlock &block)
17525 {
17526 // While loops do not take initializers, so declare all of them outside.
17527 for (auto &loop_var : block.loop_variables)
17528 {
17529 auto &var = get<SPIRVariable>(loop_var);
17530 statement(variable_decl(var), ";");
17531 }
17532 }
17533
17534 string CompilerGLSL::emit_for_loop_initializers(const SPIRBlock &block)
17535 {
17536 if (block.loop_variables.empty())
17537 return "";
17538
17539 bool same_types = for_loop_initializers_are_same_type(block);
17540 // We can only declare for loop initializers if all variables are of same type.
17541 // If we cannot do this, declare individual variables before the loop header.
17542
17543 // We might have a loop variable candidate which was not assigned to for some reason.
17544 uint32_t missing_initializers = 0;
17545 for (auto &variable : block.loop_variables)
17546 {
17547 uint32_t expr = get<SPIRVariable>(variable).static_expression;
17548
17549 // Sometimes loop variables are initialized with OpUndef, but we can just declare
17550 // a plain variable without initializer in this case.
17551 if (expr == 0 || ir.ids[expr].get_type() == TypeUndef)
17552 missing_initializers++;
17553 }
17554
17555 if (block.loop_variables.size() == 1 && missing_initializers == 0)
17556 {
17557 return variable_decl(get<SPIRVariable>(block.loop_variables.front()));
17558 }
17559 else if (!same_types || missing_initializers == uint32_t(block.loop_variables.size()))
17560 {
17561 for (auto &loop_var : block.loop_variables)
17562 statement(variable_decl(get<SPIRVariable>(loop_var)), ";");
17563 return "";
17564 }
17565 else
17566 {
17567 // We have a mix of loop variables, either ones with a clear initializer, or ones without.
17568 // Separate the two streams.
17569 string expr;
17570
17571 for (auto &loop_var : block.loop_variables)
17572 {
17573 uint32_t static_expr = get<SPIRVariable>(loop_var).static_expression;
17574 if (static_expr == 0 || ir.ids[static_expr].get_type() == TypeUndef)
17575 {
17576 statement(variable_decl(get<SPIRVariable>(loop_var)), ";");
17577 }
17578 else
17579 {
17580 auto &var = get<SPIRVariable>(loop_var);
17581 auto &type = get_variable_data_type(var);
17582 if (expr.empty())
17583 {
17584 // For loop initializers are of the form <type id = value, id = value, id = value, etc ...
17585 expr = join(to_qualifiers_glsl(var.self), type_to_glsl(type), " ");
17586 }
17587 else
17588 {
17589 expr += ", ";
17590 // In MSL, being based on C++, the asterisk marking a pointer
17591 // binds to the identifier, not the type.
17592 if (type.pointer)
17593 expr += "* ";
17594 }
17595
17596 expr += join(to_name(loop_var), " = ", to_pointer_expression(var.static_expression));
17597 }
17598 }
17599 return expr;
17600 }
17601 }
17602
17603 bool CompilerGLSL::for_loop_initializers_are_same_type(const SPIRBlock &block)
17604 {
17605 if (block.loop_variables.size() <= 1)
17606 return true;
17607
17608 uint32_t expected = 0;
17609 Bitset expected_flags;
17610 for (auto &var : block.loop_variables)
17611 {
17612 // Don't care about uninitialized variables as they will not be part of the initializers.
17613 uint32_t expr = get<SPIRVariable>(var).static_expression;
17614 if (expr == 0 || ir.ids[expr].get_type() == TypeUndef)
17615 continue;
17616
17617 if (expected == 0)
17618 {
17619 expected = get<SPIRVariable>(var).basetype;
17620 expected_flags = get_decoration_bitset(var);
17621 }
17622 else if (expected != get<SPIRVariable>(var).basetype)
17623 return false;
17624
17625 // Precision flags and things like that must also match.
17626 if (expected_flags != get_decoration_bitset(var))
17627 return false;
17628 }
17629
17630 return true;
17631 }
17632
17633 void CompilerGLSL::emit_block_instructions_with_masked_debug(SPIRBlock &block)
17634 {
17635 // Have to block debug instructions such as OpLine here, since it will be treated as a statement otherwise,
17636 // which breaks loop optimizations.
17637 // Any line directive would be declared outside the loop body, which would just be confusing either way.
17638 bool old_block_debug_directives = block_debug_directives;
17639 block_debug_directives = true;
17640 emit_block_instructions(block);
17641 block_debug_directives = old_block_debug_directives;
17642 }
17643
17644 bool CompilerGLSL::attempt_emit_loop_header(SPIRBlock &block, SPIRBlock::Method method)
17645 {
17646 SPIRBlock::ContinueBlockType continue_type = continue_block_type(get<SPIRBlock>(block.continue_block));
17647
17648 if (method == SPIRBlock::MergeToSelectForLoop || method == SPIRBlock::MergeToSelectContinueForLoop)
17649 {
17650 uint32_t current_count = statement_count;
17651 // If we're trying to create a true for loop,
17652 // we need to make sure that all opcodes before branch statement do not actually emit any code.
17653 // We can then take the condition expression and create a for (; cond ; ) { body; } structure instead.
17654 emit_block_instructions_with_masked_debug(block);
17655
17656 bool condition_is_temporary = forced_temporaries.find(block.condition) == end(forced_temporaries);
17657
17658 bool flushes_phi = flush_phi_required(block.self, block.true_block) ||
17659 flush_phi_required(block.self, block.false_block);
17660
17661 // This can work! We only did trivial things which could be forwarded in block body!
17662 if (!flushes_phi && current_count == statement_count && condition_is_temporary)
17663 {
17664 switch (continue_type)
17665 {
17666 case SPIRBlock::ForLoop:
17667 {
17668 // This block may be a dominating block, so make sure we flush undeclared variables before building the for loop header.
17669 flush_undeclared_variables(block);
17670
17671 // Important that we do this in this order because
17672 // emitting the continue block can invalidate the condition expression.
17673 auto initializer = emit_for_loop_initializers(block);
17674 auto condition = to_expression(block.condition);
17675
17676 // Condition might have to be inverted.
17677 if (execution_is_noop(get<SPIRBlock>(block.true_block), get<SPIRBlock>(block.merge_block)))
17678 condition = join("!", enclose_expression(condition));
17679
17680 emit_block_hints(block);
17681 if (method != SPIRBlock::MergeToSelectContinueForLoop)
17682 {
17683 auto continue_block = emit_continue_block(block.continue_block, false, false);
17684 statement("for (", initializer, "; ", condition, "; ", continue_block, ")");
17685 }
17686 else
17687 statement("for (", initializer, "; ", condition, "; )");
17688 break;
17689 }
17690
17691 case SPIRBlock::WhileLoop:
17692 {
17693 // This block may be a dominating block, so make sure we flush undeclared variables before building the while loop header.
17694 flush_undeclared_variables(block);
17695 emit_while_loop_initializers(block);
17696 emit_block_hints(block);
17697
17698 auto condition = to_expression(block.condition);
17699 // Condition might have to be inverted.
17700 if (execution_is_noop(get<SPIRBlock>(block.true_block), get<SPIRBlock>(block.merge_block)))
17701 condition = join("!", enclose_expression(condition));
17702
17703 statement("while (", condition, ")");
17704 break;
17705 }
17706
17707 default:
17708 block.disable_block_optimization = true;
17709 force_recompile();
17710 begin_scope(); // We'll see an end_scope() later.
17711 return false;
17712 }
17713
17714 begin_scope();
17715 return true;
17716 }
17717 else
17718 {
17719 block.disable_block_optimization = true;
17720 force_recompile();
17721 begin_scope(); // We'll see an end_scope() later.
17722 return false;
17723 }
17724 }
17725 else if (method == SPIRBlock::MergeToDirectForLoop)
17726 {
17727 auto &child = get<SPIRBlock>(block.next_block);
17728
17729 // This block may be a dominating block, so make sure we flush undeclared variables before building the for loop header.
17730 flush_undeclared_variables(child);
17731
17732 uint32_t current_count = statement_count;
17733
17734 // If we're trying to create a true for loop,
17735 // we need to make sure that all opcodes before branch statement do not actually emit any code.
17736 // We can then take the condition expression and create a for (; cond ; ) { body; } structure instead.
17737 emit_block_instructions_with_masked_debug(child);
17738
17739 bool condition_is_temporary = forced_temporaries.find(child.condition) == end(forced_temporaries);
17740
17741 bool flushes_phi = flush_phi_required(child.self, child.true_block) ||
17742 flush_phi_required(child.self, child.false_block);
17743
17744 if (!flushes_phi && current_count == statement_count && condition_is_temporary)
17745 {
17746 uint32_t target_block = child.true_block;
17747
17748 switch (continue_type)
17749 {
17750 case SPIRBlock::ForLoop:
17751 {
17752 // Important that we do this in this order because
17753 // emitting the continue block can invalidate the condition expression.
17754 auto initializer = emit_for_loop_initializers(block);
17755 auto condition = to_expression(child.condition);
17756
17757 // Condition might have to be inverted.
17758 if (execution_is_noop(get<SPIRBlock>(child.true_block), get<SPIRBlock>(block.merge_block)))
17759 {
17760 condition = join("!", enclose_expression(condition));
17761 target_block = child.false_block;
17762 }
17763
17764 auto continue_block = emit_continue_block(block.continue_block, false, false);
17765 emit_block_hints(block);
17766 statement("for (", initializer, "; ", condition, "; ", continue_block, ")");
17767 break;
17768 }
17769
17770 case SPIRBlock::WhileLoop:
17771 {
17772 emit_while_loop_initializers(block);
17773 emit_block_hints(block);
17774
17775 auto condition = to_expression(child.condition);
17776 // Condition might have to be inverted.
17777 if (execution_is_noop(get<SPIRBlock>(child.true_block), get<SPIRBlock>(block.merge_block)))
17778 {
17779 condition = join("!", enclose_expression(condition));
17780 target_block = child.false_block;
17781 }
17782
17783 statement("while (", condition, ")");
17784 break;
17785 }
17786
17787 default:
17788 block.disable_block_optimization = true;
17789 force_recompile();
17790 begin_scope(); // We'll see an end_scope() later.
17791 return false;
17792 }
17793
17794 begin_scope();
17795 branch(child.self, target_block);
17796 return true;
17797 }
17798 else
17799 {
17800 block.disable_block_optimization = true;
17801 force_recompile();
17802 begin_scope(); // We'll see an end_scope() later.
17803 return false;
17804 }
17805 }
17806 else
17807 return false;
17808 }
17809
17810 void CompilerGLSL::flush_undeclared_variables(SPIRBlock &block)
17811 {
17812 for (auto &v : block.dominated_variables)
17813 flush_variable_declaration(v);
17814 }
17815
17816 void CompilerGLSL::emit_hoisted_temporaries(SmallVector<pair<TypeID, ID>> &temporaries)
17817 {
17818 // If we need to force temporaries for certain IDs due to continue blocks, do it before starting loop header.
17819 // Need to sort these to ensure that reference output is stable.
17820 sort(begin(temporaries), end(temporaries),
17821 [](const pair<TypeID, ID> &a, const pair<TypeID, ID> &b) { return a.second < b.second; });
17822
17823 for (auto &tmp : temporaries)
17824 {
17825 auto &type = get<SPIRType>(tmp.first);
17826
17827 // There are some rare scenarios where we are asked to declare pointer types as hoisted temporaries.
17828 // This should be ignored unless we're doing actual variable pointers and backend supports it.
17829 // Access chains cannot normally be lowered to temporaries in GLSL and HLSL.
17830 if (type.pointer && !backend.native_pointers)
17831 continue;
17832
17833 add_local_variable_name(tmp.second);
17834 auto &flags = get_decoration_bitset(tmp.second);
17835
17836 // Not all targets support pointer literals, so don't bother with that case.
17837 string initializer;
17838 if (options.force_zero_initialized_variables && type_can_zero_initialize(type))
17839 initializer = join(" = ", to_zero_initialized_expression(tmp.first));
17840
17841 statement(flags_to_qualifiers_glsl(type, flags), variable_decl(type, to_name(tmp.second)), initializer, ";");
17842
17843 hoisted_temporaries.insert(tmp.second);
17844 forced_temporaries.insert(tmp.second);
17845
17846 // The temporary might be read from before it's assigned, set up the expression now.
17847 set<SPIRExpression>(tmp.second, to_name(tmp.second), tmp.first, true);
17848
17849 // If we have hoisted temporaries in multi-precision contexts, emit that here too ...
17850 // We will not be able to analyze hoisted-ness for dependent temporaries that we hallucinate here.
17851 auto mirrored_precision_itr = temporary_to_mirror_precision_alias.find(tmp.second);
17852 if (mirrored_precision_itr != temporary_to_mirror_precision_alias.end())
17853 {
17854 uint32_t mirror_id = mirrored_precision_itr->second;
17855 auto &mirror_flags = get_decoration_bitset(mirror_id);
17856 statement(flags_to_qualifiers_glsl(type, mirror_flags),
17857 variable_decl(type, to_name(mirror_id)),
17858 initializer, ";");
17859 // The temporary might be read from before it's assigned, set up the expression now.
17860 set<SPIRExpression>(mirror_id, to_name(mirror_id), tmp.first, true);
17861 hoisted_temporaries.insert(mirror_id);
17862 }
17863 }
17864 }
17865
17866 void CompilerGLSL::emit_block_chain(SPIRBlock &block)
17867 {
17868 bool select_branch_to_true_block = false;
17869 bool select_branch_to_false_block = false;
17870 bool skip_direct_branch = false;
17871 bool emitted_loop_header_variables = false;
17872 bool force_complex_continue_block = false;
17873 ValueSaver<uint32_t> loop_level_saver(current_loop_level);
17874
17875 if (block.merge == SPIRBlock::MergeLoop)
17876 add_loop_level();
17877
17878 // If we're emitting PHI variables with precision aliases, we have to emit them as hoisted temporaries.
17879 for (auto var_id : block.dominated_variables)
17880 {
17881 auto &var = get<SPIRVariable>(var_id);
17882 if (var.phi_variable)
17883 {
17884 auto mirrored_precision_itr = temporary_to_mirror_precision_alias.find(var_id);
17885 if (mirrored_precision_itr != temporary_to_mirror_precision_alias.end() &&
17886 find_if(block.declare_temporary.begin(), block.declare_temporary.end(),
17887 [mirrored_precision_itr](const std::pair<TypeID, VariableID> &p) {
17888 return p.second == mirrored_precision_itr->second;
17889 }) == block.declare_temporary.end())
17890 {
17891 block.declare_temporary.push_back({ var.basetype, mirrored_precision_itr->second });
17892 }
17893 }
17894 }
17895
17896 emit_hoisted_temporaries(block.declare_temporary);
17897
17898 SPIRBlock::ContinueBlockType continue_type = SPIRBlock::ContinueNone;
17899 if (block.continue_block)
17900 {
17901 continue_type = continue_block_type(get<SPIRBlock>(block.continue_block));
17902 // If we know we cannot emit a loop, mark the block early as a complex loop so we don't force unnecessary recompiles.
17903 if (continue_type == SPIRBlock::ComplexLoop)
17904 block.complex_continue = true;
17905 }
17906
17907 // If we have loop variables, stop masking out access to the variable now.
17908 for (auto var_id : block.loop_variables)
17909 {
17910 auto &var = get<SPIRVariable>(var_id);
17911 var.loop_variable_enable = true;
17912 // We're not going to declare the variable directly, so emit a copy here.
17913 emit_variable_temporary_copies(var);
17914 }
17915
17916 // Remember deferred declaration state. We will restore it before returning.
17917 SmallVector<bool, 64> rearm_dominated_variables(block.dominated_variables.size());
17918 for (size_t i = 0; i < block.dominated_variables.size(); i++)
17919 {
17920 uint32_t var_id = block.dominated_variables[i];
17921 auto &var = get<SPIRVariable>(var_id);
17922 rearm_dominated_variables[i] = var.deferred_declaration;
17923 }
17924
17925 // This is the method often used by spirv-opt to implement loops.
17926 // The loop header goes straight into the continue block.
17927 // However, don't attempt this on ESSL 1.0, because if a loop variable is used in a continue block,
17928 // it *MUST* be used in the continue block. This loop method will not work.
17929 if (!is_legacy_es() && block_is_loop_candidate(block, SPIRBlock::MergeToSelectContinueForLoop))
17930 {
17931 flush_undeclared_variables(block);
17932 if (attempt_emit_loop_header(block, SPIRBlock::MergeToSelectContinueForLoop))
17933 {
17934 if (execution_is_noop(get<SPIRBlock>(block.true_block), get<SPIRBlock>(block.merge_block)))
17935 select_branch_to_false_block = true;
17936 else
17937 select_branch_to_true_block = true;
17938
17939 emitted_loop_header_variables = true;
17940 force_complex_continue_block = true;
17941 }
17942 }
17943 // This is the older loop behavior in glslang which branches to loop body directly from the loop header.
17944 else if (block_is_loop_candidate(block, SPIRBlock::MergeToSelectForLoop))
17945 {
17946 flush_undeclared_variables(block);
17947 if (attempt_emit_loop_header(block, SPIRBlock::MergeToSelectForLoop))
17948 {
17949 // The body of while, is actually just the true (or false) block, so always branch there unconditionally.
17950 if (execution_is_noop(get<SPIRBlock>(block.true_block), get<SPIRBlock>(block.merge_block)))
17951 select_branch_to_false_block = true;
17952 else
17953 select_branch_to_true_block = true;
17954
17955 emitted_loop_header_variables = true;
17956 }
17957 }
17958 // This is the newer loop behavior in glslang which branches from Loop header directly to
17959 // a new block, which in turn has a OpBranchSelection without a selection merge.
17960 else if (block_is_loop_candidate(block, SPIRBlock::MergeToDirectForLoop))
17961 {
17962 flush_undeclared_variables(block);
17963 if (attempt_emit_loop_header(block, SPIRBlock::MergeToDirectForLoop))
17964 {
17965 skip_direct_branch = true;
17966 emitted_loop_header_variables = true;
17967 }
17968 }
17969 else if (continue_type == SPIRBlock::DoWhileLoop)
17970 {
17971 flush_undeclared_variables(block);
17972 emit_while_loop_initializers(block);
17973 emitted_loop_header_variables = true;
17974 // We have some temporaries where the loop header is the dominator.
17975 // We risk a case where we have code like:
17976 // for (;;) { create-temporary; break; } consume-temporary;
17977 // so force-declare temporaries here.
17978 emit_hoisted_temporaries(block.potential_declare_temporary);
17979 statement("do");
17980 begin_scope();
17981
17982 emit_block_instructions(block);
17983 }
17984 else if (block.merge == SPIRBlock::MergeLoop)
17985 {
17986 flush_undeclared_variables(block);
17987 emit_while_loop_initializers(block);
17988 emitted_loop_header_variables = true;
17989
17990 // We have a generic loop without any distinguishable pattern like for, while or do while.
17991 get<SPIRBlock>(block.continue_block).complex_continue = true;
17992 continue_type = SPIRBlock::ComplexLoop;
17993
17994 // We have some temporaries where the loop header is the dominator.
17995 // We risk a case where we have code like:
17996 // for (;;) { create-temporary; break; } consume-temporary;
17997 // so force-declare temporaries here.
17998 emit_hoisted_temporaries(block.potential_declare_temporary);
17999 emit_block_hints(block);
18000 statement("for (;;)");
18001 begin_scope();
18002
18003 emit_block_instructions(block);
18004 }
18005 else
18006 {
18007 emit_block_instructions(block);
18008 }
18009
18010 // If we didn't successfully emit a loop header and we had loop variable candidates, we have a problem
18011 // as writes to said loop variables might have been masked out, we need a recompile.
18012 if (!emitted_loop_header_variables && !block.loop_variables.empty())
18013 {
18014 force_recompile_guarantee_forward_progress();
18015 for (auto var : block.loop_variables)
18016 get<SPIRVariable>(var).loop_variable = false;
18017 block.loop_variables.clear();
18018 }
18019
18020 flush_undeclared_variables(block);
18021 bool emit_next_block = true;
18022
18023 // Handle end of block.
18024 switch (block.terminator)
18025 {
18026 case SPIRBlock::Direct:
18027 // True when emitting complex continue block.
18028 if (block.loop_dominator == block.next_block)
18029 {
18030 branch(block.self, block.next_block);
18031 emit_next_block = false;
18032 }
18033 // True if MergeToDirectForLoop succeeded.
18034 else if (skip_direct_branch)
18035 emit_next_block = false;
18036 else if (is_continue(block.next_block) || is_break(block.next_block) || is_conditional(block.next_block))
18037 {
18038 branch(block.self, block.next_block);
18039 emit_next_block = false;
18040 }
18041 break;
18042
18043 case SPIRBlock::Select:
18044 // True if MergeToSelectForLoop or MergeToSelectContinueForLoop succeeded.
18045 if (select_branch_to_true_block)
18046 {
18047 if (force_complex_continue_block)
18048 {
18049 assert(block.true_block == block.continue_block);
18050
18051 // We're going to emit a continue block directly here, so make sure it's marked as complex.
18052 auto &complex_continue = get<SPIRBlock>(block.continue_block).complex_continue;
18053 bool old_complex = complex_continue;
18054 complex_continue = true;
18055 branch(block.self, block.true_block);
18056 complex_continue = old_complex;
18057 }
18058 else
18059 branch(block.self, block.true_block);
18060 }
18061 else if (select_branch_to_false_block)
18062 {
18063 if (force_complex_continue_block)
18064 {
18065 assert(block.false_block == block.continue_block);
18066
18067 // We're going to emit a continue block directly here, so make sure it's marked as complex.
18068 auto &complex_continue = get<SPIRBlock>(block.continue_block).complex_continue;
18069 bool old_complex = complex_continue;
18070 complex_continue = true;
18071 branch(block.self, block.false_block);
18072 complex_continue = old_complex;
18073 }
18074 else
18075 branch(block.self, block.false_block);
18076 }
18077 else
18078 branch(block.self, block.condition, block.true_block, block.false_block);
18079 break;
18080
18081 case SPIRBlock::MultiSelect:
18082 {
18083 auto &type = expression_type(block.condition);
18084 bool unsigned_case = type.basetype == SPIRType::UInt || type.basetype == SPIRType::UShort ||
18085 type.basetype == SPIRType::UByte || type.basetype == SPIRType::UInt64;
18086
18087 if (block.merge == SPIRBlock::MergeNone)
18088 SPIRV_CROSS_THROW("Switch statement is not structured");
18089
18090 if (!backend.support_64bit_switch && (type.basetype == SPIRType::UInt64 || type.basetype == SPIRType::Int64))
18091 {
18092 // SPIR-V spec suggests this is allowed, but we cannot support it in higher level languages.
18093 SPIRV_CROSS_THROW("Cannot use 64-bit switch selectors.");
18094 }
18095
18096 const char *label_suffix = "";
18097 if (type.basetype == SPIRType::UInt && backend.uint32_t_literal_suffix)
18098 label_suffix = "u";
18099 else if (type.basetype == SPIRType::Int64 && backend.support_64bit_switch)
18100 label_suffix = "l";
18101 else if (type.basetype == SPIRType::UInt64 && backend.support_64bit_switch)
18102 label_suffix = "ul";
18103 else if (type.basetype == SPIRType::UShort)
18104 label_suffix = backend.uint16_t_literal_suffix;
18105 else if (type.basetype == SPIRType::Short)
18106 label_suffix = backend.int16_t_literal_suffix;
18107
18108 current_emitting_switch_stack.push_back(&block);
18109
18110 if (block.need_ladder_break)
18111 statement("bool _", block.self, "_ladder_break = false;");
18112
18113 // Find all unique case constructs.
18114 unordered_map<uint32_t, SmallVector<uint64_t>> case_constructs;
18115 SmallVector<uint32_t> block_declaration_order;
18116 SmallVector<uint64_t> literals_to_merge;
18117
18118 // If a switch case branches to the default block for some reason, we can just remove that literal from consideration
18119 // and let the default: block handle it.
18120 // 2.11 in SPIR-V spec states that for fall-through cases, there is a very strict declaration order which we can take advantage of here.
18121 // We only need to consider possible fallthrough if order[i] branches to order[i + 1].
18122 auto &cases = get_case_list(block);
18123 for (auto &c : cases)
18124 {
18125 if (c.block != block.next_block && c.block != block.default_block)
18126 {
18127 if (!case_constructs.count(c.block))
18128 block_declaration_order.push_back(c.block);
18129 case_constructs[c.block].push_back(c.value);
18130 }
18131 else if (c.block == block.next_block && block.default_block != block.next_block)
18132 {
18133 // We might have to flush phi inside specific case labels.
18134 // If we can piggyback on default:, do so instead.
18135 literals_to_merge.push_back(c.value);
18136 }
18137 }
18138
18139 // Empty literal array -> default.
18140 if (block.default_block != block.next_block)
18141 {
18142 auto &default_block = get<SPIRBlock>(block.default_block);
18143
18144 // We need to slide in the default block somewhere in this chain
18145 // if there are fall-through scenarios since the default is declared separately in OpSwitch.
18146 // Only consider trivial fall-through cases here.
18147 size_t num_blocks = block_declaration_order.size();
18148 bool injected_block = false;
18149
18150 for (size_t i = 0; i < num_blocks; i++)
18151 {
18152 auto &case_block = get<SPIRBlock>(block_declaration_order[i]);
18153 if (execution_is_direct_branch(case_block, default_block))
18154 {
18155 // Fallthrough to default block, we must inject the default block here.
18156 block_declaration_order.insert(begin(block_declaration_order) + i + 1, block.default_block);
18157 injected_block = true;
18158 break;
18159 }
18160 else if (execution_is_direct_branch(default_block, case_block))
18161 {
18162 // Default case is falling through to another case label, we must inject the default block here.
18163 block_declaration_order.insert(begin(block_declaration_order) + i, block.default_block);
18164 injected_block = true;
18165 break;
18166 }
18167 }
18168
18169 // Order does not matter.
18170 if (!injected_block)
18171 block_declaration_order.push_back(block.default_block);
18172 else if (is_legacy_es())
18173 SPIRV_CROSS_THROW("Default case label fallthrough to other case label is not supported in ESSL 1.0.");
18174
18175 case_constructs[block.default_block] = {};
18176 }
18177
18178 size_t num_blocks = block_declaration_order.size();
18179
18180 const auto to_case_label = [](uint64_t literal, uint32_t width, bool is_unsigned_case) -> string
18181 {
18182 if (is_unsigned_case)
18183 return convert_to_string(literal);
18184
18185 // For smaller cases, the literals are compiled as 32 bit wide
18186 // literals so we don't need to care for all sizes specifically.
18187 if (width <= 32)
18188 {
18189 return convert_to_string(int64_t(int32_t(literal)));
18190 }
18191
18192 return convert_to_string(int64_t(literal));
18193 };
18194
18195 const auto to_legacy_case_label = [&](uint32_t condition, const SmallVector<uint64_t> &labels,
18196 const char *suffix) -> string {
18197 string ret;
18198 size_t count = labels.size();
18199 for (size_t i = 0; i < count; i++)
18200 {
18201 if (i)
18202 ret += " || ";
18203 ret += join(count > 1 ? "(" : "", to_enclosed_expression(condition), " == ", labels[i], suffix,
18204 count > 1 ? ")" : "");
18205 }
18206 return ret;
18207 };
18208
18209 // We need to deal with a complex scenario for OpPhi. If we have case-fallthrough and Phi in the picture,
18210 // we need to flush phi nodes outside the switch block in a branch,
18211 // and skip any Phi handling inside the case label to make fall-through work as expected.
18212 // This kind of code-gen is super awkward and it's a last resort. Normally we would want to handle this
18213 // inside the case label if at all possible.
18214 for (size_t i = 1; backend.support_case_fallthrough && i < num_blocks; i++)
18215 {
18216 if (flush_phi_required(block.self, block_declaration_order[i]) &&
18217 flush_phi_required(block_declaration_order[i - 1], block_declaration_order[i]))
18218 {
18219 uint32_t target_block = block_declaration_order[i];
18220
18221 // Make sure we flush Phi, it might have been marked to be ignored earlier.
18222 get<SPIRBlock>(target_block).ignore_phi_from_block = 0;
18223
18224 auto &literals = case_constructs[target_block];
18225
18226 if (literals.empty())
18227 {
18228 // Oh boy, gotta make a complete negative test instead! o.o
18229 // Find all possible literals that would *not* make us enter the default block.
18230 // If none of those literals match, we flush Phi ...
18231 SmallVector<string> conditions;
18232 for (size_t j = 0; j < num_blocks; j++)
18233 {
18234 auto &negative_literals = case_constructs[block_declaration_order[j]];
18235 for (auto &case_label : negative_literals)
18236 conditions.push_back(join(to_enclosed_expression(block.condition),
18237 " != ", to_case_label(case_label, type.width, unsigned_case)));
18238 }
18239
18240 statement("if (", merge(conditions, " && "), ")");
18241 begin_scope();
18242 flush_phi(block.self, target_block);
18243 end_scope();
18244 }
18245 else
18246 {
18247 SmallVector<string> conditions;
18248 conditions.reserve(literals.size());
18249 for (auto &case_label : literals)
18250 conditions.push_back(join(to_enclosed_expression(block.condition),
18251 " == ", to_case_label(case_label, type.width, unsigned_case)));
18252 statement("if (", merge(conditions, " || "), ")");
18253 begin_scope();
18254 flush_phi(block.self, target_block);
18255 end_scope();
18256 }
18257
18258 // Mark the block so that we don't flush Phi from header to case label.
18259 get<SPIRBlock>(target_block).ignore_phi_from_block = block.self;
18260 }
18261 }
18262
18263 // If there is only one default block, and no cases, this is a case where SPIRV-opt decided to emulate
18264 // non-structured exits with the help of a switch block.
18265 // This is buggy on FXC, so just emit the logical equivalent of a do { } while(false), which is more idiomatic.
18266 bool block_like_switch = cases.empty();
18267
18268 // If this is true, the switch is completely meaningless, and we should just avoid it.
18269 bool collapsed_switch = block_like_switch && block.default_block == block.next_block;
18270
18271 if (!collapsed_switch)
18272 {
18273 if (block_like_switch || is_legacy())
18274 {
18275 // ESSL 1.0 is not guaranteed to support do/while.
18276 if (is_legacy_es())
18277 {
18278 uint32_t counter = statement_count;
18279 statement("for (int spvDummy", counter, " = 0; spvDummy", counter, " < 1; spvDummy", counter,
18280 "++)");
18281 }
18282 else
18283 statement("do");
18284 }
18285 else
18286 {
18287 emit_block_hints(block);
18288 statement("switch (", to_unpacked_expression(block.condition), ")");
18289 }
18290 begin_scope();
18291 }
18292
18293 for (size_t i = 0; i < num_blocks; i++)
18294 {
18295 uint32_t target_block = block_declaration_order[i];
18296 auto &literals = case_constructs[target_block];
18297
18298 if (literals.empty())
18299 {
18300 // Default case.
18301 if (!block_like_switch)
18302 {
18303 if (is_legacy())
18304 statement("else");
18305 else
18306 statement("default:");
18307 }
18308 }
18309 else
18310 {
18311 if (is_legacy())
18312 {
18313 statement((i ? "else " : ""), "if (", to_legacy_case_label(block.condition, literals, label_suffix),
18314 ")");
18315 }
18316 else
18317 {
18318 for (auto &case_literal : literals)
18319 {
18320 // The case label value must be sign-extended properly in SPIR-V, so we can assume 32-bit values here.
18321 statement("case ", to_case_label(case_literal, type.width, unsigned_case), label_suffix, ":");
18322 }
18323 }
18324 }
18325
18326 auto &case_block = get<SPIRBlock>(target_block);
18327 if (backend.support_case_fallthrough && i + 1 < num_blocks &&
18328 execution_is_direct_branch(case_block, get<SPIRBlock>(block_declaration_order[i + 1])))
18329 {
18330 // We will fall through here, so just terminate the block chain early.
18331 // We still need to deal with Phi potentially.
18332 // No need for a stack-like thing here since we only do fall-through when there is a
18333 // single trivial branch to fall-through target..
18334 current_emitting_switch_fallthrough = true;
18335 }
18336 else
18337 current_emitting_switch_fallthrough = false;
18338
18339 if (!block_like_switch)
18340 begin_scope();
18341 branch(block.self, target_block);
18342 if (!block_like_switch)
18343 end_scope();
18344
18345 current_emitting_switch_fallthrough = false;
18346 }
18347
18348 // Might still have to flush phi variables if we branch from loop header directly to merge target.
18349 // This is supposed to emit all cases where we branch from header to merge block directly.
18350 // There are two main scenarios where cannot rely on default fallthrough.
18351 // - There is an explicit default: label already.
18352 // In this case, literals_to_merge need to form their own "default" case, so that we avoid executing that block.
18353 // - Header -> Merge requires flushing PHI. In this case, we need to collect all cases and flush PHI there.
18354 bool header_merge_requires_phi = flush_phi_required(block.self, block.next_block);
18355 bool need_fallthrough_block = block.default_block == block.next_block || !literals_to_merge.empty();
18356 if (!collapsed_switch && ((header_merge_requires_phi && need_fallthrough_block) || !literals_to_merge.empty()))
18357 {
18358 for (auto &case_literal : literals_to_merge)
18359 statement("case ", to_case_label(case_literal, type.width, unsigned_case), label_suffix, ":");
18360
18361 if (block.default_block == block.next_block)
18362 {
18363 if (is_legacy())
18364 statement("else");
18365 else
18366 statement("default:");
18367 }
18368
18369 begin_scope();
18370 flush_phi(block.self, block.next_block);
18371 statement("break;");
18372 end_scope();
18373 }
18374
18375 if (!collapsed_switch)
18376 {
18377 if ((block_like_switch || is_legacy()) && !is_legacy_es())
18378 end_scope_decl("while(false)");
18379 else
18380 end_scope();
18381 }
18382 else
18383 flush_phi(block.self, block.next_block);
18384
18385 if (block.need_ladder_break)
18386 {
18387 statement("if (_", block.self, "_ladder_break)");
18388 begin_scope();
18389 statement("break;");
18390 end_scope();
18391 }
18392
18393 current_emitting_switch_stack.pop_back();
18394 break;
18395 }
18396
18397 case SPIRBlock::Return:
18398 {
18399 for (auto &line : current_function->fixup_hooks_out)
18400 line();
18401
18402 if (processing_entry_point)
18403 emit_fixup();
18404
18405 auto &cfg = get_cfg_for_current_function();
18406
18407 if (block.return_value)
18408 {
18409 auto &type = expression_type(block.return_value);
18410 if (!type.array.empty() && !backend.can_return_array)
18411 {
18412 // If we cannot return arrays, we will have a special out argument we can write to instead.
18413 // The backend is responsible for setting this up, and redirection the return values as appropriate.
18414 if (ir.ids[block.return_value].get_type() != TypeUndef)
18415 {
18416 emit_array_copy("spvReturnValue", 0, block.return_value, StorageClassFunction,
18417 get_expression_effective_storage_class(block.return_value));
18418 }
18419
18420 if (!cfg.node_terminates_control_flow_in_sub_graph(current_function->entry_block, block.self) ||
18421 block.loop_dominator != BlockID(SPIRBlock::NoDominator))
18422 {
18423 statement("return;");
18424 }
18425 }
18426 else
18427 {
18428 // OpReturnValue can return Undef, so don't emit anything for this case.
18429 if (ir.ids[block.return_value].get_type() != TypeUndef)
18430 statement("return ", to_unpacked_expression(block.return_value), ";");
18431 }
18432 }
18433 else if (!cfg.node_terminates_control_flow_in_sub_graph(current_function->entry_block, block.self) ||
18434 block.loop_dominator != BlockID(SPIRBlock::NoDominator))
18435 {
18436 // If this block is the very final block and not called from control flow,
18437 // we do not need an explicit return which looks out of place. Just end the function here.
18438 // In the very weird case of for(;;) { return; } executing return is unconditional,
18439 // but we actually need a return here ...
18440 statement("return;");
18441 }
18442 break;
18443 }
18444
18445 // If the Kill is terminating a block with a (probably synthetic) return value, emit a return value statement.
18446 case SPIRBlock::Kill:
18447 statement(backend.discard_literal, ";");
18448 if (block.return_value)
18449 statement("return ", to_unpacked_expression(block.return_value), ";");
18450 break;
18451
18452 case SPIRBlock::Unreachable:
18453 {
18454 // If the entry point ends with unreachable and has a return value, insert a return
18455 // statement to avoid potential compiler errors from non-void functions without a return value.
18456 if (block.return_value)
18457 {
18458 statement("return ", to_unpacked_expression(block.return_value), ";");
18459 break;
18460 }
18461
18462 // Avoid emitting false fallthrough, which can happen for
18463 // if (cond) break; else discard; inside a case label.
18464 // Discard is not always implementable as a terminator.
18465
18466 auto &cfg = get_cfg_for_current_function();
18467 bool inner_dominator_is_switch = false;
18468 ID id = block.self;
18469
18470 while (id)
18471 {
18472 auto &iter_block = get<SPIRBlock>(id);
18473 if (iter_block.terminator == SPIRBlock::MultiSelect ||
18474 iter_block.merge == SPIRBlock::MergeLoop)
18475 {
18476 ID next_block = iter_block.merge == SPIRBlock::MergeLoop ?
18477 iter_block.merge_block : iter_block.next_block;
18478 bool outside_construct = next_block && cfg.find_common_dominator(next_block, block.self) == next_block;
18479 if (!outside_construct)
18480 {
18481 inner_dominator_is_switch = iter_block.terminator == SPIRBlock::MultiSelect;
18482 break;
18483 }
18484 }
18485
18486 if (cfg.get_preceding_edges(id).empty())
18487 break;
18488
18489 id = cfg.get_immediate_dominator(id);
18490 }
18491
18492 if (inner_dominator_is_switch)
18493 statement("break; // unreachable workaround");
18494
18495 emit_next_block = false;
18496 break;
18497 }
18498
18499 case SPIRBlock::IgnoreIntersection:
18500 statement("ignoreIntersectionEXT;");
18501 break;
18502
18503 case SPIRBlock::TerminateRay:
18504 statement("terminateRayEXT;");
18505 break;
18506
18507 case SPIRBlock::EmitMeshTasks:
18508 emit_mesh_tasks(block);
18509 break;
18510
18511 default:
18512 SPIRV_CROSS_THROW("Unimplemented block terminator.");
18513 }
18514
18515 if (block.next_block && emit_next_block)
18516 {
18517 // If we hit this case, we're dealing with an unconditional branch, which means we will output
18518 // that block after this. If we had selection merge, we already flushed phi variables.
18519 if (block.merge != SPIRBlock::MergeSelection)
18520 {
18521 flush_phi(block.self, block.next_block);
18522 // For a direct branch, need to remember to invalidate expressions in the next linear block instead.
18523 get<SPIRBlock>(block.next_block).invalidate_expressions = block.invalidate_expressions;
18524 }
18525
18526 // For switch fallthrough cases, we terminate the chain here, but we still need to handle Phi.
18527 if (!current_emitting_switch_fallthrough)
18528 {
18529 // For merge selects we might have ignored the fact that a merge target
18530 // could have been a break; or continue;
18531 // We will need to deal with it here.
18532 if (is_loop_break(block.next_block))
18533 {
18534 // Cannot check for just break, because switch statements will also use break.
18535 assert(block.merge == SPIRBlock::MergeSelection);
18536 statement("break;");
18537 }
18538 else if (is_continue(block.next_block))
18539 {
18540 assert(block.merge == SPIRBlock::MergeSelection);
18541 branch_to_continue(block.self, block.next_block);
18542 }
18543 else if (BlockID(block.self) != block.next_block)
18544 emit_block_chain(get<SPIRBlock>(block.next_block));
18545 }
18546 }
18547
18548 if (block.merge == SPIRBlock::MergeLoop)
18549 {
18550 if (continue_type == SPIRBlock::DoWhileLoop)
18551 {
18552 // Make sure that we run the continue block to get the expressions set, but this
18553 // should become an empty string.
18554 // We have no fallbacks if we cannot forward everything to temporaries ...
18555 const auto &continue_block = get<SPIRBlock>(block.continue_block);
18556 bool positive_test = execution_is_noop(get<SPIRBlock>(continue_block.true_block),
18557 get<SPIRBlock>(continue_block.loop_dominator));
18558
18559 uint32_t current_count = statement_count;
18560 auto statements = emit_continue_block(block.continue_block, positive_test, !positive_test);
18561 if (statement_count != current_count)
18562 {
18563 // The DoWhile block has side effects, force ComplexLoop pattern next pass.
18564 get<SPIRBlock>(block.continue_block).complex_continue = true;
18565 force_recompile();
18566 }
18567
18568 // Might have to invert the do-while test here.
18569 auto condition = to_expression(continue_block.condition);
18570 if (!positive_test)
18571 condition = join("!", enclose_expression(condition));
18572
18573 end_scope_decl(join("while (", condition, ")"));
18574 }
18575 else
18576 end_scope();
18577
18578 loop_level_saver.release();
18579
18580 // We cannot break out of two loops at once, so don't check for break; here.
18581 // Using block.self as the "from" block isn't quite right, but it has the same scope
18582 // and dominance structure, so it's fine.
18583 if (is_continue(block.merge_block))
18584 branch_to_continue(block.self, block.merge_block);
18585 else
18586 emit_block_chain(get<SPIRBlock>(block.merge_block));
18587 }
18588
18589 // Forget about control dependent expressions now.
18590 block.invalidate_expressions.clear();
18591
18592 // After we return, we must be out of scope, so if we somehow have to re-emit this function,
18593 // re-declare variables if necessary.
18594 assert(rearm_dominated_variables.size() == block.dominated_variables.size());
18595 for (size_t i = 0; i < block.dominated_variables.size(); i++)
18596 {
18597 uint32_t var = block.dominated_variables[i];
18598 get<SPIRVariable>(var).deferred_declaration = rearm_dominated_variables[i];
18599 }
18600
18601 // Just like for deferred declaration, we need to forget about loop variable enable
18602 // if our block chain is reinstantiated later.
18603 for (auto &var_id : block.loop_variables)
18604 get<SPIRVariable>(var_id).loop_variable_enable = false;
18605 }
18606
18607 void CompilerGLSL::begin_scope()
18608 {
18609 statement("{");
18610 indent++;
18611 }
18612
18613 void CompilerGLSL::end_scope()
18614 {
18615 if (!indent)
18616 SPIRV_CROSS_THROW("Popping empty indent stack.");
18617 indent--;
18618 statement("}");
18619 }
18620
18621 void CompilerGLSL::end_scope(const string &trailer)
18622 {
18623 if (!indent)
18624 SPIRV_CROSS_THROW("Popping empty indent stack.");
18625 indent--;
18626 statement("}", trailer);
18627 }
18628
18629 void CompilerGLSL::end_scope_decl()
18630 {
18631 if (!indent)
18632 SPIRV_CROSS_THROW("Popping empty indent stack.");
18633 indent--;
18634 statement("};");
18635 }
18636
18637 void CompilerGLSL::end_scope_decl(const string &decl)
18638 {
18639 if (!indent)
18640 SPIRV_CROSS_THROW("Popping empty indent stack.");
18641 indent--;
18642 statement("} ", decl, ";");
18643 }
18644
18645 void CompilerGLSL::check_function_call_constraints(const uint32_t *args, uint32_t length)
18646 {
18647 // If our variable is remapped, and we rely on type-remapping information as
18648 // well, then we cannot pass the variable as a function parameter.
18649 // Fixing this is non-trivial without stamping out variants of the same function,
18650 // so for now warn about this and suggest workarounds instead.
18651 for (uint32_t i = 0; i < length; i++)
18652 {
18653 auto *var = maybe_get<SPIRVariable>(args[i]);
18654 if (!var || !var->remapped_variable)
18655 continue;
18656
18657 auto &type = get<SPIRType>(var->basetype);
18658 if (type.basetype == SPIRType::Image && type.image.dim == DimSubpassData)
18659 {
18660 SPIRV_CROSS_THROW("Tried passing a remapped subpassInput variable to a function. "
18661 "This will not work correctly because type-remapping information is lost. "
18662 "To workaround, please consider not passing the subpass input as a function parameter, "
18663 "or use in/out variables instead which do not need type remapping information.");
18664 }
18665 }
18666 }
18667
18668 const Instruction *CompilerGLSL::get_next_instruction_in_block(const Instruction &instr)
18669 {
18670 // FIXME: This is kind of hacky. There should be a cleaner way.
18671 auto offset = uint32_t(&instr - current_emitting_block->ops.data());
18672 if ((offset + 1) < current_emitting_block->ops.size())
18673 return &current_emitting_block->ops[offset + 1];
18674 else
18675 return nullptr;
18676 }
18677
18678 uint32_t CompilerGLSL::mask_relevant_memory_semantics(uint32_t semantics)
18679 {
18680 return semantics & (MemorySemanticsAtomicCounterMemoryMask | MemorySemanticsImageMemoryMask |
18681 MemorySemanticsWorkgroupMemoryMask | MemorySemanticsUniformMemoryMask |
18682 MemorySemanticsCrossWorkgroupMemoryMask | MemorySemanticsSubgroupMemoryMask);
18683 }
18684
18685 bool CompilerGLSL::emit_array_copy(const char *expr, uint32_t lhs_id, uint32_t rhs_id, StorageClass, StorageClass)
18686 {
18687 string lhs;
18688 if (expr)
18689 lhs = expr;
18690 else
18691 lhs = to_expression(lhs_id);
18692
18693 statement(lhs, " = ", to_expression(rhs_id), ";");
18694 return true;
18695 }
18696
18697 bool CompilerGLSL::unroll_array_to_complex_store(uint32_t target_id, uint32_t source_id)
18698 {
18699 if (!backend.force_gl_in_out_block)
18700 return false;
18701 // This path is only relevant for GL backends.
18702
18703 auto *var = maybe_get<SPIRVariable>(target_id);
18704 if (!var || var->storage != StorageClassOutput)
18705 return false;
18706
18707 if (!is_builtin_variable(*var) || BuiltIn(get_decoration(var->self, DecorationBuiltIn)) != BuiltInSampleMask)
18708 return false;
18709
18710 auto &type = expression_type(source_id);
18711 string array_expr;
18712 if (type.array_size_literal.back())
18713 {
18714 array_expr = convert_to_string(type.array.back());
18715 if (type.array.back() == 0)
18716 SPIRV_CROSS_THROW("Cannot unroll an array copy from unsized array.");
18717 }
18718 else
18719 array_expr = to_expression(type.array.back());
18720
18721 SPIRType target_type { OpTypeInt };
18722 target_type.basetype = SPIRType::Int;
18723
18724 statement("for (int i = 0; i < int(", array_expr, "); i++)");
18725 begin_scope();
18726 statement(to_expression(target_id), "[i] = ",
18727 bitcast_expression(target_type, type.basetype, join(to_expression(source_id), "[i]")),
18728 ";");
18729 end_scope();
18730
18731 return true;
18732 }
18733
18734 void CompilerGLSL::unroll_array_from_complex_load(uint32_t target_id, uint32_t source_id, std::string &expr)
18735 {
18736 if (!backend.force_gl_in_out_block)
18737 return;
18738 // This path is only relevant for GL backends.
18739
18740 auto *var = maybe_get<SPIRVariable>(source_id);
18741 if (!var)
18742 return;
18743
18744 if (var->storage != StorageClassInput && var->storage != StorageClassOutput)
18745 return;
18746
18747 auto &type = get_variable_data_type(*var);
18748 if (type.array.empty())
18749 return;
18750
18751 auto builtin = BuiltIn(get_decoration(var->self, DecorationBuiltIn));
18752 bool is_builtin = is_builtin_variable(*var) &&
18753 (builtin == BuiltInPointSize ||
18754 builtin == BuiltInPosition ||
18755 builtin == BuiltInSampleMask);
18756 bool is_tess = is_tessellation_shader();
18757 bool is_patch = has_decoration(var->self, DecorationPatch);
18758 bool is_sample_mask = is_builtin && builtin == BuiltInSampleMask;
18759
18760 // Tessellation input arrays are special in that they are unsized, so we cannot directly copy from it.
18761 // We must unroll the array load.
18762 // For builtins, we couldn't catch this case normally,
18763 // because this is resolved in the OpAccessChain in most cases.
18764 // If we load the entire array, we have no choice but to unroll here.
18765 if (!is_patch && (is_builtin || is_tess))
18766 {
18767 auto new_expr = join("_", target_id, "_unrolled");
18768 statement(variable_decl(type, new_expr, target_id), ";");
18769 string array_expr;
18770 if (type.array_size_literal.back())
18771 {
18772 array_expr = convert_to_string(type.array.back());
18773 if (type.array.back() == 0)
18774 SPIRV_CROSS_THROW("Cannot unroll an array copy from unsized array.");
18775 }
18776 else
18777 array_expr = to_expression(type.array.back());
18778
18779 // The array size might be a specialization constant, so use a for-loop instead.
18780 statement("for (int i = 0; i < int(", array_expr, "); i++)");
18781 begin_scope();
18782 if (is_builtin && !is_sample_mask)
18783 statement(new_expr, "[i] = gl_in[i].", expr, ";");
18784 else if (is_sample_mask)
18785 {
18786 SPIRType target_type { OpTypeInt };
18787 target_type.basetype = SPIRType::Int;
18788 statement(new_expr, "[i] = ", bitcast_expression(target_type, type.basetype, join(expr, "[i]")), ";");
18789 }
18790 else
18791 statement(new_expr, "[i] = ", expr, "[i];");
18792 end_scope();
18793
18794 expr = std::move(new_expr);
18795 }
18796 }
18797
18798 void CompilerGLSL::cast_from_variable_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type)
18799 {
18800 // We will handle array cases elsewhere.
18801 if (!expr_type.array.empty())
18802 return;
18803
18804 auto *var = maybe_get_backing_variable(source_id);
18805 if (var)
18806 source_id = var->self;
18807
18808 // Only interested in standalone builtin variables.
18809 if (!has_decoration(source_id, DecorationBuiltIn))
18810 {
18811 // Except for int attributes in legacy GLSL, which are cast from float.
18812 if (is_legacy() && expr_type.basetype == SPIRType::Int && var && var->storage == StorageClassInput)
18813 expr = join(type_to_glsl(expr_type), "(", expr, ")");
18814 return;
18815 }
18816
18817 auto builtin = static_cast<BuiltIn>(get_decoration(source_id, DecorationBuiltIn));
18818 auto expected_type = expr_type.basetype;
18819
18820 // TODO: Fill in for more builtins.
18821 switch (builtin)
18822 {
18823 case BuiltInLayer:
18824 case BuiltInPrimitiveId:
18825 case BuiltInViewportIndex:
18826 case BuiltInInstanceId:
18827 case BuiltInInstanceIndex:
18828 case BuiltInVertexId:
18829 case BuiltInVertexIndex:
18830 case BuiltInSampleId:
18831 case BuiltInBaseVertex:
18832 case BuiltInBaseInstance:
18833 case BuiltInDrawIndex:
18834 case BuiltInFragStencilRefEXT:
18835 case BuiltInInstanceCustomIndexNV:
18836 case BuiltInSampleMask:
18837 case BuiltInPrimitiveShadingRateKHR:
18838 case BuiltInShadingRateKHR:
18839 expected_type = SPIRType::Int;
18840 break;
18841
18842 case BuiltInGlobalInvocationId:
18843 case BuiltInLocalInvocationId:
18844 case BuiltInWorkgroupId:
18845 case BuiltInLocalInvocationIndex:
18846 case BuiltInWorkgroupSize:
18847 case BuiltInNumWorkgroups:
18848 case BuiltInIncomingRayFlagsNV:
18849 case BuiltInLaunchIdNV:
18850 case BuiltInLaunchSizeNV:
18851 case BuiltInPrimitiveTriangleIndicesEXT:
18852 case BuiltInPrimitiveLineIndicesEXT:
18853 case BuiltInPrimitivePointIndicesEXT:
18854 expected_type = SPIRType::UInt;
18855 break;
18856
18857 default:
18858 break;
18859 }
18860
18861 if (expected_type != expr_type.basetype)
18862 expr = bitcast_expression(expr_type, expected_type, expr);
18863 }
18864
18865 SPIRType::BaseType CompilerGLSL::get_builtin_basetype(BuiltIn builtin, SPIRType::BaseType default_type)
18866 {
18867 // TODO: Fill in for more builtins.
18868 switch (builtin)
18869 {
18870 case BuiltInLayer:
18871 case BuiltInPrimitiveId:
18872 case BuiltInViewportIndex:
18873 case BuiltInFragStencilRefEXT:
18874 case BuiltInSampleMask:
18875 case BuiltInPrimitiveShadingRateKHR:
18876 case BuiltInShadingRateKHR:
18877 return SPIRType::Int;
18878
18879 default:
18880 return default_type;
18881 }
18882 }
18883
18884 void CompilerGLSL::cast_to_variable_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type)
18885 {
18886 auto *var = maybe_get_backing_variable(target_id);
18887 if (var)
18888 target_id = var->self;
18889
18890 // Only interested in standalone builtin variables.
18891 if (!has_decoration(target_id, DecorationBuiltIn))
18892 return;
18893
18894 auto builtin = static_cast<BuiltIn>(get_decoration(target_id, DecorationBuiltIn));
18895 auto expected_type = get_builtin_basetype(builtin, expr_type.basetype);
18896
18897 if (expected_type != expr_type.basetype)
18898 {
18899 auto type = expr_type;
18900 type.basetype = expected_type;
18901 expr = bitcast_expression(type, expr_type.basetype, expr);
18902 }
18903 }
18904
18905 void CompilerGLSL::convert_non_uniform_expression(string &expr, uint32_t ptr_id)
18906 {
18907 if (*backend.nonuniform_qualifier == '\0')
18908 return;
18909
18910 auto *var = maybe_get_backing_variable(ptr_id);
18911 if (!var)
18912 return;
18913
18914 if (var->storage != StorageClassUniformConstant &&
18915 var->storage != StorageClassStorageBuffer &&
18916 var->storage != StorageClassUniform)
18917 return;
18918
18919 auto &backing_type = get<SPIRType>(var->basetype);
18920 if (backing_type.array.empty())
18921 return;
18922
18923 // If we get here, we know we're accessing an arrayed resource which
18924 // might require nonuniform qualifier.
18925
18926 auto start_array_index = expr.find_first_of('[');
18927
18928 if (start_array_index == string::npos)
18929 return;
18930
18931 // We've opened a bracket, track expressions until we can close the bracket.
18932 // This must be our resource index.
18933 size_t end_array_index = string::npos;
18934 unsigned bracket_count = 1;
18935 for (size_t index = start_array_index + 1; index < expr.size(); index++)
18936 {
18937 if (expr[index] == ']')
18938 {
18939 if (--bracket_count == 0)
18940 {
18941 end_array_index = index;
18942 break;
18943 }
18944 }
18945 else if (expr[index] == '[')
18946 bracket_count++;
18947 }
18948
18949 assert(bracket_count == 0);
18950
18951 // Doesn't really make sense to declare a non-arrayed image with nonuniformEXT, but there's
18952 // nothing we can do here to express that.
18953 if (start_array_index == string::npos || end_array_index == string::npos || end_array_index < start_array_index)
18954 return;
18955
18956 start_array_index++;
18957
18958 expr = join(expr.substr(0, start_array_index), backend.nonuniform_qualifier, "(",
18959 expr.substr(start_array_index, end_array_index - start_array_index), ")",
18960 expr.substr(end_array_index, string::npos));
18961 }
18962
18963 void CompilerGLSL::emit_block_hints(const SPIRBlock &block)
18964 {
18965 if ((options.es && options.version < 310) || (!options.es && options.version < 140))
18966 return;
18967
18968 switch (block.hint)
18969 {
18970 case SPIRBlock::HintFlatten:
18971 require_extension_internal("GL_EXT_control_flow_attributes");
18972 statement("SPIRV_CROSS_FLATTEN");
18973 break;
18974 case SPIRBlock::HintDontFlatten:
18975 require_extension_internal("GL_EXT_control_flow_attributes");
18976 statement("SPIRV_CROSS_BRANCH");
18977 break;
18978 case SPIRBlock::HintUnroll:
18979 require_extension_internal("GL_EXT_control_flow_attributes");
18980 statement("SPIRV_CROSS_UNROLL");
18981 break;
18982 case SPIRBlock::HintDontUnroll:
18983 require_extension_internal("GL_EXT_control_flow_attributes");
18984 statement("SPIRV_CROSS_LOOP");
18985 break;
18986 default:
18987 break;
18988 }
18989 }
18990
18991 void CompilerGLSL::preserve_alias_on_reset(uint32_t id)
18992 {
18993 preserved_aliases[id] = get_name(id);
18994 }
18995
18996 void CompilerGLSL::reset_name_caches()
18997 {
18998 for (auto &preserved : preserved_aliases)
18999 set_name(preserved.first, preserved.second);
19000
19001 preserved_aliases.clear();
19002 resource_names.clear();
19003 block_input_names.clear();
19004 block_output_names.clear();
19005 block_ubo_names.clear();
19006 block_ssbo_names.clear();
19007 block_names.clear();
19008 function_overloads.clear();
19009 }
19010
19011 void CompilerGLSL::fixup_anonymous_struct_names(std::unordered_set<uint32_t> &visited, const SPIRType &type)
19012 {
19013 if (visited.count(type.self))
19014 return;
19015 visited.insert(type.self);
19016
19017 for (uint32_t i = 0; i < uint32_t(type.member_types.size()); i++)
19018 {
19019 auto &mbr_type = get<SPIRType>(type.member_types[i]);
19020
19021 if (mbr_type.basetype == SPIRType::Struct)
19022 {
19023 // If there are multiple aliases, the output might be somewhat unpredictable,
19024 // but the only real alternative in that case is to do nothing, which isn't any better.
19025 // This check should be fine in practice.
19026 if (get_name(mbr_type.self).empty() && !get_member_name(type.self, i).empty())
19027 {
19028 auto anon_name = join("anon_", get_member_name(type.self, i));
19029 ParsedIR::sanitize_underscores(anon_name);
19030 set_name(mbr_type.self, anon_name);
19031 }
19032
19033 fixup_anonymous_struct_names(visited, mbr_type);
19034 }
19035 }
19036 }
19037
19038 void CompilerGLSL::fixup_anonymous_struct_names()
19039 {
19040 // HLSL codegen can often end up emitting anonymous structs inside blocks, which
19041 // breaks GL linking since all names must match ...
19042 // Try to emit sensible code, so attempt to find such structs and emit anon_$member.
19043
19044 // Breaks exponential explosion with weird type trees.
19045 std::unordered_set<uint32_t> visited;
19046
19047 ir.for_each_typed_id<SPIRType>([&](uint32_t, SPIRType &type) {
19048 if (type.basetype == SPIRType::Struct &&
19049 (has_decoration(type.self, DecorationBlock) ||
19050 has_decoration(type.self, DecorationBufferBlock)))
19051 {
19052 fixup_anonymous_struct_names(visited, type);
19053 }
19054 });
19055 }
19056
19057 void CompilerGLSL::fixup_type_alias()
19058 {
19059 // Due to how some backends work, the "master" type of type_alias must be a block-like type if it exists.
19060 ir.for_each_typed_id<SPIRType>([&](uint32_t self, SPIRType &type) {
19061 if (!type.type_alias)
19062 return;
19063
19064 if (has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock))
19065 {
19066 // Top-level block types should never alias anything else.
19067 type.type_alias = 0;
19068 }
19069 else if (type_is_block_like(type) && type.self == ID(self))
19070 {
19071 // A block-like type is any type which contains Offset decoration, but not top-level blocks,
19072 // i.e. blocks which are placed inside buffers.
19073 // Become the master.
19074 ir.for_each_typed_id<SPIRType>([&](uint32_t other_id, SPIRType &other_type) {
19075 if (other_id == self)
19076 return;
19077
19078 if (other_type.type_alias == type.type_alias)
19079 other_type.type_alias = self;
19080 });
19081
19082 this->get<SPIRType>(type.type_alias).type_alias = self;
19083 type.type_alias = 0;
19084 }
19085 });
19086 }
19087
19088 void CompilerGLSL::reorder_type_alias()
19089 {
19090 // Reorder declaration of types so that the master of the type alias is always emitted first.
19091 // We need this in case a type B depends on type A (A must come before in the vector), but A is an alias of a type Abuffer, which
19092 // means declaration of A doesn't happen (yet), and order would be B, ABuffer and not ABuffer, B. Fix this up here.
19093 auto loop_lock = ir.create_loop_hard_lock();
19094
19095 auto &type_ids = ir.ids_for_type[TypeType];
19096 for (auto alias_itr = begin(type_ids); alias_itr != end(type_ids); ++alias_itr)
19097 {
19098 auto &type = get<SPIRType>(*alias_itr);
19099 if (type.type_alias != TypeID(0) &&
19100 !has_extended_decoration(type.type_alias, SPIRVCrossDecorationBufferBlockRepacked))
19101 {
19102 // We will skip declaring this type, so make sure the type_alias type comes before.
19103 auto master_itr = find(begin(type_ids), end(type_ids), ID(type.type_alias));
19104 assert(master_itr != end(type_ids));
19105
19106 if (alias_itr < master_itr)
19107 {
19108 // Must also swap the type order for the constant-type joined array.
19109 auto &joined_types = ir.ids_for_constant_undef_or_type;
19110 auto alt_alias_itr = find(begin(joined_types), end(joined_types), *alias_itr);
19111 auto alt_master_itr = find(begin(joined_types), end(joined_types), *master_itr);
19112 assert(alt_alias_itr != end(joined_types));
19113 assert(alt_master_itr != end(joined_types));
19114
19115 swap(*alias_itr, *master_itr);
19116 swap(*alt_alias_itr, *alt_master_itr);
19117 }
19118 }
19119 }
19120 }
19121
19122 void CompilerGLSL::emit_line_directive(uint32_t file_id, uint32_t line_literal)
19123 {
19124 // If we are redirecting statements, ignore the line directive.
19125 // Common case here is continue blocks.
19126 if (redirect_statement)
19127 return;
19128
19129 // If we're emitting code in a sensitive context such as condition blocks in for loops, don't emit
19130 // any line directives, because it's not possible.
19131 if (block_debug_directives)
19132 return;
19133
19134 if (options.emit_line_directives)
19135 {
19136 require_extension_internal("GL_GOOGLE_cpp_style_line_directive");
19137 statement_no_indent("#line ", line_literal, " \"", get<SPIRString>(file_id).str, "\"");
19138 }
19139 }
19140
19141 void CompilerGLSL::emit_copy_logical_type(uint32_t lhs_id, uint32_t lhs_type_id, uint32_t rhs_id, uint32_t rhs_type_id,
19142 SmallVector<uint32_t> chain)
19143 {
19144 // Fully unroll all member/array indices one by one.
19145
19146 auto &lhs_type = get<SPIRType>(lhs_type_id);
19147 auto &rhs_type = get<SPIRType>(rhs_type_id);
19148
19149 if (!lhs_type.array.empty())
19150 {
19151 // Could use a loop here to support specialization constants, but it gets rather complicated with nested array types,
19152 // and this is a rather obscure opcode anyways, keep it simple unless we are forced to.
19153 uint32_t array_size = to_array_size_literal(lhs_type);
19154 chain.push_back(0);
19155
19156 for (uint32_t i = 0; i < array_size; i++)
19157 {
19158 chain.back() = i;
19159 emit_copy_logical_type(lhs_id, lhs_type.parent_type, rhs_id, rhs_type.parent_type, chain);
19160 }
19161 }
19162 else if (lhs_type.basetype == SPIRType::Struct)
19163 {
19164 chain.push_back(0);
19165 uint32_t member_count = uint32_t(lhs_type.member_types.size());
19166 for (uint32_t i = 0; i < member_count; i++)
19167 {
19168 chain.back() = i;
19169 emit_copy_logical_type(lhs_id, lhs_type.member_types[i], rhs_id, rhs_type.member_types[i], chain);
19170 }
19171 }
19172 else
19173 {
19174 // Need to handle unpack/packing fixups since this can differ wildly between the logical types,
19175 // particularly in MSL.
19176 // To deal with this, we emit access chains and go through emit_store_statement
19177 // to deal with all the special cases we can encounter.
19178
19179 AccessChainMeta lhs_meta, rhs_meta;
19180 auto lhs = access_chain_internal(lhs_id, chain.data(), uint32_t(chain.size()),
19181 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT, &lhs_meta);
19182 auto rhs = access_chain_internal(rhs_id, chain.data(), uint32_t(chain.size()),
19183 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT, &rhs_meta);
19184
19185 uint32_t id = ir.increase_bound_by(2);
19186 lhs_id = id;
19187 rhs_id = id + 1;
19188
19189 {
19190 auto &lhs_expr = set<SPIRExpression>(lhs_id, std::move(lhs), lhs_type_id, true);
19191 lhs_expr.need_transpose = lhs_meta.need_transpose;
19192
19193 if (lhs_meta.storage_is_packed)
19194 set_extended_decoration(lhs_id, SPIRVCrossDecorationPhysicalTypePacked);
19195 if (lhs_meta.storage_physical_type != 0)
19196 set_extended_decoration(lhs_id, SPIRVCrossDecorationPhysicalTypeID, lhs_meta.storage_physical_type);
19197
19198 forwarded_temporaries.insert(lhs_id);
19199 suppressed_usage_tracking.insert(lhs_id);
19200 }
19201
19202 {
19203 auto &rhs_expr = set<SPIRExpression>(rhs_id, std::move(rhs), rhs_type_id, true);
19204 rhs_expr.need_transpose = rhs_meta.need_transpose;
19205
19206 if (rhs_meta.storage_is_packed)
19207 set_extended_decoration(rhs_id, SPIRVCrossDecorationPhysicalTypePacked);
19208 if (rhs_meta.storage_physical_type != 0)
19209 set_extended_decoration(rhs_id, SPIRVCrossDecorationPhysicalTypeID, rhs_meta.storage_physical_type);
19210
19211 forwarded_temporaries.insert(rhs_id);
19212 suppressed_usage_tracking.insert(rhs_id);
19213 }
19214
19215 emit_store_statement(lhs_id, rhs_id);
19216 }
19217 }
19218
19219 bool CompilerGLSL::subpass_input_is_framebuffer_fetch(uint32_t id) const
19220 {
19221 if (!has_decoration(id, DecorationInputAttachmentIndex))
19222 return false;
19223
19224 uint32_t input_attachment_index = get_decoration(id, DecorationInputAttachmentIndex);
19225 for (auto &remap : subpass_to_framebuffer_fetch_attachment)
19226 if (remap.first == input_attachment_index)
19227 return true;
19228
19229 return false;
19230 }
19231
19232 const SPIRVariable *CompilerGLSL::find_subpass_input_by_attachment_index(uint32_t index) const
19233 {
19234 const SPIRVariable *ret = nullptr;
19235 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
19236 if (has_decoration(var.self, DecorationInputAttachmentIndex) &&
19237 get_decoration(var.self, DecorationInputAttachmentIndex) == index)
19238 {
19239 ret = &var;
19240 }
19241 });
19242 return ret;
19243 }
19244
19245 const SPIRVariable *CompilerGLSL::find_color_output_by_location(uint32_t location) const
19246 {
19247 const SPIRVariable *ret = nullptr;
19248 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, const SPIRVariable &var) {
19249 if (var.storage == StorageClassOutput && get_decoration(var.self, DecorationLocation) == location)
19250 ret = &var;
19251 });
19252 return ret;
19253 }
19254
19255 void CompilerGLSL::emit_inout_fragment_outputs_copy_to_subpass_inputs()
19256 {
19257 for (auto &remap : subpass_to_framebuffer_fetch_attachment)
19258 {
19259 auto *subpass_var = find_subpass_input_by_attachment_index(remap.first);
19260 auto *output_var = find_color_output_by_location(remap.second);
19261 if (!subpass_var)
19262 continue;
19263 if (!output_var)
19264 SPIRV_CROSS_THROW("Need to declare the corresponding fragment output variable to be able "
19265 "to read from it.");
19266 if (is_array(get<SPIRType>(output_var->basetype)))
19267 SPIRV_CROSS_THROW("Cannot use GL_EXT_shader_framebuffer_fetch with arrays of color outputs.");
19268
19269 auto &func = get<SPIRFunction>(get_entry_point().self);
19270 func.fixup_hooks_in.push_back([=]() {
19271 if (is_legacy())
19272 {
19273 statement(to_expression(subpass_var->self), " = ", "gl_LastFragData[",
19274 get_decoration(output_var->self, DecorationLocation), "];");
19275 }
19276 else
19277 {
19278 uint32_t num_rt_components = this->get<SPIRType>(output_var->basetype).vecsize;
19279 statement(to_expression(subpass_var->self), vector_swizzle(num_rt_components, 0), " = ",
19280 to_expression(output_var->self), ";");
19281 }
19282 });
19283 }
19284 }
19285
19286 bool CompilerGLSL::variable_is_depth_or_compare(VariableID id) const
19287 {
19288 return is_depth_image(get<SPIRType>(get<SPIRVariable>(id).basetype), id);
19289 }
19290
19291 const char *CompilerGLSL::ShaderSubgroupSupportHelper::get_extension_name(Candidate c)
19292 {
19293 static const char *const retval[CandidateCount] = { "GL_KHR_shader_subgroup_ballot",
19294 "GL_KHR_shader_subgroup_basic",
19295 "GL_KHR_shader_subgroup_vote",
19296 "GL_KHR_shader_subgroup_arithmetic",
19297 "GL_NV_gpu_shader_5",
19298 "GL_NV_shader_thread_group",
19299 "GL_NV_shader_thread_shuffle",
19300 "GL_ARB_shader_ballot",
19301 "GL_ARB_shader_group_vote",
19302 "GL_AMD_gcn_shader" };
19303 return retval[c];
19304 }
19305
19306 SmallVector<std::string> CompilerGLSL::ShaderSubgroupSupportHelper::get_extra_required_extension_names(Candidate c)
19307 {
19308 switch (c)
19309 {
19310 case ARB_shader_ballot:
19311 return { "GL_ARB_shader_int64" };
19312 case AMD_gcn_shader:
19313 return { "GL_AMD_gpu_shader_int64", "GL_NV_gpu_shader5" };
19314 default:
19315 return {};
19316 }
19317 }
19318
19319 const char *CompilerGLSL::ShaderSubgroupSupportHelper::get_extra_required_extension_predicate(Candidate c)
19320 {
19321 switch (c)
19322 {
19323 case ARB_shader_ballot:
19324 return "defined(GL_ARB_shader_int64)";
19325 case AMD_gcn_shader:
19326 return "(defined(GL_AMD_gpu_shader_int64) || defined(GL_NV_gpu_shader5))";
19327 default:
19328 return "";
19329 }
19330 }
19331
19332 CompilerGLSL::ShaderSubgroupSupportHelper::FeatureVector CompilerGLSL::ShaderSubgroupSupportHelper::
19333 get_feature_dependencies(Feature feature)
19334 {
19335 switch (feature)
19336 {
19337 case SubgroupAllEqualT:
19338 return { SubgroupBroadcast_First, SubgroupAll_Any_AllEqualBool };
19339 case SubgroupElect:
19340 return { SubgroupBallotFindLSB_MSB, SubgroupBallot, SubgroupInvocationID };
19341 case SubgroupInverseBallot_InclBitCount_ExclBitCout:
19342 return { SubgroupMask };
19343 case SubgroupBallotBitCount:
19344 return { SubgroupBallot };
19345 case SubgroupArithmeticIAddReduce:
19346 case SubgroupArithmeticIAddInclusiveScan:
19347 case SubgroupArithmeticFAddReduce:
19348 case SubgroupArithmeticFAddInclusiveScan:
19349 case SubgroupArithmeticIMulReduce:
19350 case SubgroupArithmeticIMulInclusiveScan:
19351 case SubgroupArithmeticFMulReduce:
19352 case SubgroupArithmeticFMulInclusiveScan:
19353 return { SubgroupSize, SubgroupBallot, SubgroupBallotBitCount, SubgroupMask, SubgroupBallotBitExtract };
19354 case SubgroupArithmeticIAddExclusiveScan:
19355 case SubgroupArithmeticFAddExclusiveScan:
19356 case SubgroupArithmeticIMulExclusiveScan:
19357 case SubgroupArithmeticFMulExclusiveScan:
19358 return { SubgroupSize, SubgroupBallot, SubgroupBallotBitCount,
19359 SubgroupMask, SubgroupElect, SubgroupBallotBitExtract };
19360 default:
19361 return {};
19362 }
19363 }
19364
19365 CompilerGLSL::ShaderSubgroupSupportHelper::FeatureMask CompilerGLSL::ShaderSubgroupSupportHelper::
19366 get_feature_dependency_mask(Feature feature)
19367 {
19368 return build_mask(get_feature_dependencies(feature));
19369 }
19370
19371 bool CompilerGLSL::ShaderSubgroupSupportHelper::can_feature_be_implemented_without_extensions(Feature feature)
19372 {
19373 static const bool retval[FeatureCount] = {
19374 false, false, false, false, false, false,
19375 true, // SubgroupBalloFindLSB_MSB
19376 false, false, false, false,
19377 true, // SubgroupMemBarrier - replaced with workgroup memory barriers
19378 false, false, true, false,
19379 false, false, false, false, false, false, // iadd, fadd
19380 false, false, false, false, false, false, // imul , fmul
19381 };
19382
19383 return retval[feature];
19384 }
19385
19386 CompilerGLSL::ShaderSubgroupSupportHelper::Candidate CompilerGLSL::ShaderSubgroupSupportHelper::
19387 get_KHR_extension_for_feature(Feature feature)
19388 {
19389 static const Candidate extensions[FeatureCount] = {
19390 KHR_shader_subgroup_ballot, KHR_shader_subgroup_basic, KHR_shader_subgroup_basic, KHR_shader_subgroup_basic,
19391 KHR_shader_subgroup_basic, KHR_shader_subgroup_ballot, KHR_shader_subgroup_ballot, KHR_shader_subgroup_vote,
19392 KHR_shader_subgroup_vote, KHR_shader_subgroup_basic, KHR_shader_subgroup_basic, KHR_shader_subgroup_basic,
19393 KHR_shader_subgroup_ballot, KHR_shader_subgroup_ballot, KHR_shader_subgroup_ballot, KHR_shader_subgroup_ballot,
19394 KHR_shader_subgroup_arithmetic, KHR_shader_subgroup_arithmetic, KHR_shader_subgroup_arithmetic,
19395 KHR_shader_subgroup_arithmetic, KHR_shader_subgroup_arithmetic, KHR_shader_subgroup_arithmetic,
19396 KHR_shader_subgroup_arithmetic, KHR_shader_subgroup_arithmetic, KHR_shader_subgroup_arithmetic,
19397 KHR_shader_subgroup_arithmetic, KHR_shader_subgroup_arithmetic, KHR_shader_subgroup_arithmetic,
19398 };
19399
19400 return extensions[feature];
19401 }
19402
19403 void CompilerGLSL::ShaderSubgroupSupportHelper::request_feature(Feature feature)
19404 {
19405 feature_mask |= (FeatureMask(1) << feature) | get_feature_dependency_mask(feature);
19406 }
19407
19408 bool CompilerGLSL::ShaderSubgroupSupportHelper::is_feature_requested(Feature feature) const
19409 {
19410 return (feature_mask & (1u << feature)) != 0;
19411 }
19412
19413 CompilerGLSL::ShaderSubgroupSupportHelper::Result CompilerGLSL::ShaderSubgroupSupportHelper::resolve() const
19414 {
19415 Result res;
19416
19417 for (uint32_t i = 0u; i < FeatureCount; ++i)
19418 {
19419 if (feature_mask & (1u << i))
19420 {
19421 auto feature = static_cast<Feature>(i);
19422 std::unordered_set<uint32_t> unique_candidates;
19423
19424 auto candidates = get_candidates_for_feature(feature);
19425 unique_candidates.insert(candidates.begin(), candidates.end());
19426
19427 auto deps = get_feature_dependencies(feature);
19428 for (Feature d : deps)
19429 {
19430 candidates = get_candidates_for_feature(d);
19431 if (!candidates.empty())
19432 unique_candidates.insert(candidates.begin(), candidates.end());
19433 }
19434
19435 for (uint32_t c : unique_candidates)
19436 ++res.weights[static_cast<Candidate>(c)];
19437 }
19438 }
19439
19440 return res;
19441 }
19442
19443 CompilerGLSL::ShaderSubgroupSupportHelper::CandidateVector CompilerGLSL::ShaderSubgroupSupportHelper::
19444 get_candidates_for_feature(Feature ft, const Result &r)
19445 {
19446 auto c = get_candidates_for_feature(ft);
19447 auto cmp = [&r](Candidate a, Candidate b) {
19448 if (r.weights[a] == r.weights[b])
19449 return a < b; // Prefer candidates with lower enum value
19450 return r.weights[a] > r.weights[b];
19451 };
19452 std::sort(c.begin(), c.end(), cmp);
19453 return c;
19454 }
19455
19456 CompilerGLSL::ShaderSubgroupSupportHelper::CandidateVector CompilerGLSL::ShaderSubgroupSupportHelper::
19457 get_candidates_for_feature(Feature feature)
19458 {
19459 switch (feature)
19460 {
19461 case SubgroupMask:
19462 return { KHR_shader_subgroup_ballot, NV_shader_thread_group, ARB_shader_ballot };
19463 case SubgroupSize:
19464 return { KHR_shader_subgroup_basic, NV_shader_thread_group, AMD_gcn_shader, ARB_shader_ballot };
19465 case SubgroupInvocationID:
19466 return { KHR_shader_subgroup_basic, NV_shader_thread_group, ARB_shader_ballot };
19467 case SubgroupID:
19468 return { KHR_shader_subgroup_basic, NV_shader_thread_group };
19469 case NumSubgroups:
19470 return { KHR_shader_subgroup_basic, NV_shader_thread_group };
19471 case SubgroupBroadcast_First:
19472 return { KHR_shader_subgroup_ballot, NV_shader_thread_shuffle, ARB_shader_ballot };
19473 case SubgroupBallotFindLSB_MSB:
19474 return { KHR_shader_subgroup_ballot, NV_shader_thread_group };
19475 case SubgroupAll_Any_AllEqualBool:
19476 return { KHR_shader_subgroup_vote, NV_gpu_shader_5, ARB_shader_group_vote, AMD_gcn_shader };
19477 case SubgroupAllEqualT:
19478 return {}; // depends on other features only
19479 case SubgroupElect:
19480 return {}; // depends on other features only
19481 case SubgroupBallot:
19482 return { KHR_shader_subgroup_ballot, NV_shader_thread_group, ARB_shader_ballot };
19483 case SubgroupBarrier:
19484 return { KHR_shader_subgroup_basic, NV_shader_thread_group, ARB_shader_ballot, AMD_gcn_shader };
19485 case SubgroupMemBarrier:
19486 return { KHR_shader_subgroup_basic };
19487 case SubgroupInverseBallot_InclBitCount_ExclBitCout:
19488 return {};
19489 case SubgroupBallotBitExtract:
19490 return { NV_shader_thread_group };
19491 case SubgroupBallotBitCount:
19492 return {};
19493 case SubgroupArithmeticIAddReduce:
19494 case SubgroupArithmeticIAddExclusiveScan:
19495 case SubgroupArithmeticIAddInclusiveScan:
19496 case SubgroupArithmeticFAddReduce:
19497 case SubgroupArithmeticFAddExclusiveScan:
19498 case SubgroupArithmeticFAddInclusiveScan:
19499 case SubgroupArithmeticIMulReduce:
19500 case SubgroupArithmeticIMulExclusiveScan:
19501 case SubgroupArithmeticIMulInclusiveScan:
19502 case SubgroupArithmeticFMulReduce:
19503 case SubgroupArithmeticFMulExclusiveScan:
19504 case SubgroupArithmeticFMulInclusiveScan:
19505 return { KHR_shader_subgroup_arithmetic, NV_shader_thread_shuffle };
19506 default:
19507 return {};
19508 }
19509 }
19510
19511 CompilerGLSL::ShaderSubgroupSupportHelper::FeatureMask CompilerGLSL::ShaderSubgroupSupportHelper::build_mask(
19512 const SmallVector<Feature> &features)
19513 {
19514 FeatureMask mask = 0;
19515 for (Feature f : features)
19516 mask |= FeatureMask(1) << f;
19517 return mask;
19518 }
19519
19520 CompilerGLSL::ShaderSubgroupSupportHelper::Result::Result()
19521 {
19522 for (auto &weight : weights)
19523 weight = 0;
19524
19525 // Make sure KHR_shader_subgroup extensions are always prefered.
19526 const uint32_t big_num = FeatureCount;
19527 weights[KHR_shader_subgroup_ballot] = big_num;
19528 weights[KHR_shader_subgroup_basic] = big_num;
19529 weights[KHR_shader_subgroup_vote] = big_num;
19530 weights[KHR_shader_subgroup_arithmetic] = big_num;
19531 }
19532
19533 void CompilerGLSL::request_workaround_wrapper_overload(TypeID id)
19534 {
19535 // Must be ordered to maintain deterministic output, so vector is appropriate.
19536 if (find(begin(workaround_ubo_load_overload_types), end(workaround_ubo_load_overload_types), id) ==
19537 end(workaround_ubo_load_overload_types))
19538 {
19539 force_recompile();
19540 workaround_ubo_load_overload_types.push_back(id);
19541 }
19542 }
19543
19544 void CompilerGLSL::rewrite_load_for_wrapped_row_major(std::string &expr, TypeID loaded_type, ID ptr)
19545 {
19546 // Loading row-major matrices from UBOs on older AMD Windows OpenGL drivers is problematic.
19547 // To load these types correctly, we must first wrap them in a dummy function which only purpose is to
19548 // ensure row_major decoration is actually respected.
19549 auto *var = maybe_get_backing_variable(ptr);
19550 if (!var)
19551 return;
19552
19553 auto &backing_type = get<SPIRType>(var->basetype);
19554 bool is_ubo = backing_type.basetype == SPIRType::Struct && backing_type.storage == StorageClassUniform &&
19555 has_decoration(backing_type.self, DecorationBlock);
19556 if (!is_ubo)
19557 return;
19558
19559 auto *type = &get<SPIRType>(loaded_type);
19560 bool rewrite = false;
19561 bool relaxed = options.es;
19562
19563 if (is_matrix(*type))
19564 {
19565 // To avoid adding a lot of unnecessary meta tracking to forward the row_major state,
19566 // we will simply look at the base struct itself. It is exceptionally rare to mix and match row-major/col-major state.
19567 // If there is any row-major action going on, we apply the workaround.
19568 // It is harmless to apply the workaround to column-major matrices, so this is still a valid solution.
19569 // If an access chain occurred, the workaround is not required, so loading vectors or scalars don't need workaround.
19570 type = &backing_type;
19571 }
19572 else
19573 {
19574 // If we're loading a composite, we don't have overloads like these.
19575 relaxed = false;
19576 }
19577
19578 if (type->basetype == SPIRType::Struct)
19579 {
19580 // If we're loading a struct where any member is a row-major matrix, apply the workaround.
19581 for (uint32_t i = 0; i < uint32_t(type->member_types.size()); i++)
19582 {
19583 auto decorations = combined_decoration_for_member(*type, i);
19584 if (decorations.get(DecorationRowMajor))
19585 rewrite = true;
19586
19587 // Since we decide on a per-struct basis, only use mediump wrapper if all candidates are mediump.
19588 if (!decorations.get(DecorationRelaxedPrecision))
19589 relaxed = false;
19590 }
19591 }
19592
19593 if (rewrite)
19594 {
19595 request_workaround_wrapper_overload(loaded_type);
19596 expr = join("spvWorkaroundRowMajor", (relaxed ? "MP" : ""), "(", expr, ")");
19597 }
19598 }
19599
19600 void CompilerGLSL::mask_stage_output_by_location(uint32_t location, uint32_t component)
19601 {
19602 masked_output_locations.insert({ location, component });
19603 }
19604
19605 void CompilerGLSL::mask_stage_output_by_builtin(BuiltIn builtin)
19606 {
19607 masked_output_builtins.insert(builtin);
19608 }
19609
19610 bool CompilerGLSL::is_stage_output_variable_masked(const SPIRVariable &var) const
19611 {
19612 auto &type = get<SPIRType>(var.basetype);
19613 bool is_block = has_decoration(type.self, DecorationBlock);
19614 // Blocks by themselves are never masked. Must be masked per-member.
19615 if (is_block)
19616 return false;
19617
19618 bool is_builtin = has_decoration(var.self, DecorationBuiltIn);
19619
19620 if (is_builtin)
19621 {
19622 return is_stage_output_builtin_masked(BuiltIn(get_decoration(var.self, DecorationBuiltIn)));
19623 }
19624 else
19625 {
19626 if (!has_decoration(var.self, DecorationLocation))
19627 return false;
19628
19629 return is_stage_output_location_masked(
19630 get_decoration(var.self, DecorationLocation),
19631 get_decoration(var.self, DecorationComponent));
19632 }
19633 }
19634
19635 bool CompilerGLSL::is_stage_output_block_member_masked(const SPIRVariable &var, uint32_t index, bool strip_array) const
19636 {
19637 auto &type = get<SPIRType>(var.basetype);
19638 bool is_block = has_decoration(type.self, DecorationBlock);
19639 if (!is_block)
19640 return false;
19641
19642 BuiltIn builtin = BuiltInMax;
19643 if (is_member_builtin(type, index, &builtin))
19644 {
19645 return is_stage_output_builtin_masked(builtin);
19646 }
19647 else
19648 {
19649 uint32_t location = get_declared_member_location(var, index, strip_array);
19650 uint32_t component = get_member_decoration(type.self, index, DecorationComponent);
19651 return is_stage_output_location_masked(location, component);
19652 }
19653 }
19654
19655 bool CompilerGLSL::is_per_primitive_variable(const SPIRVariable &var) const
19656 {
19657 if (has_decoration(var.self, DecorationPerPrimitiveEXT))
19658 return true;
19659
19660 auto &type = get<SPIRType>(var.basetype);
19661 if (!has_decoration(type.self, DecorationBlock))
19662 return false;
19663
19664 for (uint32_t i = 0, n = uint32_t(type.member_types.size()); i < n; i++)
19665 if (!has_member_decoration(type.self, i, DecorationPerPrimitiveEXT))
19666 return false;
19667
19668 return true;
19669 }
19670
19671 bool CompilerGLSL::is_stage_output_location_masked(uint32_t location, uint32_t component) const
19672 {
19673 return masked_output_locations.count({ location, component }) != 0;
19674 }
19675
19676 bool CompilerGLSL::is_stage_output_builtin_masked(spv::BuiltIn builtin) const
19677 {
19678 return masked_output_builtins.count(builtin) != 0;
19679 }
19680
19681 uint32_t CompilerGLSL::get_declared_member_location(const SPIRVariable &var, uint32_t mbr_idx, bool strip_array) const
19682 {
19683 auto &block_type = get<SPIRType>(var.basetype);
19684 if (has_member_decoration(block_type.self, mbr_idx, DecorationLocation))
19685 return get_member_decoration(block_type.self, mbr_idx, DecorationLocation);
19686 else
19687 return get_accumulated_member_location(var, mbr_idx, strip_array);
19688 }
19689
19690 uint32_t CompilerGLSL::get_accumulated_member_location(const SPIRVariable &var, uint32_t mbr_idx, bool strip_array) const
19691 {
19692 auto &type = strip_array ? get_variable_element_type(var) : get_variable_data_type(var);
19693 uint32_t location = get_decoration(var.self, DecorationLocation);
19694
19695 for (uint32_t i = 0; i < mbr_idx; i++)
19696 {
19697 auto &mbr_type = get<SPIRType>(type.member_types[i]);
19698
19699 // Start counting from any place we have a new location decoration.
19700 if (has_member_decoration(type.self, mbr_idx, DecorationLocation))
19701 location = get_member_decoration(type.self, mbr_idx, DecorationLocation);
19702
19703 uint32_t location_count = type_to_location_count(mbr_type);
19704 location += location_count;
19705 }
19706
19707 return location;
19708 }
19709
19710 StorageClass CompilerGLSL::get_expression_effective_storage_class(uint32_t ptr)
19711 {
19712 auto *var = maybe_get_backing_variable(ptr);
19713
19714 // If the expression has been lowered to a temporary, we need to use the Generic storage class.
19715 // We're looking for the effective storage class of a given expression.
19716 // An access chain or forwarded OpLoads from such access chains
19717 // will generally have the storage class of the underlying variable, but if the load was not forwarded
19718 // we have lost any address space qualifiers.
19719 bool forced_temporary = ir.ids[ptr].get_type() == TypeExpression && !get<SPIRExpression>(ptr).access_chain &&
19720 (forced_temporaries.count(ptr) != 0 || forwarded_temporaries.count(ptr) == 0);
19721
19722 if (var && !forced_temporary)
19723 {
19724 if (variable_decl_is_remapped_storage(*var, StorageClassWorkgroup))
19725 return StorageClassWorkgroup;
19726 if (variable_decl_is_remapped_storage(*var, StorageClassStorageBuffer))
19727 return StorageClassStorageBuffer;
19728
19729 // Normalize SSBOs to StorageBuffer here.
19730 if (var->storage == StorageClassUniform &&
19731 has_decoration(get<SPIRType>(var->basetype).self, DecorationBufferBlock))
19732 return StorageClassStorageBuffer;
19733 else
19734 return var->storage;
19735 }
19736 else
19737 return expression_type(ptr).storage;
19738 }
19739
19740 uint32_t CompilerGLSL::type_to_location_count(const SPIRType &type) const
19741 {
19742 uint32_t count;
19743 if (type.basetype == SPIRType::Struct)
19744 {
19745 uint32_t mbr_count = uint32_t(type.member_types.size());
19746 count = 0;
19747 for (uint32_t i = 0; i < mbr_count; i++)
19748 count += type_to_location_count(get<SPIRType>(type.member_types[i]));
19749 }
19750 else
19751 {
19752 count = type.columns > 1 ? type.columns : 1;
19753 }
19754
19755 uint32_t dim_count = uint32_t(type.array.size());
19756 for (uint32_t i = 0; i < dim_count; i++)
19757 count *= to_array_size_literal(type, i);
19758
19759 return count;
19760 }
19761
19762 std::string CompilerGLSL::format_float(float value) const
19763 {
19764 if (float_formatter)
19765 return float_formatter->format_float(value);
19766
19767 // default behavior
19768 return convert_to_string(value, current_locale_radix_character);
19769 }
19770
19771 std::string CompilerGLSL::format_double(double value) const
19772 {
19773 if (float_formatter)
19774 return float_formatter->format_double(value);
19775
19776 // default behavior
19777 return convert_to_string(value, current_locale_radix_character);
19778 }
19779