Debian Codegraph @

thirdparty/spirv-cross/spirv_msl.hpp

raw symbols SCIP
1 /*
2 * Copyright 2016-2021 The Brenwill Workshop Ltd.
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 #ifndef SPIRV_CROSS_MSL_HPP
25 #define SPIRV_CROSS_MSL_HPP
26
27 #include "spirv_glsl.hpp"
28 #include <map>
29 #include <set>
30 #include <stddef.h>
31 #include <unordered_map>
32 #include <unordered_set>
33
34 namespace SPIRV_CROSS_NAMESPACE
35 {
36
37 // Indicates the format of a shader interface variable. Currently limited to specifying
38 // if the input is an 8-bit unsigned integer, 16-bit unsigned integer, or
39 // some other format.
40 enum MSLShaderVariableFormat
41 {
42 MSL_SHADER_VARIABLE_FORMAT_OTHER = 0,
43 MSL_SHADER_VARIABLE_FORMAT_UINT8 = 1,
44 MSL_SHADER_VARIABLE_FORMAT_UINT16 = 2,
45 MSL_SHADER_VARIABLE_FORMAT_ANY16 = 3,
46 MSL_SHADER_VARIABLE_FORMAT_ANY32 = 4,
47
48 // Deprecated aliases.
49 MSL_VERTEX_FORMAT_OTHER = MSL_SHADER_VARIABLE_FORMAT_OTHER,
50 MSL_VERTEX_FORMAT_UINT8 = MSL_SHADER_VARIABLE_FORMAT_UINT8,
51 MSL_VERTEX_FORMAT_UINT16 = MSL_SHADER_VARIABLE_FORMAT_UINT16,
52 MSL_SHADER_INPUT_FORMAT_OTHER = MSL_SHADER_VARIABLE_FORMAT_OTHER,
53 MSL_SHADER_INPUT_FORMAT_UINT8 = MSL_SHADER_VARIABLE_FORMAT_UINT8,
54 MSL_SHADER_INPUT_FORMAT_UINT16 = MSL_SHADER_VARIABLE_FORMAT_UINT16,
55 MSL_SHADER_INPUT_FORMAT_ANY16 = MSL_SHADER_VARIABLE_FORMAT_ANY16,
56 MSL_SHADER_INPUT_FORMAT_ANY32 = MSL_SHADER_VARIABLE_FORMAT_ANY32,
57
58 MSL_SHADER_VARIABLE_FORMAT_INT_MAX = 0x7fffffff
59 };
60
61 // Indicates the rate at which a variable changes value, one of: per-vertex,
62 // per-primitive, or per-patch.
63 enum MSLShaderVariableRate
64 {
65 MSL_SHADER_VARIABLE_RATE_PER_VERTEX = 0,
66 MSL_SHADER_VARIABLE_RATE_PER_PRIMITIVE = 1,
67 MSL_SHADER_VARIABLE_RATE_PER_PATCH = 2,
68
69 MSL_SHADER_VARIABLE_RATE_INT_MAX = 0x7fffffff,
70 };
71
72 // Defines MSL characteristics of a shader interface variable at a particular location.
73 // After compilation, it is possible to query whether or not this location was used.
74 // If vecsize is nonzero, it must be greater than or equal to the vecsize declared in the shader,
75 // or behavior is undefined.
76 struct MSLShaderInterfaceVariable
77 {
78 uint32_t location = 0;
79 uint32_t component = 0;
80 MSLShaderVariableFormat format = MSL_SHADER_VARIABLE_FORMAT_OTHER;
81 spv::BuiltIn builtin = spv::BuiltInMax;
82 uint32_t vecsize = 0;
83 MSLShaderVariableRate rate = MSL_SHADER_VARIABLE_RATE_PER_VERTEX;
84 };
85
86 // Matches the binding index of a MSL resource for a binding within a descriptor set.
87 // Taken together, the stage, desc_set and binding combine to form a reference to a resource
88 // descriptor used in a particular shading stage. The count field indicates the number of
89 // resources consumed by this binding, if the binding represents an array of resources.
90 // If the resource array is a run-time-sized array, which are legal in GLSL or SPIR-V, this value
91 // will be used to declare the array size in MSL, which does not support run-time-sized arrays.
92 // If pad_argument_buffer_resources is enabled, the base_type and count values are used to
93 // specify the base type and array size of the resource in the argument buffer, if that resource
94 // is not defined and used by the shader. With pad_argument_buffer_resources enabled, this
95 // information will be used to pad the argument buffer structure, in order to align that
96 // structure consistently for all uses, across all shaders, of the descriptor set represented
97 // by the arugment buffer. If pad_argument_buffer_resources is disabled, base_type does not
98 // need to be populated, and if the resource is also not a run-time sized array, the count
99 // field does not need to be populated.
100 // If using MSL 2.0 argument buffers, the descriptor set is not marked as a discrete descriptor set,
101 // and (for iOS only) the resource is not a storage image (sampled != 2), the binding reference we
102 // remap to will become an [[id(N)]] attribute within the "descriptor set" argument buffer structure.
103 // For resources which are bound in the "classic" MSL 1.0 way or discrete descriptors, the remap will
104 // become a [[buffer(N)]], [[texture(N)]] or [[sampler(N)]] depending on the resource types used.
105 struct MSLResourceBinding
106 {
107 spv::ExecutionModel stage = spv::ExecutionModelMax;
108 SPIRType::BaseType basetype = SPIRType::Unknown;
109 uint32_t desc_set = 0;
110 uint32_t binding = 0;
111 uint32_t count = 0;
112 uint32_t msl_buffer = 0;
113 uint32_t msl_texture = 0;
114 uint32_t msl_sampler = 0;
115 };
116
117 enum MSLSamplerCoord
118 {
119 MSL_SAMPLER_COORD_NORMALIZED = 0,
120 MSL_SAMPLER_COORD_PIXEL = 1,
121 MSL_SAMPLER_INT_MAX = 0x7fffffff
122 };
123
124 enum MSLSamplerFilter
125 {
126 MSL_SAMPLER_FILTER_NEAREST = 0,
127 MSL_SAMPLER_FILTER_LINEAR = 1,
128 MSL_SAMPLER_FILTER_INT_MAX = 0x7fffffff
129 };
130
131 enum MSLSamplerMipFilter
132 {
133 MSL_SAMPLER_MIP_FILTER_NONE = 0,
134 MSL_SAMPLER_MIP_FILTER_NEAREST = 1,
135 MSL_SAMPLER_MIP_FILTER_LINEAR = 2,
136 MSL_SAMPLER_MIP_FILTER_INT_MAX = 0x7fffffff
137 };
138
139 enum MSLSamplerAddress
140 {
141 MSL_SAMPLER_ADDRESS_CLAMP_TO_ZERO = 0,
142 MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE = 1,
143 MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER = 2,
144 MSL_SAMPLER_ADDRESS_REPEAT = 3,
145 MSL_SAMPLER_ADDRESS_MIRRORED_REPEAT = 4,
146 MSL_SAMPLER_ADDRESS_INT_MAX = 0x7fffffff
147 };
148
149 enum MSLSamplerCompareFunc
150 {
151 MSL_SAMPLER_COMPARE_FUNC_NEVER = 0,
152 MSL_SAMPLER_COMPARE_FUNC_LESS = 1,
153 MSL_SAMPLER_COMPARE_FUNC_LESS_EQUAL = 2,
154 MSL_SAMPLER_COMPARE_FUNC_GREATER = 3,
155 MSL_SAMPLER_COMPARE_FUNC_GREATER_EQUAL = 4,
156 MSL_SAMPLER_COMPARE_FUNC_EQUAL = 5,
157 MSL_SAMPLER_COMPARE_FUNC_NOT_EQUAL = 6,
158 MSL_SAMPLER_COMPARE_FUNC_ALWAYS = 7,
159 MSL_SAMPLER_COMPARE_FUNC_INT_MAX = 0x7fffffff
160 };
161
162 enum MSLSamplerBorderColor
163 {
164 MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK = 0,
165 MSL_SAMPLER_BORDER_COLOR_OPAQUE_BLACK = 1,
166 MSL_SAMPLER_BORDER_COLOR_OPAQUE_WHITE = 2,
167 MSL_SAMPLER_BORDER_COLOR_INT_MAX = 0x7fffffff
168 };
169
170 enum MSLFormatResolution
171 {
172 MSL_FORMAT_RESOLUTION_444 = 0,
173 MSL_FORMAT_RESOLUTION_422,
174 MSL_FORMAT_RESOLUTION_420,
175 MSL_FORMAT_RESOLUTION_INT_MAX = 0x7fffffff
176 };
177
178 enum MSLChromaLocation
179 {
180 MSL_CHROMA_LOCATION_COSITED_EVEN = 0,
181 MSL_CHROMA_LOCATION_MIDPOINT,
182 MSL_CHROMA_LOCATION_INT_MAX = 0x7fffffff
183 };
184
185 enum MSLComponentSwizzle
186 {
187 MSL_COMPONENT_SWIZZLE_IDENTITY = 0,
188 MSL_COMPONENT_SWIZZLE_ZERO,
189 MSL_COMPONENT_SWIZZLE_ONE,
190 MSL_COMPONENT_SWIZZLE_R,
191 MSL_COMPONENT_SWIZZLE_G,
192 MSL_COMPONENT_SWIZZLE_B,
193 MSL_COMPONENT_SWIZZLE_A,
194 MSL_COMPONENT_SWIZZLE_INT_MAX = 0x7fffffff
195 };
196
197 enum MSLSamplerYCbCrModelConversion
198 {
199 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY = 0,
200 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY,
201 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709,
202 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601,
203 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020,
204 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_INT_MAX = 0x7fffffff
205 };
206
207 enum MSLSamplerYCbCrRange
208 {
209 MSL_SAMPLER_YCBCR_RANGE_ITU_FULL = 0,
210 MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW,
211 MSL_SAMPLER_YCBCR_RANGE_INT_MAX = 0x7fffffff
212 };
213
214 struct MSLConstexprSampler
215 {
216 MSLSamplerCoord coord = MSL_SAMPLER_COORD_NORMALIZED;
217 MSLSamplerFilter min_filter = MSL_SAMPLER_FILTER_NEAREST;
218 MSLSamplerFilter mag_filter = MSL_SAMPLER_FILTER_NEAREST;
219 MSLSamplerMipFilter mip_filter = MSL_SAMPLER_MIP_FILTER_NONE;
220 MSLSamplerAddress s_address = MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE;
221 MSLSamplerAddress t_address = MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE;
222 MSLSamplerAddress r_address = MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE;
223 MSLSamplerCompareFunc compare_func = MSL_SAMPLER_COMPARE_FUNC_NEVER;
224 MSLSamplerBorderColor border_color = MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK;
225 float lod_clamp_min = 0.0f;
226 float lod_clamp_max = 1000.0f;
227 int max_anisotropy = 1;
228
229 // Sampler Y'CbCr conversion parameters
230 uint32_t planes = 0;
231 MSLFormatResolution resolution = MSL_FORMAT_RESOLUTION_444;
232 MSLSamplerFilter chroma_filter = MSL_SAMPLER_FILTER_NEAREST;
233 MSLChromaLocation x_chroma_offset = MSL_CHROMA_LOCATION_COSITED_EVEN;
234 MSLChromaLocation y_chroma_offset = MSL_CHROMA_LOCATION_COSITED_EVEN;
235 MSLComponentSwizzle swizzle[4]; // IDENTITY, IDENTITY, IDENTITY, IDENTITY
236 MSLSamplerYCbCrModelConversion ycbcr_model = MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;
237 MSLSamplerYCbCrRange ycbcr_range = MSL_SAMPLER_YCBCR_RANGE_ITU_FULL;
238 uint32_t bpc = 8;
239
240 bool compare_enable = false;
241 bool lod_clamp_enable = false;
242 bool anisotropy_enable = false;
243 bool ycbcr_conversion_enable = false;
244
245 MSLConstexprSampler()
246 {
247 for (uint32_t i = 0; i < 4; i++)
248 swizzle[i] = MSL_COMPONENT_SWIZZLE_IDENTITY;
249 }
250 bool swizzle_is_identity() const
251 {
252 return (swizzle[0] == MSL_COMPONENT_SWIZZLE_IDENTITY && swizzle[1] == MSL_COMPONENT_SWIZZLE_IDENTITY &&
253 swizzle[2] == MSL_COMPONENT_SWIZZLE_IDENTITY && swizzle[3] == MSL_COMPONENT_SWIZZLE_IDENTITY);
254 }
255 bool swizzle_has_one_or_zero() const
256 {
257 return (swizzle[0] == MSL_COMPONENT_SWIZZLE_ZERO || swizzle[0] == MSL_COMPONENT_SWIZZLE_ONE ||
258 swizzle[1] == MSL_COMPONENT_SWIZZLE_ZERO || swizzle[1] == MSL_COMPONENT_SWIZZLE_ONE ||
259 swizzle[2] == MSL_COMPONENT_SWIZZLE_ZERO || swizzle[2] == MSL_COMPONENT_SWIZZLE_ONE ||
260 swizzle[3] == MSL_COMPONENT_SWIZZLE_ZERO || swizzle[3] == MSL_COMPONENT_SWIZZLE_ONE);
261 }
262 };
263
264 // Special constant used in a MSLResourceBinding desc_set
265 // element to indicate the bindings for the push constants.
266 // Kinda deprecated. Just use ResourceBindingPushConstant{DescriptorSet,Binding} directly.
267 static const uint32_t kPushConstDescSet = ResourceBindingPushConstantDescriptorSet;
268
269 // Special constant used in a MSLResourceBinding binding
270 // element to indicate the bindings for the push constants.
271 // Kinda deprecated. Just use ResourceBindingPushConstant{DescriptorSet,Binding} directly.
272 static const uint32_t kPushConstBinding = ResourceBindingPushConstantBinding;
273
274 // Special constant used in a MSLResourceBinding binding
275 // element to indicate the buffer binding for swizzle buffers.
276 static const uint32_t kSwizzleBufferBinding = ~(1u);
277
278 // Special constant used in a MSLResourceBinding binding
279 // element to indicate the buffer binding for buffer size buffers to support OpArrayLength.
280 static const uint32_t kBufferSizeBufferBinding = ~(2u);
281
282 // Special constant used in a MSLResourceBinding binding
283 // element to indicate the buffer binding used for the argument buffer itself.
284 // This buffer binding should be kept as small as possible as all automatic bindings for buffers
285 // will start at max(kArgumentBufferBinding) + 1.
286 static const uint32_t kArgumentBufferBinding = ~(3u);
287
288 static const uint32_t kMaxArgumentBuffers = 8;
289
290 // Decompiles SPIR-V to Metal Shading Language
291 class CompilerMSL : public CompilerGLSL
292 {
293 public:
294 // Options for compiling to Metal Shading Language
295 struct Options
296 {
297 typedef enum
298 {
299 iOS = 0,
300 macOS = 1
301 } Platform;
302
303 Platform platform = macOS;
304 uint32_t msl_version = make_msl_version(1, 2);
305 uint32_t texel_buffer_texture_width = 4096; // Width of 2D Metal textures used as 1D texel buffers
306 uint32_t r32ui_linear_texture_alignment = 4;
307 uint32_t r32ui_alignment_constant_id = 65535;
308 uint32_t swizzle_buffer_index = 30;
309 uint32_t indirect_params_buffer_index = 29;
310 uint32_t shader_output_buffer_index = 28;
311 uint32_t shader_patch_output_buffer_index = 27;
312 uint32_t shader_tess_factor_buffer_index = 26;
313 uint32_t buffer_size_buffer_index = 25;
314 uint32_t view_mask_buffer_index = 24;
315 uint32_t dynamic_offsets_buffer_index = 23;
316 uint32_t shader_input_buffer_index = 22;
317 uint32_t shader_index_buffer_index = 21;
318 uint32_t shader_patch_input_buffer_index = 20;
319 uint32_t shader_input_wg_index = 0;
320 uint32_t device_index = 0;
321 uint32_t enable_frag_output_mask = 0xffffffff;
322 // Metal doesn't allow setting a fixed sample mask directly in the pipeline.
323 // We can evade this restriction by ANDing the internal sample_mask output
324 // of the shader with the additional fixed sample mask.
325 uint32_t additional_fixed_sample_mask = 0xffffffff;
326 bool enable_point_size_builtin = true;
327 bool enable_point_size_default = false;
328 float default_point_size = 1.0f;
329 bool enable_frag_depth_builtin = true;
330 bool enable_frag_stencil_ref_builtin = true;
331 bool disable_rasterization = false;
332 bool capture_output_to_buffer = false;
333 bool swizzle_texture_samples = false;
334 bool tess_domain_origin_lower_left = false;
335 bool multiview = false;
336 bool multiview_layered_rendering = true;
337 bool view_index_from_device_index = false;
338 bool dispatch_base = false;
339 bool texture_1D_as_2D = false;
340
341 // Enable use of Metal argument buffers.
342 // MSL 2.0 must also be enabled.
343 bool argument_buffers = false;
344
345 // Defines Metal argument buffer tier levels.
346 // Uses same values as Metal MTLArgumentBuffersTier enumeration.
347 enum class ArgumentBuffersTier
348 {
349 Tier1 = 0,
350 Tier2 = 1,
351 };
352
353 // When using Metal argument buffers, indicates the Metal argument buffer tier level supported by the Metal platform.
354 // Ignored when Options::argument_buffers is disabled.
355 // - Tier1 supports writable images on macOS, but not on iOS.
356 // - Tier2 supports writable images on macOS and iOS, and higher resource count limits.
357 // Tier capabilities based on recommendations from Apple engineering.
358 ArgumentBuffersTier argument_buffers_tier = ArgumentBuffersTier::Tier1;
359
360 // Enables specifick argument buffer format with extra information to track SSBO-length
361 bool runtime_array_rich_descriptor = false;
362
363 // Ensures vertex and instance indices start at zero. This reflects the behavior of HLSL with SV_VertexID and SV_InstanceID.
364 bool enable_base_index_zero = false;
365
366 // Fragment output in MSL must have at least as many components as the render pass.
367 // Add support to explicit pad out components.
368 bool pad_fragment_output_components = false;
369
370 // Specifies whether the iOS target version supports the [[base_vertex]] and [[base_instance]] attributes.
371 bool ios_support_base_vertex_instance = false;
372
373 // Use Metal's native frame-buffer fetch API for subpass inputs.
374 bool use_framebuffer_fetch_subpasses = false;
375
376 // Enables use of "fma" intrinsic for invariant float math
377 bool invariant_float_math = false;
378
379 // Emulate texturecube_array with texture2d_array for iOS where this type is not available
380 bool emulate_cube_array = false;
381
382 // Allow user to enable decoration binding
383 bool enable_decoration_binding = false;
384
385 // Requires MSL 2.1, use the native support for texel buffers.
386 bool texture_buffer_native = false;
387
388 // Forces all resources which are part of an argument buffer to be considered active.
389 // This ensures ABI compatibility between shaders where some resources might be unused,
390 // and would otherwise declare a different IAB.
391 bool force_active_argument_buffer_resources = false;
392
393 // Aligns each resource in an argument buffer to its assigned index value, id(N),
394 // by adding synthetic padding members in the argument buffer struct for any resources
395 // in the argument buffer that are not defined and used by the shader. This allows
396 // the shader to index into the correct argument in a descriptor set argument buffer
397 // that is shared across shaders, where not all resources in the argument buffer are
398 // defined in each shader. For this to work, an MSLResourceBinding must be provided for
399 // all descriptors in any descriptor set held in an argument buffer in the shader, and
400 // that MSLResourceBinding must have the basetype and count members populated correctly.
401 // The implementation here assumes any inline blocks in the argument buffer is provided
402 // in a Metal buffer, and doesn't take into consideration inline blocks that are
403 // optionally embedded directly into the argument buffer via add_inline_uniform_block().
404 bool pad_argument_buffer_resources = false;
405
406 // Forces the use of plain arrays, which works around certain driver bugs on certain versions
407 // of Intel Macbooks. See https://github.com/KhronosGroup/SPIRV-Cross/issues/1210.
408 // May reduce performance in scenarios where arrays are copied around as value-types.
409 bool force_native_arrays = false;
410
411 // If a shader writes clip distance, also emit user varyings which
412 // can be read in subsequent stages.
413 bool enable_clip_distance_user_varying = true;
414
415 // In a tessellation control shader, assume that more than one patch can be processed in a
416 // single workgroup. This requires changes to the way the InvocationId and PrimitiveId
417 // builtins are processed, but should result in more efficient usage of the GPU.
418 bool multi_patch_workgroup = false;
419
420 // Use storage buffers instead of vertex-style attributes for tessellation evaluation
421 // input. This may require conversion of inputs in the generated post-tessellation
422 // vertex shader, but allows the use of nested arrays.
423 bool raw_buffer_tese_input = false;
424
425 // If set, a vertex shader will be compiled as part of a tessellation pipeline.
426 // It will be translated as a compute kernel, so it can use the global invocation ID
427 // to index the output buffer.
428 bool vertex_for_tessellation = false;
429
430 // Assume that SubpassData images have multiple layers. Layered input attachments
431 // are addressed relative to the Layer output from the vertex pipeline. This option
432 // has no effect with multiview, since all input attachments are assumed to be layered
433 // and will be addressed using the current ViewIndex.
434 bool arrayed_subpass_input = false;
435
436 // Whether to use SIMD-group or quadgroup functions to implement group non-uniform
437 // operations. Some GPUs on iOS do not support the SIMD-group functions, only the
438 // quadgroup functions.
439 bool ios_use_simdgroup_functions = false;
440
441 // If set, the subgroup size will be assumed to be one, and subgroup-related
442 // builtins and operations will be emitted accordingly. This mode is intended to
443 // be used by MoltenVK on hardware/software configurations which do not provide
444 // sufficient support for subgroups.
445 bool emulate_subgroups = false;
446
447 // If nonzero, a fixed subgroup size to assume. Metal, similarly to VK_EXT_subgroup_size_control,
448 // allows the SIMD-group size (aka thread execution width) to vary depending on
449 // register usage and requirements. In certain circumstances--for example, a pipeline
450 // in MoltenVK without VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT--
451 // this is undesirable. This fixes the value of the SubgroupSize builtin, instead of
452 // mapping it to the Metal builtin [[thread_execution_width]]. If the thread
453 // execution width is reduced, the extra invocations will appear to be inactive.
454 // If zero, the SubgroupSize will be allowed to vary, and the builtin will be mapped
455 // to the Metal [[thread_execution_width]] builtin.
456 uint32_t fixed_subgroup_size = 0;
457
458 enum class IndexType
459 {
460 None = 0,
461 UInt16 = 1,
462 UInt32 = 2
463 };
464
465 // The type of index in the index buffer, if present. For a compute shader, Metal
466 // requires specifying the indexing at pipeline creation, rather than at draw time
467 // as with graphics pipelines. This means we must create three different pipelines,
468 // for no indexing, 16-bit indices, and 32-bit indices. Each requires different
469 // handling for the gl_VertexIndex builtin. We may as well, then, create three
470 // different shaders for these three scenarios.
471 IndexType vertex_index_type = IndexType::None;
472
473 // If set, a dummy [[sample_id]] input is added to a fragment shader if none is present.
474 // This will force the shader to run at sample rate, assuming Metal does not optimize
475 // the extra threads away.
476 bool force_sample_rate_shading = false;
477
478 // If set, gl_HelperInvocation will be set manually whenever a fragment is discarded.
479 // Some Metal devices have a bug where simd_is_helper_thread() does not return true
480 // after a fragment has been discarded. This is a workaround that is only expected to be needed
481 // until the bug is fixed in Metal; it is provided as an option to allow disabling it when that occurs.
482 bool manual_helper_invocation_updates = true;
483
484 // If set, extra checks will be emitted in fragment shaders to prevent writes
485 // from discarded fragments. Some Metal devices have a bug where writes to storage resources
486 // from discarded fragment threads continue to occur, despite the fragment being
487 // discarded. This is a workaround that is only expected to be needed until the
488 // bug is fixed in Metal; it is provided as an option so it can be enabled
489 // only when the bug is present.
490 bool check_discarded_frag_stores = false;
491
492 // If set, Lod operands to OpImageSample*DrefExplicitLod for 1D and 2D array images
493 // will be implemented using a gradient instead of passing the level operand directly.
494 // Some Metal devices have a bug where the level() argument to depth2d_array<T>::sample_compare()
495 // in a fragment shader is biased by some unknown amount, possibly dependent on the
496 // partial derivatives of the texture coordinates. This is a workaround that is only
497 // expected to be needed until the bug is fixed in Metal; it is provided as an option
498 // so it can be enabled only when the bug is present.
499 bool sample_dref_lod_array_as_grad = false;
500
501 // MSL doesn't guarantee coherence between writes and subsequent reads of read_write textures.
502 // This inserts fences before each read of a read_write texture to ensure coherency.
503 // If you're sure you never rely on this, you can set this to false for a possible performance improvement.
504 // Note: Only Apple's GPU compiler takes advantage of the lack of coherency, so make sure to test on Apple GPUs if you disable this.
505 bool readwrite_texture_fences = true;
506
507 // Metal 3.1 introduced a Metal regression bug which causes infinite recursion during
508 // Metal's analysis of an entry point input structure that is itself recursive. Enabling
509 // this option will replace the recursive input declaration with a alternate variable of
510 // type void*, and then cast to the correct type at the top of the entry point function.
511 // The bug has been reported to Apple, and will hopefully be fixed in future releases.
512 bool replace_recursive_inputs = false;
513
514 // If set, manual fixups of gradient vectors for cube texture lookups will be performed.
515 // All released Apple Silicon GPUs to date behave incorrectly when sampling a cube texture
516 // with explicit gradients. They will ignore one of the three partial derivatives based
517 // on the selected major axis, and expect the remaining derivatives to be partially
518 // transformed.
519 bool agx_manual_cube_grad_fixup = false;
520
521 // Metal will discard fragments with side effects under certain circumstances prematurely.
522 // Example: CTS test dEQP-VK.fragment_operations.early_fragment.discard_no_early_fragment_tests_depth
523 // Test will render a full screen quad with varying depth [0,1] for each fragment.
524 // Each fragment will do an operation with side effects, modify the depth value and
525 // discard the fragment. The test expects the fragment to be run due to:
526 // https://registry.khronos.org/vulkan/specs/1.0-extensions/html/vkspec.html#fragops-shader-depthreplacement
527 // which states that the fragment shader must be run due to replacing the depth in shader.
528 // However, Metal may prematurely discards fragments without executing them
529 // (I believe this to be due to a greedy optimization on their end) making the test fail.
530 // This option enforces fragment execution for such cases where the fragment has operations
531 // with side effects. Provided as an option hoping Metal will fix this issue in the future.
532 bool force_fragment_with_side_effects_execution = false;
533
534 // If set, adds a depth pass through statement to circumvent the following issue:
535 // When the same depth/stencil is used as input and depth/stencil attachment, we need to
536 // force Metal to perform the depth/stencil write after fragment execution. Otherwise,
537 // Metal will write to the depth attachment before fragment execution. This happens
538 // if the fragment does not modify the depth value.
539 bool input_attachment_is_ds_attachment = false;
540
541 // If BuiltInPosition is not written, automatically disable rasterization.
542 // The result can be queried with get_is_rasterization_disabled.
543 bool auto_disable_rasterization = false;
544
545 // Use Fast Math pragmas in MSL code, based on SPIR-V float controls and FP ExecutionModes.
546 // Requires MSL 3.2 or above, and has no effect with earlier MSL versions.
547 bool use_fast_math_pragmas = false;
548
549 bool is_ios() const
550 {
551 return platform == iOS;
552 }
553
554 bool is_macos() const
555 {
556 return platform == macOS;
557 }
558
559 bool use_quadgroup_operation() const
560 {
561 return is_ios() && !ios_use_simdgroup_functions;
562 }
563
564 void set_msl_version(uint32_t major, uint32_t minor = 0, uint32_t patch = 0)
565 {
566 msl_version = make_msl_version(major, minor, patch);
567 }
568
569 bool supports_msl_version(uint32_t major, uint32_t minor = 0, uint32_t patch = 0) const
570 {
571 return msl_version >= make_msl_version(major, minor, patch);
572 }
573
574 static uint32_t make_msl_version(uint32_t major, uint32_t minor = 0, uint32_t patch = 0)
575 {
576 return (major * 10000) + (minor * 100) + patch;
577 }
578 };
579
580 const Options &get_msl_options() const
581 {
582 return msl_options;
583 }
584
585 void set_msl_options(const Options &opts)
586 {
587 msl_options = opts;
588 }
589
590 // Provide feedback to calling API to allow runtime to disable pipeline
591 // rasterization if vertex shader requires rasterization to be disabled.
592 bool get_is_rasterization_disabled() const
593 {
594 return is_rasterization_disabled && (get_entry_point().model == spv::ExecutionModelVertex ||
595 get_entry_point().model == spv::ExecutionModelTessellationControl ||
596 get_entry_point().model == spv::ExecutionModelTessellationEvaluation);
597 }
598
599 // Provide feedback to calling API to allow it to pass an auxiliary
600 // swizzle buffer if the shader needs it.
601 bool needs_swizzle_buffer() const
602 {
603 return used_swizzle_buffer;
604 }
605
606 // Provide feedback to calling API to allow it to pass a buffer
607 // containing STORAGE_BUFFER buffer sizes to support OpArrayLength.
608 bool needs_buffer_size_buffer() const
609 {
610 return !buffers_requiring_array_length.empty();
611 }
612
613 bool buffer_requires_array_length(VariableID id) const
614 {
615 return buffers_requiring_array_length.count(id) != 0;
616 }
617
618 // Provide feedback to calling API to allow it to pass a buffer
619 // containing the view mask for the current multiview subpass.
620 bool needs_view_mask_buffer() const
621 {
622 return msl_options.multiview && !msl_options.view_index_from_device_index;
623 }
624
625 // Provide feedback to calling API to allow it to pass a buffer
626 // containing the dispatch base workgroup ID.
627 bool needs_dispatch_base_buffer() const
628 {
629 return msl_options.dispatch_base && !msl_options.supports_msl_version(1, 2);
630 }
631
632 // Provide feedback to calling API to allow it to pass an output
633 // buffer if the shader needs it.
634 bool needs_output_buffer() const
635 {
636 return capture_output_to_buffer && stage_out_var_id != ID(0);
637 }
638
639 // Provide feedback to calling API to allow it to pass a patch output
640 // buffer if the shader needs it.
641 bool needs_patch_output_buffer() const
642 {
643 return capture_output_to_buffer && patch_stage_out_var_id != ID(0);
644 }
645
646 // Provide feedback to calling API to allow it to pass an input threadgroup
647 // buffer if the shader needs it.
648 bool needs_input_threadgroup_mem() const
649 {
650 return capture_output_to_buffer && stage_in_var_id != ID(0);
651 }
652
653 explicit CompilerMSL(std::vector<uint32_t> spirv);
654 CompilerMSL(const uint32_t *ir, size_t word_count);
655 explicit CompilerMSL(const ParsedIR &ir);
656 explicit CompilerMSL(ParsedIR &&ir);
657
658 // input is a shader interface variable description used to fix up shader input variables.
659 // If shader inputs are provided, is_msl_shader_input_used() will return true after
660 // calling ::compile() if the location were used by the MSL code.
661 void add_msl_shader_input(const MSLShaderInterfaceVariable &input);
662
663 // output is a shader interface variable description used to fix up shader output variables.
664 // If shader outputs are provided, is_msl_shader_output_used() will return true after
665 // calling ::compile() if the location were used by the MSL code.
666 void add_msl_shader_output(const MSLShaderInterfaceVariable &output);
667
668 // resource is a resource binding to indicate the MSL buffer,
669 // texture or sampler index to use for a particular SPIR-V description set
670 // and binding. If resource bindings are provided,
671 // is_msl_resource_binding_used() will return true after calling ::compile() if
672 // the set/binding combination was used by the MSL code.
673 void add_msl_resource_binding(const MSLResourceBinding &resource);
674
675 // desc_set and binding are the SPIR-V descriptor set and binding of a buffer resource
676 // in this shader. index is the index within the dynamic offset buffer to use. This
677 // function marks that resource as using a dynamic offset (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC
678 // or VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC). This function only has any effect if argument buffers
679 // are enabled. If so, the buffer will have its address adjusted at the beginning of the shader with
680 // an offset taken from the dynamic offset buffer.
681 void add_dynamic_buffer(uint32_t desc_set, uint32_t binding, uint32_t index);
682
683 // desc_set and binding are the SPIR-V descriptor set and binding of a buffer resource
684 // in this shader. This function marks that resource as an inline uniform block
685 // (VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT). This function only has any effect if argument buffers
686 // are enabled. If so, the buffer block will be directly embedded into the argument
687 // buffer, instead of being referenced indirectly via pointer.
688 void add_inline_uniform_block(uint32_t desc_set, uint32_t binding);
689
690 // When using MSL argument buffers, we can force "classic" MSL 1.0 binding schemes for certain descriptor sets.
691 // This corresponds to VK_KHR_push_descriptor in Vulkan.
692 void add_discrete_descriptor_set(uint32_t desc_set);
693
694 // If an argument buffer is large enough, it may need to be in the device storage space rather than
695 // constant. Opt-in to this behavior here on a per set basis.
696 void set_argument_buffer_device_address_space(uint32_t desc_set, bool device_storage);
697
698 // Query after compilation is done. This allows you to check if an input location was used by the shader.
699 bool is_msl_shader_input_used(uint32_t location);
700
701 // Query after compilation is done. This allows you to check if an output location were used by the shader.
702 bool is_msl_shader_output_used(uint32_t location);
703
704 // If not using add_msl_shader_input, it's possible
705 // that certain builtin attributes need to be automatically assigned locations.
706 // This is typical for tessellation builtin inputs such as tess levels, gl_Position, etc.
707 // This returns k_unknown_location if the location was explicitly assigned with
708 // add_msl_shader_input or the builtin is not used, otherwise returns N in [[attribute(N)]].
709 uint32_t get_automatic_builtin_input_location(spv::BuiltIn builtin) const;
710
711 // If not using add_msl_shader_output, it's possible
712 // that certain builtin attributes need to be automatically assigned locations.
713 // This is typical for tessellation builtin outputs such as tess levels, gl_Position, etc.
714 // This returns k_unknown_location if the location were explicitly assigned with
715 // add_msl_shader_output or the builtin were not used, otherwise returns N in [[attribute(N)]].
716 uint32_t get_automatic_builtin_output_location(spv::BuiltIn builtin) const;
717
718 // NOTE: Only resources which are remapped using add_msl_resource_binding will be reported here.
719 // Constexpr samplers are always assumed to be emitted.
720 // No specific MSLResourceBinding remapping is required for constexpr samplers as long as they are remapped
721 // by remap_constexpr_sampler(_by_binding).
722 bool is_msl_resource_binding_used(spv::ExecutionModel model, uint32_t set, uint32_t binding) const;
723
724 // This must only be called after a successful call to CompilerMSL::compile().
725 // For a variable resource ID obtained through reflection API, report the automatically assigned resource index.
726 // If the descriptor set was part of an argument buffer, report the [[id(N)]],
727 // or [[buffer/texture/sampler]] binding for other resources.
728 // If the resource was a combined image sampler, report the image binding here,
729 // use the _secondary version of this call to query the sampler half of the resource.
730 // If no binding exists, uint32_t(-1) is returned.
731 uint32_t get_automatic_msl_resource_binding(uint32_t id) const;
732
733 // Same as get_automatic_msl_resource_binding, but should only be used for combined image samplers, in which case the
734 // sampler's binding is returned instead. For any other resource type, -1 is returned.
735 // Secondary bindings are also used for the auxillary image atomic buffer.
736 uint32_t get_automatic_msl_resource_binding_secondary(uint32_t id) const;
737
738 // Same as get_automatic_msl_resource_binding, but should only be used for combined image samplers for multiplanar images,
739 // in which case the second plane's binding is returned instead. For any other resource type, -1 is returned.
740 uint32_t get_automatic_msl_resource_binding_tertiary(uint32_t id) const;
741
742 // Same as get_automatic_msl_resource_binding, but should only be used for combined image samplers for triplanar images,
743 // in which case the third plane's binding is returned instead. For any other resource type, -1 is returned.
744 uint32_t get_automatic_msl_resource_binding_quaternary(uint32_t id) const;
745
746 // Compiles the SPIR-V code into Metal Shading Language.
747 std::string compile() override;
748
749 // Remap a sampler with ID to a constexpr sampler.
750 // Older iOS targets must use constexpr samplers in certain cases (PCF),
751 // so a static sampler must be used.
752 // The sampler will not consume a binding, but be declared in the entry point as a constexpr sampler.
753 // This can be used on both combined image/samplers (sampler2D) or standalone samplers.
754 // The remapped sampler must not be an array of samplers.
755 // Prefer remap_constexpr_sampler_by_binding unless you're also doing reflection anyways.
756 void remap_constexpr_sampler(VariableID id, const MSLConstexprSampler &sampler);
757
758 // Same as remap_constexpr_sampler, except you provide set/binding, rather than variable ID.
759 // Remaps based on ID take priority over set/binding remaps.
760 void remap_constexpr_sampler_by_binding(uint32_t desc_set, uint32_t binding, const MSLConstexprSampler &sampler);
761
762 // If using CompilerMSL::Options::pad_fragment_output_components, override the number of components we expect
763 // to use for a particular location. The default is 4 if number of components is not overridden.
764 void set_fragment_output_components(uint32_t location, uint32_t components);
765
766 void set_combined_sampler_suffix(const char *suffix);
767 const char *get_combined_sampler_suffix() const;
768
769 // Information about specialization constants that are translated into MSL macros
770 // instead of using function constant
771 // These must only be called after a successful call to CompilerMSL::compile().
772 bool specialization_constant_is_macro(uint32_t constant_id) const;
773
774 // Returns a mask of SPIR-V FP Fast Math Mode flags, that represents the set of flags that can be applied
775 // across all floating-point types. Each FPFastMathDefault execution mode operation identifies the flags
776 // for one floating-point type, and the value returned here is a bitwise-AND combination across all types.
777 // If incl_ops is enabled, the FPFastMathMode of any SPIR-V operations are also included in the bitwise-AND
778 // to determine the minimal fast-math that applies to all default execution modes and all operations.
779 // The returned value is also affected by execution modes SignedZeroInfNanPreserve and ContractionOff.
780 uint32_t get_fp_fast_math_flags(bool incl_ops);
781
782 protected:
783 // An enum of SPIR-V functions that are implemented in additional
784 // source code that is added to the shader if necessary.
785 enum SPVFuncImpl : uint8_t
786 {
787 SPVFuncImplNone,
788 SPVFuncImplMod,
789 SPVFuncImplSMod,
790 SPVFuncImplRadians,
791 SPVFuncImplDegrees,
792 SPVFuncImplFindILsb,
793 SPVFuncImplFindSMsb,
794 SPVFuncImplFindUMsb,
795 SPVFuncImplSSign,
796 SPVFuncImplArrayCopy,
797 SPVFuncImplArrayCopyMultidim,
798 SPVFuncImplTexelBufferCoords,
799 SPVFuncImplImage2DAtomicCoords, // Emulate texture2D atomic operations
800 SPVFuncImplGradientCube,
801 SPVFuncImplFMul,
802 SPVFuncImplFAdd,
803 SPVFuncImplFSub,
804 SPVFuncImplQuantizeToF16,
805 SPVFuncImplCubemapTo2DArrayFace,
806 SPVFuncImplUnsafeArray, // Allow Metal to use the array<T> template to make arrays a value type
807 SPVFuncImplStorageMatrix, // Allow threadgroup construction of matrices
808 SPVFuncImplInverse4x4,
809 SPVFuncImplInverse3x3,
810 SPVFuncImplInverse2x2,
811 // It is very important that this come before *Swizzle, to ensure it's emitted before them.
812 SPVFuncImplGetSwizzle,
813 SPVFuncImplTextureSwizzle,
814 SPVFuncImplGatherReturn,
815 SPVFuncImplGatherCompareReturn,
816 SPVFuncImplGatherSwizzle,
817 SPVFuncImplGatherCompareSwizzle,
818 SPVFuncImplGatherConstOffsets,
819 SPVFuncImplGatherCompareConstOffsets,
820 SPVFuncImplSubgroupBroadcast,
821 SPVFuncImplSubgroupBroadcastFirst,
822 SPVFuncImplSubgroupBallot,
823 SPVFuncImplSubgroupBallotBitExtract,
824 SPVFuncImplSubgroupBallotFindLSB,
825 SPVFuncImplSubgroupBallotFindMSB,
826 SPVFuncImplSubgroupBallotBitCount,
827 SPVFuncImplSubgroupAllEqual,
828 SPVFuncImplSubgroupShuffle,
829 SPVFuncImplSubgroupShuffleXor,
830 SPVFuncImplSubgroupShuffleUp,
831 SPVFuncImplSubgroupShuffleDown,
832 SPVFuncImplSubgroupRotate,
833 SPVFuncImplSubgroupClusteredAdd,
834 SPVFuncImplSubgroupClusteredFAdd = SPVFuncImplSubgroupClusteredAdd,
835 SPVFuncImplSubgroupClusteredIAdd = SPVFuncImplSubgroupClusteredAdd,
836 SPVFuncImplSubgroupClusteredMul,
837 SPVFuncImplSubgroupClusteredFMul = SPVFuncImplSubgroupClusteredMul,
838 SPVFuncImplSubgroupClusteredIMul = SPVFuncImplSubgroupClusteredMul,
839 SPVFuncImplSubgroupClusteredMin,
840 SPVFuncImplSubgroupClusteredFMin = SPVFuncImplSubgroupClusteredMin,
841 SPVFuncImplSubgroupClusteredSMin = SPVFuncImplSubgroupClusteredMin,
842 SPVFuncImplSubgroupClusteredUMin = SPVFuncImplSubgroupClusteredMin,
843 SPVFuncImplSubgroupClusteredMax,
844 SPVFuncImplSubgroupClusteredFMax = SPVFuncImplSubgroupClusteredMax,
845 SPVFuncImplSubgroupClusteredSMax = SPVFuncImplSubgroupClusteredMax,
846 SPVFuncImplSubgroupClusteredUMax = SPVFuncImplSubgroupClusteredMax,
847 SPVFuncImplSubgroupClusteredAnd,
848 SPVFuncImplSubgroupClusteredBitwiseAnd = SPVFuncImplSubgroupClusteredAnd,
849 SPVFuncImplSubgroupClusteredLogicalAnd = SPVFuncImplSubgroupClusteredAnd,
850 SPVFuncImplSubgroupClusteredOr,
851 SPVFuncImplSubgroupClusteredBitwiseOr = SPVFuncImplSubgroupClusteredOr,
852 SPVFuncImplSubgroupClusteredLogicalOr = SPVFuncImplSubgroupClusteredOr,
853 SPVFuncImplSubgroupClusteredXor,
854 SPVFuncImplSubgroupClusteredBitwiseXor = SPVFuncImplSubgroupClusteredXor,
855 SPVFuncImplSubgroupClusteredLogicalXor = SPVFuncImplSubgroupClusteredXor,
856 SPVFuncImplQuadBroadcast,
857 SPVFuncImplQuadSwap,
858 SPVFuncImplReflectScalar,
859 SPVFuncImplRefractScalar,
860 SPVFuncImplFaceForwardScalar,
861 SPVFuncImplChromaReconstructNearest2Plane,
862 SPVFuncImplChromaReconstructNearest3Plane,
863 SPVFuncImplChromaReconstructLinear422CositedEven2Plane,
864 SPVFuncImplChromaReconstructLinear422CositedEven3Plane,
865 SPVFuncImplChromaReconstructLinear422Midpoint2Plane,
866 SPVFuncImplChromaReconstructLinear422Midpoint3Plane,
867 SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane,
868 SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane,
869 SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane,
870 SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane,
871 SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane,
872 SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane,
873 SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane,
874 SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane,
875 SPVFuncImplExpandITUFullRange,
876 SPVFuncImplExpandITUNarrowRange,
877 SPVFuncImplConvertYCbCrBT709,
878 SPVFuncImplConvertYCbCrBT601,
879 SPVFuncImplConvertYCbCrBT2020,
880 SPVFuncImplDynamicImageSampler,
881 SPVFuncImplRayQueryIntersectionParams,
882 SPVFuncImplVariableDescriptor,
883 SPVFuncImplVariableSizedDescriptor,
884 SPVFuncImplVariableDescriptorArray,
885 SPVFuncImplPaddedStd140,
886 SPVFuncImplReduceAdd,
887 SPVFuncImplImageFence,
888 SPVFuncImplTextureCast,
889 SPVFuncImplMulExtended,
890 SPVFuncImplSetMeshOutputsEXT,
891 SPVFuncImplAssume,
892 };
893
894 // If the underlying resource has been used for comparison then duplicate loads of that resource must be too
895 // Use Metal's native frame-buffer fetch API for subpass inputs.
896 void emit_texture_op(const Instruction &i, bool sparse) override;
897 void emit_binary_ptr_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
898 std::string to_ptr_expression(uint32_t id, bool register_expression_read = true);
899 void emit_binary_unord_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
900 void emit_instruction(const Instruction &instr) override;
901 void emit_glsl_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
902 uint32_t count) override;
903 void emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t result_id, uint32_t op,
904 const uint32_t *args, uint32_t count) override;
905 void emit_header() override;
906 void emit_function_prototype(SPIRFunction &func, const Bitset &return_flags) override;
907 void emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id) override;
908 void emit_subgroup_op(const Instruction &i) override;
909 void emit_subgroup_cluster_op(uint32_t result_type, uint32_t result_id, uint32_t cluster_size, uint32_t op0,
910 const char *op);
911 void emit_subgroup_cluster_op_cast(uint32_t result_type, uint32_t result_id, uint32_t cluster_size, uint32_t op0,
912 const char *op, SPIRType::BaseType input_type,
913 SPIRType::BaseType expected_result_type);
914 std::string to_texture_op(const Instruction &i, bool sparse, bool *forward,
915 SmallVector<uint32_t> &inherited_expressions) override;
916 void emit_fixup() override;
917 std::string to_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
918 const std::string &qualifier = "");
919 void emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
920 const std::string &qualifier = "", uint32_t base_offset = 0) override;
921 void emit_struct_padding_target(const SPIRType &type) override;
922 std::string type_to_glsl(const SPIRType &type, uint32_t id, bool member);
923 std::string type_to_glsl(const SPIRType &type, uint32_t id = 0) override;
924 void emit_block_hints(const SPIRBlock &block) override;
925 void emit_mesh_entry_point();
926 void emit_mesh_outputs();
927 void emit_mesh_tasks(SPIRBlock &block) override;
928 void emit_workgroup_initialization(const SPIRVariable &var) override;
929
930 // Allow Metal to use the array<T> template to make arrays a value type
931 std::string type_to_array_glsl(const SPIRType &type, uint32_t variable_id) override;
932 std::string constant_op_expression(const SPIRConstantOp &cop) override;
933
934 bool variable_decl_is_remapped_storage(const SPIRVariable &variable, spv::StorageClass storage) const override;
935
936 // GCC workaround of lambdas calling protected functions (for older GCC versions)
937 std::string variable_decl(const SPIRType &type, const std::string &name, uint32_t id = 0) override;
938
939 std::string image_type_glsl(const SPIRType &type, uint32_t id, bool member) override;
940 std::string sampler_type(const SPIRType &type, uint32_t id, bool member);
941 std::string builtin_to_glsl(spv::BuiltIn builtin, spv::StorageClass storage) override;
942 std::string to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id) override;
943 std::string to_name(uint32_t id, bool allow_alias = true) const override;
944 std::string to_function_name(const TextureFunctionNameArguments &args) override;
945 std::string to_function_args(const TextureFunctionArguments &args, bool *p_forward) override;
946 std::string to_initializer_expression(const SPIRVariable &var) override;
947 std::string to_zero_initialized_expression(uint32_t type_id) override;
948
949 std::string unpack_expression_type(std::string expr_str, const SPIRType &type, uint32_t physical_type_id,
950 bool is_packed, bool row_major) override;
951
952 // Returns true for BuiltInSampleMask because gl_SampleMask[] is an array in SPIR-V, but [[sample_mask]] is a scalar in Metal.
953 bool builtin_translates_to_nonarray(spv::BuiltIn builtin) const override;
954
955 std::string bitcast_glsl_op(const SPIRType &result_type, const SPIRType &argument_type) override;
956 bool emit_complex_bitcast(uint32_t result_id, uint32_t id, uint32_t op0) override;
957 bool skip_argument(uint32_t id) const override;
958 std::string to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain_is_resolved) override;
959 std::string to_qualifiers_glsl(uint32_t id) override;
960 void replace_illegal_names() override;
961 void declare_constant_arrays();
962
963 void replace_illegal_entry_point_names();
964 void sync_entry_point_aliases_and_names();
965
966 static const std::unordered_set<std::string> &get_reserved_keyword_set();
967 static const std::unordered_set<std::string> &get_illegal_func_names();
968
969 // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries
970 void declare_complex_constant_arrays();
971
972 bool is_patch_block(const SPIRType &type);
973 bool is_non_native_row_major_matrix(uint32_t id) override;
974 bool member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index) override;
975 std::string convert_row_major_matrix(std::string exp_str, const SPIRType &exp_type, uint32_t physical_type_id,
976 bool is_packed, bool relaxed) override;
977
978 bool is_tesc_shader() const;
979 bool is_tese_shader() const;
980 bool is_mesh_shader() const;
981
982 void preprocess_op_codes();
983 void localize_global_variables();
984 void extract_global_variables_from_functions();
985 void mark_packable_structs();
986 void mark_as_packable(SPIRType &type);
987 void mark_as_workgroup_struct(SPIRType &type);
988
989 std::unordered_map<uint32_t, std::set<uint32_t>> function_global_vars;
990 void extract_global_variables_from_function(uint32_t func_id, std::set<uint32_t> &added_arg_ids,
991 std::unordered_set<uint32_t> &global_var_ids,
992 std::unordered_set<uint32_t> &processed_func_ids);
993 uint32_t add_interface_block(spv::StorageClass storage, bool patch = false);
994 uint32_t add_interface_block_pointer(uint32_t ib_var_id, spv::StorageClass storage);
995 uint32_t add_meshlet_block(bool per_primitive);
996
997 struct InterfaceBlockMeta
998 {
999 struct LocationMeta
1000 {
1001 uint32_t base_type_id = 0;
1002 uint32_t num_components = 0;
1003 bool flat = false;
1004 bool noperspective = false;
1005 bool centroid = false;
1006 bool sample = false;
1007 };
1008 std::unordered_map<uint32_t, LocationMeta> location_meta;
1009 bool strip_array = false;
1010 bool allow_local_declaration = false;
1011 };
1012
1013 std::string to_tesc_invocation_id();
1014 void emit_local_masked_variable(const SPIRVariable &masked_var, bool strip_array);
1015 void add_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref, SPIRType &ib_type,
1016 SPIRVariable &var, InterfaceBlockMeta &meta);
1017 void add_composite_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref,
1018 SPIRType &ib_type, SPIRVariable &var, InterfaceBlockMeta &meta);
1019 void add_plain_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref,
1020 SPIRType &ib_type, SPIRVariable &var, InterfaceBlockMeta &meta);
1021 bool add_component_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref,
1022 SPIRVariable &var, const SPIRType &type,
1023 InterfaceBlockMeta &meta);
1024 void add_plain_member_variable_to_interface_block(spv::StorageClass storage,
1025 const std::string &ib_var_ref, SPIRType &ib_type,
1026 SPIRVariable &var, SPIRType &var_type,
1027 uint32_t mbr_idx, InterfaceBlockMeta &meta,
1028 const std::string &mbr_name_qual,
1029 const std::string &var_chain_qual,
1030 uint32_t &location, uint32_t &var_mbr_idx);
1031 void add_composite_member_variable_to_interface_block(spv::StorageClass storage,
1032 const std::string &ib_var_ref, SPIRType &ib_type,
1033 SPIRVariable &var, SPIRType &var_type,
1034 uint32_t mbr_idx, InterfaceBlockMeta &meta,
1035 const std::string &mbr_name_qual,
1036 const std::string &var_chain_qual,
1037 uint32_t &location, uint32_t &var_mbr_idx,
1038 const Bitset &interpolation_qual);
1039 void add_tess_level_input_to_interface_block(const std::string &ib_var_ref, SPIRType &ib_type, SPIRVariable &var);
1040 void add_tess_level_input(const std::string &base_ref, const std::string &mbr_name, SPIRVariable &var);
1041
1042 void ensure_struct_members_valid_vecsizes(SPIRType &struct_type, uint32_t &location);
1043 void fix_up_interface_member_indices(spv::StorageClass storage, uint32_t ib_type_id);
1044
1045 void mark_location_as_used_by_shader(uint32_t location, const SPIRType &type,
1046 spv::StorageClass storage, bool fallback = false);
1047 uint32_t ensure_correct_builtin_type(uint32_t type_id, spv::BuiltIn builtin);
1048 uint32_t ensure_correct_input_type(uint32_t type_id, uint32_t location, uint32_t component,
1049 uint32_t num_components, bool strip_array);
1050
1051 void emit_custom_templates();
1052 void emit_custom_functions();
1053 void emit_resources();
1054 void emit_specialization_constants_and_structs();
1055 void emit_interface_block(uint32_t ib_var_id);
1056 bool maybe_emit_array_assignment(uint32_t id_lhs, uint32_t id_rhs);
1057 bool is_var_runtime_size_array(const SPIRVariable &var) const;
1058 uint32_t get_resource_array_size(const SPIRType &type, uint32_t id) const;
1059
1060 void fix_up_shader_inputs_outputs();
1061
1062 std::string func_type_decl(SPIRType &type);
1063 std::string entry_point_args_classic(bool append_comma);
1064 std::string entry_point_args_argument_buffer(bool append_comma);
1065 std::string entry_point_arg_stage_in();
1066 void entry_point_args_builtin(std::string &args);
1067 void entry_point_args_discrete_descriptors(std::string &args);
1068 std::string append_member_name(const std::string &qualifier, const SPIRType &type, uint32_t index);
1069 std::string ensure_valid_name(std::string name, std::string pfx);
1070 std::string to_sampler_expression(uint32_t id);
1071 std::string to_swizzle_expression(uint32_t id);
1072 std::string to_buffer_size_expression(uint32_t id);
1073 bool is_sample_rate() const;
1074 bool is_intersection_query() const;
1075 bool is_direct_input_builtin(spv::BuiltIn builtin);
1076 std::string builtin_qualifier(spv::BuiltIn builtin);
1077 std::string builtin_type_decl(spv::BuiltIn builtin, uint32_t id = 0);
1078 std::string built_in_func_arg(spv::BuiltIn builtin, bool prefix_comma);
1079 std::string member_attribute_qualifier(const SPIRType &type, uint32_t index);
1080 std::string member_location_attribute_qualifier(const SPIRType &type, uint32_t index);
1081 std::string argument_decl(const SPIRFunction::Parameter &arg);
1082 const char *descriptor_address_space(uint32_t id, spv::StorageClass storage, const char *plain_address_space) const;
1083 std::string round_fp_tex_coords(std::string tex_coords, bool coord_is_fp);
1084 uint32_t get_metal_resource_index(SPIRVariable &var, SPIRType::BaseType basetype, uint32_t plane = 0);
1085 uint32_t get_member_location(uint32_t type_id, uint32_t index, uint32_t *comp = nullptr) const;
1086 uint32_t get_or_allocate_builtin_input_member_location(spv::BuiltIn builtin,
1087 uint32_t type_id, uint32_t index, uint32_t *comp = nullptr);
1088 uint32_t get_or_allocate_builtin_output_member_location(spv::BuiltIn builtin,
1089 uint32_t type_id, uint32_t index, uint32_t *comp = nullptr);
1090
1091 uint32_t get_physical_tess_level_array_size(spv::BuiltIn builtin) const;
1092
1093 uint32_t get_physical_type_stride(const SPIRType &type) const override;
1094
1095 // MSL packing rules. These compute the effective packing rules as observed by the MSL compiler in the MSL output.
1096 // These values can change depending on various extended decorations which control packing rules.
1097 // We need to make these rules match up with SPIR-V declared rules.
1098 uint32_t get_declared_type_size_msl(const SPIRType &type, bool packed, bool row_major) const;
1099 uint32_t get_declared_type_array_stride_msl(const SPIRType &type, bool packed, bool row_major) const;
1100 uint32_t get_declared_type_matrix_stride_msl(const SPIRType &type, bool packed, bool row_major) const;
1101 uint32_t get_declared_type_alignment_msl(const SPIRType &type, bool packed, bool row_major) const;
1102
1103 uint32_t get_declared_struct_member_size_msl(const SPIRType &struct_type, uint32_t index) const;
1104 uint32_t get_declared_struct_member_array_stride_msl(const SPIRType &struct_type, uint32_t index) const;
1105 uint32_t get_declared_struct_member_matrix_stride_msl(const SPIRType &struct_type, uint32_t index) const;
1106 uint32_t get_declared_struct_member_alignment_msl(const SPIRType &struct_type, uint32_t index) const;
1107
1108 uint32_t get_declared_input_size_msl(const SPIRType &struct_type, uint32_t index) const;
1109 uint32_t get_declared_input_array_stride_msl(const SPIRType &struct_type, uint32_t index) const;
1110 uint32_t get_declared_input_matrix_stride_msl(const SPIRType &struct_type, uint32_t index) const;
1111 uint32_t get_declared_input_alignment_msl(const SPIRType &struct_type, uint32_t index) const;
1112
1113 const SPIRType &get_physical_member_type(const SPIRType &struct_type, uint32_t index) const;
1114 SPIRType get_presumed_input_type(const SPIRType &struct_type, uint32_t index) const;
1115
1116 uint32_t get_declared_struct_size_msl(const SPIRType &struct_type, bool ignore_alignment = false,
1117 bool ignore_padding = false) const;
1118
1119 std::string to_component_argument(uint32_t id);
1120 void align_struct(SPIRType &ib_type, std::unordered_set<uint32_t> &aligned_structs);
1121 void mark_scalar_layout_structs(const SPIRType &ib_type);
1122 void mark_struct_members_packed(const SPIRType &type);
1123 void ensure_member_packing_rules_msl(SPIRType &ib_type, uint32_t index);
1124 bool validate_member_packing_rules_msl(const SPIRType &type, uint32_t index) const;
1125 std::string get_argument_address_space(const SPIRVariable &argument);
1126 std::string get_type_address_space(const SPIRType &type, uint32_t id, bool argument = false);
1127 bool decoration_flags_signal_volatile(const Bitset &flags) const;
1128 bool decoration_flags_signal_coherent(const Bitset &flags) const;
1129 const char *to_restrict(uint32_t id, bool space);
1130 SPIRType &get_stage_in_struct_type();
1131 SPIRType &get_stage_out_struct_type();
1132 SPIRType &get_patch_stage_in_struct_type();
1133 SPIRType &get_patch_stage_out_struct_type();
1134 std::string get_tess_factor_struct_name();
1135 SPIRType &get_uint_type();
1136 uint32_t get_uint_type_id();
1137 void emit_atomic_func_op(uint32_t result_type, uint32_t result_id, const char *op, spv::Op opcode,
1138 uint32_t mem_order_1, uint32_t mem_order_2, bool has_mem_order_2, uint32_t op0, uint32_t op1 = 0,
1139 bool op1_is_pointer = false, bool op1_is_literal = false, uint32_t op2 = 0);
1140 const char *get_memory_order(uint32_t spv_mem_sem);
1141 void add_pragma_line(const std::string &line, bool recompile_on_unique);
1142 void add_typedef_line(const std::string &line);
1143 void emit_barrier(uint32_t id_exe_scope, uint32_t id_mem_scope, uint32_t id_mem_sem);
1144 bool emit_array_copy(const char *expr, uint32_t lhs_id, uint32_t rhs_id,
1145 spv::StorageClass lhs_storage, spv::StorageClass rhs_storage) override;
1146 void build_implicit_builtins();
1147 uint32_t build_constant_uint_array_pointer();
1148 void emit_entry_point_declarations() override;
1149 bool uses_explicit_early_fragment_test();
1150
1151 uint32_t builtin_frag_coord_id = 0;
1152 uint32_t builtin_sample_id_id = 0;
1153 uint32_t builtin_sample_mask_id = 0;
1154 uint32_t builtin_helper_invocation_id = 0;
1155 uint32_t builtin_vertex_idx_id = 0;
1156 uint32_t builtin_base_vertex_id = 0;
1157 uint32_t builtin_instance_idx_id = 0;
1158 uint32_t builtin_base_instance_id = 0;
1159 uint32_t builtin_view_idx_id = 0;
1160 uint32_t builtin_layer_id = 0;
1161 uint32_t builtin_invocation_id_id = 0;
1162 uint32_t builtin_primitive_id_id = 0;
1163 uint32_t builtin_subgroup_invocation_id_id = 0;
1164 uint32_t builtin_subgroup_size_id = 0;
1165 uint32_t builtin_dispatch_base_id = 0;
1166 uint32_t builtin_stage_input_size_id = 0;
1167 uint32_t builtin_local_invocation_index_id = 0;
1168 uint32_t builtin_workgroup_size_id = 0;
1169 uint32_t builtin_mesh_primitive_indices_id = 0;
1170 uint32_t builtin_mesh_sizes_id = 0;
1171 uint32_t builtin_task_grid_id = 0;
1172 uint32_t builtin_frag_depth_id = 0;
1173 uint32_t swizzle_buffer_id = 0;
1174 uint32_t buffer_size_buffer_id = 0;
1175 uint32_t view_mask_buffer_id = 0;
1176 uint32_t dynamic_offsets_buffer_id = 0;
1177 uint32_t uint_type_id = 0;
1178 uint32_t shared_uint_type_id = 0;
1179 uint32_t meshlet_type_id = 0;
1180 uint32_t argument_buffer_padding_buffer_type_id = 0;
1181 uint32_t argument_buffer_padding_image_type_id = 0;
1182 uint32_t argument_buffer_padding_sampler_type_id = 0;
1183
1184 bool does_shader_write_sample_mask = false;
1185 bool frag_shader_needs_discard_checks = false;
1186
1187 void cast_to_variable_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type) override;
1188 void cast_from_variable_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type) override;
1189 void emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression) override;
1190
1191 void analyze_sampled_image_usage();
1192 void analyze_workgroup_variables();
1193
1194 bool access_chain_needs_stage_io_builtin_translation(uint32_t base) override;
1195 bool prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type, spv::StorageClass storage,
1196 bool &is_packed) override;
1197 void fix_up_interpolant_access_chain(const uint32_t *ops, uint32_t length);
1198 bool check_physical_type_cast(std::string &expr, const SPIRType *type, uint32_t physical_type) override;
1199
1200 bool emit_tessellation_access_chain(const uint32_t *ops, uint32_t length);
1201 bool emit_tessellation_io_load(uint32_t result_type, uint32_t id, uint32_t ptr);
1202 bool is_out_of_bounds_tessellation_level(uint32_t id_lhs);
1203
1204 void ensure_builtin(spv::StorageClass storage, spv::BuiltIn builtin);
1205
1206 void mark_implicit_builtin(spv::StorageClass storage, spv::BuiltIn builtin, uint32_t id);
1207
1208 std::string convert_to_f32(const std::string &expr, uint32_t components);
1209
1210 Options msl_options;
1211 std::set<SPVFuncImpl> spv_function_implementations;
1212 // Must be ordered to ensure declarations are in a specific order.
1213 std::map<LocationComponentPair, MSLShaderInterfaceVariable> inputs_by_location;
1214 std::unordered_map<uint32_t, MSLShaderInterfaceVariable> inputs_by_builtin;
1215 std::map<LocationComponentPair, MSLShaderInterfaceVariable> outputs_by_location;
1216 std::unordered_map<uint32_t, MSLShaderInterfaceVariable> outputs_by_builtin;
1217 std::unordered_set<uint32_t> location_inputs_in_use;
1218 std::unordered_set<uint32_t> location_inputs_in_use_fallback;
1219 std::unordered_set<uint32_t> location_outputs_in_use;
1220 std::unordered_set<uint32_t> location_outputs_in_use_fallback;
1221 std::unordered_map<uint32_t, uint32_t> fragment_output_components;
1222 std::unordered_map<uint32_t, uint32_t> builtin_to_automatic_input_location;
1223 std::unordered_map<uint32_t, uint32_t> builtin_to_automatic_output_location;
1224 std::vector<std::string> pragma_lines;
1225 std::vector<std::string> typedef_lines;
1226 SmallVector<uint32_t> vars_needing_early_declaration;
1227 std::unordered_set<uint32_t> constant_macro_ids;
1228
1229 std::unordered_map<StageSetBinding, std::pair<MSLResourceBinding, bool>, InternalHasher> resource_bindings;
1230 std::unordered_map<StageSetBinding, uint32_t, InternalHasher> resource_arg_buff_idx_to_binding_number;
1231
1232 uint32_t next_metal_resource_index_buffer = 0;
1233 uint32_t next_metal_resource_index_texture = 0;
1234 uint32_t next_metal_resource_index_sampler = 0;
1235 // Intentionally uninitialized, works around MSVC 2013 bug.
1236 uint32_t next_metal_resource_ids[kMaxArgumentBuffers];
1237
1238 VariableID stage_in_var_id = 0;
1239 VariableID stage_out_var_id = 0;
1240 VariableID patch_stage_in_var_id = 0;
1241 VariableID patch_stage_out_var_id = 0;
1242 VariableID stage_in_ptr_var_id = 0;
1243 VariableID stage_out_ptr_var_id = 0;
1244 VariableID tess_level_inner_var_id = 0;
1245 VariableID tess_level_outer_var_id = 0;
1246 VariableID mesh_out_per_vertex = 0;
1247 VariableID mesh_out_per_primitive = 0;
1248 VariableID stage_out_masked_builtin_type_id = 0;
1249
1250 // Handle HLSL-style 0-based vertex/instance index.
1251 enum class TriState
1252 {
1253 Neutral,
1254 No,
1255 Yes
1256 };
1257 TriState needs_base_vertex_arg = TriState::Neutral;
1258 TriState needs_base_instance_arg = TriState::Neutral;
1259
1260 bool has_sampled_images = false;
1261 bool builtin_declaration = false; // Handle HLSL-style 0-based vertex/instance index.
1262
1263 bool is_using_builtin_array = false; // Force the use of C style array declaration.
1264 bool using_builtin_array() const;
1265
1266 bool is_rasterization_disabled = false;
1267 bool capture_output_to_buffer = false;
1268 bool needs_swizzle_buffer_def = false;
1269 bool used_swizzle_buffer = false;
1270 bool added_builtin_tess_level = false;
1271 bool needs_local_invocation_index = false;
1272 bool needs_subgroup_invocation_id = false;
1273 bool needs_subgroup_size = false;
1274 bool needs_sample_id = false;
1275 bool needs_helper_invocation = false;
1276 bool needs_workgroup_zero_init = false;
1277 bool writes_to_depth = false;
1278 bool writes_to_point_size = false;
1279 std::string qual_pos_var_name;
1280 std::string stage_in_var_name = "in";
1281 std::string stage_out_var_name = "out";
1282 std::string patch_stage_in_var_name = "patchIn";
1283 std::string patch_stage_out_var_name = "patchOut";
1284 std::string sampler_name_suffix = "Smplr";
1285 std::string swizzle_name_suffix = "Swzl";
1286 std::string buffer_size_name_suffix = "BufferSize";
1287 std::string plane_name_suffix = "Plane";
1288 std::string input_wg_var_name = "gl_in";
1289 std::string input_buffer_var_name = "spvIn";
1290 std::string output_buffer_var_name = "spvOut";
1291 std::string patch_input_buffer_var_name = "spvPatchIn";
1292 std::string patch_output_buffer_var_name = "spvPatchOut";
1293 std::string tess_factor_buffer_var_name = "spvTessLevel";
1294 std::string index_buffer_var_name = "spvIndices";
1295 spv::Op previous_instruction_opcode = spv::OpNop;
1296
1297 // Must be ordered since declaration is in a specific order.
1298 std::map<uint32_t, MSLConstexprSampler> constexpr_samplers_by_id;
1299 std::unordered_map<SetBindingPair, MSLConstexprSampler, InternalHasher> constexpr_samplers_by_binding;
1300 const MSLConstexprSampler *find_constexpr_sampler(uint32_t id) const;
1301
1302 std::unordered_set<uint32_t> buffers_requiring_array_length;
1303 SmallVector<std::pair<uint32_t, uint32_t>> buffer_aliases_argument;
1304 SmallVector<uint32_t> buffer_aliases_discrete;
1305 std::unordered_set<uint32_t> atomic_image_vars_emulated; // Emulate texture2D atomic operations
1306 std::unordered_set<uint32_t> pull_model_inputs;
1307 std::unordered_set<uint32_t> recursive_inputs;
1308
1309 SmallVector<SPIRVariable *> entry_point_bindings;
1310
1311 // Must be ordered since array is in a specific order.
1312 std::map<SetBindingPair, std::pair<uint32_t, uint32_t>> buffers_requiring_dynamic_offset;
1313
1314 SmallVector<uint32_t> disabled_frag_outputs;
1315
1316 std::unordered_set<SetBindingPair, InternalHasher> inline_uniform_blocks;
1317
1318 uint32_t argument_buffer_ids[kMaxArgumentBuffers];
1319 uint32_t argument_buffer_discrete_mask = 0;
1320 uint32_t argument_buffer_device_storage_mask = 0;
1321
1322 void emit_argument_buffer_aliased_descriptor(const SPIRVariable &aliased_var,
1323 const SPIRVariable &base_var);
1324
1325 void analyze_argument_buffers();
1326 bool descriptor_set_is_argument_buffer(uint32_t desc_set) const;
1327 const MSLResourceBinding &get_argument_buffer_resource(uint32_t desc_set, uint32_t arg_idx) const;
1328 void add_argument_buffer_padding_buffer_type(SPIRType &struct_type, uint32_t &mbr_idx, uint32_t &arg_buff_index, MSLResourceBinding &rez_bind);
1329 void add_argument_buffer_padding_image_type(SPIRType &struct_type, uint32_t &mbr_idx, uint32_t &arg_buff_index, MSLResourceBinding &rez_bind);
1330 void add_argument_buffer_padding_sampler_type(SPIRType &struct_type, uint32_t &mbr_idx, uint32_t &arg_buff_index, MSLResourceBinding &rez_bind);
1331 void add_argument_buffer_padding_type(uint32_t mbr_type_id, SPIRType &struct_type, uint32_t &mbr_idx, uint32_t &arg_buff_index, uint32_t count);
1332
1333 uint32_t get_target_components_for_fragment_location(uint32_t location) const;
1334 uint32_t build_extended_vector_type(uint32_t type_id, uint32_t components,
1335 SPIRType::BaseType basetype = SPIRType::Unknown);
1336 uint32_t build_msl_interpolant_type(uint32_t type_id, bool is_noperspective);
1337
1338 bool suppress_missing_prototypes = false;
1339 bool suppress_incompatible_pointer_types_discard_qualifiers = false;
1340 bool suppress_sometimes_unitialized = false;
1341
1342 void add_spv_func_and_recompile(SPVFuncImpl spv_func);
1343
1344 void activate_argument_buffer_resources();
1345
1346 bool type_is_msl_framebuffer_fetch(const SPIRType &type) const;
1347 bool is_supported_argument_buffer_type(const SPIRType &type) const;
1348
1349 bool variable_storage_requires_stage_io(spv::StorageClass storage) const;
1350
1351 bool needs_manual_helper_invocation_updates() const
1352 {
1353 return msl_options.manual_helper_invocation_updates && msl_options.supports_msl_version(2, 3);
1354 }
1355 bool needs_frag_discard_checks() const
1356 {
1357 return get_execution_model() == spv::ExecutionModelFragment && msl_options.supports_msl_version(2, 3) &&
1358 msl_options.check_discarded_frag_stores && frag_shader_needs_discard_checks;
1359 }
1360
1361 bool has_additional_fixed_sample_mask() const { return msl_options.additional_fixed_sample_mask != 0xffffffff; }
1362 std::string additional_fixed_sample_mask_str() const;
1363
1364 // OpcodeHandler that handles several MSL preprocessing operations.
1365 struct OpCodePreprocessor : OpcodeHandler
1366 {
1367 OpCodePreprocessor(CompilerMSL &compiler_)
1368 : compiler(compiler_)
1369 {
1370 }
1371
1372 bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
1373 CompilerMSL::SPVFuncImpl get_spv_func_impl(spv::Op opcode, const uint32_t *args, uint32_t length);
1374 void check_resource_write(uint32_t var_id);
1375
1376 CompilerMSL &compiler;
1377 std::unordered_map<uint32_t, uint32_t> result_types;
1378 std::unordered_map<uint32_t, uint32_t> image_pointers_emulated; // Emulate texture2D atomic operations
1379 bool suppress_missing_prototypes = false;
1380 bool uses_atomics = false;
1381 bool uses_image_write = false;
1382 bool uses_buffer_write = false;
1383 bool uses_discard = false;
1384 bool needs_local_invocation_index = false;
1385 bool needs_subgroup_invocation_id = false;
1386 bool needs_subgroup_size = false;
1387 bool needs_sample_id = false;
1388 bool needs_helper_invocation = false;
1389 };
1390
1391 // OpcodeHandler that scans for uses of sampled images
1392 struct SampledImageScanner : OpcodeHandler
1393 {
1394 SampledImageScanner(CompilerMSL &compiler_)
1395 : compiler(compiler_)
1396 {
1397 }
1398
1399 bool handle(spv::Op opcode, const uint32_t *args, uint32_t) override;
1400
1401 CompilerMSL &compiler;
1402 };
1403
1404 // Sorts the members of a SPIRType and associated Meta info based on a settable sorting
1405 // aspect, which defines which aspect of the struct members will be used to sort them.
1406 // Regardless of the sorting aspect, built-in members always appear at the end of the struct.
1407 struct MemberSorter
1408 {
1409 enum SortAspect
1410 {
1411 LocationThenBuiltInType,
1412 Offset
1413 };
1414
1415 void sort();
1416 bool operator()(uint32_t mbr_idx1, uint32_t mbr_idx2);
1417 MemberSorter(SPIRType &t, Meta &m, SortAspect sa);
1418
1419 SPIRType &type;
1420 Meta &meta;
1421 SortAspect sort_aspect;
1422 };
1423 };
1424 } // namespace SPIRV_CROSS_NAMESPACE
1425
1426 #endif