Debian Codegraph @

third_party/spirv-cross/spirv_glsl.hpp

raw
1 /*
2 * Copyright 2015-2020 Arm Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef SPIRV_CROSS_GLSL_HPP
18 #define SPIRV_CROSS_GLSL_HPP
19
20 #include "GLSL.std.450.h"
21 #include "spirv_cross.hpp"
22 #include <unordered_map>
23 #include <unordered_set>
24 #include <utility>
25
26 namespace SPIRV_CROSS_NAMESPACE
27 {
28 enum PlsFormat
29 {
30 PlsNone = 0,
31
32 PlsR11FG11FB10F,
33 PlsR32F,
34 PlsRG16F,
35 PlsRGB10A2,
36 PlsRGBA8,
37 PlsRG16,
38
39 PlsRGBA8I,
40 PlsRG16I,
41
42 PlsRGB10A2UI,
43 PlsRGBA8UI,
44 PlsRG16UI,
45 PlsR32UI
46 };
47
48 struct PlsRemap
49 {
50 uint32_t id;
51 PlsFormat format;
52 };
53
54 enum AccessChainFlagBits
55 {
56 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT = 1 << 0,
57 ACCESS_CHAIN_CHAIN_ONLY_BIT = 1 << 1,
58 ACCESS_CHAIN_PTR_CHAIN_BIT = 1 << 2,
59 ACCESS_CHAIN_SKIP_REGISTER_EXPRESSION_READ_BIT = 1 << 3,
60 ACCESS_CHAIN_LITERAL_MSB_FORCE_ID = 1 << 4,
61 ACCESS_CHAIN_FLATTEN_ALL_MEMBERS_BIT = 1 << 5
62 };
63 typedef uint32_t AccessChainFlags;
64
65 class CompilerGLSL : public Compiler
66 {
67 public:
68 struct Options
69 {
70 // The shading language version. Corresponds to #version $VALUE.
71 uint32_t version = 450;
72
73 // Emit the OpenGL ES shading language instead of desktop OpenGL.
74 bool es = false;
75
76 // Debug option to always emit temporary variables for all expressions.
77 bool force_temporary = false;
78
79 // If true, Vulkan GLSL features are used instead of GL-compatible features.
80 // Mostly useful for debugging SPIR-V files.
81 bool vulkan_semantics = false;
82
83 // If true, gl_PerVertex is explicitly redeclared in vertex, geometry and tessellation shaders.
84 // The members of gl_PerVertex is determined by which built-ins are declared by the shader.
85 // This option is ignored in ES versions, as redeclaration in ES is not required, and it depends on a different extension
86 // (EXT_shader_io_blocks) which makes things a bit more fuzzy.
87 bool separate_shader_objects = false;
88
89 // Flattens multidimensional arrays, e.g. float foo[a][b][c] into single-dimensional arrays,
90 // e.g. float foo[a * b * c].
91 // This function does not change the actual SPIRType of any object.
92 // Only the generated code, including declarations of interface variables are changed to be single array dimension.
93 bool flatten_multidimensional_arrays = false;
94
95 // For older desktop GLSL targets than version 420, the
96 // GL_ARB_shading_language_420pack extensions is used to be able to support
97 // layout(binding) on UBOs and samplers.
98 // If disabled on older targets, binding decorations will be stripped.
99 bool enable_420pack_extension = true;
100
101 // In non-Vulkan GLSL, emit push constant blocks as UBOs rather than plain uniforms.
102 bool emit_push_constant_as_uniform_buffer = false;
103
104 // Always emit uniform blocks as plain uniforms, regardless of the GLSL version, even when UBOs are supported.
105 // Does not apply to shader storage or push constant blocks.
106 bool emit_uniform_buffer_as_plain_uniforms = false;
107
108 // Emit OpLine directives if present in the module.
109 // May not correspond exactly to original source, but should be a good approximation.
110 bool emit_line_directives = false;
111
112 // In cases where readonly/writeonly decoration are not used at all,
113 // we try to deduce which qualifier(s) we should actually used, since actually emitting
114 // read-write decoration is very rare, and older glslang/HLSL compilers tend to just emit readwrite as a matter of fact.
115 // The default (true) is to enable automatic deduction for these cases, but if you trust the decorations set
116 // by the SPIR-V, it's recommended to set this to false.
117 bool enable_storage_image_qualifier_deduction = true;
118
119 // On some targets (WebGPU), uninitialized variables are banned.
120 // If this is enabled, all variables (temporaries, Private, Function)
121 // which would otherwise be uninitialized will now be initialized to 0 instead.
122 bool force_zero_initialized_variables = false;
123
124 // In GLSL, force use of I/O block flattening, similar to
125 // what happens on legacy GLSL targets for blocks and structs.
126 bool force_flattened_io_blocks = false;
127
128 enum Precision
129 {
130 DontCare,
131 Lowp,
132 Mediump,
133 Highp
134 };
135
136 struct VertexOptions
137 {
138 // "Vertex-like shader" here is any shader stage that can write BuiltInPosition.
139
140 // GLSL: In vertex-like shaders, rewrite [0, w] depth (Vulkan/D3D style) to [-w, w] depth (GL style).
141 // MSL: In vertex-like shaders, rewrite [-w, w] depth (GL style) to [0, w] depth.
142 // HLSL: In vertex-like shaders, rewrite [-w, w] depth (GL style) to [0, w] depth.
143 bool fixup_clipspace = false;
144
145 // In vertex-like shaders, inverts gl_Position.y or equivalent.
146 bool flip_vert_y = false;
147
148 // GLSL only, for HLSL version of this option, see CompilerHLSL.
149 // If true, the backend will assume that InstanceIndex will need to apply
150 // a base instance offset. Set to false if you know you will never use base instance
151 // functionality as it might remove some internal uniforms.
152 bool support_nonzero_base_instance = true;
153 } vertex;
154
155 struct FragmentOptions
156 {
157 // Add precision mediump float in ES targets when emitting GLES source.
158 // Add precision highp int in ES targets when emitting GLES source.
159 Precision default_float_precision = Mediump;
160 Precision default_int_precision = Highp;
161 } fragment;
162 };
163
164 void remap_pixel_local_storage(std::vector<PlsRemap> inputs, std::vector<PlsRemap> outputs)
165 {
166 pls_inputs = std::move(inputs);
167 pls_outputs = std::move(outputs);
168 remap_pls_variables();
169 }
170
171 // Redirect a subpassInput reading from input_attachment_index to instead load its value from
172 // the color attachment at location = color_location. Requires ESSL.
173 void remap_ext_framebuffer_fetch(uint32_t input_attachment_index, uint32_t color_location);
174
175 explicit CompilerGLSL(std::vector<uint32_t> spirv_)
176 : Compiler(std::move(spirv_))
177 {
178 init();
179 }
180
181 CompilerGLSL(const uint32_t *ir_, size_t word_count)
182 : Compiler(ir_, word_count)
183 {
184 init();
185 }
186
187 explicit CompilerGLSL(const ParsedIR &ir_)
188 : Compiler(ir_)
189 {
190 init();
191 }
192
193 explicit CompilerGLSL(ParsedIR &&ir_)
194 : Compiler(std::move(ir_))
195 {
196 init();
197 }
198
199 const Options &get_common_options() const
200 {
201 return options;
202 }
203
204 void set_common_options(const Options &opts)
205 {
206 options = opts;
207 }
208
209 std::string compile() override;
210
211 // Returns the current string held in the conversion buffer. Useful for
212 // capturing what has been converted so far when compile() throws an error.
213 std::string get_partial_source();
214
215 // Adds a line to be added right after #version in GLSL backend.
216 // This is useful for enabling custom extensions which are outside the scope of SPIRV-Cross.
217 // This can be combined with variable remapping.
218 // A new-line will be added.
219 //
220 // While add_header_line() is a more generic way of adding arbitrary text to the header
221 // of a GLSL file, require_extension() should be used when adding extensions since it will
222 // avoid creating collisions with SPIRV-Cross generated extensions.
223 //
224 // Code added via add_header_line() is typically backend-specific.
225 void add_header_line(const std::string &str);
226
227 // Adds an extension which is required to run this shader, e.g.
228 // require_extension("GL_KHR_my_extension");
229 void require_extension(const std::string &ext);
230
231 // Legacy GLSL compatibility method.
232 // Takes a uniform or push constant variable and flattens it into a (i|u)vec4 array[N]; array instead.
233 // For this to work, all types in the block must be the same basic type, e.g. mixing vec2 and vec4 is fine, but
234 // mixing int and float is not.
235 // The name of the uniform array will be the same as the interface block name.
236 void flatten_buffer_block(VariableID id);
237
238 // After compilation, query if a variable ID was used as a depth resource.
239 // This is meaningful for MSL since descriptor types depend on this knowledge.
240 // Cases which return true:
241 // - Images which are declared with depth = 1 image type.
242 // - Samplers which are statically used at least once with Dref opcodes.
243 // - Images which are statically used at least once with Dref opcodes.
244 bool variable_is_depth_or_compare(VariableID id) const;
245
246 protected:
247 struct ShaderSubgroupSupportHelper
248 {
249 // lower enum value = greater priority
250 enum Candidate
251 {
252 KHR_shader_subgroup_ballot,
253 KHR_shader_subgroup_basic,
254 KHR_shader_subgroup_vote,
255 NV_gpu_shader_5,
256 NV_shader_thread_group,
257 NV_shader_thread_shuffle,
258 ARB_shader_ballot,
259 ARB_shader_group_vote,
260 AMD_gcn_shader,
261
262 CandidateCount
263 };
264
265 static const char *get_extension_name(Candidate c);
266 static SmallVector<std::string> get_extra_required_extension_names(Candidate c);
267 static const char *get_extra_required_extension_predicate(Candidate c);
268
269 enum Feature
270 {
271 SubgroupMask,
272 SubgroupSize,
273 SubgroupInvocationID,
274 SubgroupID,
275 NumSubgroups,
276 SubgroupBrodcast_First,
277 SubgroupBallotFindLSB_MSB,
278 SubgroupAll_Any_AllEqualBool,
279 SubgroupAllEqualT,
280 SubgroupElect,
281 SubgroupBarrier,
282 SubgroupMemBarrier,
283 SubgroupBallot,
284 SubgroupInverseBallot_InclBitCount_ExclBitCout,
285 SubgroupBallotBitExtract,
286 SubgroupBallotBitCount,
287
288 FeatureCount
289 };
290
291 using FeatureMask = uint32_t;
292 static_assert(sizeof(FeatureMask) * 8u >= FeatureCount, "Mask type needs more bits.");
293
294 using CandidateVector = SmallVector<Candidate, CandidateCount>;
295 using FeatureVector = SmallVector<Feature>;
296
297 static FeatureVector get_feature_dependencies(Feature feature);
298 static FeatureMask get_feature_dependency_mask(Feature feature);
299 static bool can_feature_be_implemented_without_extensions(Feature feature);
300 static Candidate get_KHR_extension_for_feature(Feature feature);
301
302 struct Result
303 {
304 Result();
305 uint32_t weights[CandidateCount];
306 };
307
308 void request_feature(Feature feature);
309 bool is_feature_requested(Feature feature) const;
310 Result resolve() const;
311
312 static CandidateVector get_candidates_for_feature(Feature ft, const Result &r);
313
314 private:
315 static CandidateVector get_candidates_for_feature(Feature ft);
316 static FeatureMask build_mask(const SmallVector<Feature> &features);
317 FeatureMask feature_mask = 0;
318 };
319
320 // TODO remove this function when all subgroup ops are supported (or make it always return true)
321 static bool is_supported_subgroup_op_in_opengl(spv::Op op);
322
323 void reset();
324 void emit_function(SPIRFunction &func, const Bitset &return_flags);
325
326 bool has_extension(const std::string &ext) const;
327 void require_extension_internal(const std::string &ext);
328
329 // Virtualize methods which need to be overridden by subclass targets like C++ and such.
330 virtual void emit_function_prototype(SPIRFunction &func, const Bitset &return_flags);
331
332 SPIRBlock *current_emitting_block = nullptr;
333 SPIRBlock *current_emitting_switch = nullptr;
334 bool current_emitting_switch_fallthrough = false;
335
336 virtual void emit_instruction(const Instruction &instr);
337 void emit_block_instructions(SPIRBlock &block);
338 virtual void emit_glsl_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
339 uint32_t count);
340 virtual void emit_spv_amd_shader_ballot_op(uint32_t result_type, uint32_t result_id, uint32_t op,
341 const uint32_t *args, uint32_t count);
342 virtual void emit_spv_amd_shader_explicit_vertex_parameter_op(uint32_t result_type, uint32_t result_id, uint32_t op,
343 const uint32_t *args, uint32_t count);
344 virtual void emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t result_id, uint32_t op,
345 const uint32_t *args, uint32_t count);
346 virtual void emit_spv_amd_gcn_shader_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
347 uint32_t count);
348 virtual void emit_header();
349 void emit_line_directive(uint32_t file_id, uint32_t line_literal);
350 void build_workgroup_size(SmallVector<std::string> &arguments, const SpecializationConstant &x,
351 const SpecializationConstant &y, const SpecializationConstant &z);
352
353 void request_subgroup_feature(ShaderSubgroupSupportHelper::Feature feature);
354
355 virtual void emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id);
356 virtual void emit_texture_op(const Instruction &i, bool sparse);
357 virtual std::string to_texture_op(const Instruction &i, bool sparse, bool *forward,
358 SmallVector<uint32_t> &inherited_expressions);
359 virtual void emit_subgroup_op(const Instruction &i);
360 virtual std::string type_to_glsl(const SPIRType &type, uint32_t id = 0);
361 virtual std::string builtin_to_glsl(spv::BuiltIn builtin, spv::StorageClass storage);
362 virtual void emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
363 const std::string &qualifier = "", uint32_t base_offset = 0);
364 virtual void emit_struct_padding_target(const SPIRType &type);
365 virtual std::string image_type_glsl(const SPIRType &type, uint32_t id = 0);
366 std::string constant_expression(const SPIRConstant &c);
367 std::string constant_op_expression(const SPIRConstantOp &cop);
368 virtual std::string constant_expression_vector(const SPIRConstant &c, uint32_t vector);
369 virtual void emit_fixup();
370 virtual std::string variable_decl(const SPIRType &type, const std::string &name, uint32_t id = 0);
371 virtual std::string to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id);
372
373 struct TextureFunctionBaseArguments
374 {
375 // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
376 TextureFunctionBaseArguments() = default;
377 VariableID img = 0;
378 const SPIRType *imgtype = nullptr;
379 bool is_fetch = false, is_gather = false, is_proj = false;
380 };
381
382 struct TextureFunctionNameArguments
383 {
384 // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
385 TextureFunctionNameArguments() = default;
386 TextureFunctionBaseArguments base;
387 bool has_array_offsets = false, has_offset = false, has_grad = false;
388 bool has_dref = false, is_sparse_feedback = false, has_min_lod = false;
389 uint32_t lod = 0;
390 };
391 virtual std::string to_function_name(const TextureFunctionNameArguments &args);
392
393 struct TextureFunctionArguments
394 {
395 // GCC 4.8 workarounds, it doesn't understand '{}' constructor here, use explicit default constructor.
396 TextureFunctionArguments() = default;
397 TextureFunctionBaseArguments base;
398 uint32_t coord = 0, coord_components = 0, dref = 0;
399 uint32_t grad_x = 0, grad_y = 0, lod = 0, coffset = 0, offset = 0;
400 uint32_t bias = 0, component = 0, sample = 0, sparse_texel = 0, min_lod = 0;
401 };
402 virtual std::string to_function_args(const TextureFunctionArguments &args, bool *p_forward);
403
404 void emit_sparse_feedback_temporaries(uint32_t result_type_id, uint32_t id, uint32_t &feedback_id,
405 uint32_t &texel_id);
406 uint32_t get_sparse_feedback_texel_id(uint32_t id) const;
407 virtual void emit_buffer_block(const SPIRVariable &type);
408 virtual void emit_push_constant_block(const SPIRVariable &var);
409 virtual void emit_uniform(const SPIRVariable &var);
410 virtual std::string unpack_expression_type(std::string expr_str, const SPIRType &type, uint32_t physical_type_id,
411 bool packed_type, bool row_major);
412
413 virtual bool builtin_translates_to_nonarray(spv::BuiltIn builtin) const;
414
415 void emit_copy_logical_type(uint32_t lhs_id, uint32_t lhs_type_id, uint32_t rhs_id, uint32_t rhs_type_id,
416 SmallVector<uint32_t> chain);
417
418 StringStream<> buffer;
419
420 template <typename T>
421 inline void statement_inner(T &&t)
422 {
423 buffer << std::forward<T>(t);
424 statement_count++;
425 }
426
427 template <typename T, typename... Ts>
428 inline void statement_inner(T &&t, Ts &&... ts)
429 {
430 buffer << std::forward<T>(t);
431 statement_count++;
432 statement_inner(std::forward<Ts>(ts)...);
433 }
434
435 template <typename... Ts>
436 inline void statement(Ts &&... ts)
437 {
438 if (is_forcing_recompilation())
439 {
440 // Do not bother emitting code while force_recompile is active.
441 // We will compile again.
442 statement_count++;
443 return;
444 }
445
446 if (redirect_statement)
447 {
448 redirect_statement->push_back(join(std::forward<Ts>(ts)...));
449 statement_count++;
450 }
451 else
452 {
453 for (uint32_t i = 0; i < indent; i++)
454 buffer << " ";
455 statement_inner(std::forward<Ts>(ts)...);
456 buffer << '\n';
457 }
458 }
459
460 template <typename... Ts>
461 inline void statement_no_indent(Ts &&... ts)
462 {
463 auto old_indent = indent;
464 indent = 0;
465 statement(std::forward<Ts>(ts)...);
466 indent = old_indent;
467 }
468
469 // Used for implementing continue blocks where
470 // we want to obtain a list of statements we can merge
471 // on a single line separated by comma.
472 SmallVector<std::string> *redirect_statement = nullptr;
473 const SPIRBlock *current_continue_block = nullptr;
474
475 void begin_scope();
476 void end_scope();
477 void end_scope(const std::string &trailer);
478 void end_scope_decl();
479 void end_scope_decl(const std::string &decl);
480
481 Options options;
482
483 virtual std::string type_to_array_glsl(
484 const SPIRType &type); // Allow Metal to use the array<T> template to make arrays a value type
485 std::string to_array_size(const SPIRType &type, uint32_t index);
486 uint32_t to_array_size_literal(const SPIRType &type, uint32_t index) const;
487 uint32_t to_array_size_literal(const SPIRType &type) const;
488 virtual std::string variable_decl(const SPIRVariable &variable); // Threadgroup arrays can't have a wrapper type
489 std::string variable_decl_function_local(SPIRVariable &variable);
490
491 void add_local_variable_name(uint32_t id);
492 void add_resource_name(uint32_t id);
493 void add_member_name(SPIRType &type, uint32_t name);
494 void add_function_overload(const SPIRFunction &func);
495
496 virtual bool is_non_native_row_major_matrix(uint32_t id);
497 virtual bool member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index);
498 bool member_is_remapped_physical_type(const SPIRType &type, uint32_t index) const;
499 bool member_is_packed_physical_type(const SPIRType &type, uint32_t index) const;
500 virtual std::string convert_row_major_matrix(std::string exp_str, const SPIRType &exp_type,
501 uint32_t physical_type_id, bool is_packed);
502
503 std::unordered_set<std::string> local_variable_names;
504 std::unordered_set<std::string> resource_names;
505 std::unordered_set<std::string> block_input_names;
506 std::unordered_set<std::string> block_output_names;
507 std::unordered_set<std::string> block_ubo_names;
508 std::unordered_set<std::string> block_ssbo_names;
509 std::unordered_set<std::string> block_names; // A union of all block_*_names.
510 std::unordered_map<std::string, std::unordered_set<uint64_t>> function_overloads;
511 std::unordered_map<uint32_t, std::string> preserved_aliases;
512 void preserve_alias_on_reset(uint32_t id);
513 void reset_name_caches();
514
515 bool processing_entry_point = false;
516
517 // Can be overriden by subclass backends for trivial things which
518 // shouldn't need polymorphism.
519 struct BackendVariations
520 {
521 std::string discard_literal = "discard";
522 std::string demote_literal = "demote";
523 std::string null_pointer_literal = "";
524 bool float_literal_suffix = false;
525 bool double_literal_suffix = true;
526 bool uint32_t_literal_suffix = true;
527 bool long_long_literal_suffix = false;
528 const char *basic_int_type = "int";
529 const char *basic_uint_type = "uint";
530 const char *basic_int8_type = "int8_t";
531 const char *basic_uint8_type = "uint8_t";
532 const char *basic_int16_type = "int16_t";
533 const char *basic_uint16_type = "uint16_t";
534 const char *int16_t_literal_suffix = "s";
535 const char *uint16_t_literal_suffix = "us";
536 const char *nonuniform_qualifier = "nonuniformEXT";
537 const char *boolean_mix_function = "mix";
538 bool swizzle_is_function = false;
539 bool shared_is_implied = false;
540 bool unsized_array_supported = true;
541 bool explicit_struct_type = false;
542 bool use_initializer_list = false;
543 bool use_typed_initializer_list = false;
544 bool can_declare_struct_inline = true;
545 bool can_declare_arrays_inline = true;
546 bool native_row_major_matrix = true;
547 bool use_constructor_splatting = true;
548 bool allow_precision_qualifiers = false;
549 bool can_swizzle_scalar = false;
550 bool force_gl_in_out_block = false;
551 bool can_return_array = true;
552 bool allow_truncated_access_chain = false;
553 bool supports_extensions = false;
554 bool supports_empty_struct = false;
555 bool array_is_value_type = true;
556 bool buffer_offset_array_is_value_type = true;
557 bool comparison_image_samples_scalar = false;
558 bool native_pointers = false;
559 bool support_small_type_sampling_result = false;
560 bool support_case_fallthrough = true;
561 bool use_array_constructor = false;
562 bool needs_row_major_load_workaround = false;
563 } backend;
564
565 void emit_struct(SPIRType &type);
566 void emit_resources();
567 void emit_extension_workarounds(spv::ExecutionModel model);
568 void emit_buffer_block_native(const SPIRVariable &var);
569 void emit_buffer_reference_block(SPIRType &type, bool forward_declaration);
570 void emit_buffer_block_legacy(const SPIRVariable &var);
571 void emit_buffer_block_flattened(const SPIRVariable &type);
572 void fixup_implicit_builtin_block_names();
573 void emit_declared_builtin_block(spv::StorageClass storage, spv::ExecutionModel model);
574 bool should_force_emit_builtin_block(spv::StorageClass storage);
575 void emit_push_constant_block_vulkan(const SPIRVariable &var);
576 void emit_push_constant_block_glsl(const SPIRVariable &var);
577 void emit_interface_block(const SPIRVariable &type);
578 void emit_flattened_io_block(const SPIRVariable &var, const char *qual);
579 void emit_flattened_io_block_struct(const std::string &basename, const SPIRType &type, const char *qual,
580 const SmallVector<uint32_t> &indices);
581 void emit_flattened_io_block_member(const std::string &basename, const SPIRType &type, const char *qual,
582 const SmallVector<uint32_t> &indices);
583 void emit_block_chain(SPIRBlock &block);
584 void emit_hoisted_temporaries(SmallVector<std::pair<TypeID, ID>> &temporaries);
585 std::string constant_value_macro_name(uint32_t id);
586 void emit_constant(const SPIRConstant &constant);
587 void emit_specialization_constant_op(const SPIRConstantOp &constant);
588 std::string emit_continue_block(uint32_t continue_block, bool follow_true_block, bool follow_false_block);
589 bool attempt_emit_loop_header(SPIRBlock &block, SPIRBlock::Method method);
590
591 void branch(BlockID from, BlockID to);
592 void branch_to_continue(BlockID from, BlockID to);
593 void branch(BlockID from, uint32_t cond, BlockID true_block, BlockID false_block);
594 void flush_phi(BlockID from, BlockID to);
595 void flush_variable_declaration(uint32_t id);
596 void flush_undeclared_variables(SPIRBlock &block);
597 void emit_variable_temporary_copies(const SPIRVariable &var);
598
599 bool should_dereference(uint32_t id);
600 bool should_forward(uint32_t id) const;
601 bool should_suppress_usage_tracking(uint32_t id) const;
602 void emit_mix_op(uint32_t result_type, uint32_t id, uint32_t left, uint32_t right, uint32_t lerp);
603 void emit_nminmax_op(uint32_t result_type, uint32_t id, uint32_t op0, uint32_t op1, GLSLstd450 op);
604 bool to_trivial_mix_op(const SPIRType &type, std::string &op, uint32_t left, uint32_t right, uint32_t lerp);
605 void emit_quaternary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
606 uint32_t op3, const char *op);
607 void emit_trinary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
608 const char *op);
609 void emit_binary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
610
611 void emit_unary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op,
612 SPIRType::BaseType input_type, SPIRType::BaseType expected_result_type);
613 void emit_binary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
614 SPIRType::BaseType input_type, bool skip_cast_if_equal_type);
615 void emit_binary_func_op_cast_clustered(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
616 const char *op, SPIRType::BaseType input_type);
617 void emit_trinary_func_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
618 const char *op, SPIRType::BaseType input_type);
619 void emit_trinary_func_op_bitextract(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
620 uint32_t op2, const char *op, SPIRType::BaseType expected_result_type,
621 SPIRType::BaseType input_type0, SPIRType::BaseType input_type1,
622 SPIRType::BaseType input_type2);
623 void emit_bitfield_insert_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, uint32_t op2,
624 uint32_t op3, const char *op, SPIRType::BaseType offset_count_type);
625
626 void emit_unary_func_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
627 void emit_unrolled_unary_op(uint32_t result_type, uint32_t result_id, uint32_t operand, const char *op);
628 void emit_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
629 void emit_unrolled_binary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
630 bool negate, SPIRType::BaseType expected_type);
631 void emit_binary_op_cast(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op,
632 SPIRType::BaseType input_type, bool skip_cast_if_equal_type);
633
634 SPIRType binary_op_bitcast_helper(std::string &cast_op0, std::string &cast_op1, SPIRType::BaseType &input_type,
635 uint32_t op0, uint32_t op1, bool skip_cast_if_equal_type);
636
637 virtual bool emit_complex_bitcast(uint32_t result_type, uint32_t id, uint32_t op0);
638
639 std::string to_ternary_expression(const SPIRType &result_type, uint32_t select, uint32_t true_value,
640 uint32_t false_value);
641
642 void emit_unary_op(uint32_t result_type, uint32_t result_id, uint32_t op0, const char *op);
643 bool expression_is_forwarded(uint32_t id) const;
644 bool expression_suppresses_usage_tracking(uint32_t id) const;
645 bool expression_read_implies_multiple_reads(uint32_t id) const;
646 SPIRExpression &emit_op(uint32_t result_type, uint32_t result_id, const std::string &rhs, bool forward_rhs,
647 bool suppress_usage_tracking = false);
648
649 void access_chain_internal_append_index(std::string &expr, uint32_t base, const SPIRType *type,
650 AccessChainFlags flags, bool &access_chain_is_arrayed, uint32_t index);
651
652 std::string access_chain_internal(uint32_t base, const uint32_t *indices, uint32_t count, AccessChainFlags flags,
653 AccessChainMeta *meta);
654
655 virtual void prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type,
656 spv::StorageClass storage, bool &is_packed);
657
658 std::string access_chain(uint32_t base, const uint32_t *indices, uint32_t count, const SPIRType &target_type,
659 AccessChainMeta *meta = nullptr, bool ptr_chain = false);
660
661 std::string flattened_access_chain(uint32_t base, const uint32_t *indices, uint32_t count,
662 const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
663 uint32_t array_stride, bool need_transpose);
664 std::string flattened_access_chain_struct(uint32_t base, const uint32_t *indices, uint32_t count,
665 const SPIRType &target_type, uint32_t offset);
666 std::string flattened_access_chain_matrix(uint32_t base, const uint32_t *indices, uint32_t count,
667 const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
668 bool need_transpose);
669 std::string flattened_access_chain_vector(uint32_t base, const uint32_t *indices, uint32_t count,
670 const SPIRType &target_type, uint32_t offset, uint32_t matrix_stride,
671 bool need_transpose);
672 std::pair<std::string, uint32_t> flattened_access_chain_offset(const SPIRType &basetype, const uint32_t *indices,
673 uint32_t count, uint32_t offset,
674 uint32_t word_stride, bool *need_transpose = nullptr,
675 uint32_t *matrix_stride = nullptr,
676 uint32_t *array_stride = nullptr,
677 bool ptr_chain = false);
678
679 const char *index_to_swizzle(uint32_t index);
680 std::string remap_swizzle(const SPIRType &result_type, uint32_t input_components, const std::string &expr);
681 std::string declare_temporary(uint32_t type, uint32_t id);
682 void emit_uninitialized_temporary(uint32_t type, uint32_t id);
683 SPIRExpression &emit_uninitialized_temporary_expression(uint32_t type, uint32_t id);
684 void append_global_func_args(const SPIRFunction &func, uint32_t index, SmallVector<std::string> &arglist);
685 std::string to_expression(uint32_t id, bool register_expression_read = true);
686 std::string to_composite_constructor_expression(uint32_t id, bool uses_buffer_offset);
687 std::string to_rerolled_array_expression(const std::string &expr, const SPIRType &type);
688 std::string to_enclosed_expression(uint32_t id, bool register_expression_read = true);
689 std::string to_unpacked_expression(uint32_t id, bool register_expression_read = true);
690 std::string to_unpacked_row_major_matrix_expression(uint32_t id);
691 std::string to_enclosed_unpacked_expression(uint32_t id, bool register_expression_read = true);
692 std::string to_dereferenced_expression(uint32_t id, bool register_expression_read = true);
693 std::string to_pointer_expression(uint32_t id, bool register_expression_read = true);
694 std::string to_enclosed_pointer_expression(uint32_t id, bool register_expression_read = true);
695 std::string to_extract_component_expression(uint32_t id, uint32_t index);
696 std::string enclose_expression(const std::string &expr);
697 std::string dereference_expression(const SPIRType &expression_type, const std::string &expr);
698 std::string address_of_expression(const std::string &expr);
699 void strip_enclosed_expression(std::string &expr);
700 std::string to_member_name(const SPIRType &type, uint32_t index);
701 virtual std::string to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain);
702 std::string to_multi_member_reference(const SPIRType &type, const SmallVector<uint32_t> &indices);
703 std::string type_to_glsl_constructor(const SPIRType &type);
704 std::string argument_decl(const SPIRFunction::Parameter &arg);
705 virtual std::string to_qualifiers_glsl(uint32_t id);
706 const char *to_precision_qualifiers_glsl(uint32_t id);
707 virtual const char *to_storage_qualifiers_glsl(const SPIRVariable &var);
708 const char *flags_to_qualifiers_glsl(const SPIRType &type, const Bitset &flags);
709 const char *format_to_glsl(spv::ImageFormat format);
710 virtual std::string layout_for_member(const SPIRType &type, uint32_t index);
711 virtual std::string to_interpolation_qualifiers(const Bitset &flags);
712 std::string layout_for_variable(const SPIRVariable &variable);
713 std::string to_combined_image_sampler(VariableID image_id, VariableID samp_id);
714 virtual bool skip_argument(uint32_t id) const;
715 virtual void emit_array_copy(const std::string &lhs, uint32_t rhs_id, spv::StorageClass lhs_storage,
716 spv::StorageClass rhs_storage);
717 virtual void emit_block_hints(const SPIRBlock &block);
718 virtual std::string to_initializer_expression(const SPIRVariable &var);
719 virtual std::string to_zero_initialized_expression(uint32_t type_id);
720 bool type_can_zero_initialize(const SPIRType &type) const;
721
722 bool buffer_is_packing_standard(const SPIRType &type, BufferPackingStandard packing,
723 uint32_t *failed_index = nullptr, uint32_t start_offset = 0,
724 uint32_t end_offset = ~(0u));
725 std::string buffer_to_packing_standard(const SPIRType &type, bool support_std430_without_scalar_layout);
726
727 uint32_t type_to_packed_base_size(const SPIRType &type, BufferPackingStandard packing);
728 uint32_t type_to_packed_alignment(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
729 uint32_t type_to_packed_array_stride(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
730 uint32_t type_to_packed_size(const SPIRType &type, const Bitset &flags, BufferPackingStandard packing);
731
732 std::string bitcast_glsl(const SPIRType &result_type, uint32_t arg);
733 virtual std::string bitcast_glsl_op(const SPIRType &result_type, const SPIRType &argument_type);
734
735 std::string bitcast_expression(SPIRType::BaseType target_type, uint32_t arg);
736 std::string bitcast_expression(const SPIRType &target_type, SPIRType::BaseType expr_type, const std::string &expr);
737
738 std::string build_composite_combiner(uint32_t result_type, const uint32_t *elems, uint32_t length);
739 bool remove_duplicate_swizzle(std::string &op);
740 bool remove_unity_swizzle(uint32_t base, std::string &op);
741
742 // Can modify flags to remote readonly/writeonly if image type
743 // and force recompile.
744 bool check_atomic_image(uint32_t id);
745
746 virtual void replace_illegal_names();
747 void replace_illegal_names(const std::unordered_set<std::string> &keywords);
748 virtual void emit_entry_point_declarations();
749
750 void replace_fragment_output(SPIRVariable &var);
751 void replace_fragment_outputs();
752 std::string legacy_tex_op(const std::string &op, const SPIRType &imgtype, uint32_t id);
753
754 uint32_t indent = 0;
755
756 std::unordered_set<uint32_t> emitted_functions;
757
758 // Ensure that we declare phi-variable copies even if the original declaration isn't deferred
759 std::unordered_set<uint32_t> flushed_phi_variables;
760
761 std::unordered_set<uint32_t> flattened_buffer_blocks;
762 std::unordered_map<uint32_t, bool> flattened_structs;
763
764 ShaderSubgroupSupportHelper shader_subgroup_supporter;
765
766 std::string load_flattened_struct(const std::string &basename, const SPIRType &type);
767 std::string to_flattened_struct_member(const std::string &basename, const SPIRType &type, uint32_t index);
768 void store_flattened_struct(uint32_t lhs_id, uint32_t value);
769 void store_flattened_struct(const std::string &basename, uint32_t rhs, const SPIRType &type,
770 const SmallVector<uint32_t> &indices);
771 std::string to_flattened_access_chain_expression(uint32_t id);
772
773 // Usage tracking. If a temporary is used more than once, use the temporary instead to
774 // avoid AST explosion when SPIRV is generated with pure SSA and doesn't write stuff to variables.
775 std::unordered_map<uint32_t, uint32_t> expression_usage_counts;
776 void track_expression_read(uint32_t id);
777
778 SmallVector<std::string> forced_extensions;
779 SmallVector<std::string> header_lines;
780
781 // Used when expressions emit extra opcodes with their own unique IDs,
782 // and we need to reuse the IDs across recompilation loops.
783 // Currently used by NMin/Max/Clamp implementations.
784 std::unordered_map<uint32_t, uint32_t> extra_sub_expressions;
785
786 SmallVector<TypeID> workaround_ubo_load_overload_types;
787 void request_workaround_wrapper_overload(TypeID id);
788 void rewrite_load_for_wrapped_row_major(std::string &expr, TypeID loaded_type, ID ptr);
789
790 uint32_t statement_count = 0;
791
792 inline bool is_legacy() const
793 {
794 return (options.es && options.version < 300) || (!options.es && options.version < 130);
795 }
796
797 inline bool is_legacy_es() const
798 {
799 return options.es && options.version < 300;
800 }
801
802 inline bool is_legacy_desktop() const
803 {
804 return !options.es && options.version < 130;
805 }
806
807 bool requires_transpose_2x2 = false;
808 bool requires_transpose_3x3 = false;
809 bool requires_transpose_4x4 = false;
810
811 bool args_will_forward(uint32_t id, const uint32_t *args, uint32_t num_args, bool pure);
812 void register_call_out_argument(uint32_t id);
813 void register_impure_function_call();
814 void register_control_dependent_expression(uint32_t expr);
815
816 // GL_EXT_shader_pixel_local_storage support.
817 std::vector<PlsRemap> pls_inputs;
818 std::vector<PlsRemap> pls_outputs;
819 std::string pls_decl(const PlsRemap &variable);
820 const char *to_pls_qualifiers_glsl(const SPIRVariable &variable);
821 void emit_pls();
822 void remap_pls_variables();
823
824 // GL_EXT_shader_framebuffer_fetch support.
825 std::vector<std::pair<uint32_t, uint32_t>> subpass_to_framebuffer_fetch_attachment;
826 std::unordered_set<uint32_t> inout_color_attachments;
827 bool subpass_input_is_framebuffer_fetch(uint32_t id) const;
828 void emit_inout_fragment_outputs_copy_to_subpass_inputs();
829 const SPIRVariable *find_subpass_input_by_attachment_index(uint32_t index) const;
830 const SPIRVariable *find_color_output_by_location(uint32_t location) const;
831
832 // A variant which takes two sets of name. The secondary is only used to verify there are no collisions,
833 // but the set is not updated when we have found a new name.
834 // Used primarily when adding block interface names.
835 void add_variable(std::unordered_set<std::string> &variables_primary,
836 const std::unordered_set<std::string> &variables_secondary, std::string &name);
837
838 void check_function_call_constraints(const uint32_t *args, uint32_t length);
839 void handle_invalid_expression(uint32_t id);
840 void find_static_extensions();
841
842 std::string emit_for_loop_initializers(const SPIRBlock &block);
843 void emit_while_loop_initializers(const SPIRBlock &block);
844 bool for_loop_initializers_are_same_type(const SPIRBlock &block);
845 bool optimize_read_modify_write(const SPIRType &type, const std::string &lhs, const std::string &rhs);
846 void fixup_image_load_store_access();
847
848 bool type_is_empty(const SPIRType &type);
849
850 virtual void declare_undefined_values();
851
852 bool can_use_io_location(spv::StorageClass storage, bool block);
853 const Instruction *get_next_instruction_in_block(const Instruction &instr);
854 static uint32_t mask_relevant_memory_semantics(uint32_t semantics);
855
856 std::string convert_half_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
857 std::string convert_float_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
858 std::string convert_double_to_string(const SPIRConstant &value, uint32_t col, uint32_t row);
859
860 std::string convert_separate_image_to_expression(uint32_t id);
861
862 // Builtins in GLSL are always specific signedness, but the SPIR-V can declare them
863 // as either unsigned or signed.
864 // Sometimes we will need to automatically perform casts on load and store to make this work.
865 virtual void cast_to_builtin_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type);
866 virtual void cast_from_builtin_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type);
867 void unroll_array_from_complex_load(uint32_t target_id, uint32_t source_id, std::string &expr);
868 void convert_non_uniform_expression(const SPIRType &type, std::string &expr);
869
870 void handle_store_to_invariant_variable(uint32_t store_id, uint32_t value_id);
871 void disallow_forwarding_in_expression_chain(const SPIRExpression &expr);
872
873 bool expression_is_constant_null(uint32_t id) const;
874 bool expression_is_non_value_type_array(uint32_t ptr);
875 virtual void emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression);
876
877 uint32_t get_integer_width_for_instruction(const Instruction &instr) const;
878 uint32_t get_integer_width_for_glsl_instruction(GLSLstd450 op, const uint32_t *arguments, uint32_t length) const;
879
880 bool variable_is_lut(const SPIRVariable &var) const;
881
882 char current_locale_radix_character = '.';
883
884 void fixup_type_alias();
885 void reorder_type_alias();
886
887 void propagate_nonuniform_qualifier(uint32_t id);
888
889 static const char *vector_swizzle(int vecsize, int index);
890
891 private:
892 void init();
893 };
894 } // namespace SPIRV_CROSS_NAMESPACE
895
896 #endif